hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
624de8babfee2cc812e04c24303992ce42b54f46 | 2,861 | cpp | C++ | src/cl_glitcher/cmd_execution/execute_cmd.cpp | bridgerrholt/cl_glitcher | 48fc2a81dc7724698b462efe18e60d8feb1d3b36 | [
"MIT"
] | null | null | null | src/cl_glitcher/cmd_execution/execute_cmd.cpp | bridgerrholt/cl_glitcher | 48fc2a81dc7724698b462efe18e60d8feb1d3b36 | [
"MIT"
] | null | null | null | src/cl_glitcher/cmd_execution/execute_cmd.cpp | bridgerrholt/cl_glitcher | 48fc2a81dc7724698b462efe18e60d8feb1d3b36 | [
"MIT"
] | null | null | null | //
// Created by bridg on 3/12/2021.
//
#include <filesystem>
#include <gpu_util/build_program.h>
#include <cmd_execution/execute_cmd.h>
#include <image_util/load_image.h>
#include <gpu_util/init.h>
#include <gpu_util/buffer_wrapper.h>
#include <fstream>
namespace clglitch {
namespace {
JsonObjType const & tryGetCmd(
JsonObjType const & cmd)
{
auto cmdIt = cmd.FindMember("cmd");
if (cmdIt != cmd.MemberEnd()) {
if (cmdIt->value.IsString()) {
return cmdIt->value;
}
else {
throw std::runtime_error(
"Object in command file has non-string cmd field");
}
}
else {
throw std::runtime_error("Object in command file has no cmd field");
}
}
JsonObjType const & tryGetData(
JsonObjType const & data)
{
auto dataIt = data.FindMember("data");
if (dataIt != data.MemberEnd()) {
return dataIt->value;
}
else {
// TODO: Make this not throw (data may not always be required).
throw std::runtime_error("Object in command file has no data field");
}
}
// TODO: Make work with dynamic mods.
StaticModData const & tryGetMod(
ModSys const & modSys,
std::string const & cmdName)
{
auto const * mod = modSys.getStaticMod(cmdName);
if (mod != nullptr) {
return *mod;
}
else {
throw std::runtime_error("No such mod/cmd exists: " + cmdName);
}
}
std::string tryGetInputImage(CmdEnvironment const & cmdEnv)
{
auto const * it = cmdEnv.getVar("inputImage");
if (it != nullptr) {
return it->GetString();
}
else {
throw std::runtime_error("No inputImage specified");
}
}
}
void executeCmd(
ModSys const & modSys,
CmdEnvironment const & cmdEnv,
SystemEnvironment const & systemEnv,
std::string const & cmdPath,
JsonObjType const & cmd)
{
auto const & cmdField = tryGetCmd(cmd);
auto const & dataField = tryGetData(cmd);
auto const & mod = tryGetMod(modSys, cmdField.GetString());
std::string inputImageFilename = tryGetInputImage(cmdEnv);
auto inputImagePath =
std::filesystem::path(cmdPath).parent_path() / inputImageFilename;
bool exists = std::filesystem::exists(inputImagePath);
inputImageFilename = inputImagePath.generic_string();
std::ifstream fTest{ inputImageFilename };
cv::Mat imageMat {image_util::loadImage(inputImageFilename)};
if (imageMat.empty()) {
throw std::runtime_error(
"Failed to load inputImage file \"" + inputImageFilename + '"'
);
}
gpu_util::GpuHandle gpuHandle {gpu_util::init()};
cl::CommandQueue queue(gpuHandle.context, gpuHandle.device);
auto imgSize = imageMat.step[0] * imageMat.rows;
auto imgBuffer = gpu_util::BufferWrapper::writeBuffer(
queue, gpuHandle, CL_MEM_READ_WRITE, imageMat.data, imgSize
);
(mod.jsonObjExecute)({
dataField,
cmdEnv,
systemEnv,
imgBuffer,
imageMat,
(int)imgSize,
gpuHandle,
queue
});
}
} | 22.527559 | 73 | 0.678784 | bridgerrholt |
6253a9e2743fc74e37b6814935199d1a09e23d38 | 2,008 | cc | C++ | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | mains/pool_identity_testing_main.cc | guilhermemtr/semistandard-tableaux | bdc25df3c091bb457055579455bb05d4d7f2f5b5 | [
"MIT"
] | null | null | null | #include <iostream>
#include <boost/program_options.hpp>
#include <cstdio>
#include "placid.hpp"
namespace po = boost::program_options;
namespace p = __placid;
int
main (int argc, char **argv)
{
p::free_monoid::element aaa;
p::tropical_elements::number bbb;
po::options_description desc ("Options");
desc.add_options () ("help,h", "Produces this help message.") //
("include,i",
po::value<std::vector<std::string>> (),
"Adds semistandard tableaux to the pool.") (
"test,t", po::value<std::string> (), "Sets the identity to be tested.");
po::positional_options_description p;
p.add ("include", -1);
po::variables_map vm;
po::store (
po::command_line_parser (argc, argv).options (desc).positional (p).run (),
vm);
po::notify (vm);
if (vm.count ("help"))
{
std::cout << desc << std::endl;
return 1;
}
p::pool<p::semistandard_tableaux::tableaux> pool;
std::vector<std::string> opts = vm["include"].as<std::vector<std::string>> ();
for (size_t i = 0; i < opts.size (); i++)
{
std::string in_fn = opts[i];
p::semistandard_tableaux::tableaux input;
try
{
input.read_file (in_fn);
pool.add (input);
} catch (std::string e)
{
std::cout << e << std::endl;
return 1;
}
}
if (vm.count ("test"))
{
std::string id_to_test = vm["test"].as<std::string> ();
try
{
pool.test_identity (id_to_test);
std::cout << "Identity holds." << std::endl;
} catch (std::unordered_map<std::string, p::semistandard_tableaux::tableaux>
counter_example)
{
std::cout << "Identity does not hold." << std::endl;
for (auto it : counter_example)
{
printf ("\n%s:\n", it.first.c_str ());
it.second.write (stdout, 2);
}
} catch (...)
{
printf ("Unknown error occurred.\n");
}
} else
{
std::cout << "No identity given" << std::endl;
return 1;
}
return 0;
}
| 22.561798 | 80 | 0.571713 | guilhermemtr |
625584b9c6553ba26611179070c2a817d20fa1f9 | 1,626 | cpp | C++ | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | leetcode/leetcode_1170_easy_compare_strings_by_frequency_of_the_smallest_character/main.v01.cpp | friskit-china/leetcode-cn-repo | 5f428e77f9d3f79da3e670a38b86d85bd58c81b2 | [
"MIT"
] | null | null | null | // https://leetcode-cn.com/problems/compare-strings-by-frequency-of-the-smallest-character/
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
// submit start
class Solution {
public:
vector<int> numSmallerByFrequency(vector<string>& queries, vector<string>& words) {
vector<int> result;
int f_words[words.size()] = {0};
for (int i = 0; i < words.size(); ++i){
f_words[i] = f(words[i]);
}
for (auto it = queries.begin(); it != queries.end(); ++it){
int f_q = f(*it);
int counter = 0;
for (int i = 0; i < words.size(); ++i){
if (f_q < f_words[i]){
counter += 1;
}
}
result.push_back(counter);
}
return result;
}
int f(string s){
char min_word = 'z' + 1;
int min_counter = 0;
for (int i = 0; i < s.length(); ++i){
if (s[i] < min_word){
min_word = s[i];
min_counter = 1;
}else if(s[i] == min_word){
min_counter += 1;
}
}
return min_counter;
}
};
// submit end
int main(){
Solution sl;
// vector<string> queries = {"cbd"};
// vector<string> words = {"zaaaz"};
vector<string> queries = {"bbb", "cc"};
vector<string> words = {"a", "aa", "aaa", "aaaa"};
auto result = sl.numSmallerByFrequency(queries, words);
for (vector<int>::iterator it = result.begin(); it != result.end(); ++it){
cout<<*it<<" ";
}
cout<<endl;
return 0;
} | 26.225806 | 91 | 0.48893 | friskit-china |
625610649e940f4c7beef65f33bc9fcef38980d2 | 5,402 | cpp | C++ | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | ajaapps/crossplatform/demoapps/ntv2fieldburn/main.cpp | ibstewart/ntv2 | 0acbac70a0b5e6509cca78cfbf69974c73c10db9 | [
"MIT"
] | null | null | null | /* SPDX-License-Identifier: MIT */
/**
@file ntv2fieldburn/main.cpp
@brief Demonstration application to capture frames from the SDI input as two distinct fields
in separate, non-contiguous memory locations, "burn" a timecode window into each field,
and recombine the modified fields for SDI playout.
@copyright (C) 2013-2021 AJA Video Systems, Inc. All rights reserved.
**/
// Includes
#include "ajatypes.h"
#include "ajabase/common/options_popt.h"
#include "ntv2fieldburn.h"
#include "ajabase/system/systemtime.h"
#include <signal.h>
#include <iostream>
#include <iomanip>
using namespace std;
// Globals
static bool gGlobalQuit (false); ///< @brief Set this "true" to exit gracefully
static void SignalHandler (int inSignal)
{
(void) inSignal;
gGlobalQuit = true;
}
int main (int argc, const char ** argv)
{
char * pDeviceSpec (AJA_NULL); // Which device to use
char * pPixelFormat (AJA_NULL); // Pixel format spec
uint32_t inputNumber (1); // Which input to use (1-8, defaults to 1)
int noAudio (0); // Disable audio?
int noFieldMode (0); // Disable AutoCirculate Field Mode?
int doMultiChannel (0); // Set the board up for multi-channel/format
poptContext optionsContext; // Context for parsing command line arguments
AJADebug::Open();
// Command line option descriptions:
const struct poptOption userOptionsTable [] =
{
#if !defined(NTV2_DEPRECATE_16_0) // --board option is deprecated!
{"board", 'b', POPT_ARG_STRING, &pDeviceSpec, 0, "which device to use", "(deprecated)" },
#endif
{"device", 'd', POPT_ARG_STRING, &pDeviceSpec, 0, "which device to use", "index#, serial#, or model"},
{"input", 'i', POPT_ARG_INT, &inputNumber, 0, "which SDI input to use", "1-8"},
{"noaudio", 0, POPT_ARG_NONE, &noAudio, 0, "disables audio", AJA_NULL},
{"nofield", 0, POPT_ARG_NONE, &noFieldMode, 0, "disables field mode", AJA_NULL},
{"pixelFormat", 'p', POPT_ARG_STRING, &pPixelFormat, 0, "pixel format", "'?' or 'list' to list"},
{"multiChannel",'m', POPT_ARG_NONE, &doMultiChannel,0, "multiformat mode?", AJA_NULL},
POPT_AUTOHELP
POPT_TABLEEND
};
// Read command line arguments...
optionsContext = ::poptGetContext (AJA_NULL, argc, argv, userOptionsTable, 0);
::poptGetNextOpt (optionsContext);
optionsContext = ::poptFreeContext (optionsContext);
if (inputNumber > 8 || inputNumber < 1)
{cerr << "## ERROR: Input '" << inputNumber << "' not 1 thru 8" << endl; return 1;}
// Devices
const string legalDevices (CNTV2DemoCommon::GetDeviceStrings());
const string deviceSpec (pDeviceSpec ? pDeviceSpec : "0");
if (deviceSpec == "?" || deviceSpec == "list")
{cout << legalDevices << endl; return 0;}
if (!CNTV2DemoCommon::IsValidDevice(deviceSpec))
{cout << "## ERROR: No such device '" << deviceSpec << "'" << endl << legalDevices; return 1;}
// Pixel format
NTV2PixelFormat pixelFormat (NTV2_FBF_8BIT_YCBCR);
const string pixelFormatStr (pPixelFormat ? pPixelFormat : "1");
const string legalFBFs (CNTV2DemoCommon::GetPixelFormatStrings(PIXEL_FORMATS_ALL, deviceSpec));
if (pixelFormatStr == "?" || pixelFormatStr == "list")
{cout << CNTV2DemoCommon::GetPixelFormatStrings (PIXEL_FORMATS_ALL, deviceSpec) << endl; return 0;}
if (!pixelFormatStr.empty())
{
pixelFormat = CNTV2DemoCommon::GetPixelFormatFromString(pixelFormatStr);
if (!NTV2_IS_VALID_FRAME_BUFFER_FORMAT(pixelFormat))
{cerr << "## ERROR: Invalid '--pixelFormat' value '" << pixelFormatStr << "' -- expected values:" << endl << legalFBFs << endl; return 2;}
}
// Instantiate our NTV2FieldBurn object...
NTV2FieldBurn burner (deviceSpec, // Which device?
(noAudio ? false : true), // Include audio?
(noFieldMode ? false : true), // Field mode?
pixelFormat, // Frame buffer format
::GetNTV2InputSourceForIndex(inputNumber - 1), // Which input source?
doMultiChannel ? true : false); // Set the device up for multi-channel/format?
::signal (SIGINT, SignalHandler);
#if defined (AJAMac)
::signal (SIGHUP, SignalHandler);
::signal (SIGQUIT, SignalHandler);
#endif
const string hdg1 (" Capture Playout Capture Playout");
const string hdg2a(" Fields Fields Fields Buffer Buffer");
const string hdg2b(" Frames Frames Frames Buffer Buffer");
const string hdg3 ("Processed Dropped Dropped Level Level");
const string hdg2 (noFieldMode ? hdg2b : hdg2a);
// Initialize the NTV2FieldBurn instance...
if (AJA_FAILURE(burner.Init()))
{cerr << "## ERROR: Initialization failed" << endl; return 2;}
// Start the burner's capture and playout threads...
burner.Run ();
// Loop until someone tells us to stop...
cout << hdg1 << endl << hdg2 << endl << hdg3 << endl;
do
{
ULWord totalFrames(0), inputDrops(0), outputDrops(0), inputBufferLevel(0), outputBufferLevel(0);
burner.GetStatus (totalFrames, inputDrops, outputDrops, inputBufferLevel, outputBufferLevel);
cout << setw(9) << totalFrames << setw(9) << inputDrops << setw(9) << outputDrops << setw(9) << inputBufferLevel
<< setw(9) << outputBufferLevel << "\r" << flush;
AJATime::Sleep(500);
} while (!gGlobalQuit); // loop until signaled
cout << endl;
return 0;
} // main
| 41.236641 | 144 | 0.666235 | ibstewart |
6259cba42f6fc4ed7d503b6174f2f50ca56e30f2 | 5,700 | cpp | C++ | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/lush-pop | cdfe9d7b6a7ebb89ba036ab9a4f07d8db6817355 | [
"MIT"
] | 64 | 2020-07-08T18:49:29.000Z | 2022-03-23T22:58:49.000Z | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 1 | 2021-04-02T04:39:45.000Z | 2021-09-25T11:53:18.000Z | latte-dock/app/view/helpers/screenedgeghostwindow.cpp | VaughnValle/kanji-pop | 0153059f0c62a8aeb809545c040225da5d249bb8 | [
"MIT"
] | 11 | 2020-12-04T18:19:11.000Z | 2022-01-10T08:50:08.000Z | /*
* Copyright 2018 Michail Vourlakos <mvourlakos@gmail.com>
*
* This file is part of Latte-Dock
*
* Latte-Dock 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.
*
* Latte-Dock 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 "screenedgeghostwindow.h"
// local
#include "../view.h"
// Qt
#include <QDebug>
#include <QSurfaceFormat>
#include <QQuickView>
#include <QTimer>
// KDE
#include <KWayland/Client/plasmashell.h>
#include <KWayland/Client/surface.h>
#include <KWindowSystem>
// X11
#include <NETWM>
namespace Latte {
namespace ViewPart {
ScreenEdgeGhostWindow::ScreenEdgeGhostWindow(Latte::View *view) :
SubWindow(view, QString("Screen Ghost Window"))
{
if (m_debugMode) {
m_showColor = QColor("purple");
m_hideColor = QColor("blue");
} else {
m_showColor = QColor(Qt::transparent);
m_hideColor = QColor(Qt::transparent);
m_showColor.setAlpha(0);
m_hideColor.setAlpha(1);
}
setColor(m_showColor);
//! this timer is used in order to avoid fast enter/exit signals during first
//! appearing after edge activation
m_delayedMouseTimer.setSingleShot(true);
m_delayedMouseTimer.setInterval(50);
connect(&m_delayedMouseTimer, &QTimer::timeout, this, [this]() {
if (m_delayedContainsMouse) {
setContainsMouse(true);
} else {
setContainsMouse(false);
}
});
updateGeometry();
hideWithMask();
}
ScreenEdgeGhostWindow::~ScreenEdgeGhostWindow()
{
}
QString ScreenEdgeGhostWindow::validTitlePrefix() const
{
return QString("#subghostedge#");
}
void ScreenEdgeGhostWindow::updateGeometry()
{
if (m_latteView->positioner()->slideOffset() != 0) {
return;
}
QRect newGeometry;
if (KWindowSystem::compositingActive()) {
m_thickness = 6;
} else {
m_thickness = 2;
}
int length{30};
int lengthDifference{0};
if (m_latteView->formFactor() == Plasma::Types::Horizontal) {
//! set minimum length to be 25% of screen width
length = qMax(m_latteView->screenGeometry().width()/4,qMin(m_latteView->absoluteGeometry().width(), m_latteView->screenGeometry().width() - 1));
lengthDifference = qMax(0,length - m_latteView->absoluteGeometry().width());
} else {
//! set minimum length to be 25% of screen height
length = qMax(m_latteView->screenGeometry().height()/4,qMin(m_latteView->absoluteGeometry().height(), m_latteView->screenGeometry().height() - 1));
lengthDifference = qMax(0,length - m_latteView->absoluteGeometry().height());
}
if (m_latteView->location() == Plasma::Types::BottomEdge) {
int xF = qMax(m_latteView->screenGeometry().left(), m_latteView->absoluteGeometry().left() - lengthDifference);
newGeometry.moveLeft(xF);
newGeometry.moveTop(m_latteView->screenGeometry().bottom() - m_thickness);
} else if (m_latteView->location() == Plasma::Types::TopEdge) {
int xF = qMax(m_latteView->screenGeometry().left(), m_latteView->absoluteGeometry().left() - lengthDifference);
newGeometry.moveLeft(xF);
newGeometry.moveTop(m_latteView->screenGeometry().top());
} else if (m_latteView->location() == Plasma::Types::LeftEdge) {
int yF = qMax(m_latteView->screenGeometry().top(), m_latteView->absoluteGeometry().top() - lengthDifference);
newGeometry.moveLeft(m_latteView->screenGeometry().left());
newGeometry.moveTop(yF);
} else if (m_latteView->location() == Plasma::Types::RightEdge) {
int yF = qMax(m_latteView->screenGeometry().top(), m_latteView->absoluteGeometry().top() - lengthDifference);
newGeometry.moveLeft(m_latteView->screenGeometry().right() - m_thickness);
newGeometry.moveTop(yF);
}
if (m_latteView->formFactor() == Plasma::Types::Horizontal) {
newGeometry.setWidth(length);
newGeometry.setHeight(m_thickness + 1);
} else {
newGeometry.setWidth(m_thickness + 1);
newGeometry.setHeight(length);
}
m_calculatedGeometry = newGeometry;
emit calculatedGeometryChanged();
}
bool ScreenEdgeGhostWindow::containsMouse() const
{
return m_containsMouse;
}
void ScreenEdgeGhostWindow::setContainsMouse(bool contains)
{
if (m_containsMouse == contains) {
return;
}
m_containsMouse = contains;
emit containsMouseChanged(contains);
}
bool ScreenEdgeGhostWindow::event(QEvent *e)
{
if (e->type() == QEvent::DragEnter || e->type() == QEvent::DragMove) {
if (!m_containsMouse) {
m_delayedContainsMouse = false;
m_delayedMouseTimer.stop();
setContainsMouse(true);
emit dragEntered();
}
} else if (e->type() == QEvent::Enter) {
m_delayedContainsMouse = true;
if (!m_delayedMouseTimer.isActive()) {
m_delayedMouseTimer.start();
}
} else if (e->type() == QEvent::Leave || e->type() == QEvent::DragLeave) {
m_delayedContainsMouse = false;
if (!m_delayedMouseTimer.isActive()) {
m_delayedMouseTimer.start();
}
}
return SubWindow::event(e);
}
}
}
| 31.318681 | 155 | 0.663509 | VaughnValle |
6259f0bb6732e7ef6f0a7a5425ee9c9d74a6ef8c | 12,123 | cc | C++ | native_client_sdk/src/examples/demo/pi_generator/pi_generator.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2020-05-03T06:33:56.000Z | 2021-11-14T18:39:42.000Z | native_client_sdk/src/examples/demo/pi_generator/pi_generator.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | native_client_sdk/src/examples/demo/pi_generator/pi_generator.cc | pozdnyakov/chromium-crosswalk | 0fb25c7278bf1d93e53a3b0bcb75aa8b99d4b26e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <math.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include "ppapi/cpp/graphics_2d.h"
#include "ppapi/cpp/image_data.h"
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/rect.h"
#include "ppapi/cpp/size.h"
#include "ppapi/cpp/var.h"
#include "ppapi/utility/completion_callback_factory.h"
#ifdef WIN32
#undef PostMessage
// Allow 'this' in initializer list
#pragma warning(disable : 4355)
#endif
namespace {
const int kPthreadMutexSuccess = 0;
const char* const kPaintMethodId = "paint";
const double kInvalidPiValue = -1.0;
const int kMaxPointCount = 1000000000; // The total number of points to draw.
const uint32_t kOpaqueColorMask = 0xff000000; // Opaque pixels.
const uint32_t kRedMask = 0xff0000;
const uint32_t kBlueMask = 0xff;
const uint32_t kRedShift = 16;
const uint32_t kBlueShift = 0;
} // namespace
class PiGeneratorInstance : public pp::Instance {
public:
explicit PiGeneratorInstance(PP_Instance instance);
virtual ~PiGeneratorInstance();
// Start up the ComputePi() thread.
virtual bool Init(uint32_t argc, const char* argn[], const char* argv[]);
// Update the graphics context to the new size, and regenerate |pixel_buffer_|
// to fit the new size as well.
virtual void DidChangeView(const pp::View& view);
// Called by the browser to handle the postMessage() call in Javascript.
// The message in this case is expected to contain the string 'paint', and
// if so this invokes the Paint() function. If |var_message| is not a string
// type, or contains something other than 'paint', this method posts an
// invalid value for Pi (-1.0) back to the browser.
virtual void HandleMessage(const pp::Var& var_message);
// Return a pointer to the pixels represented by |pixel_buffer_|. When this
// method returns, the underlying |pixel_buffer_| object is locked. This
// call must have a matching UnlockPixels() or various threading errors
// (e.g. deadlock) will occur.
uint32_t* LockPixels();
// Release the image lock acquired by LockPixels().
void UnlockPixels() const;
// Flushes its contents of |pixel_buffer_| to the 2D graphics context. The
// ComputePi() thread fills in |pixel_buffer_| pixels as it computes Pi.
// This method is called by HandleMessage when a message containing 'paint'
// is received. Echos the current value of pi as computed by the Monte Carlo
// method by posting the value back to the browser.
void Paint();
bool quit() const { return quit_; }
// |pi_| is computed in the ComputePi() thread.
double pi() const { return pi_; }
int width() const {
return pixel_buffer_ ? pixel_buffer_->size().width() : 0;
}
int height() const {
return pixel_buffer_ ? pixel_buffer_->size().height() : 0;
}
// Indicate whether a flush is pending. This can only be called from the
// main thread; it is not thread safe.
bool flush_pending() const { return flush_pending_; }
void set_flush_pending(bool flag) { flush_pending_ = flag; }
private:
// Create and initialize the 2D context used for drawing.
void CreateContext(const pp::Size& size, float device_scale);
// Destroy the 2D drawing context.
void DestroyContext();
// Push the pixels to the browser, then attempt to flush the 2D context. If
// there is a pending flush on the 2D context, then update the pixels only
// and do not flush.
void FlushPixelBuffer();
void FlushCallback(int32_t result);
bool IsContextValid() const { return graphics_2d_context_ != NULL; }
pp::CompletionCallbackFactory<PiGeneratorInstance> callback_factory_;
mutable pthread_mutex_t pixel_buffer_mutex_;
pp::Graphics2D* graphics_2d_context_;
pp::ImageData* pixel_buffer_;
bool flush_pending_;
bool quit_;
pthread_t compute_pi_thread_;
int thread_create_result_;
double pi_;
float device_scale_;
// ComputePi() estimates Pi using Monte Carlo method and it is executed by a
// separate thread created in SetWindow(). ComputePi() puts kMaxPointCount
// points inside the square whose length of each side is 1.0, and calculates
// the ratio of the number of points put inside the inscribed quadrant divided
// by the total number of random points to get Pi/4.
static void* ComputePi(void* param);
};
// A small helper RAII class that implements a scoped pthread_mutex lock.
class ScopedMutexLock {
public:
explicit ScopedMutexLock(pthread_mutex_t* mutex) : mutex_(mutex) {
if (pthread_mutex_lock(mutex_) != kPthreadMutexSuccess) {
mutex_ = NULL;
}
}
~ScopedMutexLock() {
if (mutex_)
pthread_mutex_unlock(mutex_);
}
bool is_valid() const { return mutex_ != NULL; }
private:
pthread_mutex_t* mutex_; // Weak reference.
};
// A small helper RAII class used to acquire and release the pixel lock.
class ScopedPixelLock {
public:
explicit ScopedPixelLock(PiGeneratorInstance* image_owner)
: image_owner_(image_owner), pixels_(image_owner->LockPixels()) {}
~ScopedPixelLock() {
pixels_ = NULL;
image_owner_->UnlockPixels();
}
uint32_t* pixels() const { return pixels_; }
private:
PiGeneratorInstance* image_owner_; // Weak reference.
uint32_t* pixels_; // Weak reference.
};
PiGeneratorInstance::PiGeneratorInstance(PP_Instance instance)
: pp::Instance(instance),
callback_factory_(this),
graphics_2d_context_(NULL),
pixel_buffer_(NULL),
flush_pending_(false),
quit_(false),
thread_create_result_(0),
pi_(0.0),
device_scale_(1.0) {
pthread_mutex_init(&pixel_buffer_mutex_, NULL);
}
PiGeneratorInstance::~PiGeneratorInstance() {
quit_ = true;
if (thread_create_result_ == 0) {
pthread_join(compute_pi_thread_, NULL);
}
DestroyContext();
// The ComputePi() thread should be gone by now, so there is no need to
// acquire the mutex for |pixel_buffer_|.
delete pixel_buffer_;
pthread_mutex_destroy(&pixel_buffer_mutex_);
}
void PiGeneratorInstance::DidChangeView(const pp::View& view) {
pp::Size size = view.GetRect().size();
float device_scale = view.GetDeviceScale();
size.set_width(static_cast<int>(size.width() * device_scale));
size.set_height(static_cast<int>(size.height() * device_scale));
if (pixel_buffer_ && size == pixel_buffer_->size() &&
device_scale == device_scale_)
return; // Size and scale didn't change, no need to update anything.
// Create a new device context with the new size and scale.
DestroyContext();
device_scale_ = device_scale;
CreateContext(size, device_scale_);
// Delete the old pixel buffer and create a new one.
ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_);
delete pixel_buffer_;
pixel_buffer_ = NULL;
if (graphics_2d_context_ != NULL) {
pixel_buffer_ = new pp::ImageData(this,
PP_IMAGEDATAFORMAT_BGRA_PREMUL,
graphics_2d_context_->size(),
false);
}
}
bool PiGeneratorInstance::Init(uint32_t argc,
const char* argn[],
const char* argv[]) {
thread_create_result_ =
pthread_create(&compute_pi_thread_, NULL, ComputePi, this);
return thread_create_result_ == 0;
}
uint32_t* PiGeneratorInstance::LockPixels() {
void* pixels = NULL;
// Do not use a ScopedMutexLock here, since the lock needs to be held until
// the matching UnlockPixels() call.
if (pthread_mutex_lock(&pixel_buffer_mutex_) == kPthreadMutexSuccess) {
if (pixel_buffer_ != NULL && !pixel_buffer_->is_null()) {
pixels = pixel_buffer_->data();
}
}
return reinterpret_cast<uint32_t*>(pixels);
}
void PiGeneratorInstance::HandleMessage(const pp::Var& var_message) {
if (!var_message.is_string()) {
PostMessage(pp::Var(kInvalidPiValue));
}
std::string message = var_message.AsString();
if (message == kPaintMethodId) {
Paint();
} else {
PostMessage(pp::Var(kInvalidPiValue));
}
}
void PiGeneratorInstance::UnlockPixels() const {
pthread_mutex_unlock(&pixel_buffer_mutex_);
}
void PiGeneratorInstance::Paint() {
ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_);
if (!scoped_mutex.is_valid()) {
return;
}
FlushPixelBuffer();
// Post the current estimate of Pi back to the browser.
pp::Var pi_estimate(pi());
// Paint() is called on the main thread, so no need for CallOnMainThread()
// here. It's OK to just post the message.
PostMessage(pi_estimate);
}
void PiGeneratorInstance::CreateContext(const pp::Size& size,
float device_scale) {
ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_);
if (!scoped_mutex.is_valid()) {
return;
}
if (IsContextValid())
return;
graphics_2d_context_ = new pp::Graphics2D(this, size, false);
// Scale the contents of the graphics context down by the inverse of the
// device scale. This makes each pixel in the context represent a single
// physical pixel on the device when running on high-DPI displays.
// See pp::Graphics2D::SetScale for more details.
graphics_2d_context_->SetScale(1.0 / device_scale);
if (!BindGraphics(*graphics_2d_context_)) {
printf("Couldn't bind the device context\n");
}
}
void PiGeneratorInstance::DestroyContext() {
ScopedMutexLock scoped_mutex(&pixel_buffer_mutex_);
if (!scoped_mutex.is_valid()) {
return;
}
if (!IsContextValid())
return;
delete graphics_2d_context_;
graphics_2d_context_ = NULL;
}
void PiGeneratorInstance::FlushPixelBuffer() {
if (!IsContextValid())
return;
// Note that the pixel lock is held while the buffer is copied into the
// device context and then flushed.
graphics_2d_context_->PaintImageData(*pixel_buffer_, pp::Point());
if (flush_pending())
return;
set_flush_pending(true);
graphics_2d_context_->Flush(
callback_factory_.NewCallback(&PiGeneratorInstance::FlushCallback));
}
// This is called by the browser when the 2D context has been flushed to the
// browser window.
void PiGeneratorInstance::FlushCallback(int32_t result) {
set_flush_pending(false);
}
void* PiGeneratorInstance::ComputePi(void* param) {
int count = 0; // The number of points put inside the inscribed quadrant.
unsigned int seed = 1;
srand(seed);
PiGeneratorInstance* pi_generator = static_cast<PiGeneratorInstance*>(param);
for (int i = 1; i <= kMaxPointCount && !pi_generator->quit(); ++i) {
ScopedPixelLock scoped_pixel_lock(pi_generator);
uint32_t* pixel_bits = scoped_pixel_lock.pixels();
if (pixel_bits == NULL) {
// Note that if the pixel buffer never gets initialized, this won't ever
// paint anything. Which is probably the right thing to do. Also, this
// clause means that the image will not get the very first few Pi dots,
// since it's possible that this thread starts before the pixel buffer is
// initialized.
continue;
}
double x = static_cast<double>(rand()) / RAND_MAX;
double y = static_cast<double>(rand()) / RAND_MAX;
double distance = sqrt(x * x + y * y);
int px = x * pi_generator->width();
int py = (1.0 - y) * pi_generator->height();
uint32_t color = pixel_bits[pi_generator->width() * py + px];
if (distance < 1.0) {
// Set color to blue.
++count;
pi_generator->pi_ = 4.0 * count / i;
color += 4 << kBlueShift;
color &= kBlueMask;
} else {
// Set color to red.
color += 4 << kRedShift;
color &= kRedMask;
}
pixel_bits[pi_generator->width() * py + px] = color | kOpaqueColorMask;
}
return 0;
}
class PiGeneratorModule : public pp::Module {
public:
PiGeneratorModule() : pp::Module() {}
virtual ~PiGeneratorModule() {}
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new PiGeneratorInstance(instance);
}
};
namespace pp {
Module* CreateModule() { return new PiGeneratorModule(); }
} // namespace pp
| 33.863128 | 80 | 0.700569 | pozdnyakov |
625beffe0f541f450e071f72a9482b6f8578d8e6 | 2,844 | hpp | C++ | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | include/elemental/blas-like/level1/Transpose.hpp | ahmadia/Elemental-1 | f9a82c76a06728e9e04a4316e41803efbadb5a19 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2009-2013, Jack Poulson
All rights reserved.
This file is part of Elemental and is under the BSD 2-Clause License,
which can be found in the LICENSE file in the root directory, or at
http://opensource.org/licenses/BSD-2-Clause
*/
#pragma once
#ifndef BLAS_TRAPEZOID_HPP
#define BLAS_TRAPEZOID_HPP
namespace elem {
template<typename T>
inline void
Transpose( const Matrix<T>& A, Matrix<T>& B, bool conjugate=false )
{
#ifndef RELEASE
CallStackEntry entry("Transpose");
#endif
const int m = A.Height();
const int n = A.Width();
if( B.Viewing() )
{
if( B.Height() != n || B.Width() != m )
{
std::ostringstream msg;
msg << "If Transpose'ing into a view, it must be the right size:\n"
<< " A ~ " << A.Height() << " x " << A.Width() << "\n"
<< " B ~ " << B.Height() << " x " << B.Width();
throw std::logic_error( msg.str().c_str() );
}
}
else
B.ResizeTo( n, m );
if( conjugate )
{
for( int j=0; j<n; ++j )
for( int i=0; i<m; ++i )
B.Set(j,i,Conj(A.Get(i,j)));
}
else
{
for( int j=0; j<n; ++j )
for( int i=0; i<m; ++i )
B.Set(j,i,A.Get(i,j));
}
}
template<typename T,Distribution U,Distribution V,
Distribution W,Distribution Z>
inline void
Transpose
( const DistMatrix<T,U,V>& A, DistMatrix<T,W,Z>& B, bool conjugate=false )
{
#ifndef RELEASE
CallStackEntry entry("Transpose");
#endif
if( B.Viewing() )
{
if( A.Height() != B.Width() || A.Width() != B.Height() )
{
std::ostringstream msg;
msg << "If Transpose'ing into a view, it must be the right size:\n"
<< " A ~ " << A.Height() << " x " << A.Width() << "\n"
<< " B ~ " << B.Height() << " x " << B.Width();
throw std::logic_error( msg.str().c_str() );
}
}
if( U == Z && V == W &&
A.ColAlignment() == B.RowAlignment() &&
A.RowAlignment() == B.ColAlignment() )
{
Transpose( A.LockedMatrix(), B.Matrix(), conjugate );
}
else
{
DistMatrix<T,Z,W> C( B.Grid() );
if( B.Viewing() || B.ConstrainedColAlignment() )
C.AlignRowsWith( B );
if( B.Viewing() || B.ConstrainedRowAlignment() )
C.AlignColsWith( B );
C = A;
if( !B.Viewing() )
{
if( !B.ConstrainedColAlignment() )
B.AlignColsWith( C );
if( !B.ConstrainedRowAlignment() )
B.AlignRowsWith( C );
B.ResizeTo( A.Width(), A.Height() );
}
Transpose( C.LockedMatrix(), B.Matrix(), conjugate );
}
}
} // namespace elem
#endif // ifndef BLAS_TRAPEZOID_HPP
| 27.61165 | 79 | 0.503165 | ahmadia |
625d63222246bb80853d5f45b5dfeab90bafd6ad | 28,213 | cpp | C++ | src/CSSParser/CSSLex.cpp | luojilab/CSSParser | 1c507c98a0cdd37227f3b3c71f84a2165445a795 | [
"MIT"
] | 15 | 2018-08-31T06:54:27.000Z | 2022-01-06T07:01:29.000Z | src/CSSParser/CSSLex.cpp | getsync/CSSParser | 1c507c98a0cdd37227f3b3c71f84a2165445a795 | [
"MIT"
] | null | null | null | src/CSSParser/CSSLex.cpp | getsync/CSSParser | 1c507c98a0cdd37227f3b3c71f84a2165445a795 | [
"MIT"
] | 6 | 2018-08-31T06:54:36.000Z | 2021-10-09T07:10:36.000Z | //
// CSSLex.cpp
// DDCSSParser
//
// Created by 1m0nster on 2018/8/7.
// Copyright © 2018 1m0nster. All rights reserved.
//
#include "CSSLex.hpp"
#include <string.h>
#include "ContainerUtil.hpp"
#define NextChar(buffer) m_forwardPos >= m_bufferSize ? 0 : *(buffer + m_forwardPos++)
#define ErrorInLoop STATUS = LexError;stopLoop = true;
#define WS_CASE ' ': case '\r': case '\n': case '\t': case '\f'
#define NUMBER_CASE '0': case '1': case '2': case '3': case '4':\
case '5': case '6': case '7': case '8': case '9'
namespace future {
Lex::Lex()
{
m_buffer = 0;
m_firstPos = 0;
m_forwardPos = 0;
}
Lex::~Lex()
{
CleanResource();
}
void Lex::SetBufferSource(const std::string& fileName)
{
if (fileName.empty()) {
return;
}
FILE* fileHandler = fopen(fileName.c_str(), "r");
if ( !fileHandler ) {
return;
}
size_t bufferSize = 0;
fseek(fileHandler, 0, SEEK_END);
bufferSize = ftell(fileHandler);
if ( !bufferSize ) {
return;
}
fseek(fileHandler, 0, SEEK_SET);
if (m_buffer) {
delete [] m_buffer;
m_buffer = 0;
}
m_buffer = new char[bufferSize];
memset((void *)m_buffer, 0, bufferSize);
m_bufferSize = fread((void *)m_buffer, 1, bufferSize, fileHandler);
fclose(fileHandler);
m_firstPos = 0;
m_forwardPos = 0;
}
void Lex::SetBufferString(const std::string &bufferString)
{
if (bufferString.empty()) {
return;
}
if (m_buffer) {
delete [] m_buffer;
m_buffer = 0;
}
m_bufferSize = bufferString.size();
m_buffer = new char[m_bufferSize];
memcpy((void *)m_buffer, bufferString.data(), m_bufferSize);
m_firstPos = 0;
m_forwardPos = 0;
}
Lex::CSSToken* Lex::GetTextToken(char stringType)
{
enum {
_START = 0,
_ESCAPESTART,
_STRING
};
char status = _START;
CSSToken* token = new CSSToken;
m_tokenCache.insert(token);
m_forwardPos = m_firstPos;
if (m_forwardPos >= m_bufferSize) {
token->type = END;
return token;
}
char stringBoundary = stringType == 1 ? '"' : '\'';
while (1) {
char c = NextChar(m_buffer);
switch (status) {
case _START: {
if ((c != '\r' && c != '\n' && c != '\f' && c != stringBoundary) || (c & 0x80)) {
status = _STRING;
break;
} else if (c == '\\') {
status = _ESCAPESTART;
break;
}
break;
}
case _ESCAPESTART: {
if (isDigitalCharacter(c) || isLetter(c)) {
// [0-9a-z]{1,6}
for(int i = 0; i < 5; i ++) {
c = NextChar(m_buffer);
if (isDigitalCharacter(c) || isLetter(c)) {
continue;
} else {
break;
}
}
} else if (c == '\r' || c == '\n' || c == '\f') {
// \\{nl}
// nl \n|\r\n|\r|\f
} else {
// escape's \\[^\n\r\f0-9a-f]
}
status = _STRING;
break;
}
case _STRING: {
if ((c != '\r' && c != '\n' && c != '\f' && c != stringBoundary) || (c & 0x80) || c == '\\') {
--m_forwardPos;
status = _START;
} else {
token->type = STRING;
token->data = createData(m_firstPos, m_forwardPos);
return token;
}
break;
}
default:
break;
}
}
return token;
}
Lex::CSSToken* Lex::GetIdentToken()
{
CSSToken* token = new CSSToken;
m_tokenCache.insert(token);
token->type = IDENT;
CSSDFAStatus STATUS = Start;
bool stopLoop = false;
while(1) {
if (m_forwardPos >= m_bufferSize) {
STATUS = end;
break;
}
unsigned char c = NextChar(m_buffer);
switch (STATUS) {
case Start: {
if (c == IDENT_START_SIGN) {
STATUS = iDentStart;
} else if (isLetter(c) || c == UNDER_LINE_SIGN || (c & 0x80)) {
STATUS = NMStart;
} else if (c == BACK_SPLASH) {
STATUS = EscapeStartInNMStart;
} else if (isWs(c)) {
STATUS = Ws;
} else if (c == HASH_SIGN) {
STATUS = HashStart;
} else if (c == KEYWORD_SIGN) {
STATUS = AtKeyWordStart;
} else {
STATUS = LexError;
stopLoop = true;
}
break;
}
case iDentStart: {
if (isLetter(c) || c == UNDER_LINE_SIGN || (c & 0x80)) {
STATUS = NMStart;
} else if (c == BACK_SPLASH) {
STATUS = EscapeStartInNMStart;
} else {
STATUS = LexError;
stopLoop = true;
}
break;
}
case NMStart: {
if (isLetter(c) || isDigitalCharacter(c) || c == UNDER_LINE_SIGN || c == IDENT_START_SIGN || (c &0x80)) {
STATUS = NMChar;
} else if (c == BACK_SPLASH) {
STATUS = EscapeStartInNMChar;
} else {
STATUS = iDent;
stopLoop = true;
}
break;
}
case NMChar: {
if (isLetter(c) || isDigitalCharacter(c) || c == UNDER_LINE_SIGN || c == IDENT_START_SIGN || (c &0x80)) {
STATUS = NMChar;
} else if (c == BACK_SPLASH) {
STATUS = EscapeStartInNMChar;
} else {
STATUS = iDent;
stopLoop = true;
}
break;
}
case EscapeStartInNMStart: {
if (isHexCharacter(c)) {
for (int i = 0; i < 5; i++) {
c = NextChar(m_buffer);
if (c == 0) {break;}
if (isHexCharacter(c)) {
continue;
} else {
--m_forwardPos;
break;
}
}
STATUS = NMStart;
}
break;
}
case EscapeStartInNMChar: {
if (isHexCharacter(c)) {
for (int i = 0; i < 5; i++) {
c = NextChar(m_buffer);
if (c == 0) {break;}
if (isHexCharacter(c)) {
continue;
} else {
--m_forwardPos;
break;
}
}
STATUS = NMChar;
}
break;
}
default: {
STATUS = LexError;
break;
}
}
if (stopLoop) {
--m_forwardPos;
break;
}
}
token->data = createData(m_firstPos, m_forwardPos);
if (STATUS == iDent) {
token->type = IDENT;
} else if (STATUS == end) {
token->type = END;
} else {
token->type = ERROR;
}
m_firstPos = m_forwardPos;
return token;
}
Lex::CSSToken* Lex::GetNumberToken()
{
enum {_start, _numberStart, _numberFinish, _numberInDecimal, _error};
std::string s;
char status = _start;
char c = NextChar(m_buffer);
if (c == 0) {return NULL;}
std::string data;
while (1) {
switch (status) {
case _start: {
if (!isDigitalCharacter(c)) {
status = _error;
break;
} else {
status = _numberStart;
data.append(std::string(1, c));
}
break;
}
case _numberStart: {
if (!isDigitalCharacter(c)) {
if (c == '.') {
status = _numberInDecimal;
} else {
status = _numberFinish;
break;
}
}
data.append(std::string(1, c));
break;
}
case _numberInDecimal:{
if (!isDigitalCharacter(c)) {
status = _numberFinish;
}
data.append(std::string(1, c));
break;
}
default: {
status = _error;
break;
}
}
if (status == _numberFinish ||
status == _error) {
--m_forwardPos;
break;
}
if (m_bufferSize <= m_forwardPos + 1) {
status = _numberFinish;
break;
}
c = NextChar(m_buffer);
}
if (data.size() == 0) {
return NULL;
} else {
CSSToken* token = new CSSToken;
m_tokenCache.insert(token);
token->type = NUMBER;
token->data = data;
return token;
}
}
Lex::CSSToken* Lex::GetToken()
{
CSSToken* token = new CSSToken;
m_tokenCache.insert(token);
token->type = IDENT;
m_firstPos = m_forwardPos;
bool stopLoop = false;
std::string data;
static CSSDFAStatus STATUS;
if (m_firstPos >= m_bufferSize || !m_buffer) {
token->type = END;
return token;
}
while(1) {
char c = NextChar(m_buffer);
switch (STATUS) {
case Start: {
switch (c) {
case '@': {
CSSToken* identToken = GetIdentToken();
stopLoop = true;
if (identToken->type == IDENT) {
STATUS = AtKeyWord;
data = identToken->data;
} else {
STATUS = LexError;
}
break;
}
case '#': {
CSSToken* identToken = GetIdentToken();
stopLoop = true;
if (identToken->type == IDENT) {
STATUS = Hash;
data = identToken->data;
} else {
STATUS = LexError;
}
break;
}
case '~': {
if (NextChar(m_buffer) == EQUAL_SIGN) {
STATUS = include;
} else {
STATUS = tidle;
--m_forwardPos;
}
break;
}
case '|': {
if (NextChar(m_buffer) == EQUAL_SIGN) {
STATUS = dashMatch;
} else {
STATUS = LexError;
}
break;
}
case '^': {
if (NextChar(m_buffer) == EQUAL_SIGN) {
STATUS = prefixMatch;
} else {
STATUS = LexError;
}
break;
}
case '$': {
if (NextChar(m_buffer) == EQUAL_SIGN) {
STATUS = suffixMatch;
} else {
STATUS = LexError;
}
break;
}
case '*': {
if (NextChar(m_buffer) == EQUAL_SIGN) {
STATUS = subStringMatch;
} else {
--m_forwardPos;
STATUS = star;
}
break;
}
case '"': {
STATUS = string1Start;
break;
}
case '\'': {
STATUS = string2Start;
break;
}
case WS_CASE: {
STATUS = Ws;
break;
}
case '.': {
STATUS = dot;
stopLoop = true;
break;
}
case '{': {
STATUS = blockStart;
stopLoop = true;
break;
}
case '}': {
STATUS = blockEnd;
stopLoop = true;
break;
}
case ',': {
STATUS = comma;
stopLoop = true;
break;
}
case '>': {
STATUS = greater;
stopLoop = true;
break;
}
case '+': {
STATUS = plus;
stopLoop = true;
break;
}
case '[': {
STATUS = leftSqureBracket;
break;
}
case ']': {
STATUS = rightSqureBracket;
break;
}
case ':': {
STATUS = colon;
break;
}
case '=': {
STATUS = equal;
break;
}
case '/': {
char cn = NextChar(m_buffer);
if (cn == '*') {
STATUS = annotationStart;
} else {
--m_forwardPos;
goto identLabel;
}
break;
}
case ';' : {
STATUS = semicolon;
break;
}
case NUMBER_CASE: {
--m_forwardPos;
STATUS = numberStart;
break;
}
case ')': {
STATUS = rightBracket;
break;
}
case '-': {
STATUS = minus;
break;
}
default: {
identLabel:
m_forwardPos = m_firstPos;
CSSToken* idToken = GetIdentToken();
char next = NextChar(m_buffer);
if (next == '(') {
STATUS = function;
data = idToken->data;
} else {
--m_forwardPos;
if (idToken->type == IDENT) {
STATUS = iDent;
data = idToken->data;
} else if (idToken->type == END) {
STATUS = end;
} else {
STATUS = LexError;
}
}
stopLoop = true;
break;
}
}
break;
}
case Ws: {
stopLoop = true;
if (isWs(c)) {
STATUS = Ws;
stopLoop = false;
} else if (c == PLUS_SIGN) {
STATUS = plus;
} else if (c == COMMA_SIGN) {
STATUS = comma;
} else if (c == GREATER_SIGN) {
STATUS = greater;
} else if (c == TIDLE_SIGN) {
STATUS = tidle;
} else if ( c == '\0') {
STATUS = end;
} else {
--m_forwardPos;
STATUS = Ws;
}
break;
}
case include: {
stopLoop = true;
}
case blockStart: {
if (c == BLOCK_END_SIGN) {
STATUS = blockEnd;
}
while (c != BLOCK_END_SIGN) {
if (m_forwardPos >= m_bufferSize) {
STATUS = LexError;
break;
} else {
c = NextChar(m_buffer);
STATUS = blockEnd;
}
}
data = createData(m_firstPos, m_forwardPos);
stopLoop = true;
break;
}
case string1Start: {
CSSToken* stringToken = GetTextToken(1);
if (stringToken->type == STRING) {
STATUS = string1End;
data = stringToken->data;
} else {
STATUS = LexError;
}
break;
}
case string2Start: {
CSSToken* stringToken = GetTextToken(2);
if (stringToken->type == STRING) {
STATUS = string2End;
data = stringToken->data;
} else {
STATUS = LexError;
}
break;
}
case annotationStart: {
char cn = NextChar(m_buffer);
if (cn == 0) {break;}
if (c == '*' && cn == '/') {
STATUS = annotationEnd;
} else {
--m_forwardPos;
continue;
}
break;
}
case numberStart: {
--m_forwardPos;
CSSToken* numberToken = GetNumberToken();
if (numberToken) {
data = numberToken->data;
STATUS = num;
} else {
STATUS = LexError;
}
break;
}
default: {
stopLoop = true;
}
break;
}
bool resetStatus = true;
switch (STATUS) {
case AtKeyWord: {
token->type = ATKEYWORD;
token->data = data;
break;
}
case LexError: {
token->type = ERROR;
stopLoop = true;
break;
}
case Hash: {
token->type = HASH;
token->data = data;
break;
}
case Ws: {
token->type = WS;
break;
}
case include: {
token->type = INCLUDES;
stopLoop = true;
break;
}
case iDent: {
token->type = IDENT;
token->data = data;
break;
}
case dot: {
token->type = DOT;
break;
}
case blockStart: {
token->type = BLOCKSTART;
resetStatus = false;
break;
}
case blockEnd:{
token->type = BLOCKEND;
token->data = data;
STATUS = Start;
break;
}
case end: {
token->type = END;
resetStatus = true;
break;
}
case comma: {
token->type = COMMA;
break;
}
case plus:{
token->type = PLUS;
break;
}
case tidle: {
token->type = TIDLE;
stopLoop = true;
break;
}
case greater: {
token->type = GREATER;
stopLoop = true;
break;
}
case star:{
token->type = STAR;
stopLoop = true;
break;
}
case dashMatch:{
token->type = DASHMATCH;
stopLoop = true;
break;
}
case prefixMatch:{
token->type = PREFIXMATCH;
stopLoop = true;
break;
}
case suffixMatch:{
token->type = SUFFIXMATCH;
stopLoop = true;
break;
}
case includes:{
token->type = INCLUDES;
stopLoop = true;
break;
}
case subStringMatch:{
token->type = SUBSTRINGMATCH;
stopLoop = true;
break;
}
case leftSqureBracket: {
token->type = LEFTSQUREBRACKET;
stopLoop = true;
break;
}
case rightSqureBracket: {
token->type = RIGHTSQUREBRACKET;
stopLoop = true;
break;
}
case colon: {
token->type = COLON;
stopLoop = true;
break;
}
case equal: {
token->type = EQUAL;
stopLoop = true;
break;
}
case semicolon: {
token->type =SYNTAXEND;
stopLoop = true;
break;
}
case string1End: case string2End: {
token->type = STRING;
token->data = data;
stopLoop = true;
break;
}
case annotationEnd: {
token->type = ANNOTATION;
stopLoop = true;
break;
}
case function: {
token->type = FUNCTION;
token->data = data;
stopLoop = true;
break;
}
case numberStart: {
stopLoop = false;
break;
}
case num: {
token->data = data;
token->type = NUMBER;
stopLoop = true;
break;
}
case rightBracket: {
token->type = RIGHTBRACKET;
stopLoop = true;
break;
}
case minus: {
token->type = MINUS;
stopLoop = true;
break;
}
default:
break;
}
if (stopLoop) {
if (resetStatus) {
STATUS = Start;
}
break;
}
}
return token;
}
std::string Lex::createData(size_t start, size_t end)
{
if (m_buffer == NULL || start > end) {
return NULL;
}
size_t size = end - start + 1;
if (m_bufferSize < end) {
return NULL;
}
char* ptr = new char[size];
ptr[size -1] = '\0';
memmove(ptr, m_buffer + start, size - 1);
std::string ret = ptr;
delete [] ptr;
return ret;
}
void Lex::CleanResource()
{
CleanContainer<CSSToken *>(m_tokenCache);
delete [] m_buffer;
m_buffer = 0;
}
inline bool Lex::isDigitalCharacter(char c) {
return (c > 0x2F && c < 0x3A);
}
inline bool Lex::isLetter(char c) {
return (c > 0x60 && c < 0x7B) || (c > 0x40 && c < 0x5B);
}
inline bool Lex::isHexCharacter(char c) {
return isDigitalCharacter(c) || (c > 0x60 && c < 0x67) || (c > 0x40 && c < 0x47);
}
inline bool Lex::isWs(char c) {
return (c == ' ' || c == '\r' || c == '\n' || c == '\f' || c == '\t');
}
}
| 34.156174 | 125 | 0.306171 | luojilab |
625ef4959e4ed675f6b571aed964e6b44d9bd680 | 3,045 | cpp | C++ | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | 1 | 2017-09-19T16:33:06.000Z | 2017-09-19T16:33:06.000Z | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | null | null | null | src/pong_game/Ball.cpp | jjerome/Niski | 58bcc1303cdb6676c051d55e9d7a248dfea65cde | [
"MIT"
] | null | null | null | #include "pong_game/Ball.h"
#include "pong_game/Paddle.h"
#include "engine/ConVar.h"
#include "renderer/VertexBuffer2D.h"
#include "math/Math.h"
#include "utils/Log.h"
using namespace Niski::Pong_Game;
Niski::Engine::ConVar addPaddleVelocity("PongGame::Ball::AddPaddleVelocity", 0, "If enabled, when the ball collides with a paddle the y velocity of the paddle is added to the ball.");
Ball::Ball(PongWorld* world, const Niski::Math::Vector2D<float>& initialPosition, float radius) : Entity(world, "PongBall"), initialPosition_(initialPosition), radius_(radius)
{
setPosition(initialPosition);
}
Ball::~Ball(void)
{}
void Ball::render(Niski::Renderer::Renderer& renderer) const
{
//
// TODO: Kinda dangerous..
Niski::Renderer::VertexBuffer2D vBuffer;
const int16_t segments = 23;
vBuffer.setColor(Niski::Utils::Color(Niski::Utils::Color::white));
for(int16_t i = 0; i <= segments; ++i)
{
double t = (2 * Niski::Math::pi / segments) * i;
vBuffer.pushVertex(getPosition().x + (radius_ * cos(t)), getPosition().y - (radius_ * sin(t)));
}
vBuffer.setPrimitiveType(Niski::Renderer::VertexBuffer2D::lineList);
vBuffer.render(renderer);
vBuffer.flushVertices();
}
void Ball::reset(void)
{
setPosition(initialPosition_);
setVelocity(Niski::Math::Vector2D<float>(0.0f, 0.0f));
}
void Ball::onTouch(Entity* ent)
{
if(ent == nullptr)
{
Niski::Utils::bitch("Ball::OnTouch was called with a null ent.");
return;
}
Niski::Math::Vector2D<float> position(getPosition());
Niski::Math::Vector2D<float> newVelocity(getVelocity());
if(ent->getName() == "Paddle")
{
Paddle* paddle = static_cast<Paddle*>(ent);
Niski::Math::Vector2D<float> paddlePosition(paddle->getPosition());
Niski::Math::Rect2D paddleBounds(paddle->getBounds());
//
// "Push" the ball out of the paddle.
PongWorld* world = static_cast<PongWorld*>(getParent());
if(position.x < (world->getBounds().right / 2.0f))
{
if(position.x < paddleBounds.left + paddleBounds.right)
{
position.x = paddleBounds.left + paddleBounds.right + radius_;
}
}
else
{
if(position.x > paddleBounds.left)
{
position.x = paddleBounds.left - radius_;
}
}
newVelocity.x = -newVelocity.x;
if(addPaddleVelocity.getIntValue())
{
Niski::Math::Vector2D<float> paddleVelocity(paddle->getVelocity());
newVelocity.y += paddleVelocity.y;
}
}
else if(ent->getName() == "gameWorld")
{
PongWorld* world = static_cast<PongWorld*>(ent);
Niski::Math::Rect2D worldBounds(world->getBounds());
{
//
// This method is only called if we have hit the top or the bottom
// since the left and right are score material and thus handled by game rules
//
// Collision detection doesn't happen until it's in another rectangle.
// so we push it out.
if(position.y <= worldBounds.top)
{
position.y = worldBounds.top + radius_;
}
else
{
position.y = worldBounds.bottom - radius_;
}
newVelocity.y = -newVelocity.y;
}
}
setPosition(position);
setVelocity(newVelocity);
} | 25.588235 | 183 | 0.685714 | jjerome |
6262dc3851bc1588e2de148a3880a10536ff37b1 | 638 | cpp | C++ | Leetcode/0808. Soup Servings/0808.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0808. Soup Servings/0808.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | Leetcode/0808. Soup Servings/0808.cpp | Next-Gen-UI/Code-Dynamics | a9b9d5e3f27e870b3e030c75a1060d88292de01c | [
"MIT"
] | null | null | null | class Solution {
public:
double soupServings(int N) {
return N >= 4800 ? 1.0 : dfs((N + 24) / 25, (N + 24) / 25);
}
private:
vector<vector<double>> memo =
vector<vector<double>>(4800 / 25, vector<double>(4800 / 25));
double dfs(int a, int b) {
if (a <= 0 && b <= 0)
return 0.5;
if (a <= 0)
return 1.0;
if (b <= 0)
return 0.0;
if (memo[a][b] > 0)
return memo[a][b];
return memo[a][b] = 0.25 * (dfs(a - 4, b) +
dfs(a - 3, b - 1) +
dfs(a - 2, b - 2) +
dfs(a - 1, b - 3));
}
};
| 24.538462 | 67 | 0.401254 | Next-Gen-UI |
626695984253639e951f90b2e70651d7ca5877a2 | 14,973 | cc | C++ | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | libs/gather/test-gather.cc | sandtreader/obtools | 2382e2d90bb62c9665433d6d01bbd31b8ad66641 | [
"MIT"
] | null | null | null | //==========================================================================
// ObTools::Gather: test-buffer.cc
//
// Test harness for gather buffer library
//
// Copyright (c) 2010 Paul Clark. All rights reserved
// This code comes with NO WARRANTY and is subject to licence agreement
//==========================================================================
#include "ot-gather.h"
#include <gtest/gtest.h>
namespace {
using namespace std;
using namespace ObTools;
TEST(GatherTest, TestSimpleAdd)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const string expected(&data[0], strlen(data));
Gather::Segment& seg = buffer.add(reinterpret_cast<unsigned char *>(&data[0]),
strlen(data));
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(data, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestInternalAdd)
{
Gather::Buffer buffer(0);
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
ASSERT_EQ(16, buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
for (unsigned int i = 0; i < seg.length; ++i)
ASSERT_EQ(i, seg.data[i]) << "Where i = " << i;
}
TEST(GatherTest, TestSimpleInsert)
{
Gather::Buffer buffer(0);
uint32_t n = 0xDEADBEEF;
const uint32_t expected = n;
Gather::Segment &seg = buffer.insert(reinterpret_cast<Gather::data_t *>(&n),
sizeof(n));
ASSERT_EQ(sizeof(expected), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(sizeof(expected), seg.length);
for (unsigned i = 0; i < sizeof(expected); ++i)
ASSERT_EQ((expected >> (i * 8)) & 0xff, seg.data[i]) << "Where i = " << i;
}
TEST(GatherTest, TestInsertBetween)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const string expected_str(&data[0], strlen(data));
uint32_t n = 0x01234567;
const uint32_t expected_num(n);
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n), 1);
const Gather::Segment *segments = buffer.get_segments();
ASSERT_EQ(expected_str.size() * 2 + sizeof(expected_num),
buffer.get_length());
ASSERT_LE(3, buffer.get_size());
ASSERT_EQ(3, buffer.get_count());
ASSERT_TRUE(segments);
const Gather::Segment &seg1 = segments[0];
ASSERT_EQ(expected_str.size(), seg1.length);
ASSERT_EQ(expected_str,
string(reinterpret_cast<char *>(seg1.data), seg1.length));
const Gather::Segment &seg2 = segments[1];
ASSERT_EQ(sizeof(expected_num), seg2.length);
for (unsigned i = 0; i < sizeof(expected_num); ++i)
ASSERT_EQ((expected_num >> (i * 8)) & 0xff, seg2.data[i])
<< "Where i = " << i;
const Gather::Segment &seg3 = segments[2];
ASSERT_EQ(expected_str.size(), seg3.length);
ASSERT_EQ(expected_str,
string(reinterpret_cast<char *>(seg3.data), seg3.length));
}
TEST(GatherTest, TestSimpleLimit)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const unsigned int chop(8);
const string expected(&data[0], strlen(data) - chop);
Gather::Segment& seg = buffer.add(
reinterpret_cast<Gather::data_t *>(&data[0]),
strlen(data));
buffer.limit(buffer.get_length() - chop);
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(expected, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestSimpleConsume)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
const unsigned int chop(7);
const string expected(&data[chop], strlen(data) - chop);
Gather::Segment& seg = buffer.add(
reinterpret_cast<Gather::data_t *>(&data[0]),
strlen(data));
buffer.consume(chop);
ASSERT_EQ(expected.size(), buffer.get_length());
ASSERT_LE(1, buffer.get_size());
ASSERT_EQ(1, buffer.get_count());
ASSERT_EQ(expected, string(reinterpret_cast<char *>(seg.data), seg.length));
}
TEST(GatherTest, TestCopy)
{
Gather::Buffer buffer(0);
char one[] = "xHell";
char two[] = "o, wo";
char three[] = "rld!x";
const string expected = string(&one[1], strlen(one) - 1)
+ string(&two[0], strlen(two))
+ string(&three[0], strlen(three) - 1);
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
string actual;
actual.resize(expected.size());
unsigned int copied = buffer.copy(
reinterpret_cast<Gather::data_t *>(const_cast<char *>(actual.c_str())),
1, expected.size());
ASSERT_EQ(expected.size(), copied);
ASSERT_EQ(expected, actual);
}
TEST(GatherTest, TestAddFromBuffer)
{
Gather::Buffer buffer1(0);
char one[] = "xHell";
const string one_str(&one[0], strlen(one));
char two[] = "o, wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!x";
const string three_str(&three[0], strlen(three));
buffer1.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer1.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer1.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::Buffer buffer2(0);
char data[] = "Hello";
const string hello(&data[0], strlen(data));
buffer2.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
buffer2.add(buffer1, 6, 8);
const Gather::Segment *segments = buffer2.get_segments();
ASSERT_LE(3, buffer2.get_size());
ASSERT_EQ(3, buffer2.get_count());
ASSERT_TRUE(segments);
const Gather::Segment& segment1 = segments[0];
ASSERT_EQ(hello.size(), segment1.length);
ASSERT_EQ(hello,
string(reinterpret_cast<char *>(segment1.data), segment1.length));
const Gather::Segment& segment2 = segments[1];
ASSERT_EQ(two_str.substr(1).size(), segment2.length);
ASSERT_EQ(two_str.substr(1),
string(reinterpret_cast<char *>(segment2.data), segment2.length));
const Gather::Segment& segment3 = segments[2];
ASSERT_EQ(three_str.substr(0, 4).size(), segment3.length);
ASSERT_EQ(three_str.substr(0, 4),
string(reinterpret_cast<char *>(segment3.data), segment3.length));
}
TEST(GatherTest, TestAddBuffer)
{
Gather::Buffer buffer1(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer1.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
Gather::Buffer buffer2(0);
Gather::Segment& segment = buffer2.add(strlen(two));
memcpy(segment.data, &two[0], segment.length);
buffer2.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
buffer1.add(buffer2);
const Gather::Segment *segments = buffer1.get_segments();
ASSERT_LE(3, buffer1.get_size());
ASSERT_EQ(3, buffer1.get_count());
ASSERT_TRUE(segments);
const Gather::Segment& segment1 = segments[0];
ASSERT_EQ(one_str.size(), segment1.length);
ASSERT_EQ(one_str,
string(reinterpret_cast<char *>(segment1.data), segment1.length));
const Gather::Segment& segment2 = segments[1];
ASSERT_EQ(two_str.size(), segment2.length);
ASSERT_EQ(two_str,
string(reinterpret_cast<char *>(segment2.data), segment2.length));
const Gather::Segment& segment3 = segments[2];
ASSERT_EQ(three_str.size(), segment3.length);
ASSERT_EQ(three_str,
string(reinterpret_cast<char *>(segment3.data), segment3.length));
}
TEST(GatherTest, TestIteratorLoop)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
string actual;
for (Gather::Buffer::iterator it = buffer.begin(); it != buffer.end(); ++it)
actual += reinterpret_cast<char&>(*it);
ASSERT_EQ(expect.size(), actual.size());
ASSERT_EQ(expect, actual);
}
TEST(GatherTest, TestIteratorAdd)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
Gather::Buffer::iterator it = buffer.begin();
it += 7;
ASSERT_EQ(expect[7], *it);
}
TEST(GatherTest, TestIteratorSub)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
const string one_str(&one[0], strlen(one));
char two[] = ", wo";
const string two_str(&two[0], strlen(two));
char three[] = "rld!";
const string three_str(&three[0], strlen(three));
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
const string expect = one_str + two_str + three_str;
Gather::Buffer::iterator it = buffer.end();
it -= 6;
ASSERT_EQ(expect[7], *it);
it -= 1;
ASSERT_EQ(expect[6], *it);
}
TEST(GatherTest, TestDump)
{
Gather::Buffer buffer(1);
ostringstream expect;
expect << "Buffer (4/4):" << endl
<< " 0" << endl
<< " 12" << endl
<< "0000: 656c6c6f 2c20776f 726c6421 | ello, world!" << endl
<< " 4" << endl
<< "0000: 67452301 | gE#." << endl
<< "* 8" << endl
<< "0000: 00010203 04050607 | ........" << endl
<< "Total length 24" << endl;
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
uint32_t n = 0xDEADBEEF;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n));
uint32_t n2 = 0x01234567;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n2), sizeof(n2), 2);
buffer.limit(buffer.get_length() - 8);
buffer.consume(5);
ostringstream actual;
buffer.dump(actual, true);
ASSERT_EQ(actual.str(), expect.str());
}
#if !defined(PLATFORM_WINDOWS)
TEST(GatherTest, TestFill)
{
Gather::Buffer buffer(1);
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::Segment& seg = buffer.add(16);
for (unsigned int i = 0; i < seg.length; ++i)
seg.data[i] = i;
uint32_t n = 0xDEADBEEF;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n), sizeof(n));
uint32_t n2 = 0x01234567;
buffer.insert(reinterpret_cast<Gather::data_t *>(&n2), sizeof(n), 2);
buffer.limit(buffer.get_length() - 8);
buffer.consume(5);
struct iovec io[4];
buffer.fill(io, 4);
// Note: zero sized buffer is skipped
ASSERT_EQ(12, io[0].iov_len);
ASSERT_EQ(string("ello, world!"),
string(reinterpret_cast<char *>(io[0].iov_base), io[0].iov_len));
ASSERT_EQ(4, io[1].iov_len);
ASSERT_EQ(string("gE#\x01"),
string(reinterpret_cast<char *>(io[1].iov_base), io[1].iov_len));
ASSERT_EQ(8, io[2].iov_len);
ASSERT_EQ(string("\x00\x01\x02\x03\x04\x05\x06\x07", 8),
string(reinterpret_cast<char *>(io[2].iov_base), io[2].iov_len));
}
#endif
TEST(GatherTest, TestGetFlatDataSingleSegment)
{
Gather::Buffer buffer(0);
char data[] = "Hello, world!";
buffer.add(reinterpret_cast<Gather::data_t *>(&data[0]), strlen(data));
Gather::data_t buf[4];
Gather::data_t *p = buffer.get_flat_data(0, 4, buf);
ASSERT_NE(p, buf) << "Single segment get_flat_data used temporary buffer!\n";
ASSERT_EQ(string(reinterpret_cast<char *>(p), 4), "Hell");
}
TEST(GatherTest, TestGetFlatDataMultiSegment)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::data_t buf[7];
Gather::data_t *p = buffer.get_flat_data(3, 7, buf);
ASSERT_EQ(p, buf) << "Multi-segment get_flat_data didn't use temporary buffer!\n";
ASSERT_EQ(string(reinterpret_cast<char *>(p), 7), "lo, wor");
}
TEST(GatherTest, TestGetFlatDataOffEndFails)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
Gather::data_t buf[7];
Gather::data_t *p = buffer.get_flat_data(7, 7, buf);
ASSERT_FALSE(p) << "get_flat_data off the end didn't fail!\n";
}
TEST(GatherTest, TestReplaceSingleSegment)
{
Gather::Buffer buffer(0);
// Need to ensure it's owned data, not referenced
memcpy(buffer.add(13).data, "Hello, world!", 13);
buffer.replace(0, reinterpret_cast<const Gather::data_t *>("Salut"), 5);
Gather::data_t buf[13];
Gather::data_t *p = buffer.get_flat_data(0, 13, buf);
ASSERT_EQ(string(reinterpret_cast<char *>(p), 13), "Salut, world!");
}
TEST(GatherTest, TestReplaceMultiSegment)
{
Gather::Buffer buffer(0);
char one[] = "Hello";
char two[] = ", wo";
char three[] = "rld!";
buffer.add(reinterpret_cast<Gather::data_t *>(&one[0]), strlen(one));
buffer.add(reinterpret_cast<Gather::data_t *>(&two[0]), strlen(two));
buffer.add(reinterpret_cast<Gather::data_t *>(&three[0]), strlen(three));
buffer.replace(4, reinterpret_cast<const Gather::data_t *>(" freezeth"), 9);
Gather::data_t buf[13];
Gather::data_t *p = buffer.get_flat_data(0, 13, buf);
ASSERT_EQ(string(reinterpret_cast<char *>(p), 13), "Hell freezeth");
}
} // anonymous namespace
int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
| 32.980176 | 84 | 0.646631 | sandtreader |
6269092d278ad6e28176e79aea034cf363d74e23 | 151 | cc | C++ | src/foo/foo.cc | da2ce7/meson-sample-project | 225a2006d8ba207b044fd70a0ac7f4429a4fd27d | [
"MIT"
] | 86 | 2018-05-27T22:05:29.000Z | 2022-03-28T09:21:42.000Z | src/foo/foo.cc | seanwallawalla-forks/meson-sample-project | 0e09d1d1a08f9f19f7e7615e3ed21f548ac56b13 | [
"MIT"
] | 2 | 2019-08-14T09:06:29.000Z | 2019-08-16T14:20:01.000Z | src/foo/foo.cc | seanwallawalla-forks/meson-sample-project | 0e09d1d1a08f9f19f7e7615e3ed21f548ac56b13 | [
"MIT"
] | 24 | 2018-08-07T17:32:11.000Z | 2021-12-21T07:30:32.000Z | #include "foo/foo.h"
#include <config.h>
#include <iostream>
/*!
Description of implementation of foo
*/
int foo(int param) { return param + 1; }
| 16.777778 | 40 | 0.668874 | da2ce7 |
626b077564a109690a18d2404087d11dbef9bb0f | 2,319 | hpp | C++ | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | include/commands/Label.hpp | MrHands/Panini | 464999debf6ad6ee9f2184514ba719062f8375b5 | [
"MIT-0"
] | null | null | null | /*
MIT No Attribution
Copyright 2021-2022 Mr. Hands
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.
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.
*/
#pragma once
#include "commands/CommandBase.hpp"
namespace panini
{
/*!
\brief Outputs a label statement.
A label is a name and a ":" chunk. The command pops the indentation
before writing the label and restores it afterwards.
Labels are useful when you don't want to modify the current
indentation level, e.g. when writing an access identifier for a class
or a switch..case statement.
Example:
\code{.cpp}
writer << Scope("class Vehicle", [](WriterBase& writer) {
writer << Label("public") << NextLine();
writer << "Vehicle(const std::string& maker);" << NextLine();
writer << Label("private") << NextLine();
writer << "std::string m_maker;" << NextLine();
}) << ";";
\endcode
Output:
\code{.cpp}
class Vehicle
{
public:
Vehicle(const std::string& maker);
private:
std::string m_maker;
};
\endcode
\sa Scope
*/
class Label
: public CommandBase
{
public:
/*!
Create a Label command with a `name` that is moved into the
instance.
*/
Label(std::string&& name)
: m_name(name)
{
}
/*!
Create a Label command with a `name` that is copied to the
instance.
*/
Label(const std::string& name)
: m_name(name)
{
}
virtual void Visit(WriterBase& writer) final
{
writer << IndentPop() << m_name << ":" << IndentPush();
}
private:
std::string m_name;
};
};
| 23.663265 | 77 | 0.688228 | MrHands |
626cb1c5b7738cb9a823b86b9176292a870feaa5 | 5,747 | cc | C++ | ns-3-dev/src/lte/examples/lte-phy-uplink.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 11 | 2015-11-24T11:07:28.000Z | 2021-12-23T04:10:29.000Z | ns-3-dev/src/lte/examples/lte-phy-uplink.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | null | null | null | ns-3-dev/src/lte/examples/lte-phy-uplink.cc | maxvonhippel/snake | 0805773dc34e1480dffaae40174aa1f82d1c6ce8 | [
"BSD-3-Clause"
] | 6 | 2016-03-01T06:32:21.000Z | 2022-03-24T19:31:41.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2010 TELEMATICS LAB, DEE - Politecnico di Bari
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Giuseppe Piro <g.piro@poliba.it>
*/
/*
* Test for LTE PHY layer in the downlink
*
* /\ +
* /--\ __|
* /....\ | |
* /------\ |__|
* eNB UE
*
* SendPacket(Pb)
* |
* V
* |+++++++++++++++++++++++++++++| |+++++++++++++++++++++++++++++|
* | EnbLtePhy | | EnbLtePhy |
* |+++++++++++++++++++++++++++++| |+++++++++++++++++++++++++++++|
* | SpectrumPhy | SpectrumPhy | | SpectrumPhy | SpectrumPhy |
* | dl | ul | | dl | ul |
* |+++++++++++++++++++++++++++++| |+++++++++++++++++++++++++++++|
* \ |
* | |
* | |
* StartRx (pb) StartTx(bb)
* | |
* | V
* |+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
* | Uplink Spectrum Channel |
* |+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++|
*/
#include <iostream>
#include <ns3/core-module.h>
#include <ns3/network-module.h>
#include <ns3/single-model-spectrum-channel.h>
#include <ns3/log.h>
#include <string>
#include <ns3/mobility-module.h>
#include <ns3/spectrum-helper.h>
#include <ns3/internet-module.h>
#include <ns3/lte-helper.h>
#include <ns3/enb-phy.h>
#include <ns3/ue-phy.h>
#include <ns3/packet-burst.h>
#include <ns3/constant-position-mobility-model.h>
#include <ns3/constant-velocity-mobility-model.h>
#include <vector>
NS_LOG_COMPONENT_DEFINE ("TestSimpleLtePhy");
using namespace ns3;
int main (int argc, char** argv)
{
LteHelper lte;
lte.EnableLogComponents ();
// CREATE NODE CONTAINER AND CREATE LTE NODES
NodeContainer ueNodes;
NodeContainer enbNodes;
ueNodes.Create (1);
enbNodes.Create (1);
// CREATE DEVICE CONTAINER, INSTALL DEVICE TO NODE
NetDeviceContainer ueDevs, enbDevs;
ueDevs = lte.Install (ueNodes, LteHelper::DEVICE_TYPE_USER_EQUIPMENT);
enbDevs = lte.Install (enbNodes, LteHelper::DEVICE_TYPE_ENODEB);
// INSTALL INTERNET STACKS
InternetStackHelper stack;
stack.Install (ueNodes);
stack.Install (enbNodes);
Ipv4AddressHelper address;
address.SetBase ("10.1.1.0", "255.255.255.0");
Ipv4InterfaceContainer UEinterfaces = address.Assign (ueDevs);
Ipv4InterfaceContainer ENBinterface = address.Assign (enbDevs);
// MANAGE LTE NET DEVICES
Ptr<EnbNetDevice> enb;
enb = enbDevs.Get (0)->GetObject<EnbNetDevice> ();
Ptr<UeNetDevice> ue = ueDevs.Get (0)->GetObject<UeNetDevice> ();
lte.RegisterUeToTheEnb (ue, enb);
// CONFIGURE DL and UL SUB CHANNELS
// Define a list of sub channels for the downlink
std::vector<int> dlSubChannels;
for (int i = 0; i < 25; i++)
{
dlSubChannels.push_back (i);
}
// Define a list of sub channels for the uplink
std::vector<int> ulSubChannels;
for (int i = 50; i < 100; i++)
{
ulSubChannels.push_back (i);
}
enb->GetPhy ()->SetDownlinkSubChannels (dlSubChannels);
enb->GetPhy ()->SetUplinkSubChannels (ulSubChannels);
ue->GetPhy ()->SetDownlinkSubChannels (dlSubChannels);
ue->GetPhy ()->SetUplinkSubChannels (ulSubChannels);
// CONFIGURE MOBILITY
Ptr<ConstantPositionMobilityModel> enbMobility = CreateObject<ConstantPositionMobilityModel> ();
enbMobility->SetPosition (Vector (0.0, 0.0, 0.0));
lte.AddMobility (enb->GetPhy (), enbMobility);
Ptr<ConstantVelocityMobilityModel> ueMobility = CreateObject<ConstantVelocityMobilityModel> ();
ueMobility->SetPosition (Vector (30.0, 0.0, 0.0));
ueMobility->SetVelocity (Vector (30.0, 0.0, 0.0));
lte.AddMobility (ue->GetPhy (), ueMobility);
lte.AddDownlinkChannelRealization (enbMobility, ueMobility, ue->GetPhy ());
// ****** simulate a packet transmission in the downlink ******
Ptr<PacketBurst> pb = CreateObject<PacketBurst> ();
Ptr<Packet> p1 = Create<Packet> (500);
Ptr<Packet> p2 = Create<Packet> (500);
pb->AddPacket (p1);
pb->AddPacket (p2);
ue->GetPhy ()->SendPacket (pb);
Simulator::Stop (Seconds (.1));
Simulator::Run ();
Simulator::Destroy ();
return 0;
}
| 33.608187 | 98 | 0.515051 | maxvonhippel |
626d8b588ed8c82861226897531f5254cedbada8 | 2,577 | cpp | C++ | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | TG/bookcodes/ch4/la4728.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // LA4728/UVa1453 Square
// Rujia Liu
#include<cstdio>
#include<vector>
#include<cmath>
#include<algorithm>
using namespace std;
struct Point {
int x, y;
Point(int x=0, int y=0):x(x),y(y) { }
};
typedef Point Vector;
Vector operator - (const Point& A, const Point& B) {
return Vector(A.x-B.x, A.y-B.y);
}
int Cross(const Vector& A, const Vector& B) {
return A.x*B.y - A.y*B.x;
}
int Dot(const Vector& A, const Vector& B) {
return A.x*B.x + A.y*B.y;
}
int Dist2(const Point& A, const Point& B) {
return (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y);
}
bool operator < (const Point& p1, const Point& p2) {
return p1.x < p2.x || (p1.x == p2.x && p1.y < p2.y);
}
bool operator == (const Point& p1, const Point& p2) {
return p1.x == p2.x && p1.y == p2.y;
}
// 点集凸包
// 如果不希望在凸包的边上有输入点,把两个 <= 改成 <
// 注意:输入点集会被修改
vector<Point> ConvexHull(vector<Point>& p) {
// 预处理,删除重复点
sort(p.begin(), p.end());
p.erase(unique(p.begin(), p.end()), p.end());
int n = p.size();
int m = 0;
vector<Point> ch(n+1);
for(int i = 0; i < n; i++) {
while(m > 1 && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
int k = m;
for(int i = n-2; i >= 0; i--) {
while(m > k && Cross(ch[m-1]-ch[m-2], p[i]-ch[m-2]) <= 0) m--;
ch[m++] = p[i];
}
if(n > 1) m--;
ch.resize(m);
return ch;
}
// 返回点集直径的平方
int diameter2(vector<Point>& points) {
vector<Point> p = ConvexHull(points);
int n = p.size();
if(n == 1) return 0;
if(n == 2) return Dist2(p[0], p[1]);
p.push_back(p[0]); // 免得取模
int ans = 0;
for(int u = 0, v = 1; u < n; u++) {
// 一条直线贴住边p[u]-p[u+1]
for(;;) {
// 当Area(p[u], p[u+1], p[v+1]) <= Area(p[u], p[u+1], p[v])时停止旋转
// 即Cross(p[u+1]-p[u], p[v+1]-p[u]) - Cross(p[u+1]-p[u], p[v]-p[u]) <= 0
// 根据Cross(A,B) - Cross(A,C) = Cross(A,B-C)
// 化简得Cross(p[u+1]-p[u], p[v+1]-p[v]) <= 0
int diff = Cross(p[u+1]-p[u], p[v+1]-p[v]);
if(diff <= 0) {
ans = max(ans, Dist2(p[u], p[v])); // u和v是对踵点
if(diff == 0) ans = max(ans, Dist2(p[u], p[v+1])); // diff == 0时u和v+1也是对踵点
break;
}
v = (v + 1) % n;
}
}
return ans;
}
int main() {
int T;
scanf("%d", &T);
while(T--) {
int n;
scanf("%d", &n);
vector<Point> points;
for(int i = 0; i < n; i++) {
int x, y, w;
scanf("%d%d%d", &x, &y, &w);
points.push_back(Point(x, y));
points.push_back(Point(x+w, y));
points.push_back(Point(x, y+w));
points.push_back(Point(x+w, y+w));
}
printf("%d\n", diameter2(points));
}
return 0;
}
| 23.216216 | 82 | 0.503298 | Anyrainel |
627067211edef4a9f95182e1b7a389c3569596cb | 5,872 | cpp | C++ | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | 1 | 2020-10-06T08:40:10.000Z | 2020-10-06T08:40:10.000Z | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | src/tests/possumwood/subnetwork_from_file.cpp | LIUJUN-liujun/possumwood | 745e48eb44450b0b7f078ece81548812ab1ccc63 | [
"MIT"
] | null | null | null | #include <actions/actions.h>
#include <actions/filesystem_mock.h>
#include <dependency_graph/graph.h>
#include <dependency_graph/metadata_register.h>
#include <dependency_graph/rtti.h>
#include <possumwood_sdk/app.h>
#include <boost/test/unit_test.hpp>
#include <dependency_graph/node_base.inl>
#include <dependency_graph/nodes.inl>
#include <dependency_graph/port.inl>
#include "common.h"
using namespace dependency_graph;
using possumwood::io::json;
namespace {
dependency_graph::NodeBase& findNode(dependency_graph::Network& net, const std::string& name) {
for(auto& n : net.nodes())
if(n.name() == name)
return n;
BOOST_REQUIRE(false && "Node not found, fail");
throw;
}
dependency_graph::NodeBase& findNode(const std::string& name) {
return findNode(possumwood::AppCore::instance().graph(), name);
}
json readJson(possumwood::IFilesystem& filesystem, const std::string& filename) {
json result;
auto stream = filesystem.read(possumwood::Filepath::fromString(filename));
(*stream) >> result;
return result;
}
} // namespace
BOOST_AUTO_TEST_CASE(network_from_file) {
auto filesystem = std::make_shared<possumwood::FilesystemMock>();
possumwood::App app(filesystem);
dependency_graph::State state;
// make sure the static handles are initialised
passThroughNode();
// three nodes, a connection, blind data
json subnetwork(
{{"nodes",
{{"input_0", {{"name", "this_is_an_input"}, {"type", "input"}}},
{"pass_through_0", {{"name", "pass_through"}, {"type", "pass_through"}}},
{"output_0", {{"name", "this_is_an_output"}, {"type", "output"}}}}},
{"connections",
{{{"in_node", "pass_through_0"}, {"in_port", "input"}, {"out_node", "input_0"}, {"out_port", "data"}},
{{"in_node", "output_0"}, {"in_port", "data"}, {"out_node", "pass_through_0"}, {"out_port", "output"}}}},
{"name", "network"},
{"type", "network"}});
subnetwork["ports"]["this_is_an_input"] = 8.0f;
(*filesystem->write(possumwood::Filepath::fromString("subnetwork_only.psw"))) << subnetwork;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("subnetwork_only.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(app.saveFile(possumwood::Filepath::fromString("subnetwork_only_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "subnetwork_only_too.psw"), subnetwork);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("subnetwork_only_too.psw")));
/////////////
// attempt to serialize a simple setup with a subnetwork
{
json setup;
BOOST_REQUIRE_NO_THROW(setup = json({{"nodes",
{{"network_0",
{{"name", "network"},
{"type", "network"},
{"nodes", subnetwork["nodes"]},
{"connections", subnetwork["connections"]},
{"ports", {{"this_is_an_input", 0.0}}}}}}},
{"connections", std::vector<std::string>()},
{"name", "network"},
{"type", "network"}}));
(*filesystem->write(possumwood::Filepath::fromString("setup_with_subnetwork.psw"))) << setup;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("setup_with_subnetwork.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(app.saveFile(possumwood::Filepath::fromString("setup_with_subnetwork_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "setup_with_subnetwork_too.psw"), setup);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("setup_with_subnetwork_too.psw")));
}
//////////////
// make a copy of that setup and try to set the source attribute - represents a network coming
// from another file
{
json setup;
BOOST_REQUIRE_NO_THROW(setup = json({{"nodes",
{{"network_0",
{{"name", "network"},
{"type", "network"},
{"source", "subnetwork_only.psw"},
{"ports", {{"this_is_an_input", 8.0}}}}}}},
{"connections", std::vector<std::string>()},
{"name", "network"},
{"type", "network"}}));
(*filesystem->write(possumwood::Filepath::fromString("setup_without_subnetwork.psw"))) << setup;
BOOST_REQUIRE_NO_THROW(state = app.loadFile(possumwood::Filepath::fromString("setup_without_subnetwork.psw")));
BOOST_REQUIRE(!state.errored());
// lets make sure this loads and saves correctly
BOOST_REQUIRE_NO_THROW(
app.saveFile(possumwood::Filepath::fromString("setup_without_subnetwork_too.psw"), false));
BOOST_CHECK_EQUAL(readJson(*filesystem, "setup_without_subnetwork_too.psw"), setup);
BOOST_REQUIRE_NO_THROW(app.loadFile(possumwood::Filepath::fromString("setup_without_subnetwork_too.psw")));
}
// check that we can set values on the network
auto& net = findNode("network").as<dependency_graph::Network>();
BOOST_CHECK_EQUAL(net.portCount(), 2u);
BOOST_CHECK_EQUAL(net.port(0).name(), "this_is_an_input");
BOOST_CHECK_EQUAL(net.port(0).get<float>(), 8.0f);
BOOST_CHECK_EQUAL(net.port(1).name(), "this_is_an_output");
BOOST_CHECK_EQUAL(net.port(1).get<float>(), 8.0f);
// test that the eval still works
BOOST_CHECK_NO_THROW(net.port(0).set(5.0f));
BOOST_CHECK_EQUAL(net.port(0).get<float>(), 5.0f);
BOOST_CHECK_EQUAL(net.port(1).get<float>(), 5.0f);
}
| 39.945578 | 113 | 0.626703 | LIUJUN-liujun |
6273a616ec80b4bf68bd6f7e18c4744366a5f8c8 | 5,425 | cpp | C++ | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | hackerlank/SourceCode | b702c9e0a9ca5d86933f3c827abb02a18ffc9a59 | [
"MIT"
] | 4 | 2021-07-31T13:56:01.000Z | 2021-11-13T02:55:10.000Z | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | null | null | null | Game/OGRE/Tests/PlayPen/src/WindowEmbedding.cpp | shacojx/SourceCodeGameTLBB | e3cea615b06761c2098a05427a5f41c236b71bf7 | [
"MIT"
] | 7 | 2021-08-31T14:34:23.000Z | 2022-01-19T08:25:58.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2005 The OGRE Team
Also see acknowledgements in Readme.html
This program is free software; you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License as published by the Free Software
Foundation; either version 2 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 Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License along with
this program; if not, write to the Free Software Foundation, Inc., 59 Temple
Place - Suite 330, Boston, MA 02111-1307, USA, or go to
http://www.gnu.org/copyleft/lesser.txt.
-----------------------------------------------------------------------------
*/
/*
-----------------------------------------------------------------------------
Filename: WindowEmbedding.cpp
Description: Stuff your windows full of OGRE
-----------------------------------------------------------------------------
*/
#include "Ogre.h"
using namespace Ogre;
void setupResources(void)
{
// Load resource paths from config file
ConfigFile cf;
cf.load("resources.cfg");
// Go through all sections & settings in the file
ConfigFile::SectionIterator seci = cf.getSectionIterator();
String secName, typeName, archName;
while (seci.hasMoreElements())
{
secName = seci.peekNextKey();
ConfigFile::SettingsMultiMap *settings = seci.getNext();
ConfigFile::SettingsMultiMap::iterator i;
for (i = settings->begin(); i != settings->end(); ++i)
{
typeName = i->first;
archName = i->second;
ResourceGroupManager::getSingleton().addResourceLocation(
archName, typeName, secName);
}
}
}
//---------------------------------------------------------------------
// Windows Test
//---------------------------------------------------------------------
#if OGRE_PLATFORM == OGRE_PLATFORM_WIN32
#include "windows.h"
RenderWindow* renderWindow = 0;
bool winActive = false;
bool winSizing = false;
LRESULT CALLBACK TestWndProc( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam )
{
if (uMsg == WM_CREATE)
{
return 0;
}
if (!renderWindow)
return DefWindowProc(hWnd, uMsg, wParam, lParam);
switch( uMsg )
{
case WM_ACTIVATE:
winActive = (LOWORD(wParam) != WA_INACTIVE);
break;
case WM_ENTERSIZEMOVE:
winSizing = true;
break;
case WM_EXITSIZEMOVE:
renderWindow->windowMovedOrResized();
renderWindow->update();
winSizing = false;
break;
case WM_MOVE:
case WM_SIZE:
if (!winSizing)
renderWindow->windowMovedOrResized();
break;
case WM_GETMINMAXINFO:
// Prevent the window from going smaller than some min size
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 100;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 100;
break;
case WM_CLOSE:
renderWindow->destroy(); // cleanup and call DestroyWindow
PostQuitMessage(0);
return 0;
case WM_PAINT:
if (!winSizing)
{
renderWindow->update();
return 0;
}
break;
}
return DefWindowProc( hWnd, uMsg, wParam, lParam );
}
INT WINAPI EmbeddedMain( HINSTANCE hInst, HINSTANCE, LPSTR strCmdLine, INT )
{
try
{
// Create a new window
// Style & size
DWORD dwStyle = WS_VISIBLE | WS_CLIPCHILDREN | WS_CLIPSIBLINGS | WS_OVERLAPPEDWINDOW;
// Register the window class
WNDCLASS wc = { 0, TestWndProc, 0, 0, hInst,
LoadIcon(0, IDI_APPLICATION), LoadCursor(NULL, IDC_ARROW),
(HBRUSH)GetStockObject(BLACK_BRUSH), 0, "TestWnd" };
RegisterClass(&wc);
HWND hwnd = CreateWindow("TestWnd", "Test embedding", dwStyle,
0, 0, 800, 600, 0, 0, hInst, 0);
Root root("", "");
root.loadPlugin("RenderSystem_GL");
//root.loadPlugin("RenderSystem_Direct3D9");
root.loadPlugin("Plugin_ParticleFX");
root.loadPlugin("Plugin_CgProgramManager");
// select first renderer & init with no window
root.setRenderSystem(*(root.getAvailableRenderers()->begin()));
root.initialise(false);
// create first window manually
NameValuePairList options;
options["externalWindowHandle"] =
StringConverter::toString((size_t)hwnd);
renderWindow = root.createRenderWindow("embedded", 800, 600, false, &options);
setupResources();
ResourceGroupManager::getSingleton().initialiseAllResourceGroups();
SceneManager *scene = root.createSceneManager(Ogre::ST_GENERIC, "default");
Camera *cam = scene->createCamera("cam");
Viewport* vp = renderWindow->addViewport(cam);
vp->setBackgroundColour(Ogre::ColourValue(0.5, 0.5, 0.7));
cam->setAutoAspectRatio(true);
cam->setPosition(0,0,300);
cam->setDirection(0,0,-1);
Entity* e = scene->createEntity("1", "ogrehead.mesh");
scene->getRootSceneNode()->createChildSceneNode()->attachObject(e);
Light* l = scene->createLight("l");
l->setPosition(300, 100, -100);
// message loop
MSG msg;
while(GetMessage(&msg, NULL, 0, 0 ) != 0)
{
TranslateMessage(&msg);
DispatchMessage(&msg);
}
}
catch( Exception& e )
{
MessageBox( NULL, e.getFullDescription().c_str(),
"An exception has occured!", MB_OK | MB_ICONERROR | MB_TASKMODAL);
}
return 0;
}
#endif
| 26.207729 | 87 | 0.655668 | hackerlank |
6273b00dc18f9cfc0eee6ce19d9e77d89b8eead3 | 3,415 | cpp | C++ | compute/tensor/src/cpu/general/dequantize.cpp | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 722 | 2019-12-02T13:07:19.000Z | 2022-03-24T08:55:38.000Z | compute/tensor/src/cpu/general/dequantize.cpp | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 89 | 2019-12-04T13:46:25.000Z | 2022-03-28T02:52:27.000Z | compute/tensor/src/cpu/general/dequantize.cpp | ishine/bolt | ea734231f7085898ba5ca10da6d02da38058a705 | [
"MIT"
] | 137 | 2019-12-03T08:41:58.000Z | 2022-03-18T19:54:59.000Z | // Copyright (C) 2019. Huawei Technologies Co., Ltd. All rights reserved.
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
// The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
// WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "cpu/general/tensor_computing_general.h"
template <typename IT, typename OT>
inline static void dequantize_kernel(
I32 len, IT *q, F32 scale, I32 biasLen, const OT *biasPtr, OT *d)
{
if (0 != biasLen) {
CHECK_REQUIREMENT(nullptr != biasPtr);
CHECK_REQUIREMENT(len % biasLen == 0);
}
F32 factor = 1 / scale;
if (biasLen > 0) {
for (int i = 0; i < len; i += biasLen) {
for (int j = 0; j < biasLen; j++) {
d[i + j] = q[i + j] * factor + biasPtr[j];
}
}
} else {
for (int i = 0; i < len; i++) {
d[i] = q[i] * factor;
}
}
}
template <typename OT>
inline static EE dequantize_wrapper(TensorDesc qDesc,
void *qData,
const F32 *scale,
TensorDesc bDesc,
const OT *bData,
TensorDesc dDesc,
OT *data)
{
if (nullptr == data || nullptr == qData || nullptr == scale) {
CHECK_STATUS(NULL_POINTER);
}
int length = tensorNumElements(qDesc);
int biasLength = tensorNumElements(bDesc);
EE ret = SUCCESS;
switch (qDesc.dt) {
case DT_I8:
CHECK_REQUIREMENT(biasLength == 0);
dequantize_kernel<INT8, OT>(length, (INT8 *)qData, scale[0], biasLength, bData, data);
break;
case DT_I32:
dequantize_kernel<I32, OT>(length, (I32 *)qData, scale[0], biasLength, bData, data);
break;
default:
ret = NOT_SUPPORTED;
break;
}
return ret;
}
EE dequantize_general(TensorDesc qDesc,
void *qData,
const F32 *scale,
TensorDesc bDesc,
void *bData,
TensorDesc dDesc,
void *data)
{
if (nullptr == data || nullptr == qData || nullptr == scale) {
CHECK_STATUS(NULL_POINTER);
}
EE ret = NOT_SUPPORTED;
switch (dDesc.dt) {
#if defined(_USE_FP32)
case DT_F32:
ret = dequantize_wrapper<F32>(
qDesc, qData, scale, bDesc, (const F32 *)bData, dDesc, (F32 *)data);
break;
#endif
#if defined(_USE_FP16)
case DT_F16:
ret = dequantize_wrapper<F16>(
qDesc, qData, scale, bDesc, (const F16 *)bData, dDesc, (F16 *)data);
break;
#endif
default:
break;
}
return ret;
}
| 34.846939 | 149 | 0.62694 | ishine |
627492e773dce21dc549ac82c039f07e89be3fe7 | 1,690 | cc | C++ | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | tictoc/txc3.cc | deezombiedude612/masters-omnetpp | 949e5af7235114ca8de2ba9140c6422907bae50d | [
"MIT"
] | null | null | null | /*
* txc3.cc
*
* Created on: May 12, 2021
* Author: deezombiedude612
*/
#include <stdio.h>
#include <string.h>
#include <omnetpp.h>
using namespace omnetpp;
/**
* In this class we add a counter, and delete the message after ten exchanges.
*/
class Txc3 : public cSimpleModule {
private:
int counter; // Note the counter here
protected:
virtual void initialize() override;
virtual void handleMessage(cMessage *msg) override;
};
Define_Module(Txc3);
void Txc3::initialize() {
/**
* Initialize counter to ten. We'll decrement it every time and delete
* the message when it reaches zero.
*/
counter = 10;
/**
* The WATCH() statement below will let you examine the variable under
* Tkenv. After doing a few steps in the simulation, double-click either
* 'tic' or 'toc', select the Contents tab in the dialog that pops up,
* and you'll find 'counter' in the list.
*/
WATCH(counter);
if(strcmp("tic", getName()) == 0) {
EV << "Sending initial message\n";
cMessage *msg = new cMessage("tictocMsg");
send(msg, "out");
}
}
void Txc3::handleMessage(cMessage *msg) {
// Increment counter and check value.
counter--;
if(counter == 0) {
/**
* If counter is 0, delete message. If you run the model, you'll
* find that the simulation will stop at this point with the message
* "no more events".
*/
EV << getName() << "'s counter reached zero, deleting message\n";
delete msg;
} else {
EV << getName() << "'s counter is " << counter << ", sending back message\n";
send(msg, "out");
}
}
| 25.606061 | 85 | 0.606509 | deezombiedude612 |
6274e3ee141928fbc234ab435016898c4d640773 | 11,781 | cpp | C++ | platform/emscripten/Rtt_EmscriptenJSPluginLoader.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 1,968 | 2018-12-30T21:14:22.000Z | 2022-03-31T23:48:16.000Z | platform/emscripten/Rtt_EmscriptenJSPluginLoader.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 303 | 2019-01-02T19:36:43.000Z | 2022-03-31T23:52:45.000Z | platform/emscripten/Rtt_EmscriptenJSPluginLoader.cpp | joehinkle11/corona | 530320beaa518a2b82fa8beb2a92f3be6b56a00e | [
"MIT"
] | 254 | 2019-01-02T19:05:52.000Z | 2022-03-30T06:32:28.000Z | //////////////////////////////////////////////////////////////////////////////
//
// This file is part of the Corona game engine.
// For overview and more information on licensing please refer to README.md
// Home page: https://github.com/coronalabs/corona
// Contact: support@coronalabs.com
//
//////////////////////////////////////////////////////////////////////////////
#include "Rtt_EmscriptenJSPluginLoader.h"
#include "Rtt_EmscriptenJSPluginLoader.h"
#include "Corona/CoronaLua.h"
#include "Rtt_Lua.h"
#if defined(EMSCRIPTEN)
#include "emscripten/emscripten.h"
#pragma region JSON
int Rtt::EmscriptenJSPluginLoader::json_decode(lua_State* L, const char* json)
{
Rtt_LUA_STACK_GUARD(L, 1);
int top = lua_gettop(L);
bool success = false;
lua_getglobal(L, "require");
lua_pushstring(L, "dkjson");
if (CoronaLuaDoCall(L, 1, 1) == 0)
{
lua_getfield(L, -1, "decode");
lua_remove(L, -2); // remove dkjson
lua_pushstring(L, json);
if (CoronaLuaDoCall(L, 1, 1) == 0)
{
if (lua_istable(L, -1))
{
lua_getfield(L, -1, "data");
lua_remove(L, -2); // remove decoded table
success = true;
}
}
}
if(!success) {
lua_pushnil(L);
}
return 1;
}
int Rtt::EmscriptenJSPluginLoader::EncodeException(lua_State*L)
{
Rtt_LUA_STACK_GUARD(L, 1);
if(lua_isfunction(L,2) && lua_istable(L, lua_upvalueindex(1)))
{
lua_pushvalue(L,2);
int ref = luaL_ref(L, LUA_REGISTRYINDEX);
lua_pushinteger(L, ref);
lua_rawseti(L, lua_upvalueindex(1), 1+lua_objlen(L, lua_upvalueindex(1)));
lua_pushinteger(L, ref);
}
else
{
lua_pushstring(L, "null");
}
lua_tostring(L, -1);
return 1;
}
const char* Rtt::EmscriptenJSPluginLoader::json_encode(lua_State* L, int valueIndex, bool storeFunctions)
{
Rtt_LUA_STACK_GUARD(L);
static std::string json;
json = "{}";
int top = lua_gettop(L);
if(storeFunctions)
{
lua_newtable(L);
}
else
{
lua_pushnil(L);
}
int exceptionUpvalueIndex = lua_gettop(L);
lua_getglobal(L, "require");
lua_pushstring(L, "dkjson");
if (CoronaLuaDoCall(L, 1, 1) == 0)
{
lua_getfield(L, -1, "encode");
lua_createtable(L, 0, 1);
lua_pushvalue(L, valueIndex);
lua_setfield(L, -2, "data");
lua_createtable(L, 0, 1);
lua_pushvalue(L, exceptionUpvalueIndex);
lua_pushcclosure(L, &EmscriptenJSPluginLoader::EncodeException, 1);
lua_setfield(L, -2, "exception");
if (CoronaLuaDoCall(L, 2, 1) == 0)
{
json = lua_tostring(L, -1);
lua_pop(L, 1);
}
if(lua_objlen(L, exceptionUpvalueIndex) > 0)
{
lua_getfield(L, -1, "encode");
lua_createtable(L, 0, 1);
lua_pushvalue(L, exceptionUpvalueIndex);
lua_setfield(L, -2, "functions");
if (CoronaLuaDoCall(L, 1, 1) == 0)
{
std::string functions = lua_tostring(L, -1);
lua_pop(L, 1);
functions[0] = ',';
json.pop_back();
json += functions; // skip first character
}
}
}
lua_pop(L, 2);
return json.c_str();
}
#pragma endregion
int Rtt::EmscriptenJSPluginLoader::JSFunctionWrapper(lua_State *L)
{
Rtt_LUA_STACK_GUARD(L, 1);
int nArgs = lua_gettop(L);
lua_createtable(L, nArgs, 0);
for(int n=1; n<=nArgs; n++)
{
lua_pushvalue(L, n);
lua_rawseti(L, -2, n);
}
const char *packageName = lua_tostring(L, lua_upvalueindex(1));
const char *property = lua_tostring(L, lua_upvalueindex(2));
const char *arguments = json_encode(L, nArgs+1, true);
lua_pop(L, 1);
char *str = (char *)EM_ASM_INT({
var module = UTF8ToString($0);
var property = UTF8ToString($1);
var args = UTF8ToString($2);
var args = JSON.parse(args);
var arguments = args.data || [];
var functions = args.functions;
var object = window[module];
var func = object[property];
var result = null;
try {
result = func.apply(object, arguments);
} catch(e) {
Module.printErr("Error while calling '" + module + "." + property + "()': ", e);
}
if(functions) {
for(var i=0; i<functions.length; i++) {
window.LuaReleaseFunction(functions[i]);
}
}
var str = JSON.stringify({data:result});
var lengthBytes = lengthBytesUTF8(str)+1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToUTF8(str, stringOnWasmHeap, lengthBytes+1);
return stringOnWasmHeap;
}, packageName, property, arguments);
json_decode(L, str);
free(str);
return 1;
}
int Rtt::EmscriptenJSPluginLoader::Index(lua_State *L)
{
Rtt_LUA_STACK_GUARD(L, 1);
const char *packageName = lua_tostring(L, lua_upvalueindex(1));
const char *property = lua_tostring(L, 2);
char *str = (char *)EM_ASM_INT({
var module = UTF8ToString($0);
var property = UTF8ToString($1);
var property = window[module][property];
var str = typeof property;
if(str != 'function') {
str = JSON.stringify({data:property});
}
var lengthBytes = lengthBytesUTF8(str)+1;
var stringOnWasmHeap = _malloc(lengthBytes);
stringToUTF8(str, stringOnWasmHeap, lengthBytes+1);
return stringOnWasmHeap;
}, packageName, property);
if(strncmp("function", str, 9) == 0) {
lua_pushstring(L, packageName);
lua_pushstring(L, property);
lua_pushcclosure(L, &EmscriptenJSPluginLoader::JSFunctionWrapper, 2);
} else {
json_decode(L, str);
}
free(str);
return 1;
}
int Rtt::EmscriptenJSPluginLoader::NewIndex(lua_State *L)
{
Rtt_LUA_STACK_GUARD(L);
const char *packageName = lua_tostring(L, lua_upvalueindex(1));
const char *key = lua_tostring(L, 2);
EM_ASM({
var module = UTF8ToString($0);
var key = UTF8ToString($1);
if(typeof window[module][key] == 'function' && window.LuaIsFunction(window[module][key])) {
window.LuaReleaseFunction(window[module][key]);
}
}, packageName, key);
if(lua_isfunction(L, 3))
{
lua_pushvalue(L, 3);
int dispatcherRef = luaL_ref(L, LUA_REGISTRYINDEX);
EM_ASM({
var module = UTF8ToString($0);
var key = UTF8ToString($1);
var refId = $2;
window[module][key] = window.LuaCreateFunction(refId);
}, packageName, key, dispatcherRef);
luaL_unref(L, LUA_REGISTRYINDEX, dispatcherRef);
}
else
{
EM_ASM({
var module = UTF8ToString($0);
var key = UTF8ToString($1);
var jsonData = UTF8ToString($2);
var value = JSON.parse(jsonData).data;
window[module][key] = value;
}, packageName, key, json_encode(L, 3, false));
}
return 0;
}
int Rtt::EmscriptenJSPluginLoader::Open(lua_State *L)
{
Rtt_LUA_STACK_GUARD(L, 1);
const char* packageName = luaL_checkstring(L, 1);
packageName = luaL_gsub( L, packageName, ".", "_" );
lua_remove(L, 1);
static const luaL_Reg kVTable[] = {{ NULL, NULL }};
luaL_openlib( L, packageName, kVTable, 0 );
lua_createtable(L, 0, 2);
lua_pushvalue(L, -1);
lua_setmetatable(L, -3);
lua_pushvalue(L, 1);
lua_pushcclosure(L, &EmscriptenJSPluginLoader::Index, 1);
lua_setfield(L, 3, "__index");
lua_pushvalue(L, 1);
lua_pushcclosure(L, &EmscriptenJSPluginLoader::NewIndex, 1);
lua_setfield(L, 3, "__newindex");
lua_pop(L,1);
return 1;
}
extern "C"
{
int EMSCRIPTEN_KEEPALIVE JSLuaFunctionRef(lua_State *L, int action, int refId, const char* data)
{
Rtt_LUA_STACK_GUARD(L);
lua_rawgeti(L, LUA_REGISTRYINDEX, refId);
if(!lua_isfunction(L, -1))
{
lua_pop(L, 1);
return 0;
}
if(action == 1) // if reference funciton
{
lua_pop(L, 1);
return 1;
}
if(action == 2) // create new reference
return luaL_ref(L, LUA_REGISTRYINDEX);
if(action == 3) // release reference
{
lua_pop(L, 1);
luaL_unref(L, LUA_REGISTRYINDEX, refId);
}
return 0;
}
const char* EMSCRIPTEN_KEEPALIVE JSLuaFunctionWrapper(lua_State *L, int refId, const char* data)
{
Rtt_LUA_STACK_GUARD(L);
const char *ret = "{\"data\":null}";
lua_rawgeti(L, LUA_REGISTRYINDEX, refId);
if(!lua_isfunction(L, -1))
return 0;
Rtt::EmscriptenJSPluginLoader::json_decode(L, data);
int argArray = lua_gettop(L);
size_t nArgs = lua_objlen(L, -1);
for(size_t i=1; i<=nArgs; i++)
{
lua_rawgeti(L, argArray, i);
}
lua_remove(L, argArray);
if(CoronaLuaDoCall(L, nArgs, 1) == 0) {
ret = Rtt::EmscriptenJSPluginLoader::json_encode(L, lua_gettop(L), true);
lua_pop(L, 1);
}
return ret;
}
}
int Rtt::EmscriptenJSPluginLoader::Loader(lua_State *L)
{
Rtt_LUA_STACK_GUARD(L, 1);
const char* packageName = luaL_checkstring(L, 1);
std::string subdirModule(luaL_gsub( L, packageName, ".", "/" ));
lua_pop(L, 1);
packageName = luaL_gsub( L, packageName, ".", "_" );
lua_remove(L, 1);
std::string module(packageName);
std::string jsFileName = module + ".js";
FILE* fi = fopen(jsFileName.c_str(), "rb");
if (fi == NULL)
{
jsFileName = subdirModule + ".js";
fi = fopen(jsFileName.c_str(), "rb");
}
if (fi == NULL)
{
lua_pushfstring(L, "\n\tno file '%s.js' or '%s.js'", module.c_str(), subdirModule.c_str());
return 1;
}
fseek(fi, 0, SEEK_END);
int size = ftell(fi);
fseek(fi, 0, SEEK_SET);
char* js = (char*) malloc(size + 1); // +1 for eol
fread(js, 1, size, fi);
fclose(fi);
js[size] = 0;
bool loaded = EM_ASM_INT({
var src = UTF8ToString($0);
var module = UTF8ToString($1);
var L = $2;
var loaded = 0;
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('charset', 'utf-8');
script.appendChild(document.createTextNode(src));
document.head.appendChild(script);
if(!window.hasOwnProperty('LuaCreateFunction')) {
var luaFunctionReferences = [];
var JSLuaFunctionRef = Module.cwrap('JSLuaFunctionRef', 'number', ['number', 'number', 'number', 'string']);
var JSLuaFunctionWrapper = Module.cwrap('JSLuaFunctionWrapper', 'string', ['number', 'number', 'string']);
window.LuaIsFunction = function(fnc) {
var refId = (fnc || {})._refId || fnc || 0;
if( typeof refId == 'number' && refId !== 0) {
return (JSLuaFunctionRef(L, 1, refId, null)!=0);
};
return false;
};
window.LuaCreateFunction = function(fnc) {
var refId = (fnc || {})._refId || fnc || 0;
if( typeof refId == 'number' && refId !== 0) {
var newRefId = JSLuaFunctionRef(L, 2, refId, null);
if (newRefId == 0)
return null;
var ret=(function(){
var f = function() {
if(typeof f._action === 'function') {
return f._action.apply(null, arguments);
} else {
Module.print("Warning: trying to invoke released Lua Function!");
}
};
f._refId = newRefId;
f._action = function() {
var args = JSON.stringify({data:Array.prototype.slice.call(arguments)});
var strRet = JSLuaFunctionWrapper(L, f._refId, args);
var luaReturns = JSON.parse(strRet);
var retData = luaReturns.data;
var functions = luaReturns.functions;
// TODO: this is very sketchy place. This is used when Lua function is returned from Lua function
for(var i=0; i<luaFunctionReferences.length; i++) {
window.LuaReleaseFunction(luaFunctionReferences[i]);
}
if(functions && functions.length) {
luaFunctionReferences = functions;
}
return retData;
};
return f;
})();
return ret;
};
return null;
};
window.LuaReleaseFunction = function(fnc) {
var refId = (fnc || {})._refId || fnc || 0;
if( typeof refId == 'number' && refId !== 0) {
JSLuaFunctionRef(L, 3, refId, null);
};
if(fnc) {
delete fnc._refId;
delete fnc._action;
}
};
}
return window.hasOwnProperty(module);
}, js, module.c_str(), L);
free(js);
if(loaded)
{
lua_pushcfunction(L, &EmscriptenJSPluginLoader::Open);
}
else
{
lua_pushfstring(L, "\n\tJS library is loaded, but object '%s' is not found!", module.c_str());
}
return 1;
}
#else
int Rtt::EmscriptenJSPluginLoader::Loader(lua_State *L) { return 0; }
int Rtt::EmscriptenJSPluginLoader::Open(lua_State *L) { return 0; }
#endif
| 25.065957 | 111 | 0.644173 | joehinkle11 |
6276f653074c7a3b38e2d082f15873a3e623b514 | 2,706 | hpp | C++ | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 5 | 2018-10-22T20:04:24.000Z | 2022-01-04T09:24:46.000Z | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 19 | 2018-10-03T12:14:35.000Z | 2019-07-07T09:33:14.000Z | navigation_layer/fovis/libfovis/libfovis/libfovis/stereo_calibration.hpp | kartavya2000/Anahita | 9afbf6c238658188df7d0d97b2fec3bd48028c03 | [
"BSD-3-Clause"
] | 15 | 2018-09-09T12:35:15.000Z | 2020-01-03T09:28:19.000Z | #ifndef __fovis_stereo_calibration_hpp__
#define __fovis_stereo_calibration_hpp__
#include <inttypes.h>
#include "camera_intrinsics.hpp"
#include "rectification.hpp"
namespace fovis
{
/**
* \ingroup DepthSources
* \brief Calibration data structure for stereo cameras.
*/
struct StereoCalibrationParameters
{
/**
* Translation vector: [ x, y, z ]
*/
double right_to_left_translation[3];
/**
* Rotation quaternion: [ w, x, y, z ]
*/
double right_to_left_rotation[4];
/**
* Intrinsics of the left camera.
*/
CameraIntrinsicsParameters left_parameters;
/**
* Intrinsics of the right camera.
*/
CameraIntrinsicsParameters right_parameters;
};
/**
* \ingroup DepthSources
* \brief Computes useful information from a StereoCalibrationParameters object
*/
class StereoCalibration
{
public:
StereoCalibration(const StereoCalibrationParameters& params);
~StereoCalibration();
/**
* Compute the 4x4 transformation matrix mapping [ u, v, disparity, 1 ]
* coordinates to [ x, y, z, w ] homogeneous coordinates in camera
* space.
*/
Eigen::Matrix4d getUvdToXyz() const {
double fx_inv = 1./_rectified_parameters.fx;
double base_inv = 1./getBaseline();
double cx = _rectified_parameters.cx;
double cy = _rectified_parameters.cy;
Eigen::Matrix4d result;
result <<
fx_inv , 0 , 0 , -cx * fx_inv ,
0 , fx_inv , 0 , -cy * fx_inv ,
0 , 0 , 0 , 1 ,
0 , 0 , fx_inv*base_inv , 0;
return result;
}
/**
* \return the width of the rectified camera.
*/
int getWidth() const {
return _rectified_parameters.width;
}
/**
* \return the height of the rectified camera.
*/
int getHeight() const {
return _rectified_parameters.height;
}
double getBaseline() const {
return -_parameters.right_to_left_translation[0];
}
const Rectification* getLeftRectification() const {
return _left_rectification;
}
const Rectification* getRightRectification() const {
return _right_rectification;
}
const CameraIntrinsicsParameters& getRectifiedParameters() const {
return _rectified_parameters;
}
/**
* \return a newly allocated copy of this calibration object.
*/
StereoCalibration* makeCopy() const;
private:
StereoCalibration() { }
void initialize();
StereoCalibrationParameters _parameters;
CameraIntrinsicsParameters _rectified_parameters;
Rectification* _left_rectification;
Rectification* _right_rectification;
};
}
#endif
| 23.530435 | 79 | 0.646711 | kartavya2000 |
62779338af81a8f087be2035267ce0bd8032074e | 1,283 | cxx | C++ | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 10 | 2018-03-26T07:41:44.000Z | 2021-11-06T08:33:24.000Z | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | null | null | null | test/telea1.cxx | paulwratt/cin-5.34.00 | 036a8202f11a4a0e29ccb10d3c02f304584cda95 | [
"MIT"
] | 1 | 2020-11-17T03:17:00.000Z | 2020-11-17T03:17:00.000Z | /* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
#include <stdio.h>
class A {
public:
int a;
};
class B : public A {
public:
int a;
};
void f(A x) {
printf("%d\n",x.a);
}
void test1() {
A a;
B b;
a.a = -12;
b.a = 1;
b.A::a = 2;
printf("%d %d %d\n", b.a , b.A::a , a.a);
a=b;
printf("%d %d %d\n", b.a , b.A::a , a.a);
f(a);
f(b);
A *pa = &a;
A *pb = &b;
pa->a = 123;
printf("%d %d %d\n", pb->a , pb->A::a , pa->a);
*pa = *pb;
printf("%d %d %d\n", pb->a , pb->A::a , pa->a);
}
void test2() {
A a[5];
B b[5];
int i;
for(i=0;i<5;i++) {
a[i].a = -12;
b[i].a = 1;
b[i].A::a = 2;
printf("%d %d %d\n", b[i].a , b[i].A::a , a[i].a);
a[i]=b[i];
printf("%d %d %d\n", b[i].a , b[i].A::a , a[i].a);
f(a[i]);
f(b[i]);
}
A *pa = a;
A *pb = b;
for(i=0;i<5;i++) {
pa[i].a = 123;
printf("%d %d %d\n", pb->a , pb[i].A::a , pa[i].a);
pa[i] = pb[i];
printf("%d %d %d\n", pb->a , pb[i].A::a , pa[i].a);
}
}
int main()
{
test1();
test2();
return 0;
}
| 16.881579 | 74 | 0.359314 | paulwratt |
62782608446126bae4ed17dfdebe4a4923d55144 | 240 | cpp | C++ | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | src/mwave/mwave_modules/src/mwave_modules/logic_component.cpp | mwaverecycling/ros2-packages | 6ae566d86dc5f724ee69255df3319f6692db6db5 | [
"MIT"
] | null | null | null | // TODO
#include "mwave_modules/logic_component.hpp"
namespace mwave_modules
{
LogicComponent::LogicComponent(const std::string & node_name, const std::string & namespace_)
: mwave_util::BroadcastNode(node_name, namespace_)
{
}
} | 20 | 94 | 0.754167 | mwaverecycling |
627a8d7ebd1e255e5da4c19be872be1eda90f71a | 11,297 | cpp | C++ | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 2 | 2020-11-02T08:23:11.000Z | 2020-11-03T18:14:51.000Z | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 4 | 2020-12-09T14:34:56.000Z | 2020-12-14T11:29:59.000Z | util.cpp | Cirras/eomap-classic | 7ba4f5208ce49aeacb17bc4ad016b278388485b8 | [
"Zlib"
] | 2 | 2020-12-09T12:40:10.000Z | 2020-12-14T20:52:10.000Z |
/* $Id: util.cpp 169 2009-10-23 20:17:53Z sausage $
* EOSERV is released under the zlib license.
* See LICENSE.txt for more info.
*/
#include "util.hpp"
#include <algorithm>
#include <ctime>
#include <limits>
#if defined(WIN32) || defined(WIN64)
#include <windows.h>
#endif // defined(WIN32) || defined(WIN64)
namespace util
{
variant::variant()
{
this->SetInt(0);
}
variant::variant(int i)
{
this->SetInt(i);
}
variant::variant(double d)
{
this->SetFloat(d);
}
variant::variant(const std::string &s)
{
this->SetString(s);
}
variant::variant(const char *p)
{
std::string s(p);
this->SetString(s);
}
variant::variant(bool b)
{
this->SetBool(b);
}
int variant::int_length(int x)
{
int count = 1;
int val = 10;
while (x >= val)
{
val *= 10;
++count;
}
return count;
}
int variant::GetInt()
{
if (this->cache_val[type_int])
{
return this->val_int;
}
this->cache_val[type_int] = true;
switch (this->type)
{
case type_float:
this->val_int = static_cast<int>(this->val_float);
break;
case type_string:
this->val_int = tdparse(this->val_string);
break;
case type_bool:
this->val_int = this->val_bool ? 0 : -1;
break;
default: ; // Shut the compiler up
}
return this->val_int;
}
double variant::GetFloat()
{
if (this->cache_val[type_float])
{
return this->val_float;
}
this->cache_val[type_float] = true;
switch (this->type)
{
case type_int:
this->val_float = static_cast<double>(this->val_int);
break;
case type_string:
this->val_float = tdparse(this->val_string);
break;
case type_bool:
this->val_float = this->val_bool ? 0.0 : 1.0;
break;
default: ; // Shut the compiler up
}
return this->val_float;
}
std::string variant::GetString()
{
if (this->cache_val[type_string])
{
return this->val_string;
}
this->cache_val[type_string] = true;
char buf[1024];
switch (this->type)
{
case type_int:
snprintf(buf, 1024, "%i", this->val_int);
this->val_string = buf;
break;
case type_float:
snprintf(buf, 1024, "%lf", this->val_float);
this->val_string = buf;
break;
case type_bool:
this->val_string = this->val_bool ? "yes" : "no";
break;
default: ; // Shut the compiler up
}
return this->val_string;
}
bool variant::GetBool()
{
if (this->cache_val[type_bool])
{
return this->val_bool;
}
this->cache_val[type_bool] = true;
int intval = 0;
std::string s = this->val_string;
switch (this->type)
{
case type_int:
this->val_bool = static_cast<bool>(this->val_int);
break;
case type_float:
this->val_bool = std::abs(this->val_float) != 0.0 && this->val_float == this->val_float;
break;
case type_string:
std::sscanf(this->val_string.c_str(), "%d", &intval);
util::lowercase(s);
this->val_bool = (s == "yes" || s == "true" || s == "enabled" || intval != 0);
break;
default: ; // Shut the compiler up
}
return this->val_bool;
}
void variant::SetType(variant::var_type type)
{
this->type = type;
for (std::size_t i = 0; i < sizeof(this->cache_val); ++i)
{
this->cache_val[i] = (static_cast<variant::var_type>(i) == type);
}
}
variant &variant::SetInt(int i)
{
this->val_int = i;
this->SetType(type_int);
return *this;
}
variant &variant::SetFloat(double d)
{
this->val_float = d;
this->SetType(type_float);
return *this;
}
variant &variant::SetString(const std::string &s)
{
this->val_string = s;
this->SetType(type_string);
return *this;
}
variant &variant::SetBool(bool b)
{
this->val_bool = b;
this->SetType(type_bool);
return *this;
}
variant &variant::operator =(int i)
{
return this->SetInt(i);
}
variant &variant::operator =(double d)
{
return this->SetFloat(d);
}
variant &variant::operator =(const std::string &s)
{
return this->SetString(s);
}
variant &variant::operator =(const char *p)
{
std::string s(p);
return this->SetString(s);
}
variant &variant::operator =(bool b)
{
return this->SetBool(b);
}
variant::operator int()
{
return this->GetInt();
}
variant::operator double()
{
return this->GetFloat();
}
variant::operator std::string()
{
return this->GetString();
}
variant::operator bool()
{
return this->GetBool();
}
std::string ltrim(const std::string &str)
{
std::size_t si = str.find_first_not_of(" \t\n\r");
if (si == std::string::npos)
{
si = 0;
}
else
{
--si;
}
++si;
return str.substr(si);
}
std::string rtrim(const std::string &str)
{
std::size_t ei = str.find_last_not_of(" \t\n\r");
if (ei == std::string::npos)
{
ei = str.length()-1;
}
++ei;
return str.substr(0, ei);
}
std::string trim(const std::string &str)
{
std::size_t si, ei;
bool notfound = false;
si = str.find_first_not_of(" \t\n\r");
if (si == std::string::npos)
{
si = 0;
notfound = true;
}
ei = str.find_last_not_of(" \t\n\r");
if (ei == std::string::npos)
{
if (notfound)
{
return "";
}
ei = str.length()-1;
}
++ei;
return str.substr(si, ei);
}
std::vector<std::string> explode(char delimiter, std::string str)
{
std::size_t lastpos = 0;
std::size_t pos = 0;
std::vector<std::string> pieces;
for (pos = str.find_first_of(delimiter); pos != std::string::npos; )
{
pieces.push_back(str.substr(lastpos, pos - lastpos));
lastpos = pos+1;
pos = str.find_first_of(delimiter, pos+1);
}
pieces.push_back(str.substr(lastpos));
return pieces;
}
std::vector<std::string> explode(std::string delimiter, std::string str)
{
std::size_t lastpos = 0;
std::size_t pos = 0;
std::vector<std::string> pieces;
if (delimiter.length() == 0)
{
return pieces;
}
if (delimiter.length() == 1)
{
return explode(delimiter[0], str);
}
for (pos = str.find(delimiter); pos != std::string::npos; )
{
pieces.push_back(str.substr(lastpos, pos - lastpos));
lastpos = pos + delimiter.length();
pos = str.find(delimiter, pos + delimiter.length());
}
pieces.push_back(str.substr(lastpos));
return pieces;
}
double tdparse(std::string timestr)
{
static char period_names[] = {'s', 'm', '%', 'k', 'h', 'd' };
static double period_mul[] = {1.0, 60.0, 100.0, 1000.0, 3600.0, 86400.0};
double ret = 0.0;
double val = 0.0;
bool decimal = false;
double decimalmulti = 0.1;
bool negate = false;
for (std::size_t i = 0; i < timestr.length(); ++i)
{
char c = timestr[i];
bool found = false;
if (c == '-')
{
negate = true;
continue;
}
if (c >= 'A' && c <= 'Z')
{
c -= 'A' - 'a';
}
for (std::size_t ii = 0; ii < sizeof(period_names)/sizeof(char); ++ii)
{
if (c == period_names[ii])
{
if (c == 'm' && timestr[i+1] == 's')
{
ret += val / 1000.0;
++i;
}
else if (c == '%')
{
ret += val / period_mul[ii];
}
else
{
ret += val * period_mul[ii];
}
found = true;
val = 0.0;
decimal = false;
decimalmulti = 0.1;
break;
}
}
if (!found)
{
if (c >= '0' && c <= '9')
{
if (!decimal)
{
val *= 10.0;
val += c - '0';
}
else
{
val += (c - '0') * decimalmulti;
decimalmulti /= 10.0;
}
}
else if (c == '.')
{
decimal = true;
decimalmulti = 0.1;
}
}
}
return (ret + val) * (negate ? -1.0 : 1.0);
}
int to_int(const std::string &subject)
{
return static_cast<int>(util::variant(subject));
}
double to_float(const std::string &subject)
{
return static_cast<double>(util::variant(subject));
}
std::string to_string(int subject)
{
return static_cast<std::string>(util::variant(subject));
}
std::string to_string(double subject)
{
return static_cast<std::string>(util::variant(subject));
}
void lowercase(std::string &subject)
{
std::transform(subject.begin(), subject.end(), subject.begin(), static_cast<int(*)(int)>(std::tolower));
}
void uppercase(std::string &subject)
{
std::transform(subject.begin(), subject.end(), subject.begin(), static_cast<int(*)(int)>(std::toupper));
}
void ucfirst(std::string &subject)
{
if (subject[0] > 'a' && subject[0] < 'z')
{
subject[0] += 'A' - 'a';
}
}
static void rand_init()
{
static bool init = false;
if (!init)
{
init = true;
std::srand(std::time(0));
}
}
static unsigned long long_rand()
{
#if RAND_MAX < 65535
return (std::rand() & 0xFF) << 24 | (std::rand() & 0xFF) << 16 | (std::rand() & 0xFF) << 8 | (std::rand() & 0xFF);
#else
#if RAND_MAX < 4294967295
return (std::rand() & 0xFFFF) << 16 | (std::rand() & 0xFFFF);
#else
return std::rand();
#endif
#endif
}
int rand(int min, int max)
{
rand_init();
rand(double(min), double(max));
return static_cast<int>(double(long_rand()) / (double(std::numeric_limits<unsigned long>::max()) + 1.0) * double(max - min + 1) + double(min));
}
double rand(double min, double max)
{
rand_init();
return double(long_rand()) / double(std::numeric_limits<unsigned long>::max()) * (max - min) + min;
}
double round(double subject)
{
return std::floor(subject + 0.5);
}
std::string timeago(double time, double current_time)
{
static bool init = false;
static std::vector<std::pair<int, std::string> > times;
if (!init)
{
init = true;
times.resize(5);
times.push_back(std::make_pair(1, "second"));
times.push_back(std::make_pair(60, "minute"));
times.push_back(std::make_pair(60*60, "hour"));
times.push_back(std::make_pair(24*60*60, "day"));
times.push_back(std::make_pair(7*24*60*60, "week"));
}
std::string ago;
double diff = current_time - time;
ago = ((diff >= 0) ? " ago" : " from now");
diff = std::abs(diff);
for (int i = times.size()-1; i >= 0; --i)
{
int x = int(diff / times[i].first);
diff -= x * times[i].first;
if (x > 0)
{
return util::to_string(x) + " " + times[i].second + ((x == 1) ? "" : "s") + ago;
}
}
return "now";
}
void sleep(double seconds)
{
#if defined(WIN32) || defined(WIN64)
Sleep(int(seconds * 1000.0));
#else // defined(WIN32) || defined(WIN64)
long sec = seconds;
long nsec = (seconds - double(sec)) * 1000000000.0;
timespec ts = {sec, nsec};
nanosleep(&ts, 0);
#endif // defined(WIN32) || defined(WIN64)
}
std::string DecodeEMFString(std::string chars)
{
reverse(chars.begin(), chars.end());
bool flippy = (chars.length() % 2) == 1;
for (std::size_t i = 0; i < chars.length(); ++i)
{
unsigned char c = chars[i];
if (flippy)
{
if (c >= 0x22 && c <= 0x4F)
c = (unsigned char)(0x71 - c);
else if (c >= 0x50 && c <= 0x7E)
c = (unsigned char)(0xCD - c);
}
else
{
if (c >= 0x22 && c <= 0x7E)
c = (unsigned char)(0x9F - c);
}
chars[i] = c;
flippy = !flippy;
}
return chars;
}
std::string EncodeEMFString(std::string chars)
{
bool flippy = (chars.length() % 2) == 1;
for (std::size_t i = 0; i < chars.length(); ++i)
{
unsigned char c = chars[i];
if (flippy)
{
if (c >= 0x22 && c <= 0x4F)
c = (unsigned char)(0x71 - c);
else if (c >= 0x50 && c <= 0x7E)
c = (unsigned char)(0xCD - c);
}
else
{
if (c >= 0x22 && c <= 0x7E)
c = (unsigned char)(0x9F - c);
}
chars[i] = c;
flippy = !flippy;
}
reverse(chars.begin(), chars.end());
return chars;
}
}
| 17.624025 | 144 | 0.589449 | Cirras |
627ab0df8852c76820a999e1c7b39467afbec5c5 | 59,582 | cpp | C++ | src/Sparrow/Sparrow/Resources/Pm6/STO-6G.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 45 | 2019-06-12T20:04:00.000Z | 2022-02-28T21:43:54.000Z | src/Sparrow/Sparrow/Resources/Pm6/STO-6G.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 12 | 2019-06-12T23:53:57.000Z | 2022-03-28T18:35:57.000Z | src/Sparrow/Sparrow/Resources/Pm6/STO-6G.cpp | qcscine/sparrow | 387e56ed8da78e10d96861758c509f7c375dcf07 | [
"BSD-3-Clause"
] | 11 | 2019-06-22T22:52:51.000Z | 2022-03-11T16:59:59.000Z | /**
* @file
* @copyright This code is licensed under the 3-clause BSD license.\n
* Copyright ETH Zurich, Laboratory of Physical Chemistry, Reiher Group.\n
* See LICENSE.txt for details.
*
* @note This file was generated by the Embed binary from runtime values.
* Prefer improving the generator over editing this file whenever possible.
*
* This file contains functions generating runtime values. It was
* generated from runtime values of its return type. It is not intended to be
* human-readable. A small guide: Return values are directly brace-initialized
* in deep nesting to keep file size to a minimum. Types are annotated only when
* necessary. Floating point values are represented in hexadecimal (see
* std::hexfloat) to ensure serialization does not cause loss of accuracy.
*
* The functions defined here might be declared and called elsewhere entirely.
*
*/
#include "Utils/DataStructures/AtomicGtos.h"
#include <unordered_map>
namespace Scine {
namespace Sparrow {
namespace Sto6g {
std::unordered_map<int, Utils::AtomicGtos> pm6() {
// clang-format off
return {
{83, {Utils::GtoExpansion {0, {{{0, 0x1.01ec5f22d5891p-2, 0x1.39692485d30e7p-4}, {0, 0x1.94b45b3df08d6p-2, 0x1.daa5fc728bf52p-2}, {0, 0x1.01fb82443c96fp+0, -0x1.352b426c06566p-1}, {0, 0x1.e166fc7188c92p+0, -0x1.978b22d123954p-4}, {0, 0x1.80be60845eaep+1, 0x1.0be9a6a4e1dadp-3}, {0, 0x1.9e90a93ed861dp+2, 0x1.0ae31cea60024p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.07c5bf87d93dep-4, 0x1.0b3eb18278761p-8}, {1, 0x1.961fa84746619p-4, 0x1.7a821505332fbp-5}, {1, 0x1.30fd93b7e5ec8p-3, 0x1.2738f082950adp-4}, {1, 0x1.3b003f66a4704p-2, -0x1.163e504487d0fp-4}, {1, 0x1.006560047b10cp-1, -0x1.12d285fe02301p-4}, {1, 0x1.298ca4b41e882p+1, 0x1.7ca0dadcf0263p-7}}}}, boost::none}},
{82, {Utils::GtoExpansion {0, {{{0, 0x1.a65c40e63afcbp-4, 0x1.40ce7ac877953p-5}, {0, 0x1.4b5c4274ed6b1p-3, 0x1.e5d95f2058e64p-3}, {0, 0x1.a6750a96eb789p-2, -0x1.3c76f8c86130dp-2}, {0, 0x1.8a288739b9252p-1, -0x1.a12922cf8a528p-5}, {0, 0x1.3b045b16b4f34p+0, 0x1.123c218ef0ceap-4}, {0, 0x1.536f16663fd59p+1, 0x1.112f65d191113p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.ab6368a8110ep-5, 0x1.9acff23baf97ep-9}, {1, 0x1.4904f73c066c9p-4, 0x1.22ec7d1fd2189p-5}, {1, 0x1.ee2c730fbb7c9p-4, 0x1.c5d1d7cebdb9cp-5}, {1, 0x1.fe64b930c96bap-3, -0x1.abb82759bd2c1p-5}, {1, 0x1.9f6fb18dd0dcep-2, -0x1.a675e0baf896bp-5}, {1, 0x1.e21de6bacc3e1p+0, 0x1.248daaddd863p-7}}}}, boost::none}},
{81, {Utils::GtoExpansion {0, {{{0, 0x1.a2c673c5a97ffp-3, 0x1.0c0bbd18d19b6p-4}, {0, 0x1.488c34328d048p-2, 0x1.95f1ef8947affp-2}, {0, 0x1.a2df0798fbbcbp-1, -0x1.086b084b63a2bp-1}, {0, 0x1.86d002c51a542p+0, -0x1.5c8da68daf2e6p-4}, {0, 0x1.3857d092bf29cp+1, 0x1.ca4457d1a04ddp-4}, {0, 0x1.508d7cdd063e2p+2, 0x1.c8834500bc0acp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.d5676c1c8c9f4p-5, 0x1.cde6929b06424p-9}, {1, 0x1.695d582a8cd37p-4, 0x1.471a57c7915bep-5}, {1, 0x1.0f609e81111ccp-3, 0x1.fe41a76cd013ep-5}, {1, 0x1.1848db6059274p-2, -0x1.e0e9089a9cb2ap-5}, {1, 0x1.c846e9a4dce0dp-2, -0x1.daff55ecae5b7p-5}, {1, 0x1.08c1a1017bec1p+1, 0x1.48ef66d42d72fp-7}}}}, boost::none}},
{80, {Utils::GtoExpansion {0, {{{0, 0x1.4d771c76e9925p-4, 0x1.0cb362bf26829p-5}, {0, 0x1.059e465a4e1fdp-3, 0x1.96efd4a76e453p-3}, {0, 0x1.4d8aae9051514p-2, -0x1.09106917b1574p-2}, {0, 0x1.3732efd7c1ffbp-1, -0x1.5d67a680aee1ep-5}, {0, 0x1.f16deeb05ff85p-1, 0x1.cb62f65bb71e8p-5}, {0, 0x1.0bfe17d15f0c5p+1, 0x1.c9a0caac47417p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.59fd2f48ab8cp-5, 0x1.3b758441a3789p-9}, {1, 0x1.0a5aed4d51d9ap-4, 0x1.becba59eafc6bp-6}, {1, 0x1.900df732a0c6cp-4, 0x1.5c7beabf4c3ddp-5}, {1, 0x1.9d2f6866ab9ddp-3, -0x1.48711babcdc14p-5}, {1, 0x1.50503716fcd42p-2, -0x1.446750a47140dp-5}, {1, 0x1.864b46121b79bp+0, 0x1.c14c57aa1c04cp-8}}}}, boost::none}},
{79, {Utils::GtoExpansion {0, {{{0, 0x1.ef6be4abbb42p-5, 0x1.ae0042a86322dp-6}, {0, 0x1.84ae17a09ba0ep-4, 0x1.459c250fcf14dp-3}, {0, 0x1.ef88f80e7607ap-3, -0x1.a82e6c6185fb7p-3}, {0, 0x1.ce574788138afp-2, -0x1.17936977cd338p-5}, {0, 0x1.718271ea5a447p-1, 0x1.6f93d867a272bp-5}, {0, 0x1.8e26722940476p+0, 0x1.6e2ba454ea6c6p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.8a47e66473adap-5, 0x1.736d0addf69e8p-9}, {1, 0x1.2f88344c8d612p-4, 0x1.07081b6e54db2p-5}, {1, 0x1.c7e48689c6406p-4, 0x1.9a4f5f7e4b526p-5}, {1, 0x1.d6db2533f74dap-3, -0x1.82b6493acadcbp-5}, {1, 0x1.7f41344bde46dp-2, -0x1.7df5155d5e6bdp-5}, {1, 0x1.bcc51355ba75fp+0, 0x1.08814a0390b91p-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.685d345976c33p+4, -0x1.5c27e225cf5e3p+1}, {2, 0x1.16b3707a9c484p+3, -0x1.942475e0692cdp+1}, {2, 0x1.2cd5c6c5f3caap+1, 0x1.af26f5118c6a6p+1}, {2, 0x1.65bff11dc80b4p+0, 0x1.4e197b6e9c3d2p+1}, {2, 0x1.bb5aba66ff565p-1, 0x1.2d2b8f967cc86p-1}, {2, 0x1.139f5dfda0cf3p-1, 0x1.9e836a9647afep-6}}}}}},
{78, {Utils::GtoExpansion {0, {{{0, 0x1.8e960efca76adp-4, 0x1.332a631235e41p-5}, {0, 0x1.38b55ed46963ep-3, 0x1.d130bb8bae7dfp-3}, {0, 0x1.8ead737c376ep-2, -0x1.2f022439bfbcfp-2}, {0, 0x1.73f8b93fa53a6p-1, -0x1.8f6c31d6fcfeap-5}, {0, 0x1.2948f95682138p+0, 0x1.0692fcd143d77p-4}, {0, 0x1.4053dbdeb215ep+1, 0x1.0591ae55cb8fp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.9fe18fd92e748p-5, 0x1.8d08728d6b3dep-9}, {1, 0x1.402924b67febep-4, 0x1.192a6e0d8149ep-5}, {1, 0x1.e0de45fb96effp-4, 0x1.b6990e10f8b86p-5}, {1, 0x1.f0a6bfdae7424p-3, -0x1.9d5f7ae4f28cbp-5}, {1, 0x1.94403a5af74fdp-2, -0x1.984a5c43e707dp-5}, {1, 0x1.d522d43606763p+0, 0x1.1abd9da15eef5p-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.1b6e76296e075p+3, -0x1.0ff7c9dac4713p-1}, {2, 0x1.b6678edc9bcc4p+1, -0x1.3bb3edd96fa08p-1}, {2, 0x1.d938de341bc85p-1, 0x1.50cd4ed6d9264p-1}, {2, 0x1.196013b3d58ep-1, 0x1.04fcd5c91b0e5p-1}, {2, 0x1.5cb45e7964191p-2, 0x1.d6874ffc18d1ep-4}, {2, 0x1.b18fe5e0fef3cp-3, 0x1.43cde4d30a8e3p-8}}}}}},
{77, {Utils::GtoExpansion {0, {{{0, 0x1.53196bdee05cfp-5, 0x1.4394d6687a62p-6}, {0, 0x1.0a09d4b926ebp-4, 0x1.ea0d2e5df8074p-4}, {0, 0x1.532d529e0e31ep-3, -0x1.3f33b735c7f87p-3}, {0, 0x1.3c74f0bfee464p-2, -0x1.a4c4d9803c739p-6}, {0, 0x1.f9d56c5df2e3bp-2, 0x1.149b5dad87586p-5}, {0, 0x1.108538289eaedp+0, 0x1.138c4ee29e4d3p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.3d31444d18808p-2, 0x1.dbed8b07d3ab4p-6}, {1, 0x1.e85f806723efep-2, 0x1.510959adbc587p-2}, {1, 0x1.6ec2157cd2326p-1, 0x1.06e0477c4076cp-1}, {1, 0x1.7acbc11eaef47p+0, -0x1.ef83ca86538e1p-2}, {1, 0x1.3452746596868p+1, -0x1.e96c1fd9cc357p-2}, {1, 0x1.65cf5b7c26f7ap+3, 0x1.52eca7590e7c7p-4}}}}, Utils::GtoExpansion {2, {{{2, 0x1.9442c5687e35cp+2, -0x1.2d094d1067d15p-2}, {2, 0x1.38a66db70c61ap+1, -0x1.5d721ad1fa164p-2}, {2, 0x1.517afea4a172ep-1, 0x1.74cccadf82ee2p-2}, {2, 0x1.9153fbf0653ffp-2, 0x1.20e1e87375f47p-2}, {2, 0x1.f15c4249c755p-3, 0x1.0468e4c7b4a47p-4}, {2, 0x1.35325c0a9a0b3p-3, 0x1.6669bd0e4ee6cp-9}}}}}},
{76, {Utils::GtoExpansion {0, {{{0, 0x1.59b9afd3bf9fbp-3, 0x1.d04da5b2e6205p-5}, {0, 0x1.0f3ca050b68adp-2, 0x1.5f95ae0c956e4p-2}, {0, 0x1.59cdfa2036e3ap-1, -0x1.ca04f64bb4afap-2}, {0, 0x1.42a3f1284c41fp+0, -0x1.2de0d93732c7ap-4}, {0, 0x1.01dbde8fd7be2p+1, 0x1.8ce66ee62beffp-4}, {0, 0x1.15d87074a538ap+2, 0x1.8b617ed4a160cp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.7e574bcedeaf6p-5, 0x1.656b7da3c433ep-9}, {1, 0x1.26571dfcd1c41p-4, 0x1.fa39dfccae589p-6}, {1, 0x1.ba164903d7f7bp-4, 0x1.8ad6745e896cep-5}, {1, 0x1.c898e75e5371dp-3, -0x1.74212b98d2fe1p-5}, {1, 0x1.73a6143dcf96ap-2, -0x1.6f8dddf800c1bp-5}, {1, 0x1.af4d103ece4afp+0, 0x1.fd0fcabb1dea9p-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.63f143f26a61fp+1, -0x1.1e816f48451fap-4}, {2, 0x1.13480324d912ap+0, -0x1.4c940ccb35b7ap-4}, {2, 0x1.2924d2ea51042p-2, 0x1.62ce26fd53f62p-4}, {2, 0x1.615c36ef0353fp-3, 0x1.12f039be47339p-4}, {2, 0x1.b5ea1bb79ff73p-4, 0x1.efae16ed27c9ep-7}, {2, 0x1.103d9c11752f9p-4, 0x1.551ce02f80f0ep-11}}}}}},
{75, {Utils::GtoExpansion {0, {{{0, 0x1.b5cf6ef0e1261p-4, 0x1.499177cc509fep-5}, {0, 0x1.577b45ec890d1p-3, 0x1.f31e4a601925fp-3}, {0, 0x1.b5e920c193d6dp-2, -0x1.451b9a736d48p-2}, {0, 0x1.98939c62a6524p-1, -0x1.ac8dce1466733p-5}, {0, 0x1.468a52868b8aep+0, 0x1.19b980e63b487p-4}, {0, 0x1.5fd9b49be9012p+1, 0x1.18a56e4096bbcp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.efed2a60c3d97p-5, 0x1.eec04202246dep-9}, {1, 0x1.7dc857448e3dep-4, 0x1.5e5dce5532851p-5}, {1, 0x1.1eb5fc7b0831fp-3, 0x1.1145de7fcc5dp-4}, {1, 0x1.281f10174d05p-2, -0x1.018e69173dad8p-4}, {1, 0x1.e20ec77780da9p-2, -0x1.fcc778103cc54p-5}, {1, 0x1.17b7399e5858fp+1, 0x1.605439648dcbap-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.6746a35e42776p+2, -0x1.e9c48e204332p-3}, {2, 0x1.15dbfff036b18p+1, -0x1.1c437244da79ep-2}, {2, 0x1.2bed3a13b89a3p-1, 0x1.2f42ed4994d12p-2}, {2, 0x1.64ab657bf31aap-2, 0x1.d5fe82110069ep-3}, {2, 0x1.ba040257ab11fp-3, 0x1.a7abb9ace80e1p-5}, {2, 0x1.12ca4ea4026ep-3, 0x1.238edfe303c37p-9}}}}}},
{74, {Utils::GtoExpansion {0, {{{0, 0x1.0b2f16908d595p-3, 0x1.7eb3cd5110e6ap-5}, {0, 0x1.a33c38698f823p-3, 0x1.21cb3fcdc600dp-2}, {0, 0x1.0b3ec4d46e461p-1, -0x1.7985d791404b2p-2}, {0, 0x1.f2afd265f98eep-1, -0x1.f1a598465728bp-5}, {0, 0x1.8e8ec50781ea3p+0, 0x1.47252dca67c72p-4}, {0, 0x1.ad7328b3bdfaep+1, 0x1.45e498bc42c6p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.8ce49b46c1ac8p-5, 0x1.76811fb30e9c8p-9}, {1, 0x1.318affdc04a74p-4, 0x1.0936335597b15p-5}, {1, 0x1.cae9ba0b78596p-4, 0x1.9db5f526aa163p-5}, {1, 0x1.d9f9b9805bf2ep-3, -0x1.85eacd132c15fp-5}, {1, 0x1.81cb35d803272p-2, -0x1.811f829539339p-5}, {1, 0x1.bfb769856ddf1p+0, 0x1.0ab282362d33bp-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.6b88342d62138p+1, -0x1.2948204da59a3p-4}, {2, 0x1.1926a7e2662d3p+0, -0x1.59165d3e53a31p-4}, {2, 0x1.2f7ace450dee5p-2, 0x1.70267c0663349p-4}, {2, 0x1.68e50ec4c6e75p-3, 0x1.1d478a03dbc1fp-4}, {2, 0x1.bf407f4770293p-4, 0x1.01296f56fbad5p-6}, {2, 0x1.160ba7d6f6ec3p-4, 0x1.61f15dc7f8562p-11}}}}}},
{73, {Utils::GtoExpansion {0, {{{0, 0x1.8a5d38cf50c8ep-2, 0x1.aef12ea05132fp-4}, {0, 0x1.356568023639dp-1, 0x1.465293fe7fb7ep-1}, {0, 0x1.8a745de0027b3p+0, -0x1.a91c159eeee3dp-1}, {0, 0x1.70080ea13a3f2p+1, -0x1.18300da0fba1dp-3}, {0, 0x1.2622d54a2386cp+2, 0x1.7061cad658cfcp-3}, {0, 0x1.3cef3bf4a8405p+3, 0x1.6ef8ccf2e14abp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.b8e12ca06fadep-2, 0x1.672288d8d93c2p-5}, {1, 0x1.5367cd7e889p-1, 0x1.fca7b4fed6053p-2}, {1, 0x1.fdc5e9d6a2b16p-1, 0x1.8cbb76160875fp-1}, {1, 0x1.0740a1718a13cp+1, -0x1.75ea48737f6efp-1}, {1, 0x1.ac8cdfacd485dp+1, -0x1.71515c078c3dep-1}, {1, 0x1.f155eed173ea3p+3, 0x1.ff811b9f48135p-4}}}}, Utils::GtoExpansion {2, {{{2, 0x1.7d841e5bdd56ap+1, -0x1.437e6c160c8fap-4}, {2, 0x1.270f439f199d9p+0, -0x1.7783bcb2a4a78p-4}, {2, 0x1.3e7e319bd6bc1p-2, 0x1.909c705315e3dp-4}, {2, 0x1.7abf92a167ecfp-3, 0x1.366eead1df3c2p-4}, {2, 0x1.d560ac919d514p-4, 0x1.17d62343c3541p-6}, {2, 0x1.23ccef60ad4e8p-4, 0x1.8126a0684eac6p-11}}}}}},
{29, {Utils::GtoExpansion {0, {{{0, 0x1.2033a70ae8b9fp+3, 0x1.4dd85b88e046dp-8}, {0, 0x1.0128e10f7c15dp+0, -0x1.fbb42f71116ecp-5}, {0, 0x1.ea12fffe49462p-2, -0x1.06ee7f7e25d5ap-3}, {0, 0x1.2d1dd1bd17e34p-3, 0x1.0ec4f34af18b3p-3}, {0, 0x1.68f98413addeap-4, 0x1.9e80c88b5c997p-5}, {0, 0x1.abb454b61a197p-5, 0x1.fb8adcf267e0ep-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.581ebc0e164bdp+4, -0x1.c27eba829a986p-4}, {1, 0x1.ca8cf3c78323fp+2, -0x1.1b97797cb9ec7p-2}, {1, 0x1.897869f85b09dp+1, -0x1.620079a4ee7b5p-2}, {1, 0x1.97b0959ce8614p-1, 0x1.bcfe6333091b2p-2}, {1, 0x1.c8f3c12e643bap-2, 0x1.2147eb8e4b1adp-2}, {1, 0x1.039bb63311273p-2, 0x1.fa3e60e6d3c36p-6}}}}, Utils::GtoExpansion {2, {{{2, 0x1.29ce603afe826p+4, 0x1.bb50f8c2cb785p+1}, {2, 0x1.7e19365ba57f4p+2, 0x1.c03b59d4a08edp+1}, {2, 0x1.3d0c0565f4621p+1, 0x1.71c8a2d4cc37ep+1}, {2, 0x1.2a8efa598dba1p+0, 0x1.9782f32eb44edp+0}, {2, 0x1.2db488279e759p-1, 0x1.bca16618022c6p-2}, {2, 0x1.36de14697834ap-2, 0x1.02260e7b03a0fp-5}}}}}},
{28, {Utils::GtoExpansion {0, {{{0, 0x1.0622c1ce1da8fp+3, 0x1.36eeefd5cddd7p-8}, {0, 0x1.d3cd6fc0e3bc1p-1, -0x1.d8dc31022a748p-5}, {0, 0x1.bdc00a253481bp-2, -0x1.e9c5f444fd786p-4}, {0, 0x1.11e1e6fcaa6fdp-3, 0x1.f85f7400520fep-4}, {0, 0x1.4853ab45fcba2p-4, 0x1.820e42c194ca5p-5}, {0, 0x1.85057403474f4p-5, 0x1.d8b5b484193b4p-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.963373dec33fcp+3, -0x1.d21770cccc5e2p-5}, {1, 0x1.0ea33ea65add6p+2, -0x1.2568ee88f7ddp-3}, {1, 0x1.d0744f20e8564p+0, -0x1.6e41f94179cfcp-3}, {1, 0x1.e13d2f1b62fd9p-2, 0x1.cc6657711b7c5p-3}, {1, 0x1.0db1bc3b49b66p-2, 0x1.2b4bccffa9689p-3}, {1, 0x1.32715dd4db2cdp-3, 0x1.05e2980292f17p-6}}}}, Utils::GtoExpansion {2, {{{2, 0x1.f78db1ca4639p+3, 0x1.4a7376671cff9p+1}, {2, 0x1.430a6c5b0c8adp+2, 0x1.4e1d778f6dcddp+1}, {2, 0x1.0c0b2d36eb64fp+1, 0x1.13a3ac3ed9389p+1}, {2, 0x1.f8d35c5bf5d3bp-1, 0x1.2fc30befe4986p+0}, {2, 0x1.fe257401cd1p-2, 0x1.4b6e3cd1f2655p-2}, {2, 0x1.06d1be22ffb85p-2, 0x1.80da0148acf3dp-6}}}}}},
{27, {Utils::GtoExpansion {0, {{{0, 0x1.19971b2cbfde9p+2, 0x1.862916e8ac379p-9}, {0, 0x1.f68545bb5b659p-2, -0x1.28ac67f75b943p-5}, {0, 0x1.ded4e68c0f2d7p-3, -0x1.3348e89a35e03p-4}, {0, 0x1.26356d78c25eep-4, 0x1.3c71d2d195f29p-4}, {0, 0x1.60b19711bad19p-5, 0x1.e46ca34200449p-6}, {0, 0x1.a1e4840b1139bp-6, 0x1.2894427dc074ap-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.581ebc0e164bdp+4, -0x1.c27eba829a986p-4}, {1, 0x1.ca8cf3c78323fp+2, -0x1.1b97797cb9ec7p-2}, {1, 0x1.897869f85b09dp+1, -0x1.620079a4ee7b5p-2}, {1, 0x1.97b0959ce8614p-1, 0x1.bcfe6333091b2p-2}, {1, 0x1.c8f3c12e643bap-2, 0x1.2147eb8e4b1adp-2}, {1, 0x1.039bb63311273p-2, 0x1.fa3e60e6d3c36p-6}}}}, Utils::GtoExpansion {2, {{{2, 0x1.138976575ed55p+3, 0x1.cc271b99d7233p-1}, {2, 0x1.6186b00cdd365p+1, 0x1.d141473e52822p-1}, {2, 0x1.2556c7b623a55p+0, 0x1.7fd3da5902771p-1}, {2, 0x1.143ba9792ab7cp-1, 0x1.a6fcf9830b823p-2}, {2, 0x1.1724fa8806e3bp-2, 0x1.cd844fd7527b4p-4}, {2, 0x1.1f9f21e23a7dep-3, 0x1.0bf3e72ecb776p-7}}}}}},
{26, {Utils::GtoExpansion {0, {{{0, 0x1.c4ad5089d7037p+2, 0x1.1682a9ab77a6cp-8}, {0, 0x1.93eb5bf4fb2b2p-1, -0x1.a78d546d205adp-5}, {0, 0x1.80e0e5d553764p-2, -0x1.b6b399f260213p-4}, {0, 0x1.d8f64b22038d9p-4, 0x1.c3c75e3eca2a4p-4}, {0, 0x1.1b7d9264e541bp-4, 0x1.59cc9e10c9032p-5}, {0, 0x1.4fe58415a68d5p-5, 0x1.a76adb507127cp-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.5860b355a4abap+6, -0x1.3ed8a61c46f2ap-1}, {1, 0x1.cae4da99b4426p+4, -0x1.916f45889715ep+0}, {1, 0x1.89c3d70e9710bp+3, -0x1.f51a558b5b1b8p+0}, {1, 0x1.97febc8025b64p+1, 0x1.3af3de8077fcfp+1}, {1, 0x1.c94b598fb2f39p+0, 0x1.997cecc0470d1p+0}, {1, 0x1.03cd7a29cbc48p+0, 0x1.664dad102ec8dp-3}}}}, Utils::GtoExpansion {2, {{{2, 0x1.7403cbb4a0238p+1, 0x1.131ecf352feeap-3}, {2, 0x1.dd4fbe446f87ep-1, 0x1.162bc12bb4fd9p-3}, {2, 0x1.8c0cd5d1b8449p-2, 0x1.caf9006198a52p-4}, {2, 0x1.74f46424fe8fep-3, 0x1.f9ccd31e25b4bp-5}, {2, 0x1.78e2ad38d8dfcp-4, 0x1.13ef984023387p-6}, {2, 0x1.8454b2dabc37fp-5, 0x1.40697e53ccbd8p-10}}}}}},
{25, {Utils::GtoExpansion {0, {{{0, 0x1.d616368c17812p+3, 0x1.e1d7f7251919ap-8}, {0, 0x1.a3743506ffc47p+0, -0x1.6e63625bf9b2bp-4}, {0, 0x1.8fae46ac32f3ep-1, -0x1.7b7e3b9181c86p-3}, {0, 0x1.eb26e9622dc23p-3, 0x1.86ce2cc5dec13p-3}, {0, 0x1.2664b83b716a5p-3, 0x1.2b21123911033p-4}, {0, 0x1.5cd0a295c5c95p-4, 0x1.6e45904f876a8p-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.6418d065c4d8bp+2, -0x1.4c7768a34ebf8p-6}, {1, 0x1.da829906d1a3p+0, -0x1.a2952e4b72538p-5}, {1, 0x1.972a33490b337p-1, -0x1.054115ca0c365p-4}, {1, 0x1.a5e11086f3084p-3, 0x1.48680cb19072cp-4}, {1, 0x1.d8db28836f8ebp-4, 0x1.aafae6d389135p-5}, {1, 0x1.0ca4cc63c35f9p-4, 0x1.759bebe3f28cfp-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.0ec05d3ac625ap+4, 0x1.7741be2465302p+1}, {2, 0x1.5b62d524c9df2p+2, 0x1.7b6aee5c094dcp+1}, {2, 0x1.203e87c278d07p+1, 0x1.390362c24b82ap+1}, {2, 0x1.0f6f780bd9906p+0, 0x1.58f2ebcc72a42p+0}, {2, 0x1.124bd74321b41p-1, 0x1.785e853575df8p-2}, {2, 0x1.1aa04da1f1c73p-2, 0x1.b50895042aadap-6}}}}}},
{24, {Utils::GtoExpansion {0, {{{0, 0x1.16d425c5b1798p+5, 0x1.cc909332228dep-7}, {0, 0x1.f197a5c74f984p+1, -0x1.5e3540a93cc82p-3}, {0, 0x1.da22bfc3c8eaep+0, -0x1.6abbf24676675p-2}, {0, 0x1.2352ca0bbcbd7p-1, 0x1.758bfff62496fp-2}, {0, 0x1.5d3c1ea21a15fp-2, 0x1.1deb52dae686ep-3}, {0, 0x1.9dcb5b7b52fp-3, 0x1.5e18bfbe0fa94p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.4421910776df9p+1, -0x1.f11ea1b802e36p-8}, {1, 0x1.afea2afbceecbp-1, -0x1.38f1429182987p-6}, {1, 0x1.729d645b7a02cp-2, -0x1.86a3c89b68955p-6}, {1, 0x1.80021d93d0d34p-4, 0x1.eb0c884b92a5ep-6}, {1, 0x1.ae68bd46dcb79p-5, 0x1.3f3871487944ep-6}, {1, 0x1.e90e84db4173p-6, 0x1.1751ac53fdcc3p-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.a38c9884bebadp+2, 0x1.1d8833fa6f96ep-1}, {2, 0x1.0d266d20e5874p+1, 0x1.20b2b3d10e2d9p-1}, {2, 0x1.bea7d7c7d8d1bp-1, 0x1.dc5793286ed0fp-2}, {2, 0x1.a49beef616166p-2, 0x1.06788890e9718p-2}, {2, 0x1.a90acc29eff9cp-3, 0x1.1e60e3c117a64p-4}, {2, 0x1.b5f3345a26c5ep-4, 0x1.4c89ad9065b9cp-8}}}}}},
{23, {Utils::GtoExpansion {0, {{{0, 0x1.933fca7ef8fd3p+3, 0x1.ad7d5a288c04fp-8}, {0, 0x1.67d0bdb03e198p+0, -0x1.469431d7875a4p-4}, {0, 0x1.56da85b21eb46p-1, -0x1.52428703a0069p-3}, {0, 0x1.a551bf8d1707ap-3, 0x1.5c57d0c953af4p-3}, {0, 0x1.f91284fa0d889p-4, 0x1.0aa0b5d68ccd4p-4}, {0, 0x1.2b3850f1350adp-4, 0x1.46799d4240caap-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.59b57ca8a2f89p+1, -0x1.0d69af80b9109p-7}, {1, 0x1.ccaaf65b631e6p-1, -0x1.53326342dfac7p-6}, {1, 0x1.8b497fac3e4f4p-2, -0x1.a769a21951a4ap-6}, {1, 0x1.99927a05e5f68p-4, 0x1.0a1f71f039bdfp-5}, {1, 0x1.cb0fe01595dbdp-5, 0x1.5a0067c25914p-6}, {1, 0x1.04ce920d542a9p-5, 0x1.2ec0aa22e0cacp-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.35d1fb72cd868p+2, 0x1.4fefaff8b9d2ap-2}, {2, 0x1.8d8359f8144b2p+0, 0x1.53a9431a745dcp-2}, {2, 0x1.49d6566f9e545p-1, 0x1.1836fadc3192ep-2}, {2, 0x1.369a5aac80cbep-2, 0x1.34cddbb530474p-3}, {2, 0x1.39e067df6e66ap-3, 0x1.50eea009893f8p-5}, {2, 0x1.436893e14b9b2p-4, 0x1.873d669148f26p-9}}}}}},
{22, {Utils::GtoExpansion {0, {{{0, 0x1.6ea55bb6027cbp+6, 0x1.db92240309e8cp-6}, {0, 0x1.472797e4eaedfp+3, -0x1.699e557eb993bp-2}, {0, 0x1.37bb857425d1bp+2, -0x1.768d821bbeb5bp-1}, {0, 0x1.7f1369e3abcbap+0, 0x1.81b7c0196f313p-1}, {0, 0x1.cb39fd1fcd403p-1, 0x1.273c2c4706b83p-2}, {0, 0x1.100f3e6ba3fe5p-1, 0x1.6980e6d406f18p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.9e7d77646de7ap+1, -0x1.520133c57039ep-7}, {1, 0x1.142911b2b0d81p+0, -0x1.a98e36fbc9f7ap-6}, {1, 0x1.d9eea423d492dp-2, -0x1.099b323c822b4p-5}, {1, 0x1.eb0f3333d31f5p-4, 0x1.4de087828cc7cp-5}, {1, 0x1.1332a19f66983p-4, 0x1.b217beefef447p-6}, {1, 0x1.38b23d2596975p-5, 0x1.7bd52a9e5cd7p-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.405616bc65d4fp+2, 0x1.6424d68acffe7p-2}, {2, 0x1.9b017183852b5p+0, 0x1.6817c5f6cd54cp-2}, {2, 0x1.5508608bcd90dp-1, 0x1.29121051230e7p-2}, {2, 0x1.4125430b4eeb4p-2, 0x1.4761320d19e9p-3}, {2, 0x1.4487c24912a26p-3, 0x1.65331c7229ae8p-5}, {2, 0x1.4e62c1908dc3ap-4, 0x1.9ec62ea06df1ep-9}}}}}},
{21, {Utils::GtoExpansion {0, {{{0, 0x1.96f57a0e2bd1dp+2, 0x1.0122d556060e8p-8}, {0, 0x1.6b2022f2e6b92p-1, -0x1.870be677980e5p-5}, {0, 0x1.5a01f8aa5d4cbp-2, -0x1.9508887bc0f69p-4}, {0, 0x1.a931fda119b95p-4, 0x1.a11b5ffb7244p-4}, {0, 0x1.fdb801e054ddcp-5, 0x1.3f42c762a3d75p-5}, {0, 0x1.2df90122db38ap-5, 0x1.86ec12a3d82efp-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.14c1ca4314f9bp+2, -0x1.e538ea614e68ep-7}, {1, 0x1.70c98814dadd1p+0, -0x1.3173f288eae1ap-5}, {1, 0x1.3c725e8b60221p-1, -0x1.7d4a70c683f8ap-5}, {1, 0x1.47e1f5bb0cce8p-3, 0x1.df4c027f79d77p-5}, {1, 0x1.6f806fabfbea5p-4, 0x1.3794aa7b6726fp-5}, {1, 0x1.a193d7ab037dap-5, 0x1.10a25ca00b8e8p-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.132e080ede78ep+3, 0x1.cb1c07183625cp-1}, {2, 0x1.611160c09d028p+1, 0x1.d0333c9d5801ap-1}, {2, 0x1.24f5712f1b908p+0, 0x1.7ef512bd9fb9cp-1}, {2, 0x1.13e0000ef9671p-1, 0x1.a607772986a6cp-2}, {2, 0x1.16c859ccc283p-2, 0x1.cc7870a6aba44p-4}, {2, 0x1.1f3fb108fc071p-3, 0x1.0b5861030703cp-7}}}}}},
{20, {Utils::GtoExpansion {0, {{{0, 0x1.e33bde588e70fp+2, 0x1.247ea96fdeeb9p-8}, {0, 0x1.af2f596f7a511p-1, -0x1.bcd1b54e3ea9p-5}, {0, 0x1.9adbd97091ecap-2, -0x1.ccbab67f0f1abp-4}, {0, 0x1.f8e363007e062p-4, 0x1.da76934e6e10cp-4}, {0, 0x1.2ea0790adb6e8p-4, 0x1.6b298de2e85e4p-5}, {0, 0x1.669206feeaedfp-5, 0x1.bcad8112bbe0dp-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.448adfca4e615p+3, -0x1.60130c7d1d9c9p-5}, {1, 0x1.b0767e5d5bfcep+1, -0x1.bb45054e3d39dp-4}, {1, 0x1.7315cd474a9fbp+0, -0x1.14a98cd44e883p-3}, {1, 0x1.807ee076c5f2p-2, 0x1.5bc6641b5dae9p-3}, {1, 0x1.aef4936f6610dp-3, 0x1.c42986b8abcacp-4}, {1, 0x1.e9ad68dfc85b7p-4, 0x1.8ba4bd92d0f16p-7}}}}, boost::none}},
{19, {Utils::GtoExpansion {0, {{{0, 0x1.d19a5a6c00cabp+6, 0x1.1c7432220ffacp-5}, {0, 0x1.9f73fb953d28dp+3, -0x1.b0973dd23a40cp-2}, {0, 0x1.8bde55791688dp+2, -0x1.c01046c46bc2ap-1}, {0, 0x1.e6779d580cb43p+0, 0x1.cd6b7c4902f9dp-1}, {0, 0x1.2395de5737745p+0, 0x1.612dc1d1fc54ep-2}, {0, 0x1.597ce5aef5b52p-1, 0x1.b0740860fb6bfp-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.84dc11ba137e7p+1, -0x1.38156f15d8c32p-7}, {1, 0x1.03156fe318d14p+0, -0x1.88eba20caec0fp-6}, {1, 0x1.bca045e845d7ap-2, -0x1.ea7988e77aefbp-6}, {1, 0x1.ccb1b5345bbcdp-4, 0x1.3445cb9d3fb8ep-5}, {1, 0x1.022e3ceee6b1ep-4, 0x1.90cd8f44c4d5ep-6}, {1, 0x1.255c3e3c2895dp-5, 0x1.5eb439463d0ccp-9}}}}, boost::none}},
{18, {Utils::GtoExpansion {0, {{{0, 0x1.d1922b58d22fp+6, 0x1.1c70722804196p-5}, {0, 0x1.9f6cae2ae9043p+3, -0x1.b09189e940a7ep-2}, {0, 0x1.8bd7602eb09dcp+2, -0x1.c00a5ea3b884p-1}, {0, 0x1.e66f1062c7211p+0, 0x1.cd65671524c4dp-1}, {0, 0x1.2390be4afb76cp+0, 0x1.612919e9147e6p-2}, {0, 0x1.5976d317320a3p-1, 0x1.b06e54eed471fp-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.677214049754ap+7, -0x1.8fcbf07c42cd1p+1}, {1, 0x1.7ba1b9c5cabb8p+5, -0x1.4291a6249431dp+1}, {1, 0x1.fd4c9befabfeap+2, 0x1.8fc8a7a91166dp+1}, {1, 0x1.005aa01893c12p+2, 0x1.cfbcd6ee875c3p+1}, {1, 0x1.1346e0d6a365ep+1, 0x1.737884008706bp+0}, {1, 0x1.2c64f78bcb5dap+0, 0x1.083bdc894b741p-3}}}}, boost::none}},
{17, {Utils::GtoExpansion {0, {{{0, 0x1.6c2c1e5a0be94p+4, -0x1.9c3a736d73118p-5}, {0, 0x1.997b0c095ed0cp+2, -0x1.4b22fd5af4f51p-3}, {0, 0x1.3fd991a75c18fp+1, -0x1.cca19622f0c45p-3}, {0, 0x1.338196047fe1p-1, 0x1.13915e618c7b9p-2}, {0, 0x1.559e1b73ef77fp-2, 0x1.4158544659975p-3}, {0, 0x1.840dc541d20bcp-3, 0x1.e47e20a40c92ap-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.6c854d2862af8p+4, -0x1.e3d8ca0567fd6p-3}, {1, 0x1.80fde979a2449p+2, -0x1.866224cd79a4fp-3}, {1, 0x1.023ebd98b1b23p+0, 0x1.e3d4d06d71ee6p-3}, {1, 0x1.03f938d07fbd2p-1, 0x1.189d7b22645eep-2}, {1, 0x1.1729df341b576p-2, 0x1.c190e1a28c503p-4}, {1, 0x1.30a2bf97a1a95p-3, 0x1.3fc8ca6bc246fp-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.172d56974d8f4p+2, 0x1.17f726c547882p-2}, {2, 0x1.6632536a30615p+0, 0x1.1b11d984515e9p-2}, {2, 0x1.2936dcf99ff4p-1, 0x1.d30e375c80e0ep-3}, {2, 0x1.17e1e466a7919p-2, 0x1.015a93c534c87p-3}, {2, 0x1.1ad50e2598ce3p-3, 0x1.18cb9d17d8b67p-5}, {2, 0x1.236be109a16b9p-4, 0x1.460e06eb6c471p-9}}}}}},
{16, {Utils::GtoExpansion {0, {{{0, 0x1.f7a27f835ce7bp+3, -0x1.3896739c0f095p-5}, {0, 0x1.1b25a8edc037ep+2, -0x1.f6319c8fb9395p-4}, {0, 0x1.ba56b4a1f2f73p+0, -0x1.5d4a7f922b53cp-3}, {0, 0x1.a944959bcab68p-2, 0x1.a1eb61e305f6dp-3}, {0, 0x1.d871499cb08a3p-3, 0x1.e7581250f86cfp-4}, {0, 0x1.0c54b5649e674p-3, 0x1.6f6287c593a03p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.1364eaadaecdcp+4, -0x1.54cc9c5437a4dp-3}, {1, 0x1.22dc2e5190ca3p+2, -0x1.12f7cab0063fep-3}, {1, 0x1.8634e5cadaafdp-1, 0x1.54c9cf95503c3p-3}, {1, 0x1.88d17be8550d3p-2, 0x1.8b4dfa30548e7p-3}, {1, 0x1.a5d0774e60084p-3, 0x1.3ca744b5ea49bp-4}, {1, 0x1.cc4d77c892761p-4, 0x1.c27b85515aa69p-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.80ecb1c3263b3p+4, 0x1.5b4d49d5e0f6cp+2}, {2, 0x1.ede013167c9b6p+2, 0x1.5f27200a2015fp+2}, {2, 0x1.99cb42235d29cp+1, 0x1.21b1f7acfa3d2p+2}, {2, 0x1.81e5a39953085p+0, 0x1.3f4076918699dp+1}, {2, 0x1.85f6d84c16616p-1, 0x1.5c54d9f5d1de3p-1}, {2, 0x1.91ce8b9b48fabp-2, 0x1.9479fec8e93a4p-5}}}}}},
{15, {Utils::GtoExpansion {0, {{{0, 0x1.e7c57e4f78f35p+3, -0x1.312c8575f0681p-5}, {0, 0x1.123a889b7d77ep+2, -0x1.ea487482f065fp-4}, {0, 0x1.ac67f482c5db1p+0, -0x1.5501b7b334e86p-3}, {0, 0x1.9bdf7b7d282dcp-2, 0x1.9801e97fc6abbp-3}, {0, 0x1.c98fcc4bb31cep-3, 0x1.dbc913f949aedp-4}, {0, 0x1.03e10d206996cp-3, 0x1.66abe3b7b29a9p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.08cea813378dbp+4, -0x1.4480887d8eb7fp-3}, {1, 0x1.17adb7133d0d5p+2, -0x1.05d19fb2d19abp-3}, {1, 0x1.7734b96a0f48dp-1, 0x1.447dde0514f58p-3}, {1, 0x1.79b79bb6c741dp-2, 0x1.7866a4b4a9f48p-3}, {1, 0x1.95993ab1ed256p-3, 0x1.2d82c91950945p-4}, {1, 0x1.ba9b73ff00b68p-4, 0x1.acf0b26513bdap-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.e22468cf2c384p+1, 0x1.b11c50bde7164p-3}, {2, 0x1.354e0eb9b0ff5p+0, 0x1.b5e9b9a24e5c3p-3}, {2, 0x1.00a57720c9289p-1, 0x1.694556d58c669p-3}, {2, 0x1.e35c3a6ec7d3p-3, 0x1.8e214e8742383p-4}, {2, 0x1.e874676b943f6p-4, 0x1.b264ff5cf54eep-6}, {2, 0x1.f749cc98869efp-5, 0x1.f869590a0bc1bp-10}}}}}},
{14, {Utils::GtoExpansion {0, {{{0, 0x1.41c3410e9d915p+3, -0x1.bec09d6aab187p-6}, {0, 0x1.69cb6e6ebd8d7p+1, -0x1.66de8d0fe063fp-4}, {0, 0x1.1a9a10a3dba12p+0, -0x1.f33581bc0d54ep-4}, {0, 0x1.0fb213caecdaep-2, 0x1.2aa589295ff76p-3}, {0, 0x1.2dd5a77ff486ap-3, 0x1.5c41f53fd7febp-4}, {0, 0x1.56dcf11b14dc8p-4, 0x1.0688d19895719p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.d2bfc148cd8f7p+2, -0x1.d202578bc6ff6p-5}, {1, 0x1.ecf612c65141cp+0, -0x1.77fdc9196a421p-5}, {1, 0x1.4aab39e0a490cp-2, 0x1.d1fe8377a7e4dp-5}, {1, 0x1.4ce1ccaa2ff39p-3, 0x1.0e4517b902632p-4}, {1, 0x1.65742e9226a94p-4, 0x1.b0fdf86097ac2p-6}, {1, 0x1.8611cfbb69a8cp-5, 0x1.33febb511b536p-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.68c69d1918158p+3, 0x1.70bdfe33e4dc2p+0}, {2, 0x1.cee430f4f75dap+1, 0x1.74d4b06a3ee4cp+0}, {2, 0x1.8015c3489050bp+0, 0x1.339443b5a193cp+0}, {2, 0x1.69aff0c25483bp-1, 0x1.52f5de4e60f36p-1}, {2, 0x1.6d7fd32c26bcep-2, 0x1.71d5d3a2a667p-3}, {2, 0x1.789953dcaa958p-3, 0x1.ad72475b8fcfep-7}}}}}},
{1, {Utils::GtoExpansion {0, {{{0, 0x1.297723c9aadecp+5, 0x1.92ce4fd55f77fp-4}, {0, 0x1.b451d33216bf5p+2, 0x1.2ffb38956138fp-3}, {0, 0x1.e8441add89aa8p+0, 0x1.8f4172ba8ac08p-3}, {0, 0x1.4f77123bece8bp-1, 0x1.89e6278551ap-3}, {0, 0x1.048ab67eb2728p-2, 0x1.b39247af08014p-4}, {0, 0x1.ad38da6b1904dp-4, 0x1.184de099a329fp-6}}}}, boost::none, boost::none}},
{2, {Utils::GtoExpansion {0, {{{0, 0x1.fb38018e040edp+7, 0x1.a902c544e1fa2p-2}, {0, 0x1.73fdf587bf1aap+5, 0x1.40bd0d5e53934p-1}, {0, 0x1.a047a4aa54888p+3, 0x1.a543ce23f3ce5p-1}, {0, 0x1.1e01b928f2706p+2, 0x1.9f9ceb063b0ap-1}, {0, 0x1.bc42568c31631p+0, 0x1.cb952169accc8p-2}, {0, 0x1.6df0de1c93e14p-1, 0x1.27c192c5eee06p-4}}}}, Utils::GtoExpansion {1, {{{1, 0x1.39f1c5663f167p+6, 0x1.51c095de81e31p+1}, {1, 0x1.477b352df90d9p+4, 0x1.98984e42e41e3p+1}, {1, 0x1.d4b424fbc7918p+2, 0x1.a149b3f4c1e28p+1}, {1, 0x1.87daad069487ep+1, 0x1.2b37144c42d2dp+1}, {1, 0x1.665d68181ffadp+0, 0x1.bde10a561b732p-1}, {1, 0x1.52d83341ee9d1p-1, 0x1.6e948f8ff20acp-4}}}}, boost::none}},
{3, {Utils::GtoExpansion {0, {{{0, 0x1.aa528e3fa790dp+4, -0x1.1c3f2bc3101bap-5}, {0, 0x1.38bb9b1b9ea31p+2, -0x1.8ca27c60f7286p-5}, {0, 0x1.5f89e7e3aea86p+0, -0x1.7d72194fbc4dfp-5}, {0, 0x1.922aa06ed6648p-3, 0x1.2029b6d3a2afep-4}, {0, 0x1.6d0e487cab44ap-4, 0x1.0ba9a5e8313e1p-4}, {0, 0x1.5c2fa39abd49ap-5, 0x1.767ba85adb518p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.99813c7c4939cp+5, 0x1.8be9767f89b25p+0}, {1, 0x1.ab29813379351p+3, 0x1.def41611b21ddp+0}, {1, 0x1.31af73aa65fc3p+2, 0x1.e924b0428cd55p+0}, {1, 0x1.ff21194b0ea4fp+0, 0x1.5ebd2750a6325p+0}, {1, 0x1.d3723e3419faep-1, 0x1.055431b72d9f5p-1}, {1, 0x1.b9fbf4766c1dfp-2, 0x1.adb43e09d6c33p-5}}}}, boost::none}},
{4, {Utils::GtoExpansion {0, {{{0, 0x1.45a1764567fe4p+5, -0x1.86941a4f4a77p-5}, {0, 0x1.ddbd28178da2ap+2, -0x1.1081220284146p-4}, {0, 0x1.0c8286ec652a7p+1, -0x1.0611a682109f3p-4}, {0, 0x1.332e18894defdp-2, 0x1.8bf5ae11d6552p-4}, {0, 0x1.16d59bd3573ebp-3, 0x1.6fca675955521p-4}, {0, 0x1.09f2f8bd5e3c5p-4, 0x1.01490a28dd978p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.31fb0f41849e2p+3, 0x1.84f651f483387p-3}, {1, 0x1.3f2c96f8a96dep+1, 0x1.d68bc5decd3b4p-3}, {1, 0x1.c8d0729ea7ca6p-1, 0x1.e08e9591083bdp-3}, {1, 0x1.7dea077003b4cp-2, 0x1.58950246ed394p-3}, {1, 0x1.5d463c2095d91p-3, 0x1.00bdd6b5fed76p-4}, {1, 0x1.4a3fca74a45c6p-4, 0x1.a6293ec36b234p-8}}}}, boost::none}},
{5, {Utils::GtoExpansion {0, {{{0, 0x1.27bbc6a08f5cp+6, -0x1.318cca78b6fd2p-4}, {0, 0x1.b1e04a77584c3p+3, -0x1.aa5c67c547527p-4}, {0, 0x1.e7b6d70af3f31p+1, -0x1.9a089944a33a7p-4}, {0, 0x1.16fa13c9bb9f3p-1, 0x1.35c2788c3a927p-3}, {0, 0x1.fa77a9dc40e2p-3, 0x1.1fb9151846225p-3}, {0, 0x1.e3101b45e47f7p-4, 0x1.928c9201fc719p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.9ae093fc45efdp+3, 0x1.1920156f1a59bp-2}, {1, 0x1.ac97fef1a9b8cp+1, 0x1.541733649088ap-2}, {1, 0x1.32b5b84af134ap+0, 0x1.5b537de4f4f59p-2}, {1, 0x1.006bd0c7132ap-1, 0x1.f21938e92bf3bp-3}, {1, 0x1.d5034bf095c6bp-3, 0x1.731fae8d2f10ep-4}, {1, 0x1.bb7729b85bcd3p-4, 0x1.311ebecadabadp-7}}}}, boost::none}},
{6, {Utils::GtoExpansion {0, {{{0, 0x1.d046b063665bfp+6, -0x1.ac89abb522e84p-4}, {0, 0x1.5492f75767fa7p+4, -0x1.2afd066416d46p-3}, {0, 0x1.7ed5ac80da257p+2, -0x1.1f89e8952bd4ep-3}, {0, 0x1.b5f83b4ae60f7p-1, 0x1.b271217f3c228p-3}, {0, 0x1.8d8e1d14a4988p-2, 0x1.938902b2f5b9cp-3}, {0, 0x1.7b2effd40a2c5p-3, 0x1.1a4a47fffe5dap-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.1041dac49f699p+4, 0x1.8fbc08e24dccp-2}, {1, 0x1.1bff21ead167fp+2, 0x1.e393e930ea822p-2}, {1, 0x1.96777e7de4b1cp+0, 0x1.edddb30a1099p-2}, {1, 0x1.53d25eff3bf67p-1, 0x1.6220124eda112p-2}, {1, 0x1.36c7815087c83p-2, 0x1.07da1e494d342p-3}, {1, 0x1.25d9da93c0265p-3, 0x1.b1da567920eeep-7}}}}, boost::none}},
{7, {Utils::GtoExpansion {0, {{{0, 0x1.39be921c7492cp+7, -0x1.0c95b23aedbffp-3}, {0, 0x1.cc4cdfc30424bp+4, -0x1.76c7b5d251e02p-3}, {0, 0x1.02b5685aa37afp+3, -0x1.686d92d5c9c18p-3}, {0, 0x1.27f79e614eb8ap+0, 0x1.1048ffcefaa14p-2}, {0, 0x1.0ca802b1eecd3p-1, 0x1.f9d434273ad25p-3}, {0, 0x1.003dc81415094p-2, 0x1.61d9584de820ep-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.774984176ce0dp+4, 0x1.2a84ddd061032p-1}, {1, 0x1.877813b7c4782p+2, 0x1.6921f1688568fp-1}, {1, 0x1.182488d2010cfp+1, 0x1.70d0d69a2722ap-1}, {1, 0x1.d46b876cff132p-1, 0x1.087556310847ep-1}, {1, 0x1.ac6318df73dacp-2, 0x1.8a15f64bc4af6p-3}, {1, 0x1.950d77df0819fp-3, 0x1.43ff95a248b2ap-6}}}}, boost::none}},
{8, {Utils::GtoExpansion {0, {{{0, 0x1.96e7b14e7731cp+9, -0x1.cd9e9814254dap-2}, {0, 0x1.2a7d2ed355bdp+7, -0x1.4211beaa91e41p-1}, {0, 0x1.4f8703001764dp+5, -0x1.35bc5b0ac243dp-1}, {0, 0x1.7fd96b463cf42p+2, 0x1.d3fabbe811606p-1}, {0, 0x1.5c6dc80fcac88p+1, 0x1.b2afd2d63f649p-1}, {0, 0x1.4c53d5fd9abbdp+0, 0x1.3015013231813p-3}}}}, Utils::GtoExpansion {1, {{{1, 0x1.e43a7583aa17bp+4, 0x1.9a841a2fcde26p-1}, {1, 0x1.f91b8dca3f302p+2, 0x1.f09ee53b6705ap-1}, {1, 0x1.6976f31cba57p+1, 0x1.fb2fb8bc6ac9ep-1}, {1, 0x1.2e32c1680f66cp+0, 0x1.6bad37fb91fap-1}, {1, 0x1.145f0b2a954d4p-1, 0x1.0ef7f37835051p-2}, {1, 0x1.055131b6689d3p-2, 0x1.bd8dfbf892d05p-6}}}}, boost::none}},
{9, {Utils::GtoExpansion {0, {{{0, 0x1.f9a3c27b3cf45p+9, -0x1.0fa7480b1220ap-1}, {0, 0x1.72eaad82fec0dp+7, -0x1.7b0fe82d11066p-1}, {0, 0x1.a0f1408339c01p+5, -0x1.6c8bcaaf35e7dp-1}, {0, 0x1.dcfd4fe6c1d1p+2, 0x1.13656864e4ebdp+0}, {0, 0x1.b0f96e888c15dp+1, 0x1.ff9bb4b471149p-1}, {0, 0x1.9cf74e0fc96b8p+0, 0x1.65e451f15cdd8p-3}}}}, Utils::GtoExpansion {1, {{{1, 0x1.8ca6959fb5078p+5, 0x1.7c70692d7d2a3p+0}, {1, 0x1.9dc0f6e2eb45fp+3, 0x1.cc3c36c14e33ep+0}, {1, 0x1.28170f81d72ep+2, 0x1.d606de30ce18dp+0}, {1, 0x1.ef15d327e901p+0, 0x1.51080d8806d1dp+0}, {1, 0x1.c4c5fdf903ec4p-1, 0x1.f63b427c9285bp-2}, {1, 0x1.ac1c4f2421714p-2, 0x1.9ce91ab33ef2ep-5}}}}, boost::none}},
{10, {Utils::GtoExpansion {0, {{{0, 0x1.d7570079428d9p+6, -0x1.61b4e789ac146p-3}, {0, 0x1.08fd9d1540669p+5, -0x1.1c208b29ff696p-1}, {0, 0x1.9df96cb39e109p+3, -0x1.8b3cf13c6ee67p-1}, {0, 0x1.8dff88185359fp+1, 0x1.d8e4e734df24fp-1}, {0, 0x1.ba25d51015bfp+0, 0x1.13b9bd3c038a5p-1}, {0, 0x1.f63fc2aea9e96p-1, 0x1.9fb64a08c7331p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.5923cc070cac3p+6, 0x1.7c365b273c5dfp+1}, {1, 0x1.68059491280a9p+4, 0x1.cbf5fb75c1828p+1}, {1, 0x1.01a37213e8f84p+3, 0x1.d5bf2461b09bdp+1}, {1, 0x1.aeca8c487391ep+1, 0x1.50d49f3f06fddp+1}, {1, 0x1.89f9630be4016p+0, 0x1.f5ee9e96974c1p-1}, {1, 0x1.7483a0bdd0f43p-1, 0x1.9caa1829e430ep-4}}}}, boost::none}},
{11, {Utils::GtoExpansion {0, {{{0, 0x1.8aafc4ba7e823p+0, -0x1.b5df28ec23708p-8}, {0, 0x1.bbca944f5a50ep-2, -0x1.5fbc51cb699a2p-6}, {0, 0x1.5aa67bc43b048p-3, -0x1.e9491ba6b1f19p-6}, {0, 0x1.4d45b92a89ba5p-5, 0x1.24b5c4bdad972p-5}, {0, 0x1.723df2db58ddap-6, 0x1.5555ba4f926c4p-6}, {0, 0x1.a491b00aa256p-7, 0x1.0150d2228e5bbp-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.255882cbd2176p+2, -0x1.04c63c8866976p-5}, {1, 0x1.35d1dbfcef892p+0, -0x1.a4cd6fb76b538p-6}, {1, 0x1.9fa4679e366cfp-3, 0x1.04c418170a0c5p-5}, {1, 0x1.a26c92a7c63bfp-4, 0x1.2e7b236b75bcfp-5}, {1, 0x1.c14f6bcf78e1cp-5, 0x1.e498bc8e3a3bp-7}, {1, 0x1.ea4eb096ceef6p-6, 0x1.58b3c98e6988ap-10}}}}, boost::none}},
{12, {Utils::GtoExpansion {0, {{{0, 0x1.67ef1f714ed05p+2, -0x1.20f1025794f22p-6}, {0, 0x1.94b70fe5422dp+0, -0x1.d0345642a8311p-5}, {0, 0x1.3c20a00d684d4p-1, -0x1.42de46665053cp-4}, {0, 0x1.2fed6b1a0a809p-3, 0x1.824e21118f817p-4}, {0, 0x1.51a44f53a07d5p-4, 0x1.c27a5f0be0863p-5}, {0, 0x1.7f899fa8600b3p-5, 0x1.5397e89be4f11p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.3975755d5babdp+3, -0x1.50ead1f11fcf2p-4}, {1, 0x1.4b0ff782fc9c9p+1, -0x1.0fd5f81b27d2dp-4}, {1, 0x1.bc23f599f59edp-2, 0x1.50e80d5c4af17p-4}, {1, 0x1.bf1cf4f5eefbfp-3, 0x1.86cd3ef7f237bp-4}, {1, 0x1.e01deef8903d8p-4, 0x1.390be37aa3b0ap-5}, {1, 0x1.05f666e9299aep-4, 0x1.bd59e32fc8c0ep-9}}}}, boost::none}},
{71, {Utils::GtoExpansion {0, {{{0, 0x1.19ad266f85b0ep-1, 0x1.198c13fe5538cp-3}, {0, 0x1.b9f9a2c71b1ep-1, 0x1.aa646d885c252p-1}, {0, 0x1.19bdae70ac426p+1, -0x1.15bc97e94d883p+0}, {0, 0x1.06de3e2c610dfp+2, -0x1.6e1c19aa16066p-3}, {0, 0x1.a42d0f9c7d2b2p+2, 0x1.e159811be0e99p-3}, {0, 0x1.c4be699342346p+3, 0x1.df81cfad723bdp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.b937eff8b539bp-5, 0x1.ab7f07b923a4dp-9}, {1, 0x1.53aa989cc4d37p-4, 0x1.2ebd2159b5894p-5}, {1, 0x1.fe2a3c0312393p-4, 0x1.d8400fac05b77p-5}, {1, 0x1.077470007830fp-2, -0x1.bd1703d441825p-5}, {1, 0x1.ace135dfe2eafp-2, -0x1.b79e1068d7986p-5}, {1, 0x1.f1b7ce662ade3p+0, 0x1.306f405db1248p-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.17b188b23d979p+2, -0x1.3bffa36904123p-3}, {2, 0x1.b09f683841267p+0, -0x1.6ed0652f11639p-3}, {2, 0x1.d2fb2a3fe1256p-2, 0x1.87543d15ffc5ap-3}, {2, 0x1.15aa176d99653p-2, 0x1.2f3d99f0569b3p-3}, {2, 0x1.581b10a7439c5p-3, 0x1.115a4e09311b6p-5}, {2, 0x1.abd8189ab9f99p-4, 0x1.783a20b081bb9p-10}}}}}},
{13, {Utils::GtoExpansion {0, {{{0, 0x1.24ba01670a957p+4, -0x1.5df2d6287c02bp-5}, {0, 0x1.49256100a2d1bp+2, -0x1.191bbab0939c8p-3}, {0, 0x1.01197f5e3dd69p+1, -0x1.8709e9240dd62p-3}, {0, 0x1.ee5aec1213452p-2, 0x1.d3dea66ac874fp-3}, {0, 0x1.1298c73472e6ep-2, 0x1.10cbc6dc95a9ep-3}, {0, 0x1.37ec3d9157e93p-3, 0x1.9b4b91afb1777p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.f1217d9122198p+3, -0x1.2bd11c049fc39p-3}, {1, 0x1.06864cacb9f71p+2, -0x1.e3cdd06aa01ap-4}, {1, 0x1.60315ef9164e9p-1, 0x1.2bcea576ba87cp-3}, {1, 0x1.628cd2eea1f7fp-2, 0x1.5bc487a67b8dfp-3}, {1, 0x1.7cb8a978f6544p-3, 0x1.169318f2c3561p-4}, {1, 0x1.9f75c9cf12e48p-4, 0x1.8c4f6c170a2cfp-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.009b5964dceebp+2, 0x1.e3215214882bcp-3}, {2, 0x1.493ce8f71d711p+0, 0x1.e87cb6ba2111fp-3}, {2, 0x1.112f912bb5493p-1, 0x1.92fe63224acb4p-3}, {2, 0x1.01414e5e80029p-2, 0x1.bc1c1b2c2ce53p-4}, {2, 0x1.03f76ae1d37f6p-3, 0x1.e48ff641b263p-6}, {2, 0x1.0bdc79d0aaf78p-4, 0x1.1955308a29c35p-9}}}}}},
{72, {Utils::GtoExpansion {0, {{{0, 0x1.663bd85f8347cp-3, 0x1.dcd89c15a71bap-5}, {0, 0x1.190cdc72b8241p-2, 0x1.69151e761ed38p-2}, {0, 0x1.6650de9a542c2p-1, -0x1.d66477910ca45p-2}, {0, 0x1.4e5048c98e5fp+0, -0x1.3608890ef037ap-4}, {0, 0x1.0b3032193dc7p+1, 0x1.979f42247da1p-4}, {0, 0x1.1fe5e26833ap+2, 0x1.960fd050564ap-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.75b0074985e2cp-5, 0x1.5b5642e220fb5p-9}, {1, 0x1.1fadb8c98a4fap-4, 0x1.ebf1fd786507ap-6}, {1, 0x1.b014d9f8a61ecp-4, 0x1.7fb2ffdc7efd2p-5}, {1, 0x1.be4365fb2be49p-3, -0x1.69a1b5b3d9d68p-5}, {1, 0x1.6b3cc30a7bc2bp-2, -0x1.652f730a32be1p-5}, {1, 0x1.a58a1f9aada11p+0, 0x1.eeb36df08a1a7p-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.7e97a34574e17p+1, -0x1.4517af5425c82p-4}, {2, 0x1.27e458ddeff1p+0, -0x1.795ed01cc56e1p-4}, {2, 0x1.3f643318c4c27p-2, 0x1.929743d708f18p-4}, {2, 0x1.7bd117da5b727p-3, 0x1.37f7a815a7197p-4}, {2, 0x1.d6b3a4e9d0668p-4, 0x1.19382b05eb6dbp-6}, {2, 0x1.249faa18a6b4cp-4, 0x1.830de4c3ccc36p-11}}}}}},
{30, {Utils::GtoExpansion {0, {{{0, 0x1.d98dfcd80b6d2p+2, 0x1.2016f390229fcp-8}, {0, 0x1.a68c5c245cbf8p-1, -0x1.b61eb6735b856p-5}, {0, 0x1.92a116293f45p-2, -0x1.c5ca60373b821p-4}, {0, 0x1.eec677f8d0dc6p-4, 0x1.d35149a7d94a1p-4}, {0, 0x1.2890b107026edp-4, 0x1.65b162c591c21p-5}, {0, 0x1.5f636244ce9ccp-5, 0x1.b5fb0dcd6ac2dp-10}}}}, Utils::GtoExpansion {1, {{{1, 0x1.e9c23878e4401p+2, -0x1.ef2eb18e8bf37p-6}, {1, 0x1.464f2c868a9b5p+1, -0x1.37b90fb76afa4p-4}, {1, 0x1.17ff5d7d0b9eap+0, -0x1.851e12818ee61p-4}, {1, 0x1.221dbf61083fbp-2, 0x1.e922a689f2d62p-4}, {1, 0x1.452bfc1631babp-3, 0x1.3df9fb118c545p-4}, {1, 0x1.717ad0bc7ee29p-4, 0x1.163b049ae670ap-7}}}}, boost::none}},
{31, {Utils::GtoExpansion {0, {{{0, 0x1.1b007bd86e6efp+4, 0x1.14ebf8bc4fbccp-7}, {0, 0x1.f90a2e138e369p+0, -0x1.a522d7ec92358p-4}, {0, 0x1.e13b6834ec8bap-1, -0x1.b432fe3fe4e88p-3}, {0, 0x1.27aeffc2de29ap-2, 0x1.c133aa040307bp-3}, {0, 0x1.627637d14ff3dp-3, 0x1.57d3ab285f70ep-4}, {0, 0x1.a3fcd10485943p-4, 0x1.a5009126a3f82p-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.c986649b78b9ep+2, -0x1.c6c8eedb75c3dp-6}, {1, 0x1.30d54437a3fa9p+1, -0x1.1e4ace80910abp-4}, {1, 0x1.0591c0e2e2018p+0, -0x1.655f73835e039p-4}, {1, 0x1.0f05a60a07452p-2, 0x1.c13b2e54c39c8p-4}, {1, 0x1.2fc53df4d7661p-3, 0x1.24091f0dd75fdp-4}, {1, 0x1.592989f220297p-4, 0x1.ff107c497a2bp-8}}}}, boost::none}},
{32, {Utils::GtoExpansion {0, {{{0, 0x1.4f4f34222b895p+4, 0x1.3a7c0e4d29271p-7}, {0, 0x1.2b31805d17d83p+1, -0x1.de42c21cb0ba8p-4}, {0, 0x1.1d16dd1c5b406p+0, -0x1.ef5df8e6d7e17p-3}, {0, 0x1.5e55c67d53a4dp-2, 0x1.fe22287a6d923p-3}, {0, 0x1.a3fa2f860c288p-3, 0x1.86770683d3135p-4}, {0, 0x1.f19d3f9fbb05cp-4, 0x1.de1bd51785c92p-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.bec37342593acp+2, -0x1.b97400a5a49bfp-6}, {1, 0x1.29a9be4c319e5p+1, -0x1.15e654158ef4ep-4}, {1, 0x1.fed57a368627dp-1, -0x1.5ae58c7c3d8f4p-4}, {1, 0x1.08a5b717c5054p-2, 0x1.b40feda690671p-4}, {1, 0x1.28a01e0181f44p-3, 0x1.1b798aab276f8p-4}, {1, 0x1.510b2d68dcc52p-4, 0x1.f01534af9ac45p-8}}}}, boost::none}},
{33, {Utils::GtoExpansion {0, {{{0, 0x1.bae5cf09b7493p+4, 0x1.83795cf3792eep-7}, {0, 0x1.8b31813d53786p+1, -0x1.26a17790a93e2p-3}, {0, 0x1.789059100a37bp+0, -0x1.312b43e37c99ap-2}, {0, 0x1.cebe9a245513ap-2, 0x1.3a4408c7da438p-2}, {0, 0x1.155dbe28631c8p-2, 0x1.e116c135880dcp-4}, {0, 0x1.48a3dbb0d9278p-3, 0x1.26897ca6fd814p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.dc8d799dab0dbp+2, -0x1.de8c7653befb9p-6}, {1, 0x1.3d82b336d5405p+1, -0x1.2d4074effb0dcp-4}, {1, 0x1.107293680832bp+0, -0x1.780bed53bb2cp-4}, {1, 0x1.1a4b1c327fbbfp-2, 0x1.d8b46b6ccd081p-4}, {1, 0x1.3c675cd1d4233p-3, 0x1.334b997934209p-4}, {1, 0x1.678457442a07p-4, 0x1.0ce26cc28915cp-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.1f67e20be7d3bp+3, -0x1.0271490cd3fadp-4}, {2, 0x1.4cd3285bbbf74p+1, -0x1.bb80aa0673e49p-5}, {2, 0x1.b682835009253p-2, 0x1.2579a66ef8df6p-4}, {2, 0x1.b5304be2469aap-3, 0x1.45a2487eb4c41p-4}, {2, 0x1.d4b11afd69824p-4, 0x1.e5f919ae08c8dp-6}, {2, 0x1.009d90cffa4dep-4, 0x1.3cf8e92987d0ep-9}}}}}},
{34, {Utils::GtoExpansion {0, {{{0, 0x1.467d6dd1c3c58p+4, 0x1.34429c9150a3dp-7}, {0, 0x1.2352e920b3585p+1, -0x1.d4cb7c54d91f3p-4}, {0, 0x1.15973dc4d56dfp+0, -0x1.e59006540654cp-3}, {0, 0x1.551ed3a44b2b4p-2, 0x1.f409644b41ffcp-3}, {0, 0x1.98ee4ebaab063p-3, 0x1.7ebc99c249025p-4}, {0, 0x1.e4869beffa016p-4, 0x1.d4a5548ae1412p-9}}}}, Utils::GtoExpansion {1, {{{1, 0x1.3434cdcb1da05p+3, -0x1.4a10215672eb7p-5}, {1, 0x1.9ab1c181d008ep+1, -0x1.9f8e8805048d5p-4}, {1, 0x1.6067faf0359d5p+0, -0x1.035d9868f24eep-3}, {1, 0x1.6d243f59fa813p-2, 0x1.460848e1c027ap-3}, {1, 0x1.994343882a6cfp-3, 0x1.a7e4b62c7089fp-4}, {1, 0x1.d107672311efdp-4, 0x1.72e8809c8725ap-7}}}}, boost::none}},
{35, {Utils::GtoExpansion {0, {{{0, 0x1.1a19eab7f65bep+6, 0x1.86b0fe4cb9f12p-6}, {0, 0x1.f76eb6f676094p+2, -0x1.2913beee479ap-2}, {0, 0x1.dfb3569e2fab8p+1, -0x1.33b3f1cd145c9p-1}, {0, 0x1.26be19a353836p+0, 0x1.3ce00cd132398p-1}, {0, 0x1.61556e72016fp-1, 0x1.e51560585d0a8p-3}, {0, 0x1.a2a6a5117030fp-2, 0x1.28fb910b7e03ep-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.3ce105c34e22p+3, -0x1.55b6989a7c10ap-5}, {1, 0x1.a64044067c80fp+1, -0x1.ae3985e6f4a75p-4}, {1, 0x1.6a5299cae08e9p+0, -0x1.0c853c686c06bp-3}, {1, 0x1.776a9c1ed1ba1p-2, 0x1.518a5456f63cp-3}, {1, 0x1.a4c775f58f381p-3, 0x1.b6db089dbd618p-4}, {1, 0x1.de1d524540d8bp-4, 0x1.80000c2e0e4d4p-7}}}}, Utils::GtoExpansion {2, {{{2, 0x1.571655e2d5574p+3, -0x1.60558f3b3fdadp-4}, {2, 0x1.8d4e41a0effffp+1, -0x1.2e5029d840e47p-4}, {2, 0x1.05bba1ed084a5p-1, 0x1.90181d6508c79p-4}, {2, 0x1.04f1c2f4e5096p-2, 0x1.bbefa5ff74e6cp-4}, {2, 0x1.17bf657fb261fp-3, 0x1.4b4359816605dp-5}, {2, 0x1.3254e9b4ae1ffp-4, 0x1.b020b56d01fdp-9}}}}}},
{36, {Utils::GtoExpansion {0, {{{0, 0x1.36d05beee0918p+1, 0x1.e9cc6bf230af3p-9}, {0, 0x1.bfb26ba70ec47p-1, 0x1.86b5b8b07cce5p-7}, {0, 0x1.45d960f401465p-2, -0x1.da609bce3255bp-6}, {0, 0x1.7633b45895e94p-3, -0x1.a849f8be1dddp-4}, {0, 0x1.02d395050a07bp-4, 0x1.9028f1a2fa541p-4}, {0, 0x1.3841e68e393f6p-5, 0x1.38ac02cacb502p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.81a6db293ec97p+5, -0x1.34de715a6d5ecp-2}, {1, 0x1.00f24a876e67ep+4, -0x1.84df77f785626p-1}, {1, 0x1.b8f54a24dce1cp+2, -0x1.e56c1c8898846p-1}, {1, 0x1.c8e4ca7c2a5d6p+0, 0x1.3118dab931d78p+0}, {1, 0x1.000cffd5308a5p+0, 0x1.8cac9bbe362d1p-1}, {1, 0x1.22f0b5ce0f0cap-1, 0x1.5b17633e1d73bp-4}}}}, boost::none}},
{37, {Utils::GtoExpansion {0, {{{0, 0x1.5682d873f5745p+5, 0x1.0766c4f66835bp-5}, {0, 0x1.ed5a8aeb299d1p+3, 0x1.a43a6142df1bfp-4}, {0, 0x1.671464ab09bc2p+2, -0x1.fe3777bee8349p-3}, {0, 0x1.9c5d13b6a424cp+1, -0x1.c858140dcebe2p-1}, {0, 0x1.1d38d264a63e2p+0, 0x1.ae646003907cep-1}, {0, 0x1.581a12c69eap-1, 0x1.504b5991a2569p-3}}}}, Utils::GtoExpansion {1, {{{1, 0x1.af1bcedccbe86p+2, 0x1.d7b19b3789032p-10}, {1, 0x1.3f60375f0d8d8p-1, -0x1.7a22bf24fed21p-6}, {1, 0x1.3341eaf99a42ep-2, -0x1.6621c292ca297p-5}, {1, 0x1.8a98e85957409p-4, 0x1.659d3c743ee11p-5}, {1, 0x1.e624fcfcb9b64p-5, 0x1.463432f2bace6p-6}, {1, 0x1.2d64baab17ea4p-5, 0x1.6a8ea37d77433p-10}}}}, boost::none}},
{38, {Utils::GtoExpansion {0, {{{0, 0x1.b3bb25797937ep+2, 0x1.0951b0d49c8cep-7}, {0, 0x1.39d05d3ce01f6p+1, 0x1.a749974b094b8p-6}, {0, 0x1.c8cf198823ed1p-1, -0x1.00f732e0ada77p-4}, {0, 0x1.064c2866cf813p-1, -0x1.cbaa99ffc7d62p-3}, {0, 0x1.6ad9871d02398p-3, 0x1.b186879525081p-3}, {0, 0x1.b5c135345987ap-4, 0x1.52be20958216cp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.69f25847413a9p+3, 0x1.c2ce6931c0bbdp-9}, {1, 0x1.0c2393272a642p+0, -0x1.696423dd15288p-5}, {1, 0x1.01f6f8f1a08dcp-1, -0x1.5645eb9bc0db2p-4}, {1, 0x1.4b4af352bef58p-3, 0x1.55c743cd135cdp-4}, {1, 0x1.98273943ac29fp-4, 0x1.37c24cc447f39p-5}, {1, 0x1.fa153bbe6e9a1p-5, 0x1.5a80a208b07dep-9}}}}, boost::none}},
{39, {Utils::GtoExpansion {0, {{{0, 0x1.fc66c90449702p-2, 0x1.29dbbc597e983p-10}, {0, 0x1.6e26b91feb3ebp-3, 0x1.db334316937c6p-9}, {0, 0x1.0a7f55487758bp-4, -0x1.207af99aff2dap-7}, {0, 0x1.320b02ba42bp-5, -0x1.0205380da3f59p-5}, {0, 0x1.a75d7b4266bd5p-7, 0x1.e6b1a33868cbp-6}, {0, 0x1.fec33f8060fc5p-8, 0x1.7c49672522288p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.0c98fac8fa547p+3, 0x1.36800c42d56ddp-9}, {1, 0x1.8df7a4129d21fp-1, -0x1.f1d40042420e1p-6}, {1, 0x1.7eddef0d8b6efp-2, -0x1.d77e0dbc22734p-5}, {1, 0x1.ebb2fd0464325p-4, 0x1.d6cf94e1f094p-5}, {1, 0x1.2ee3175f1ba74p-4, 0x1.ad754aa787b51p-6}, {1, 0x1.778f55c02f8edp-5, 0x1.dd51868c47e5ap-10}}}}, Utils::GtoExpansion {2, {{{2, 0x1.942c0cb700e23p+3, -0x1.d5571cfc7d883p-4}, {2, 0x1.d40b370e0282ep+1, -0x1.92b531eecb6e9p-4}, {2, 0x1.345543ee6adbcp-1, 0x1.0a7afb737ea9dp-3}, {2, 0x1.336773cd60203p-2, 0x1.27ae59e1deb62p-3}, {2, 0x1.498e20fb6f73dp-3, 0x1.b9458ca5bce2dp-5}, {2, 0x1.68df549c0d8d1p-4, 0x1.1fd0f095b831ep-8}}}}}},
{40, {Utils::GtoExpansion {0, {{{0, 0x1.028c6f35b23bep+2, 0x1.66bfdc5cfed1fp-8}, {0, 0x1.7469f36393c58p+0, 0x1.1e2c337479c6bp-6}, {0, 0x1.0f0e3789707f7p-1, -0x1.5b745027a77a2p-5}, {0, 0x1.37470c73992fp-2, -0x1.36c476aa63844p-3}, {0, 0x1.ae9b39ba1258cp-4, 0x1.251824b18ab81p-3}, {0, 0x1.03bfd5ccf92e1p-4, 0x1.ca075645a4ab9p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.5b5c302f41c11p+3, 0x1.ac365c3e5a72dp-9}, {1, 0x1.01553851897e7p+0, -0x1.5747538a3e241p-5}, {1, 0x1.ef232ae823b81p-2, -0x1.451e665bea8b3p-4}, {1, 0x1.3df10bc6ca433p-3, 0x1.44a617997e123p-4}, {1, 0x1.87b45c2a720bap-4, 0x1.28224a2cd5098p-5}, {1, 0x1.e5b00a9d9d95fp-5, 0x1.4922d91667a3cp-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.6c52111c1707bp+3, -0x1.87600bef491c5p-4}, {2, 0x1.a5e50088631ebp+1, -0x1.4fcfba555de72p-4}, {2, 0x1.15ee6b8c9df5ap-1, 0x1.bc6d62a1307a3p-4}, {2, 0x1.15180e386ea3ep-2, 0x1.ed208f8d96c18p-4}, {2, 0x1.290f99fce8413p-3, 0x1.6ff81f6065f1bp-5}, {2, 0x1.454a4df5dc45p-4, 0x1.e002a8c5fbdafp-9}}}}}},
{41, {Utils::GtoExpansion {0, {{{0, 0x1.f4c1fc0b3ca7p+2, 0x1.267e487de3621p-7}, {0, 0x1.68a56ef1df116p+1, 0x1.d5d4e8c08001fp-6}, {0, 0x1.067d9a99d4d6bp+0, -0x1.1d38a51ece6a2p-4}, {0, 0x1.2d7112bde526cp-1, -0x1.fe35f7c752489p-3}, {0, 0x1.a0fffac3b2d7bp-3, 0x1.e1320b13cb189p-3}, {0, 0x1.f7155bfeae3e9p-4, 0x1.77fd8dfd5ed6cp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.d12a93d83265ap+2, 0x1.035cc8f22f8bap-9}, {1, 0x1.589b4b6a10c7bp-1, -0x1.9fd6a524c42d6p-6}, {1, 0x1.4b87e9edc1a2p-2, -0x1.89d70f9b55a9ap-5}, {1, 0x1.a9c544feef7b8p-4, 0x1.894552d20907ep-5}, {1, 0x1.0646673e06ce6p-4, 0x1.66ba8a2edda3p-6}, {1, 0x1.4534217b6e9d8p-5, 0x1.8eb4e5337f8bdp-10}}}}, Utils::GtoExpansion {2, {{{2, 0x1.21e768ef54b7ep+4, -0x1.b9479fb5be13dp-3}, {2, 0x1.4fb7bfea7947ep+2, -0x1.7aa18cae84ddbp-3}, {2, 0x1.ba5245a670aa5p-1, 0x1.f518bb2b1d102p-3}, {2, 0x1.b8fd1da1c8b36p-2, 0x1.1600cdbb3d827p-2}, {2, 0x1.d8c4065041cebp-3, 0x1.9ee3aa0af8299p-4}, {2, 0x1.02d894334ca1p-3, 0x1.0e9bc4b531f9ep-7}}}}}},
{42, {Utils::GtoExpansion {0, {{{0, 0x1.95f0a00ad3582p+0, 0x1.63cee7f0da4fdp-9}, {0, 0x1.245bbc74458a2p-1, 0x1.1bd3929d21697p-7}, {0, 0x1.a993a7b56d359p-3, -0x1.589b109ad2731p-6}, {0, 0x1.e8ba6ccbb072bp-4, -0x1.3438370738492p-4}, {0, 0x1.520aa296bf8fep-5, 0x1.22b0fcd7e6ae5p-4}, {0, 0x1.97d3443ca82e9p-6, 0x1.c646030a137b7p-7}}}}, Utils::GtoExpansion {1, {{{1, 0x1.b901f7a828848p+2, 0x1.e545688ee993ep-10}, {1, 0x1.46b5956dd642bp-1, -0x1.85052426c37ecp-6}, {1, 0x1.3a500cfb83fap-2, -0x1.7070c0377cfa7p-5}, {1, 0x1.93a871d523cd9p-4, 0x1.6fe8698f3ba5dp-5}, {1, 0x1.f14ea95814296p-5, 0x1.4f97eb83af687p-6}, {1, 0x1.345064549ab3dp-5, 0x1.74fe3d0d9d564p-10}}}}, Utils::GtoExpansion {2, {{{2, 0x1.ef152f8eaf14dp+3, -0x1.4eb2a89d8aae6p-3}, {2, 0x1.1ea91d5feac1ap+2, -0x1.1f2e3ed9faa6ep-3}, {2, 0x1.79afc6c06fd2cp-1, 0x1.7c113491a691cp-3}, {2, 0x1.788c78d0bc6a5p-2, 0x1.a5b6eff086094p-3}, {2, 0x1.93aea84ac0453p-3, 0x1.3aae75aceab65p-4}, {2, 0x1.ba0b2c68fa086p-4, 0x1.9a7f50174ed46p-8}}}}}},
{43, {Utils::GtoExpansion {0, {{{0, 0x1.595ed164b0c0ep+2, 0x1.bdc1de50bd946p-8}, {0, 0x1.f178e08ddfd9fp+0, 0x1.639410f8af9acp-6}, {0, 0x1.6a13c61eb9c7p-1, -0x1.afb907ecbbb8ap-5}, {0, 0x1.9fce54594a869p-2, -0x1.82235e074da0ep-3}, {0, 0x1.1f9a5ceb9cffbp-3, 0x1.6c2dc26cadf7cp-3}, {0, 0x1.5af971fe41b24p-4, 0x1.1c8eb12453c7dp-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.10a1e6460e1f5p+7, 0x1.3c576a7ee7befp-4}, {1, 0x1.93f210d01a67ep+3, -0x1.fb318a3d982b9p-1}, {1, 0x1.849e49d09f285p+2, -0x1.e05cc283f82abp+0}, {1, 0x1.f315de5ba8ff8p+0, 0x1.dfab0167f5debp+0}, {1, 0x1.336fe0000c98dp+0, 0x1.b5898fa1f7a8dp-1}, {1, 0x1.7d3396ee3e817p-1, 0x1.e64c4a40e8515p-5}}}}, Utils::GtoExpansion {2, {{{2, 0x1.cf35e9d6d6d44p+3, -0x1.29e7ec1b436bap-3}, {2, 0x1.0c34c4f479a1ap+2, -0x1.ff39626a7f50fp-4}, {2, 0x1.615f43f29cafap-1, 0x1.5249bafdd3d35p-3}, {2, 0x1.604eb6e3d9fa6p-2, 0x1.775b767697585p-3}, {2, 0x1.79b1b8e6e6d9bp-3, 0x1.1817014c78826p-4}, {2, 0x1.9d9604cba1dfcp-4, 0x1.6d5f810640a4p-8}}}}}},
{44, {Utils::GtoExpansion {0, {{{0, 0x1.80526f9be88f2p+1, 0x1.1f2a97ee5e859p-8}, {0, 0x1.14ca01f6645dp+0, 0x1.ca2473d5c4277p-7}, {0, 0x1.92e9c1a71d321p-2, -0x1.162002c299c88p-5}, {0, 0x1.ceb394c4f38dfp-3, -0x1.f18453f643531p-4}, {0, 0x1.400a1b40a7c23p-4, 0x1.d53935461ee17p-4}, {0, 0x1.821b5ff11b178p-5, 0x1.6ea2cade1ab75p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.cf6b5b55db108p+6, 0x1.02253c591bbabp-4}, {1, 0x1.574ffb84adca5p+3, -0x1.9de32292d38eap-1}, {1, 0x1.4a492c4681451p+2, -0x1.87fdf9c2feca6p+0}, {1, 0x1.a82becb714a7bp+0, 0x1.876cec0972c2cp+0}, {1, 0x1.054a3f1d8b99ep+0, 0x1.650ba174894ep-1}, {1, 0x1.43fb791f5a01bp-1, 0x1.8cd5f6d86111ep-5}}}}, Utils::GtoExpansion {2, {{{2, 0x1.44ddd499aa1b4p+4, -0x1.0d4aae2516f1dp-2}, {2, 0x1.78349d5b46b75p+2, -0x1.ce1ed66444856p-3}, {2, 0x1.efaa63babd7cep-1, 0x1.31cb8787acf51p-2}, {2, 0x1.ee2c16f0198e1p-2, 0x1.534dc2ee7e09ep-2}, {2, 0x1.08e4095cddcd5p-2, 0x1.fa5fb076890dap-4}, {2, 0x1.22101fef3689p-3, 0x1.4a474e3e3c7f1p-7}}}}}},
{45, {Utils::GtoExpansion {0, {{{0, 0x1.3cd864d8012d9p+1, 0x1.f0e8ea412f8b7p-9}, {0, 0x1.c86273873df12p-1, 0x1.8c61eb8416515p-7}, {0, 0x1.4c2c1ab1fc7cp-2, -0x1.e143c8ccc6cb2p-6}, {0, 0x1.7d76a214599d6p-3, -0x1.ae72fa4ab3421p-4}, {0, 0x1.07d95bb8fbf91p-4, 0x1.95f84447a1211p-4}, {0, 0x1.3e511b3e317a1p-5, 0x1.3d36280bda75fp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.18430aeaf0b54p+6, 0x1.1359116eb7b8fp-5}, {1, 0x1.9f3ff0396fc21p+2, -0x1.b977d83568891p-2}, {1, 0x1.8f7e5b3894421p+1, -0x1.a21d2a2dded79p-1}, {1, 0x1.0086a99232f07p+0, 0x1.a18271e98ad79p-1}, {1, 0x1.3c0a5bdaf32fp-1, 0x1.7cd6a5b349c49p-2}, {1, 0x1.87de86070c21cp-2, 0x1.a747c8d934f08p-6}}}}, Utils::GtoExpansion {2, {{{2, 0x1.3818127859a07p+5, -0x1.a6317e5c07797p-1}, {2, 0x1.696a220b53758p+3, -0x1.6a411b161fd25p-1}, {2, 0x1.dc2d8d0ac5a1fp+0, 0x1.df6c455bee6a7p-1}, {2, 0x1.dabe4812833d5p-1, 0x1.09fa937df848p+0}, {2, 0x1.fcf3dc235d22p-2, 0x1.8cf1bef8fc384p-2}, {2, 0x1.16a8a95ac7a36p-2, 0x1.02e76b5bb46a7p-5}}}}}},
{46, {Utils::GtoExpansion {0, {{{0, 0x1.f07ab17faf014p+1, 0x1.5bf7899136133p-8}, {0, 0x1.65909a84b92f5p+0, 0x1.15924e013f609p-6}, {0, 0x1.043f777607de2p-1, -0x1.5102e5c6215c7p-5}, {0, 0x1.2addbd549bb39p-2, -0x1.2d6d53ed43645p-3}, {0, 0x1.9d6fe39f1a559p-4, 0x1.1c48fd6661641p-3}, {0, 0x1.f2c8fb34a91c1p-5, 0x1.bc43215b1c3d9p-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.4391fb1daa4d4p+2, 0x1.49863977501f1p-10}, {1, 0x1.df6ae3db05595p-2, -0x1.082a33d69f145p-6}, {1, 0x1.cd3a018a51105p-3, -0x1.f461621e2a1fdp-6}, {1, 0x1.282aa0fa35f87p-4, 0x1.f3a838ae79121p-6}, {1, 0x1.6ce0ab5936b51p-5, 0x1.c7c5512361b2ap-7}, {1, 0x1.c46c8f632064cp-6, 0x1.fa903c93d75e3p-11}}}}, Utils::GtoExpansion {2, {{{2, 0x1.6d6268a57ca63p+4, -0x1.4aca22a9746f2p-2}, {2, 0x1.a72061ebf0975p+2, -0x1.1bd3c45f882e7p-2}, {2, 0x1.16be2ee488d21p+0, 0x1.77a10edfbb37fp-2}, {2, 0x1.15e73151b11b8p-1, 0x1.a0ca4ac87d74cp-2}, {2, 0x1.29edaa23d2bdap-2, 0x1.3701c5a8090cdp-3}, {2, 0x1.463d78512f299p-3, 0x1.95b4332cbc1a1p-7}}}}}},
{47, {Utils::GtoExpansion {0, {{{0, 0x1.66d4e226cbe53p+2, 0x1.cab9a91881174p-8}, {0, 0x1.026e4c5ddd39fp+1, 0x1.6dec3f7b9522cp-6}, {0, 0x1.783089d8ca4b6p-1, -0x1.bc484cee1d8cep-5}, {0, 0x1.b003316df972p-2, -0x1.8d5f24d4b1be8p-3}, {0, 0x1.2ad0083266549p-3, 0x1.76c5fe1e3783dp-3}, {0, 0x1.687f83f177b92p-4, 0x1.24d5f14569aa9p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.c1af93ec69e55p+0, 0x1.5f997ac7b192fp-12}, {1, 0x1.4d23683e55021p-3, -0x1.19dc8f62bce94p-8}, {1, 0x1.407f6ce0da8p-4, -0x1.0af3633cefa68p-7}, {1, 0x1.9b99e72fd1fc1p-6, 0x1.0a909ac80574cp-7}, {1, 0x1.fb17e2acc8b1ep-7, 0x1.e64daa5e7f4bap-9}, {1, 0x1.3a618c39de684p-7, 0x1.0e3fd53a0fdcep-12}}}}, Utils::GtoExpansion {2, {{{2, 0x1.4e7b13abd3f07p+7, -0x1.51034387afebdp+3}, {2, 0x1.8356d07d6a0aep+5, -0x1.212ab7da94dc3p+3}, {2, 0x1.fe55a3cf318bcp+2, 0x1.7eb223d1ff291p+3}, {2, 0x1.fccc06a53e424p+1, 0x1.a8a19c814260ep+3}, {2, 0x1.10bae55eba35ap+1, 0x1.3cdb9fd9d247dp+2}, {2, 0x1.2aa5b17ee95bcp+0, 0x1.9d5620408a511p-2}}}}}},
{48, {Utils::GtoExpansion {0, {{{0, 0x1.59c973465144ep+1, 0x1.0949e0b8c34ccp-8}, {0, 0x1.f2127879dda6dp-1, 0x1.a73d2056e408p-7}, {0, 0x1.6a8390808db5ap-2, -0x1.00efa1bddb808p-5}, {0, 0x1.a04eb56b7a811p-3, -0x1.cb9d10cd7ad2ep-4}, {0, 0x1.1ff328e60d7acp-4, 0x1.b179c3730bd18p-4}, {0, 0x1.5b6492a7a3795p-5, 0x1.52b426f8ac0bfp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.cf490984ad13fp+3, 0x1.32e09d7979ea3p-8}, {1, 0x1.57368ec4fa2adp+0, -0x1.ec0509dfd4a48p-5}, {1, 0x1.4a30b67e5fb1cp-1, -0x1.d1fdc0de19debp-4}, {1, 0x1.a80c82fbe6cf4p-3, 0x1.d1515125515ecp-4}, {1, 0x1.0536e56718b31p-3, 0x1.a8728b193d1e4p-5}, {1, 0x1.43e37ad8d4b55p-4, 0x1.d7bfd2cdea13ep-9}}}}, boost::none}},
{49, {Utils::GtoExpansion {0, {{{0, 0x1.71600c66fd7e4p+2, 0x1.d4cc3365165dep-8}, {0, 0x1.0a063d578fc16p+1, 0x1.75f5230015ec8p-6}, {0, 0x1.833e45b0ed098p-1, -0x1.c609a8001d65p-5}, {0, 0x1.bcb4d4eddd156p-2, -0x1.9618cf3c63327p-3}, {0, 0x1.3397ba952c30fp-3, 0x1.7f00a19cad3eap-3}, {0, 0x1.7317375c37a82p-4, 0x1.2b44004c62db5p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.0c4d82ea6a7dbp+4, 0x1.70be159a3dbd6p-8}, {1, 0x1.8d87d2ce6eda1p+0, -0x1.279ab5243eb34p-4}, {1, 0x1.7e725bf093b1dp-1, -0x1.17f76bb46d60dp-3}, {1, 0x1.eb28d5be858bp-3, 0x1.178fd24159edp-3}, {1, 0x1.2e8dfd1a8da3p-3, 0x1.fe039edc5ee3bp-5}, {1, 0x1.7725d038ecc2fp-4, 0x1.1b6d09e9fa324p-8}}}}, boost::none}},
{50, {Utils::GtoExpansion {0, {{{0, 0x1.0072bb915d22ap+3, 0x1.2bd4caeedab7dp-7}, {0, 0x1.716371b1a8dcap+1, 0x1.de590661fddf4p-6}, {0, 0x1.0cda812b5b15cp+0, -0x1.2264216441e4bp-4}, {0, 0x1.34bfafd518a1ap-1, -0x1.03bab9bed296dp-2}, {0, 0x1.ab1bb2450cb2bp-3, 0x1.e9eae3b080335p-3}, {0, 0x1.01a3a2dc07886p-3, 0x1.7ece3a4ec1ee2p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.0009e3df20ae2p+4, 0x1.5bcb948915efep-8}, {1, 0x1.7b5c01ae01e94p+0, -0x1.16cfd4237e4ecp-4}, {1, 0x1.6cf70cd602797p-1, -0x1.080ff5380430bp-3}, {1, 0x1.d4b56469de06p-3, 0x1.07ae3e61e003ap-3}, {1, 0x1.20b98f3a9ec8fp-3, 0x1.e10aa5fffb02dp-5}, {1, 0x1.65ffea7034239p-4, 0x1.0b53442b5c515p-8}}}}, boost::none}},
{51, {Utils::GtoExpansion {0, {{{0, 0x1.0201eef565a57p+3, 0x1.2d3293be5e1d5p-7}, {0, 0x1.73a274229ff16p+1, 0x1.e0871148d39fp-6}, {0, 0x1.0e7d04224e682p+0, -0x1.23b6e6e9d70e4p-4}, {0, 0x1.36a04d2cc60cbp-1, -0x1.04e9ba1dfa9e2p-2}, {0, 0x1.adb48e343d285p-3, 0x1.ec266dea4c923p-3}, {0, 0x1.0334b0e10b323p-3, 0x1.808ccf782c844p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.7c1af8fa85a05p+3, 0x1.df4099cb29b17p-9}, {1, 0x1.1997646c3653dp+0, -0x1.8031f1e220c1bp-5}, {1, 0x1.0ee81e3fb8f61p-1, -0x1.6bdee5de3aa36p-4}, {1, 0x1.5be9e0c15975bp-3, 0x1.6b58401b1401fp-4}, {1, 0x1.aca14d0d8a4bcp-4, 0x1.4b6e5c72dead9p-5}, {1, 0x1.09bc87eabe6b7p-4, 0x1.705dee1bd33d1p-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.572cda599c51bp+2, -0x1.c40170b988a7cp-3}, {2, 0x1.096843a1c216fp+1, -0x1.06589bd9c938bp-2}, {2, 0x1.1e7c5322f6363p-1, 0x1.17e11ab6e06aep-2}, {2, 0x1.54af8361d64bdp-2, 0x1.b1c1b02896123p-3}, {2, 0x1.a634fe82a53cp-3, 0x1.87013e505ec24p-5}, {2, 0x1.0679c82cc9c92p-3, 0x1.0d140ddf7712bp-9}}}}}},
{52, {Utils::GtoExpansion {0, {{{0, 0x1.5a32c0a3b5a98p+3, 0x1.77826730b2bb5p-7}, {0, 0x1.f2aa25eacc974p+1, 0x1.2b8abecac789ap-5}, {0, 0x1.6af1f5e54c8aap+0, -0x1.6bafc4e3205f4p-4}, {0, 0x1.a0cd7c8755ac3p-1, -0x1.45492786c9d3ap-2}, {0, 0x1.204ad950dfffbp-2, 0x1.32c977f60d77ap-2}, {0, 0x1.5bce5d37ede4fp-3, 0x1.df6d3b06529e4p-5}}}}, Utils::GtoExpansion {1, {{{1, 0x1.6a70fe475fcd5p+3, 0x1.c3939f02d8d41p-9}, {1, 0x1.0c81662a9067ep+0, -0x1.6a023c13ba883p-5}, {1, 0x1.02513c953ec5dp-1, -0x1.56dba6ca83182p-4}, {1, 0x1.4bbedf72e4034p-3, 0x1.565cc793adf96p-4}, {1, 0x1.98b60a4c273e4p-4, 0x1.384aaeab50ad4p-5}, {1, 0x1.fac651008f14dp-5, 0x1.5b1836dc7afacp-9}}}}, boost::none}},
{53, {Utils::GtoExpansion {0, {{{0, 0x1.c89babc4a1af3p+4, 0x1.849f3954c88aep-6}, {0, 0x1.48d97efd915b8p+3, 0x1.360076f13cdbbp-4}, {0, 0x1.deb228b3d000dp+1, -0x1.7862e6cc77d38p-3}, {0, 0x1.12dd6839e4bcp+1, -0x1.50a501d80ee1ep-1}, {0, 0x1.7c3c1d94c07fep-1, 0x1.3d7ff42fcb923p-1}, {0, 0x1.caba8ddbce5dbp-2, 0x1.f02b01eeb5be4p-4}}}}, Utils::GtoExpansion {1, {{{1, 0x1.bc62d53e742e3p+3, 0x1.234f420f59669p-8}, {1, 0x1.49364c1e81fdep+0, -0x1.d30f4655f3d62p-5}, {1, 0x1.3cb87404a688ap-1, -0x1.ba5a041dcfdb6p-4}, {1, 0x1.96c0103343ff8p-3, 0x1.b9b653caf330fp-4}, {1, 0x1.f51defd794acep-4, 0x1.92ea53bfedb2fp-5}, {1, 0x1.36ad07c452c56p-4, 0x1.bfd14e979e085p-9}}}}, Utils::GtoExpansion {2, {{{2, 0x1.8cff5d261d8cap+1, -0x1.5ad07d93893e3p-4}, {2, 0x1.3308630fed00fp+0, -0x1.9295d8cdfddd3p-4}, {2, 0x1.4b6abed03ceffp-2, 0x1.ad7db417e75dcp-4}, {2, 0x1.8a1e10f13d3d2p-3, 0x1.4ccff408b91dbp-4}, {2, 0x1.e86ca355f4bd9p-4, 0x1.2c0282c927bd9p-6}, {2, 0x1.2fa433af6427p-4, 0x1.9cea92e157cb5p-11}}}}}},
{54, {Utils::GtoExpansion {0, {{{0, 0x1.1e9f644adbd9ep-3, 0x1.93667a5ada1ebp-5}, {0, 0x1.c1bc7b21e093ap-3, 0x1.317791a606878p-2}, {0, 0x1.1eb0369c77b2cp-1, -0x1.8df0ce211001cp-2}, {0, 0x1.0b7bef3434e44p+0, -0x1.0647dcee29e53p-4}, {0, 0x1.ab8de92cba2afp+0, 0x1.58d6a4987a556p-4}, {0, 0x1.ccb1aaae6a4f9p+1, 0x1.5784b8f18cecp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.d8d1164de8cf4p+3, 0x1.3aca209e0d324p-8}, {1, 0x1.5e4634e05e8d5p+0, -0x1.f8b4902a219a4p-5}, {1, 0x1.50fbc5c543a8fp-1, -0x1.de017ad6d8baap-4}, {1, 0x1.b0c5e8da52d16p-3, 0x1.dd5098f808a23p-4}, {1, 0x1.0a96abc4eaa3ep-3, 0x1.b3641079e3ecap-5}, {1, 0x1.4a8d597b84b2dp-4, 0x1.e3e98e38bf85bp-9}}}}, boost::none}},
{55, {Utils::GtoExpansion {0, {{{0, 0x1.4dbdc2c17ed35p-1, 0x1.3fbd37c74012bp-3}, {0, 0x1.05d5b3d92c381p+0, 0x1.e43b86fb5de56p-1}, {0, 0x1.4dd159005d5a6p+1, -0x1.3b69688e4cee1p+0}, {0, 0x1.3774de77adb74p+2, -0x1.9fc5ccd8ec6b6p-3}, {0, 0x1.f1d751f8559d6p+2, 0x1.115289f64c128p-2}, {0, 0x1.0c36df09d31e8p+4, 0x1.1046b320db7bep-4}}}}, Utils::GtoExpansion {1, {{{1, 0x1.8aaf30df72705p-5, 0x1.73e6affdbdb83p-9}, {1, 0x1.2fd7b8b3d6351p-4, 0x1.075e408da4d58p-5}, {1, 0x1.c85bf50549d8ep-4, 0x1.9ad5c0bddb418p-5}, {1, 0x1.d7567f3455117p-3, -0x1.8334eff90e213p-5}, {1, 0x1.7fa59b4e877ddp-2, -0x1.7e722d76d5611p-5}, {1, 0x1.bd3997dcc1da8p+0, 0x1.08d7eaaa992e1p-7}}}}, boost::none}},
{56, {Utils::GtoExpansion {0, {{{0, 0x1.25178168dd42cp-5, 0x1.220fecb005c61p-6}, {0, 0x1.cbe311e87db19p-5, 0x1.b749b88b3beefp-4}, {0, 0x1.2528b4ec81a7ep-3, -0x1.1e22f0072f319p-3}, {0, 0x1.1185771daf4f1p-2, -0x1.792ea9aa3820bp-6}, {0, 0x1.b53455026af0fp-2, 0x1.efe84c510ed1ep-6}, {0, 0x1.d71791e698447p-1, 0x1.ee0256db28179p-8}}}}, Utils::GtoExpansion {1, {{{1, 0x1.33c9e1e920b6cp-5, 0x1.108a53975d10cp-9}, {1, 0x1.d9e4e9f15e409p-5, 0x1.82021ca68b7cap-6}, {1, 0x1.63e2833aaf66p-4, 0x1.2d127dfae3ebp-5}, {1, 0x1.6f90d2041e05ep-3, -0x1.1bc1bcef328a9p-5}, {1, 0x1.2b2e64b582c79p-2, -0x1.1844981a9dadap-5}, {1, 0x1.5b33b312c3894p+0, 0x1.842ba3c6b953bp-8}}}}, boost::none}},
{57, {Utils::GtoExpansion {0, {{{0, 0x1.0d0942c02138p-3, 0x1.80b0bfe7facep-5}, {0, 0x1.a6243d36fcecbp-3, 0x1.234ca3d42c797p-2}, {0, 0x1.0d190cd824cd5p-1, -0x1.7b7be6ca92ccep-2}, {0, 0x1.f624d7fceb89ep-1, -0x1.f43b6797a6c78p-5}, {0, 0x1.915217850ba78p+0, 0x1.48d83e051a96ap-4}, {0, 0x1.b06d4e3fa0f74p+1, 0x1.4795fea11719bp-6}}}}, Utils::GtoExpansion {1, {{{1, 0x1.d4e8c60682e19p-6, 0x1.83e624232fe2ep-10}, {1, 0x1.68fbd870b591fp-5, 0x1.12b284a18a9a8p-6}, {1, 0x1.0f17664320547p-4, 0x1.ac81f4512c588p-6}, {1, 0x1.17fd3be8ac436p-3, -0x1.93dcf0b6f90f3p-6}, {1, 0x1.c7cbce3fbf547p-3, -0x1.8ee5c0f73e352p-6}, {1, 0x1.087a3215ca623p+0, 0x1.143c6daa57419p-8}}}}, Utils::GtoExpansion {2, {{{2, 0x1.41e9ab2ef42b1p+1, -0x1.e09b77f90f6d6p-5}, {2, 0x1.f1ed26baf9cb2p-1, -0x1.16f258f19cb6fp-4}, {2, 0x1.0cbc4ea8ca57cp-2, 0x1.2996dcd6ea245p-4}, {2, 0x1.3f93d136b18f3p-3, 0x1.cd3419cdf4eb6p-5}, {2, 0x1.8c0c447ff5787p-4, 0x1.9fbf1f298c97ap-7}, {2, 0x1.ec6d2ef979988p-5, 0x1.1e1ad90447ba4p-11}}}}}},
};
// clang-format on
}
} // namespace Sto6g
} // namespace Sparrow
} // namespace Scine
| 556.841121 | 988 | 0.729717 | qcscine |
627b5d30a69101c87233a69fde12f17eee36e414 | 180 | cpp | C++ | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | plasma_lambda/test2.cpp | plasma-effect/plasma_lambda | e2113076cd792e76237bd4f37869c6f39534d16f | [
"BSL-1.0"
] | null | null | null | #include"test.hpp"
#if TEST_CODE == 2
#include<iostream>
void test()
{
using namespace plasma::lambda;
auto func = _<1>();
std::cout << func(1, 2, 3) << std::endl;
}
#endif | 12 | 41 | 0.616667 | plasma-effect |
627e9e077e239b744c2577b3a674ac3d1113e855 | 11,551 | cpp | C++ | src/qt/qtwebkit/Source/JavaScriptCore/runtime/JSCJSValue.cpp | viewdy/phantomjs | eddb0db1d253fd0c546060a4555554c8ee08c13c | [
"BSD-3-Clause"
] | 1 | 2015-05-27T13:52:20.000Z | 2015-05-27T13:52:20.000Z | src/qt/qtwebkit/Source/JavaScriptCore/runtime/JSCJSValue.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | null | null | null | src/qt/qtwebkit/Source/JavaScriptCore/runtime/JSCJSValue.cpp | mrampersad/phantomjs | dca6f77a36699eb4e1c46f7600cca618f01b0ac3 | [
"BSD-3-Clause"
] | 1 | 2017-03-19T13:03:23.000Z | 2017-03-19T13:03:23.000Z | /*
* Copyright (C) 1999-2001 Harri Porten (porten@kde.org)
* Copyright (C) 2001 Peter Kelly (pmk@post.com)
* Copyright (C) 2003, 2007, 2008, 2012 Apple Inc. All rights reserved.
*
* 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 "JSCJSValue.h"
#include "BooleanConstructor.h"
#include "BooleanPrototype.h"
#include "Error.h"
#include "ExceptionHelpers.h"
#include "GetterSetter.h"
#include "JSCJSValueInlines.h"
#include "JSFunction.h"
#include "JSGlobalObject.h"
#include "JSNotAnObject.h"
#include "NumberObject.h"
#include <wtf/MathExtras.h>
#include <wtf/StringExtras.h>
namespace JSC {
static const double D32 = 4294967296.0;
// ECMA 9.4
double JSValue::toInteger(ExecState* exec) const
{
if (isInt32())
return asInt32();
double d = toNumber(exec);
return std::isnan(d) ? 0.0 : trunc(d);
}
double JSValue::toIntegerPreserveNaN(ExecState* exec) const
{
if (isInt32())
return asInt32();
return trunc(toNumber(exec));
}
double JSValue::toNumberSlowCase(ExecState* exec) const
{
ASSERT(!isInt32() && !isDouble());
if (isCell())
return asCell()->toNumber(exec);
if (isTrue())
return 1.0;
return isUndefined() ? QNaN : 0; // null and false both convert to 0.
}
JSObject* JSValue::toObjectSlowCase(ExecState* exec, JSGlobalObject* globalObject) const
{
ASSERT(!isCell());
if (isInt32() || isDouble())
return constructNumber(exec, globalObject, asValue());
if (isTrue() || isFalse())
return constructBooleanFromImmediateBoolean(exec, globalObject, asValue());
ASSERT(isUndefinedOrNull());
throwError(exec, createNotAnObjectError(exec, *this));
return JSNotAnObject::create(exec);
}
JSObject* JSValue::toThisObjectSlowCase(ExecState* exec) const
{
ASSERT(!isCell());
if (isInt32() || isDouble())
return constructNumber(exec, exec->lexicalGlobalObject(), asValue());
if (isTrue() || isFalse())
return constructBooleanFromImmediateBoolean(exec, exec->lexicalGlobalObject(), asValue());
ASSERT(isUndefinedOrNull());
return exec->globalThisValue();
}
JSObject* JSValue::synthesizePrototype(ExecState* exec) const
{
if (isCell()) {
ASSERT(isString());
return exec->lexicalGlobalObject()->stringPrototype();
}
if (isNumber())
return exec->lexicalGlobalObject()->numberPrototype();
if (isBoolean())
return exec->lexicalGlobalObject()->booleanPrototype();
ASSERT(isUndefinedOrNull());
throwError(exec, createNotAnObjectError(exec, *this));
return JSNotAnObject::create(exec);
}
// ECMA 8.7.2
void JSValue::putToPrimitive(ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
VM& vm = exec->vm();
unsigned index = propertyName.asIndex();
if (index != PropertyName::NotAnIndex) {
putToPrimitiveByIndex(exec, index, value, slot.isStrictMode());
return;
}
// Check if there are any setters or getters in the prototype chain
JSObject* obj = synthesizePrototype(exec);
JSValue prototype;
if (propertyName != exec->propertyNames().underscoreProto) {
for (; !obj->structure()->hasReadOnlyOrGetterSetterPropertiesExcludingProto(); obj = asObject(prototype)) {
prototype = obj->prototype();
if (prototype.isNull()) {
if (slot.isStrictMode())
throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
return;
}
}
}
for (; ; obj = asObject(prototype)) {
unsigned attributes;
JSCell* specificValue;
PropertyOffset offset = obj->structure()->get(vm, propertyName, attributes, specificValue);
if (offset != invalidOffset) {
if (attributes & ReadOnly) {
if (slot.isStrictMode())
throwError(exec, createTypeError(exec, StrictModeReadonlyPropertyWriteError));
return;
}
JSValue gs = obj->getDirect(offset);
if (gs.isGetterSetter()) {
JSObject* setterFunc = asGetterSetter(gs)->setter();
if (!setterFunc) {
if (slot.isStrictMode())
throwError(exec, createTypeError(exec, ASCIILiteral("setting a property that has only a getter")));
return;
}
CallData callData;
CallType callType = setterFunc->methodTable()->getCallData(setterFunc, callData);
MarkedArgumentBuffer args;
args.append(value);
// If this is WebCore's global object then we need to substitute the shell.
call(exec, setterFunc, callType, callData, *this, args);
return;
}
// If there's an existing property on the object or one of its
// prototypes it should be replaced, so break here.
break;
}
prototype = obj->prototype();
if (prototype.isNull())
break;
}
if (slot.isStrictMode())
throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
return;
}
void JSValue::putToPrimitiveByIndex(ExecState* exec, unsigned propertyName, JSValue value, bool shouldThrow)
{
if (propertyName > MAX_ARRAY_INDEX) {
PutPropertySlot slot(shouldThrow);
putToPrimitive(exec, Identifier::from(exec, propertyName), value, slot);
return;
}
if (synthesizePrototype(exec)->attemptToInterceptPutByIndexOnHoleForPrototype(exec, *this, propertyName, value, shouldThrow))
return;
if (shouldThrow)
throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
}
void JSValue::dump(PrintStream& out) const
{
if (!*this)
out.print("<JSValue()>");
else if (isInt32())
out.printf("Int32: %d", asInt32());
else if (isDouble()) {
#if USE(JSVALUE64)
out.printf("Double: %lld, %lf", (long long)reinterpretDoubleToInt64(asDouble()), asDouble());
#else
union {
double asDouble;
uint32_t asTwoInt32s[2];
} u;
u.asDouble = asDouble();
out.printf("Double: %08x:%08x, %lf", u.asTwoInt32s[1], u.asTwoInt32s[0], asDouble());
#endif
} else if (isCell()) {
if (asCell()->inherits(&JSString::s_info)) {
JSString* string = jsCast<JSString*>(asCell());
out.print("String: ");
if (string->isRope())
out.print("(rope) ");
out.print(string->tryGetValue());
} else if (asCell()->inherits(&Structure::s_info)) {
Structure* structure = jsCast<Structure*>(asCell());
out.print(
"Structure: ", RawPointer(structure), ": ", structure->classInfo()->className,
", ", IndexingTypeDump(structure->indexingTypeIncludingHistory()));
} else {
out.print("Cell: ", RawPointer(asCell()));
if (isObject() && asObject(*this)->butterfly())
out.print("->", RawPointer(asObject(*this)->butterfly()));
out.print(
" (", RawPointer(asCell()->structure()), ": ", asCell()->structure()->classInfo()->className,
", ", IndexingTypeDump(asCell()->structure()->indexingTypeIncludingHistory()), ")");
}
} else if (isTrue())
out.print("True");
else if (isFalse())
out.print("False");
else if (isNull())
out.print("Null");
else if (isUndefined())
out.print("Undefined");
else
out.print("INVALID");
}
// This in the ToInt32 operation is defined in section 9.5 of the ECMA-262 spec.
// Note that this operation is identical to ToUInt32 other than to interpretation
// of the resulting bit-pattern (as such this metod is also called to implement
// ToUInt32).
//
// The operation can be descibed as round towards zero, then select the 32 least
// bits of the resulting value in 2s-complement representation.
int32_t toInt32(double number)
{
int64_t bits = WTF::bitwise_cast<int64_t>(number);
int32_t exp = (static_cast<int32_t>(bits >> 52) & 0x7ff) - 0x3ff;
// If exponent < 0 there will be no bits to the left of the decimal point
// after rounding; if the exponent is > 83 then no bits of precision can be
// left in the low 32-bit range of the result (IEEE-754 doubles have 52 bits
// of fractional precision).
// Note this case handles 0, -0, and all infinte, NaN, & denormal value.
if (exp < 0 || exp > 83)
return 0;
// Select the appropriate 32-bits from the floating point mantissa. If the
// exponent is 52 then the bits we need to select are already aligned to the
// lowest bits of the 64-bit integer representation of tghe number, no need
// to shift. If the exponent is greater than 52 we need to shift the value
// left by (exp - 52), if the value is less than 52 we need to shift right
// accordingly.
int32_t result = (exp > 52)
? static_cast<int32_t>(bits << (exp - 52))
: static_cast<int32_t>(bits >> (52 - exp));
// IEEE-754 double precision values are stored omitting an implicit 1 before
// the decimal point; we need to reinsert this now. We may also the shifted
// invalid bits into the result that are not a part of the mantissa (the sign
// and exponent bits from the floatingpoint representation); mask these out.
if (exp < 32) {
int32_t missingOne = 1 << exp;
result &= missingOne - 1;
result += missingOne;
}
// If the input value was negative (we could test either 'number' or 'bits',
// but testing 'bits' is likely faster) invert the result appropriately.
return bits < 0 ? -result : result;
}
bool JSValue::isValidCallee()
{
return asObject(asCell())->globalObject();
}
JSString* JSValue::toStringSlowCase(ExecState* exec) const
{
VM& vm = exec->vm();
ASSERT(!isString());
if (isInt32())
return jsString(&vm, vm.numericStrings.add(asInt32()));
if (isDouble())
return jsString(&vm, vm.numericStrings.add(asDouble()));
if (isTrue())
return vm.smallStrings.trueString();
if (isFalse())
return vm.smallStrings.falseString();
if (isNull())
return vm.smallStrings.nullString();
if (isUndefined())
return vm.smallStrings.undefinedString();
ASSERT(isCell());
JSValue value = asCell()->toPrimitive(exec, PreferString);
if (exec->hadException())
return jsEmptyString(exec);
ASSERT(!value.isObject());
return value.toString(exec);
}
String JSValue::toWTFStringSlowCase(ExecState* exec) const
{
return inlineJSValueNotStringtoString(*this, exec);
}
} // namespace JSC
| 35.324159 | 129 | 0.634317 | viewdy |
62833a86648c6b50eafb78f2dcb1f5c7c34d5803 | 278 | cpp | C++ | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | 3 | 2019-10-04T13:24:16.000Z | 2020-01-22T05:07:02.000Z | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | Challenges - Fundamentals/Print Series.cpp | helewrer3/CB_Launchpad | cda17f62a25e15cb914982d1cc24f7ba0e2f7a67 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
int main()
{
//Variables
int N1, N2, n = 1, val;
//Input
cin >> N1 >> N2;
// Process
while(n <= N1)
{
val = 3*n+2;
if(val%N2 != 0)
printf("%d\n", val);
else
N1++;
n++;
}
return 0;
} | 11.12 | 24 | 0.456835 | helewrer3 |
628cb8829a20f7becc2f52bd0a7c1d992a26d812 | 16,159 | hh | C++ | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | core/iostream.hh | ducthangho/imdb | 144be294949682cc1abb247dc56c2dfe0e4fafba | [
"Apache-2.0"
] | null | null | null | /*
* This file is open source software, licensed to you under the terms
* of the Apache License, Version 2.0 (the "License"). See the NOTICE file
* distributed with this work for additional information regarding copyright
* ownership. 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.
*/
/*
* Copyright (C) 2015 Cloudius Systems, Ltd.
*/
//
// Buffered input and output streams
//
// Two abstract classes (data_source and data_sink) provide means
// to acquire bulk data from, or push bulk data to, some provider.
// These could be tied to a TCP connection, a disk file, or a memory
// buffer.
//
// Two concrete classes (input_stream and output_stream) buffer data
// from data_source and data_sink and provide easier means to process
// it.
//
#pragma once
#include "future.hh"
#include "temporary_buffer.hh"
#include "scattered_message.hh"
#ifdef __USE_KJ__
#include "core/do_with.hh"
#include "kj/debug.h"
#include "kj/async.h"
#include "kj/async-io.h"
#include <limits.h>
#endif
#if !defined(IOV_MAX) && defined(UIO_MAXIOV)
#define IOV_MAX UIO_MAXIOV
#endif
namespace net { class packet; }
class data_source_impl {
public:
virtual ~data_source_impl() {}
virtual future<temporary_buffer<char>> get() = 0;
#ifdef __USE_KJ__
virtual void setBuffer(temporary_buffer<char> && buf) = 0;
virtual kj::Promise<temporary_buffer<char>> kj_get(size_t maxBytes = 8192) = 0;
#endif
};
class data_source {
std::unique_ptr<data_source_impl> _dsi;
protected:
data_source_impl* impl() const { return _dsi.get(); }
public:
data_source() = default;
explicit data_source(std::unique_ptr<data_source_impl> dsi) : _dsi(std::move(dsi)) {}
data_source(data_source&& x) = default;
data_source& operator=(data_source&& x) = default;
future<temporary_buffer<char>> get() { return _dsi->get(); }
#ifdef __USE_KJ__
void setBuffer(temporary_buffer<char> && buf){
_dsi->setBuffer(std::move(buf) );
}
kj::Promise<temporary_buffer<char>> kj_get(size_t maxBytes = 8192) {
return _dsi->kj_get(maxBytes);
};
#endif
};
class data_sink_impl {
public:
virtual ~data_sink_impl() {}
virtual temporary_buffer<char> allocate_buffer(size_t size) {
return temporary_buffer<char>(size);
}
virtual future<> put(net::packet data) = 0;
virtual future<> put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return put(std::move(p));
}
virtual future<> put(temporary_buffer<char> buf) {
return put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual future<> close() = 0;
#ifdef __USE_KJ__
virtual kj::Promise<void> kj_put(net::packet data) = 0;
virtual kj::Promise<void> kj_put(std::vector<temporary_buffer<char>> data) {
net::packet p;
p.reserve(data.size());
for (auto& buf : data) {
p = net::packet(std::move(p), net::fragment{buf.get_write(), buf.size()}, buf.release());
}
return kj_put(std::move(p));
}
virtual kj::Promise<void> kj_put(temporary_buffer<char> buf) {
return kj_put(net::packet(net::fragment{buf.get_write(), buf.size()}, buf.release()));
}
virtual kj::Promise<void> kj_close() = 0;
#endif
};
class data_sink {
std::unique_ptr<data_sink_impl> _dsi;
public:
data_sink() = default;
explicit data_sink(std::unique_ptr<data_sink_impl> dsi) : _dsi(std::move(dsi)) {}
data_sink(data_sink&& x) = default;
data_sink& operator=(data_sink&& x) = default;
temporary_buffer<char> allocate_buffer(size_t size) {
return _dsi->allocate_buffer(size);
}
future<> put(std::vector<temporary_buffer<char>> data) {
return _dsi->put(std::move(data));
}
future<> put(temporary_buffer<char> data) {
return _dsi->put(std::move(data));
}
future<> put(net::packet p) {
return _dsi->put(std::move(p));
}
future<> close() { return _dsi->close(); }
#ifdef __USE_KJ__
kj::Promise<void> kj_put(std::vector<temporary_buffer<char>> data) {
return _dsi->kj_put(std::move(data));
}
kj::Promise<void> kj_put(temporary_buffer<char> data) {
return _dsi->kj_put(std::move(data));
}
kj::Promise<void> kj_put(net::packet p) {
return _dsi->kj_put(std::move(p));
}
kj::Promise<void> kj_close() { return _dsi->kj_close(); }
#endif
};
#ifdef __USE_KJ__
template <typename CharType>
class input_stream final : public kj::AsyncInputStream {
#else
template <typename CharType>
class input_stream final {
#endif
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_source _fd;
temporary_buffer<CharType> _buf;
bool _eof = false;
private:
using tmp_buf = temporary_buffer<CharType>;
size_t available() const { return _buf.size(); }
protected:
void reset() { _buf = {}; }
data_source* fd() { return &_fd; }
public:
// Consumer concept, for consume() method:
using unconsumed_remainder = std::experimental::optional<tmp_buf>;
struct ConsumerConcept {
// The consumer should operate on the data given to it, and
// return a future "unconsumed remainder", which can be undefined
// if the consumer consumed all the input given to it and is ready
// for more, or defined when the consumer is done (and in that case
// the value is the unconsumed part of the last data buffer - this
// can also happen to be empty).
future<unconsumed_remainder> operator()(tmp_buf data);
};
using char_type = CharType;
input_stream() = default;
explicit input_stream(data_source fd) : _fd(std::move(fd)), _buf(0) {}
input_stream(input_stream&&) = default;
input_stream& operator=(input_stream&&) = default;
future<temporary_buffer<CharType>> read_exactly(size_t n);
template <typename Consumer>
future<> consume(Consumer& c);
bool eof() { return _eof; }
#ifdef __USE_KJ__
template <typename Consumer>
kj::Promise<void> kj_consume(Consumer& c);
kj::Promise<size_t> tryRead(void* buffer, size_t minBytes, size_t maxBytes) override {
return tryReadInternal(buffer, minBytes, maxBytes, 0);
}
kj::Promise<size_t> read(void* buffer, size_t minBytes, size_t maxBytes) override {
return tryReadInternal(buffer, minBytes, maxBytes, 0).then([ = ](size_t result) {
KJ_REQUIRE(result >= minBytes, "Premature EOF") {
// Pretend we read zeros from the input.
memset(reinterpret_cast<kj::byte*>(buffer) + result, 0, minBytes - result);
return minBytes;
}
return result;
});
}
kj::Promise<temporary_buffer<CharType>> kj_read_exactly(size_t n);
#endif
private:
future<temporary_buffer<CharType>> read_exactly_part(size_t n, tmp_buf buf, size_t completed);
#ifdef __USE_KJ__
kj::Promise<temporary_buffer<CharType>> kj_read_exactly_part(size_t n, tmp_buf buf, size_t completed);
kj::Promise<size_t> tryReadInternal(void* buffer, size_t minBytes, size_t maxBytes,
size_t alreadyRead) {
// printf("tryReadInternal %zu, %zu \n",minBytes,maxBytes);
if (available()) {//Should not happen now
printf("Available \n");
auto now = std::min(maxBytes, available());
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Copy here\n");
std::copy(_buf.get(), _buf.get() + now, reinterpret_cast<CharType*>(buffer) + alreadyRead);
}
_buf.trim_front(now);
alreadyRead += now;
minBytes -= now;
maxBytes -= now;
}
// printf("Buffer now = %zu %zu\t%zu\t%zu\n",(size_t)buffer,alreadyRead,minBytes,maxBytes);
if (minBytes <= 0) {
printf("Done %zu\n",alreadyRead);
return alreadyRead;
}
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Copy here\n");
_buf = std::move( temporary_buffer<CharType>(reinterpret_cast<CharType*>(buffer)+alreadyRead, maxBytes, make_free_deleter(NULL) ) );
}
// printf("_buf now = %zu %zu\n",(size_t)_buf.get(),alreadyRead);
// _buf is now empty
_fd.setBuffer(std::move(_buf));
return _fd.kj_get(maxBytes).then([this, minBytes, maxBytes, buffer, alreadyRead] (auto buf) mutable {
if (buf.size() == 0) {
_eof = true;
// printf("OK, Done %zu\n",alreadyRead);
return kj::Promise<size_t>(alreadyRead);
}
_buf = std::move(buf);
// printf("Buff now = %zu %zu\n",(size_t)_buf.get(),_buf.size() );
auto now = kj::min(minBytes, _buf.size());
// KJ_DBG(now);
if (_buf.get() != reinterpret_cast<CharType*>(buffer) + alreadyRead){
printf("Oh crap\n");
std::copy(_buf.get(), _buf.get() + now, reinterpret_cast<CharType*>(buffer) + alreadyRead);
}
alreadyRead += _buf.size();
minBytes -= now;
maxBytes -= now;
// for (size_t i=0;i<21;++i){
// printf("%d\t",(int)_buf[i]);
// }
// printf("\n");
_buf.trim_front(_buf.size());
// printf("Buff after trim now = %zu\t%zu\n",(size_t)_buf.get(), (size_t)(reinterpret_cast<CharType*>(buffer) + alreadyRead) );
// printf("Hey a, alreadyRead = %zu, buff size = %zu, minBytes = %zu\n",alreadyRead,_buf.size(),minBytes);
if (minBytes<=0) {
// printf("Returned %zu\n",alreadyRead);
return kj::Promise<size_t>(alreadyRead);
}
return this->tryReadInternal(buffer, minBytes, maxBytes, alreadyRead);
});
}
#endif
};
// Facilitates data buffering before it's handed over to data_sink.
//
// When trim_to_size is true it's guaranteed that data sink will not receive
// chunks larger than the configured size, which could be the case when a
// single write call is made with data larger than the configured size.
//
// The data sink will not receive empty chunks.
//
#ifdef __USE_KJ__
template <typename CharType>
class output_stream final : public kj::AsyncOutputStream {
#else
template <typename CharType>
class output_stream final {
#endif
static_assert(sizeof(CharType) == 1, "must buffer stream of bytes");
data_sink _fd;
temporary_buffer<CharType> _buf;
size_t _size = 0;
size_t _begin = 0;
size_t _end = 0;
bool _trim_to_size = false;
private:
size_t available() const { return _end - _begin; }
size_t possibly_available() const { return _size - _begin; }
future<> split_and_put(temporary_buffer<CharType> buf);
#ifdef __USE_KJ__
kj::Promise<void> kj_split_and_put(temporary_buffer<CharType> buf);
#endif
public:
using char_type = CharType;
output_stream() = default;
output_stream(data_sink fd, size_t size, bool trim_to_size = false)
: _fd(std::move(fd)), _size(size), _trim_to_size(trim_to_size) {}
output_stream(output_stream&&) = default;
output_stream& operator=(output_stream&&) = default;
future<> write(const char_type* buf, size_t n);
future<> write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
future<> write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
future<> write(const std::basic_string<char_type>& s);
future<> write(net::packet p);
future<> write(scattered_message<char_type> msg);
future<> flush();
future<> close() { return flush().then([this] { return _fd.close(); }); }
#ifdef __USE_KJ__
kj::Promise<void> kj_write(const char_type* buf, size_t n);
kj::Promise<void> kj_write(const char_type* buf);
template <typename StringChar, typename SizeType, SizeType MaxSize>
kj::Promise<void> kj_write(const basic_sstring<StringChar, SizeType, MaxSize>& s);
kj::Promise<void> kj_write(const std::basic_string<char_type>& s);
kj::Promise<void> kj_write(net::packet p);
kj::Promise<void> kj_write(scattered_message<char_type> msg);
kj::Promise<void> kj_flush();
kj::Promise<void> kj_close() { return kj_flush().then([this] { return _fd.kj_close(); }); }
kj::Promise<void> write(const void* buffer, size_t size) override {
return kj_write((const char_type*)buffer, size).then([this]() {
return kj_flush();
});
}
kj::Promise<void> write(kj::ArrayPtr<const kj::ArrayPtr<const kj::byte>> pieces) override {
if (pieces.size() == 0) {
return writeInternal(nullptr, nullptr);
} else {
return writeInternal(pieces[0], pieces.slice(1, pieces.size()));
}
}
private:
kj::Promise<void> writeInternal(kj::ArrayPtr<const kj::byte> firstPiece,
kj::ArrayPtr<const kj::ArrayPtr<const kj::byte>> morePieces) {
scattered_message<char> msg;
msg.append_static((char*)firstPiece.begin(),firstPiece.size() );
for (size_t i =0;i<morePieces.size();++i){
auto& buf = morePieces[i];
msg.append_static((char*)buf.begin(),buf.size() );
}
return kj_write(std::move(msg));
// auto promise = kj_write((const char_type*)firstPiece.begin(),firstPiece.size() );
// for (size_t i = 0;i<morePieces.size();++i){
// auto & pieces = morePieces[i];
// promise = promise.then([&pieces,this](){
// return kj_write((const char_type*)pieces.begin(),pieces.size() );
// });
// };
// return promise.then([this]() {
// return kj_flush();
// });
/*KJ_NONBLOCKING_SYSCALL(writeResult = ::writev(fd, iov.begin(), iov.size())) {
// Error.
// We can't "return kj::READY_NOW;" inside this block because it causes a memory leak due to
// a bug that exists in both Clang and GCC:
// http://gcc.gnu.org/bugzilla/show_bug.cgi?id=33799
// http://llvm.org/bugs/show_bug.cgi?id=12286
goto error;
}
if (false) {
error:
return kj::READY_NOW;
}
// A negative result means EAGAIN, which we can treat the same as having written zero bytes.
size_t n = writeResult < 0 ? 0 : writeResult;
// Discard all data that was written, then issue a new write for what's left (if any).
for (;;) {
if (n < firstPiece.size()) {
// Only part of the first piece was consumed. Wait for POLLOUT and then write again.
firstPiece = firstPiece.slice(n, firstPiece.size());
return onWritable().then([=]() {
return writeInternal(firstPiece, morePieces);
});
} else if (morePieces.size() == 0) {
// First piece was fully-consumed and there are no more pieces, so we're done.
KJ_DASSERT(n == firstPiece.size(), n);
return kj::READY_NOW;
} else {
// First piece was fully consumed, so move on to the next piece.
n -= firstPiece.size();
firstPiece = morePieces[0];
morePieces = morePieces.slice(1, morePieces.size());
}
}//*/
}
#endif
private:
};
#include "iostream-impl.hh"
| 36.230942 | 144 | 0.622811 | ducthangho |
628d2c09b4a99861261f68edf0a120f5761d6f3f | 4,717 | cpp | C++ | font.cpp | m-ll/ncha | 847f249df178bc43e97fb3df5ba4745ee375f951 | [
"MIT"
] | null | null | null | font.cpp | m-ll/ncha | 847f249df178bc43e97fb3df5ba4745ee375f951 | [
"MIT"
] | null | null | null | font.cpp | m-ll/ncha | 847f249df178bc43e97fb3df5ba4745ee375f951 | [
"MIT"
] | null | null | null | ///
/// Copyright (c) 2002-19 m-ll. All Rights Reserved.
///
/// Licensed under the MIT License.
/// See LICENSE file in the project root for full license information.
///
/// 2b13c8312f53d4b9202b6c8c0f0e790d10044f9a00d8bab3edf3cd287457c979
/// 29c355784a3921aa290371da87bce9c1617b8584ca6ac6fb17fb37ba4a07d191
///
#include "font.h"
font::~font()
{
SDL_FreeSurface(alpha);
}
SDL_Surface * & font::get_alpha()
{
return alpha;
}
void font::init(char * dir,int taille,int r,int g,int b)
{
char namef[255],name[255];
int tr=0,tg=0,tb=0;
FILE * fd;
sprintf(namef,"%s/info.ini",dir);
if(!(fd=fopen(namef,"r")))
erreur("on peut pas ouvrir le font du rep %s",namef);
while(!feof(fd))
{
fscanf(fd,"%s%d%d%d%d",namef,&tr,&tg,&tb,&width);
if(width==taille)
break;
}
if(width!=taille) erreur("ce n'est pas la bonne taille de font");
sprintf(name,"%s/%s",dir,namef);
if(verif_bmp(name)==1)
erreur("Le fichier font %s n'est pas valide",name);
if(!(alpha=SDL_LoadBMP(name)))
erreur("pour ouvir le fichier font %s",name);
if(tr>=0)
SDL_SetColorKey(alpha,SDL_SRCCOLORKEY,SDL_MapRGB(alpha->format,tr,tg,tb));
if(r!=0||g!=0||b!=0) change_color(r,g,b);
}
void font::get_pix(int x,int y,int & r,int & g,int & b)
{
Uint8 tr=0,tg=0,tb=0;
SDL_LockSurface(alpha);
int bpp=alpha->format->BytesPerPixel;
Uint8 *p=(Uint8 *)alpha->pixels+y*alpha->pitch+x*bpp;
switch(bpp)
{
case 3:
if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
*p= p[0] << 16 | p[1] << 8 | p[2];
else
*p= p[0] | p[1] << 8 | p[2] << 16;
}
SDL_GetRGB(*(Uint32 *)p,alpha->format,&tr,&tg,&tb);
SDL_UnlockSurface(alpha);
r=tr;
g=tg;
b=tb;
}
void font::set_pix(int x,int y,int r,int g,int b)
{
Uint32 color=SDL_MapRGB(alpha->format,r,g,b);
SDL_LockSurface(alpha);
switch (alpha->format->BytesPerPixel)
{
case 1:
{
Uint8 *bufp;
bufp = (Uint8 *)alpha->pixels + y*alpha->pitch + x;
*bufp = color;
}
break;
case 2:
{
Uint16 *bufp;
bufp = (Uint16 *)alpha->pixels + y*alpha->pitch/2 + x;
*bufp = color;
}
break;
case 3:
{
Uint8 *bufp;
bufp = (Uint8 *)alpha->pixels + y*alpha->pitch + x * 3;
if(SDL_BYTEORDER == SDL_LIL_ENDIAN) {
bufp[0] = color;
bufp[1] = color >> 8;
bufp[2] = color >> 16;
} else {
bufp[2] = color;
bufp[1] = color >> 8;
bufp[0] = color >> 16;
}
}
break;
case 4:
{
Uint32 *bufp;
bufp = (Uint32 *)alpha->pixels + y*alpha->pitch/4 + x;
*bufp = color;
}
break;
}
SDL_UnlockSurface(alpha);
}
void font::change_color(int r,int g,int b)
{
int tr=0,tg=0,tb=0;
for(int i=0;i<alpha->w;i++)
for(int j=0;j<alpha->h;j++)
{
get_pix(i,j,tr,tg,tb);
if(tr==0&&tg==0&&tb==0)
set_pix(i,j,r,g,b);
}
}
void font::drawletter(SDL_Surface * s,int xs,int ys,int x,int y,int w,int h)
{
SDL_Rect dest;
dest.x=xs;
dest.y=ys;
SDL_Rect src;
src.x=x;
src.y=y;
src.w=w;
src.h=h;
SDL_BlitSurface(alpha,&src,s,&dest);
}
void font::drawstring(SDL_Surface * s,int x,int y,char * str,...)
{
char string[1024];
int code;
va_list ap;
va_start(ap,str);
vsprintf(string,str,ap);
va_end(ap);
x-=width;
for(int i=0;i<(int)strlen(string);i++)
{
code=string[i];
drawletter(s,x+=width,y,
(code%16)*width,
(code/16)*width,
width,
width);
}
}
void font::drawstring_h(SDL_Surface * s,int w,char * str,...)
{
char string[1024];
int code;
va_list ap;
va_start(ap, str);
vsprintf(string, str, ap);
va_end(ap);
w-=width;
for(int i=0;i<(int)strlen(string);i++)
{
code=string[i];
drawletter(s,w+=width,s->h/2-width/2,
(code%16)*width,
(code/16)*width,
width,
width);
}
}
void font::drawstring_w(SDL_Surface * s,int h,char * str,...)
{
char string[1024];
int code;
int w;
va_list ap;
va_start(ap, str);
vsprintf(string, str, ap);
va_end(ap);
w=s->w/2-(int)((strlen(string)/2.0)*width);
w-=width;
for(int i=0;i<(int)strlen(string);i++)
{
code=string[i];
drawletter(s,w+=width,h,
(code%16)*width,
(code/16)*width,
width,
width);
}
}
void font::drawstring_center(SDL_Surface * s,char * str,...)
{
char string[1024];
int code;
int w;
va_list ap;
va_start(ap, str);
vsprintf(string, str, ap);
va_end(ap);
w=s->w/2-(int)((strlen(string)/2.0)*width);
w-=width;
for(int i=0;i<(int)strlen(string);i++)
{
code=string[i];
drawletter(s,w+=width,s->h/2-width/2,
(code%16)*width,
(code/16)*width,
width,
width);
}
} | 17.8 | 76 | 0.571974 | m-ll |
6292a4835c424a9b242c5283f6c9f4bf5f3f2ad5 | 479 | cpp | C++ | test/ssc_test/cmod_geothermal_costs_test.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 1 | 2019-08-12T07:05:44.000Z | 2019-08-12T07:05:44.000Z | test/ssc_test/cmod_geothermal_costs_test.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 10 | 2018-06-11T16:52:24.000Z | 2021-04-12T16:01:17.000Z | test/ssc_test/cmod_geothermal_costs_test.cpp | gjsoto/ssc | 70ef4fdafb9afe0418a9c552485a7116a1b3a743 | [
"BSD-3-Clause"
] | 4 | 2019-01-09T19:33:03.000Z | 2022-02-02T09:17:05.000Z | #include <gtest/gtest.h>
#include "cmod_geothermal_costs_test.h"
//Fixture is currently testing binary plant (Conversion type = 0)
TEST_F(CMGeothermalCosts, CostModuleTest_cmod_geothermal_costs)
{
//Check whether module runs with any errors:
int geothermal_errors = run_module(data, "geothermal_costs");
ASSERT_EQ(geothermal_errors, 0);
ssc_number_t baseline_cost;
ssc_data_get_number(data, "baseline_cost", &baseline_cost);
EXPECT_NEAR(baseline_cost, 2300, 100 );
}
| 28.176471 | 65 | 0.791232 | gjsoto |
62949e8bd8513e581a54f3f25af9e3391f1cb932 | 12,728 | cpp | C++ | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 6 | 2018-01-29T10:20:20.000Z | 2021-06-13T05:35:32.000Z | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | null | null | null | headers/linker.cpp | Laxen/object_identification_localization | 658aad68c6e93386a6c49a810bd8620215a54440 | [
"Unlicense"
] | 2 | 2019-04-03T12:10:54.000Z | 2019-05-13T09:44:01.000Z | #include "linker.h"
bool
Linker::poses_comparator(const Pose_Data& pose1, const Pose_Data& pose2) {
return pose1.inlier_fraction > pose2.inlier_fraction;
}
bool
Linker::id_comparator(const ID_Data& id1, const ID_Data& id2) {
return id1.scores[0] < id2.scores[0];
}
/**
Links pose data from the merged cloud called prev_merged_name to the merged cloud called current_merged_name
@param ar Access_Results object
@param m Manipulation object
@param prev_merged_name The main folder name of the previous merged cloud
@param current_merged_name The main folder name of the current merged cloud
@param model_names The model names for each cluster in the current merged cloud, as identified in the pose estimation for the previous merged cloud
@param view_indices The model view indices for clusters in the current merged cloud, as identified in pose estimation for the prev merged cloud
@param model_scores The model scores for clusters in the current merged cloud, as identified in the pose estimation for the prev merged cloud
@returns The merged clusters
*/
std::vector<Linker::Point_Cloud_N::Ptr>
Linker::link_pose_data(Access_Results ar,
Manipulation m,
std::string prev_merged_name,
std::string current_merged_name,
std::vector<std::vector<std::string> > &model_names,
std::vector<std::vector<std::vector<int> > > &view_indices,
std::vector<std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > > poses,
std::vector<std::vector<double> > inlier_fractions,
std::vector<std::vector<double> > accuracies) {
std::vector<std::string> links; // Used for debugging
Point_Cloud_N::Ptr scene_original (new Point_Cloud_N);
Point_Cloud_N::Ptr scene (new Point_Cloud_N);
std::vector<Point_Cloud_N::Ptr> prev_merged_clusters;
std::vector<Point_Cloud_N::Ptr> current_merged_clusters;
std::vector<std::vector<Pose_Data> > cluster_pose_data; // Object used to keep track of all pose data for each cluster
// Get clusters
ar.load_segmentation_results(prev_merged_name + "/merged", scene_original, scene, prev_merged_clusters);
ar.load_segmentation_results(current_merged_name + "/merged", scene_original, scene, current_merged_clusters);
model_names.resize(current_merged_clusters.size());
view_indices.resize(current_merged_clusters.size());
poses.resize(current_merged_clusters.size());
inlier_fractions.resize(current_merged_clusters.size());
accuracies.resize(current_merged_clusters.size());
cluster_pose_data.resize(current_merged_clusters.size());
// Get transformation matrices and compute transformation between clouds
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_CtoH = ar.get_T_CtoH();
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_prev_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + prev_merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_current_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + current_merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_prev_to_current = T_CtoH.inverse() * T_current_merged.inverse()*T_prev_merged * T_CtoH;
// Loop through each cluster in prev_merged_clusters
for(int i = 0; i < prev_merged_clusters.size(); i++) {
// Transform the previous cluster to the current_merged_clusters coordinate system
Point_Cloud_N::Ptr prev_cluster = prev_merged_clusters[i];
pcl::transformPointCloud(*prev_cluster, *prev_cluster, T_prev_to_current);
/*
std::vector<std::string> model_names_prev;
std::vector<std::vector<int> > view_indices_prev;
std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > poses_prev;
std::vector<double> inlier_fractions_prev;
std::vector<double> accuracies_prev;
ar.load_pose_estimation_results(prev_merged_name, i, model_names_prev, view_indices_prev, poses_prev, inlier_fractions_prev, accuracies_prev);
*/
std::vector<Pose_Data> prev_pose_data;
ar.load_pose_estimation_results_pose_format(prev_merged_name, i, prev_pose_data);
// Loop through each cluster in current_merged_clusters
for(int n = 0; n < current_merged_clusters.size(); n++) {
// Compute inliers when fitting the previous cluster to the current cluster
std::vector<int> inliers;
std::vector<int> outliers;
m.compute_inliers(current_merged_clusters[n], prev_merged_clusters[i], 0.001, &inliers, &outliers);
double inlier_fraction = (double) inliers.size() / (double) prev_merged_clusters[i]->points.size();
// If it fits, data for the current cluster should be equal to data for the previous cluster
if(inlier_fraction > 0) {
std::cout << "Linked pose data from previous cluster " << i << " to current cluster " << n << '\n';
/*
if(cluster_pose_data[n].size() > 0) {
std::cout << "\tCurrent cluster " << n << " has already been merged before!!" << '\n';
}
*/
cluster_pose_data[n].insert(cluster_pose_data[n].end(), prev_pose_data.begin(), prev_pose_data.end());
/*
model_names[n].insert(model_names[n].end(), model_names_prev.begin(), model_names_prev.end());
view_indices[n].insert(view_indices[n].end(), view_indices_prev.begin(), view_indices_prev.end());
poses[n].insert(poses[n].end(), poses_prev.begin(), poses_prev.end());
inlier_fractions[n].insert(inlier_fractions[n].end(), inlier_fractions_prev.begin(), inlier_fractions_prev.end());
accuracies[n].insert(accuracies[n].end(), accuracies_prev.begin(), accuracies_prev.end());
*/
/*
model_names[n] = model_names_prev;
view_indices[n] = view_indices_prev;
poses[n] = poses_prev;
inlier_fractions[n] = inlier_fractions_prev;
accuracies[n] = accuracies_prev;
*/
std::ostringstream oss;
oss << i << "->" << n;
links.push_back(oss.str());
break;
}
}
}
// Sort cluster_pose_data for each cluster based on inlier_fraction
for(int c = 0; c < cluster_pose_data.size(); c++) {
std::sort(cluster_pose_data[c].begin(), cluster_pose_data[c].end(), poses_comparator);
}
// Move data back into vectors
for(int c = 0; c < cluster_pose_data.size(); c++) {
std::cout << "Linked pose data from cluster " << c << '\n';
std::vector<std::string> m_n;
std::vector<std::vector<int> > v_i;
std::vector<Eigen::Matrix<float,4,4,Eigen::DontAlign> > p;
std::vector<double> i_f;
std::vector<double> acc;
for(int i = 0; i < cluster_pose_data[c].size(); i++) {
std::cout << "\t" << cluster_pose_data[c][i].model_name << ",";
for(int n = 0; n < cluster_pose_data[c][i].view_indices.size(); n++) {
std::cout << cluster_pose_data[c][i].view_indices[n] << "+";
}
std::cout << "," << cluster_pose_data[c][i].inlier_fraction << "," << cluster_pose_data[c][i].accuracy << '\n';
m_n.push_back(cluster_pose_data[c][i].model_name);
v_i.push_back(cluster_pose_data[c][i].view_indices);
p.push_back(cluster_pose_data[c][i].transformation);
i_f.push_back(cluster_pose_data[c][i].inlier_fraction);
acc.push_back(cluster_pose_data[c][i].accuracy);
}
model_names[c] = m_n;
view_indices[c] = v_i;
poses[c] = p;
inlier_fractions[c] = i_f;
accuracies[c] = acc;
}
// Write link data (for debugging purposes)
std::ofstream ofs;
std::string p = ar.path_to_segmentation_results().string() + "/" + current_merged_name + "/merged/pose_link_" + prev_merged_name;
std::cout << "WRITING POSE LINK DEBUG DATA TO " << p << '\n';
ofs.open(p.c_str());
for(int i = 0; i < links.size(); i++) {
ofs << links[i] << "\n";
}
ofs.close();
return current_merged_clusters;
}
/**
Links identification data from single_name to merged_name
@param ar Access_Results object
@param m Manipulation object
@param single_name The main folder name of the single cloud
@param merged_name The main folder name of the merged cloud
@param models_single_in_merged The model names for each merged clusters, as identified in the linked single cluster
@param model_view_indices_1_in_2 The model view indices for each merged clusters, as identified in the linked single cluster
@param model_scores_1_in_2 The model scores for each merged clusters, as identified in the linked single cluster
@returns The merged clusters
*/
std::vector<Linker::Point_Cloud_N::Ptr>
Linker::link_identification_data(Access_Results ar,
Manipulation m,
std::string single_name,
std::string merged_name,
std::vector<std::vector<std::string> > &models_single_in_merged,
std::vector<std::vector<std::vector<int> > > &model_view_indices_single_in_merged,
std::vector<std::vector<std::vector<float> > > &model_scores_single_in_merged) {
std::vector<std::string> links; // Used for debugging
Point_Cloud_N::Ptr scene_original (new Point_Cloud_N);
Point_Cloud_N::Ptr scene (new Point_Cloud_N);
std::vector<Point_Cloud_N::Ptr> single_clusters;
std::vector<Point_Cloud_N::Ptr> merged_clusters;
std::vector<std::vector<ID_Data> > cluster_id_data; // Object used to keep track of all ID data for each cluster
// Get clusters
ar.load_segmentation_results(single_name + "/single", scene_original, scene, single_clusters);
ar.load_segmentation_results(merged_name + "/merged", scene_original, scene, merged_clusters);
models_single_in_merged.resize(merged_clusters.size());
model_view_indices_single_in_merged.resize(merged_clusters.size());
model_scores_single_in_merged.resize(merged_clusters.size());
cluster_id_data.resize(merged_clusters.size());
// Get transformation matrices and compute transformation between clouds
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_CtoH = ar.get_T_CtoH();
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_single = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + single_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_merged = ar.get_robot_data_matrix(ar.path_to_segmentation_results().string() + "/" + merged_name + "/robot_data.csv");
Eigen::Matrix<float,4,4,Eigen::DontAlign> T_single_to_merged = T_CtoH.inverse() * T_merged.inverse()*T_single * T_CtoH;
// Loop through each cluster in single_clusters
for(int i = 0; i < single_clusters.size(); i++) {
// Transform the single cluster to the merged_clusters coordinate system
Point_Cloud_N::Ptr single_cluster = single_clusters[i];
pcl::transformPointCloud(*single_cluster, *single_cluster, T_single_to_merged);
std::vector<ID_Data> id_data;
ar.load_identification_results_id_data_format(single_name, i, id_data);
// Loop through each cluster in merged clusters
for(int n = 0; n < merged_clusters.size(); n++) {
// Compute inliers when fitting the single cluster into the merged cluster
std::vector<int> inliers;
std::vector<int> outliers;
m.compute_inliers(merged_clusters[n], single_clusters[i], 0.001, &inliers, &outliers);
double inlier_fraction = (double) inliers.size() / (double) single_clusters[i]->points.size();
// If it fits, data for the merged cluster should be equal to data for the single cluster
if(inlier_fraction > 0) {
std::cout << "Linked ID data from single cluster " << i << " to merged cluster " << n << '\n';
cluster_id_data[n].insert(cluster_id_data[n].end(), id_data.begin(), id_data.end());
std::ostringstream oss;
oss << i << "->" << n;
links.push_back(oss.str());
break;
}
}
}
// Sort ID data
for(int c = 0; c < cluster_id_data.size(); c++) {
std::sort(cluster_id_data[c].begin(), cluster_id_data[c].end(), id_comparator);
}
// Move data back into vectors
for(int c = 0; c < cluster_id_data.size(); c++) {
std::cout << "Linked ID data for cluster " << c << '\n';
std::vector<std::string> m_n;
std::vector<std::vector<int> > v_i;
std::vector<std::vector<float> > s;
for(int i = 0; i < cluster_id_data[c].size(); i++) {
std::cout << "\t" << cluster_id_data[c][i].model_name << ",";
for(int n = 0; n < cluster_id_data[c][i].view_indices.size(); n++) {
std::cout << cluster_id_data[c][i].view_indices[n] << "," << cluster_id_data[c][i].scores[n] << ",";
}
std::cout << '\n';
m_n.push_back(cluster_id_data[c][i].model_name);
v_i.push_back(cluster_id_data[c][i].view_indices);
s.push_back(cluster_id_data[c][i].scores);
}
models_single_in_merged[c] = m_n;
model_view_indices_single_in_merged[c] = v_i;
model_scores_single_in_merged[c] = s;
}
// Write link data (for debugging purposes)
std::ofstream ofs;
std::string p = ar.path_to_segmentation_results().string() + "/" + merged_name + "/merged/id_link_" + single_name;
std::cout << "WRITING ID LINK DEBUG DATA TO " << p << '\n';
ofs.open(p.c_str());
for(int i = 0; i < links.size(); i++) {
ofs << links[i] << "\n";
}
ofs.close();
return merged_clusters;
}
| 45.620072 | 179 | 0.719045 | Laxen |
629b01a233b488961c494186634b021eb67869db | 2,622 | cpp | C++ | native/tools/simulator/libsimulator/lib/PlayerTaskServiceProtocol.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/tools/simulator/libsimulator/lib/PlayerTaskServiceProtocol.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | native/tools/simulator/libsimulator/lib/PlayerTaskServiceProtocol.cpp | SteveLau-GameDeveloper/engine | 159e5acd0f5115a878d59ed59f924ce7627a5466 | [
"Apache-2.0",
"MIT"
] | null | null | null | /****************************************************************************
Copyright (c) 2017-2018 Xiamen Yaji Software Co., Ltd.
http://www.cocos.com
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated engine source code (the "Software"), a limited,
worldwide, royalty-free, non-assignable, revocable and non-exclusive license
to use Cocos Creator solely to develop games on your target platforms. You shall
not use Cocos Creator software for developing other software or tools that's
used for developing games. You are not granted to publish, distribute,
sublicense, and/or sell copies of Cocos Creator.
The software or tools in this License Agreement are licensed, not sold.
Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
****************************************************************************/
#include "PlayerTaskServiceProtocol.h"
PLAYER_NS_BEGIN
std::string PlayerTask::getName() const
{
return _name;
}
std::string PlayerTask::getExecutePath() const
{
return _executePath;
}
std::string PlayerTask::getCommandLineArguments() const
{
return _commandLineArguments;
}
std::string PlayerTask::getOutput() const
{
return _output;
}
int PlayerTask::getState() const
{
return _state;
}
bool PlayerTask::isIdle() const
{
return _state == STATE_IDLE;
}
bool PlayerTask::isRunning() const
{
return _state == STATE_RUNNING;
}
bool PlayerTask::isCompleted() const
{
return _state == STATE_COMPLETED;
}
float PlayerTask::getLifetime() const
{
return _lifetime;
}
int PlayerTask::getResultCode() const
{
return _resultCode;
}
PlayerTask::PlayerTask(const std::string &name,
const std::string &executePath,
const std::string &commandLineArguments)
: _name(name)
, _executePath(executePath)
, _commandLineArguments(commandLineArguments)
, _state(STATE_IDLE)
, _lifetime(0)
, _resultCode(0)
{
}
PLAYER_NS_END
| 27.893617 | 81 | 0.663616 | SteveLau-GameDeveloper |
629c616781ef32f74e0a856d18828aee01fb6be6 | 3,958 | cpp | C++ | libNCUI/transfer/ShellTransfer.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 24 | 2018-11-20T14:45:57.000Z | 2021-12-30T13:38:42.000Z | libNCUI/transfer/ShellTransfer.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | null | null | null | libNCUI/transfer/ShellTransfer.cpp | realmark1r8h/tomoyadeng | aceab8fe403070bc12f9d49fdb7add0feb20424d | [
"BSD-2-Clause"
] | 11 | 2018-11-29T00:09:14.000Z | 2021-11-23T08:13:17.000Z | #include "stdafx.h"
#include "transfer/ShellTransfer.h"
#include <shellapi.h>
#include <amo/path.hpp>
namespace amo {
ShellTransfer::ShellTransfer()
: ClassTransfer("shell") {
}
Any ShellTransfer::exec(IPCMessage::SmartType msg) {
std::shared_ptr<AnyArgsList> args = msg->getArgumentList();
amo::u8string strOperation(args->getString(0), true);
amo::u8string strFileName(args->getString(1), true);
amo::u8string strParam(args->getString(2), true);
amo::u8string stsrDir(args->getString(3), true);
int nShowCmd = SW_SHOWNORMAL;
if (args->isValid(4)) {
nShowCmd = args->getInt(4);
}
return (int)::ShellExecuteW(NULL,
strOperation.to_unicode().c_str(),
strFileName.to_unicode().c_str(),
strParam.to_unicode().c_str(),
stsrDir.to_unicode().c_str(),
nShowCmd);
}
Any ShellTransfer::open(IPCMessage::SmartType msg) {
std::shared_ptr<AnyArgsList> args = msg->getArgumentList();
amo::u8string strFileName(args->getString(0), true);
amo::u8string strParam(args->getString(1), true);
amo::u8string stsrDir(args->getString(3), true);
return (int)::ShellExecuteW(NULL,
L"open",
strFileName.to_unicode().c_str(),
strParam.to_unicode().c_str(),
stsrDir.to_unicode().c_str(),
SW_SHOWNORMAL);
}
Any ShellTransfer::print(IPCMessage::SmartType msg) {
amo::u8string str(msg->getArgumentList()->getString(0), true);
return (int)::ShellExecuteW(NULL,
L"print",
str.to_unicode().c_str(),
NULL,
NULL,
SW_SHOWNORMAL);
}
Any ShellTransfer::showItemInFolder(IPCMessage::SmartType msg) {
amo::u8string str(msg->getArgumentList()->getString(0), true);
amo::u8string strParam(amo::u8string("/e, /select, ", true));
strParam += str;
return (int)::ShellExecuteW(NULL,
L"open",
L"explorer.exe",
strParam.to_wide().c_str(),
NULL,
SW_SHOWNORMAL);
}
int ShellTransfer::StringToShowCmd(const amo::u8string& str) {
if (str == "SW_HIDE") {
//隐藏窗口,活动状态给令一个窗口
return SW_HIDE;
} else if (str == "SW_MINIMIZE") {
//最小化窗口,活动状态给令一个窗口
return SW_MINIMIZE;
} else if (str == "SW_RESTORE") {
//用原来的大小和位置显示一个窗口,同时令其进入活动状态
return SW_RESTORE;
} else if (str == "SW_SHOW") {
//用当前的大小和位置显示一个窗口,同时令其进入活动状态
return SW_SHOW;
} else if (str == "SW_SHOWMAXIMIZED") {
//最大化窗口,并将其激活
return SW_SHOWMAXIMIZED;
} else if (str == "SW_SHOWMINIMIZED") {
//最小化窗口,并将其激活
return SW_SHOWMINIMIZED;
} else if (str == "SW_SHOWMINNOACTIVE") {
//最小化一个窗口,同时不改变活动窗口
return SW_SHOWMINNOACTIVE;
} else if (str == "SW_SHOWNA") {
//用当前的大小和位置显示一个窗口,不改变活动窗口
return SW_SHOWNA;
} else if (str == "SW_SHOWNOACTIVATE") {
//用最近的大小和位置显示一个窗口,同时不改变活动窗口
return SW_SHOWNOACTIVATE;
} else if (str == "SW_SHOWNORMAL") {
//与RESTORE相同
return SW_SHOWNORMAL;
} else {
return SW_SHOWNORMAL;
}
}
} | 36.990654 | 70 | 0.482314 | realmark1r8h |
629ec384b53658bedad7c16f9db65fd20f75abfe | 4,237 | cpp | C++ | libs/qtmpris/src/mprisrootinterface.cpp | wdehoog/hutspot-ut | f2d1e119d7628ebb0528d28bd57912ff4d1129ad | [
"MIT"
] | 2 | 2019-12-17T14:32:55.000Z | 2019-12-19T12:24:32.000Z | libs/qtmpris/src/mprisrootinterface.cpp | wdehoog/hutspot-ubports | f2d1e119d7628ebb0528d28bd57912ff4d1129ad | [
"MIT"
] | null | null | null | libs/qtmpris/src/mprisrootinterface.cpp | wdehoog/hutspot-ubports | f2d1e119d7628ebb0528d28bd57912ff4d1129ad | [
"MIT"
] | null | null | null | // -*- c++ -*-
/*!
*
* Copyright (C) 2015 Jolla Ltd.
*
* Contact: Valerio Valerio <valerio.valerio@jolla.com>
* Author: Andres Gomez <andres.gomez@jolla.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "mpriscontroller_p.h"
#include <QtCore/QtDebug>
/*
* Implementation of interface class MprisRootInterface
*/
MprisRootInterface::MprisRootInterface(const QString &service, const QString &path, const QDBusConnection &connection, QObject *parent)
: DBusExtendedAbstractInterface(service, path, staticInterfaceName(), connection, parent)
, m_canQuit(false)
, m_canRaise(false)
, m_canSetFullscreen(false)
, m_fullscreen(false)
, m_hasTrackList(false)
{
connect(this, SIGNAL(propertyChanged(QString, QVariant)), this, SLOT(onPropertyChanged(QString, QVariant)));
}
MprisRootInterface::~MprisRootInterface()
{
}
void MprisRootInterface::onPropertyChanged(const QString &propertyName, const QVariant &value)
{
if (propertyName == QStringLiteral("CanQuit")) {
bool canQuit = value.toBool();
if (m_canQuit != canQuit) {
m_canQuit = canQuit;
emit canQuitChanged(m_canQuit);
}
} else if (propertyName == QStringLiteral("CanRaise")) {
bool canRaise = value.toBool();
if (m_canRaise != canRaise) {
m_canRaise = canRaise;
emit canRaiseChanged(m_canRaise);
}
} else if (propertyName == QStringLiteral("CanSetFullscreen")) {
bool canSetFullscreen = value.toBool();
if (m_canSetFullscreen != canSetFullscreen) {
m_canSetFullscreen = canSetFullscreen;
emit canSetFullscreenChanged(m_canSetFullscreen);
}
} else if (propertyName == QStringLiteral("DesktopEntry")) {
QString desktopEntry = value.toString();
if (m_desktopEntry != desktopEntry) {
m_desktopEntry = desktopEntry;
emit desktopEntryChanged(m_desktopEntry);
}
} else if (propertyName == QStringLiteral("Fullscreen")) {
bool fullscreen = value.toBool();
if (m_fullscreen != fullscreen) {
m_fullscreen = fullscreen;
emit fullscreenChanged(m_fullscreen);
}
} else if (propertyName == QStringLiteral("HasTrackList")) {
bool hasTrackList = value.toBool();
if (m_hasTrackList != hasTrackList) {
m_hasTrackList = hasTrackList;
emit hasTrackListChanged(m_hasTrackList);
}
} else if (propertyName == QStringLiteral("Identity")) {
QString identity= value.toString();
if (m_identity != identity) {
m_identity = identity;
emit identityChanged(m_identity);
}
} else if (propertyName == QStringLiteral("SupportedMimeTypes")) {
QStringList supportedUriSchemes = value.toStringList();
if (m_supportedUriSchemes != supportedUriSchemes) {
m_supportedUriSchemes = supportedUriSchemes;
emit supportedMimeTypesChanged(m_supportedUriSchemes);
}
} else if (propertyName == QStringLiteral("SupportedUriSchemes")) {
QStringList supportedMimeTypes = value.toStringList();
if (m_supportedMimeTypes != supportedMimeTypes) {
m_supportedMimeTypes = supportedMimeTypes;
emit supportedUriSchemesChanged(m_supportedMimeTypes);
}
} else {
qWarning() << Q_FUNC_INFO
<< "Received PropertyChanged signal from unknown property: "
<< propertyName;
}
}
| 37.495575 | 135 | 0.667217 | wdehoog |
62a2691247bc3e7481468ed36136d70a3ac99a2e | 480 | cpp | C++ | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 8 | 2020-12-23T07:54:53.000Z | 2021-11-23T02:46:35.000Z | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2020-11-07T13:22:29.000Z | 2020-12-20T12:54:00.000Z | atcoder/abc168/b.cpp | xirc/cp-algorithm | 89c67cff2f00459c5bb020ab44bff5ae419a1728 | [
"Apache-2.0"
] | 1 | 2021-01-16T03:40:10.000Z | 2021-01-16T03:40:10.000Z | // https://atcoder.jp/contests/abc168/tasks/abc168_b
#include <bits/stdc++.h>
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <string>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int K;
string S;
cin >> K >> S;
if (S.size() <= K) {
cout << S << endl;
} else {
string Q = S.substr(0, K) + "...";
cout << Q << endl;
}
return 0;
} | 17.777778 | 52 | 0.55 | xirc |
62a993753ae18d905faa64ac35935d3a7cfd92ec | 3,720 | cpp | C++ | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | 1 | 2018-12-05T18:32:50.000Z | 2018-12-05T18:32:50.000Z | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | Day25/Day25.cpp | ATRI17Z/adventofcode18 | 5d743d7d277b416e3b5a287b0df598c4d5d67c6f | [
"MIT"
] | null | null | null | #include <iostream>
#include <fstream>
#include <string>
#include <list>
#include <array>
#include <regex>
#include <vector>
typedef int ll;
ll getManhattenDist4D(std::array<ll, 4>, std::array<ll, 4>);
std::list<std::string> getInputPerLines(std::string);
int main() {
std::array<ll, 4> point;
std::vector<std::array<ll, 4>> pointList;
// PARSE INPUT
std::list<std::string> pointStrings = getInputPerLines("input_Day25.txt");
std::regex regexpr("(-?[0-9]+)");
std::smatch m;
for (std::list<std::string>::iterator it = pointStrings.begin(); it != pointStrings.end(); ++it) {
std::regex_iterator<std::string::iterator> rit(it->begin(), it->end(), regexpr);
std::regex_iterator<std::string::iterator> rend;
point[0] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[1] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[2] = std::stoi(rit->str(), nullptr, 0); ++rit;
point[3] = std::stoi(rit->str(), nullptr, 0);
//for (auto n : point) {
// std::cout << n << " ";
//}
//std::cout << std::endl;
pointList.push_back(point);
}
//std::cout << "=====================" << std::endl;
int numConst = 1;
int dist;
std::vector<int> usedPoints(pointList.size(),0);
std::vector<int> cliqueIdx;
std::vector<std::vector<int>> cliqueListIdx;
for (int i = 0; i < pointList.size(); ++i) {
if (usedPoints[i] < 1) {
cliqueIdx.push_back(i);
usedPoints[i] = numConst;
bool stillMembersToCheck = true;
while (stillMembersToCheck) {
stillMembersToCheck = false;
}
for (int j = 0; j < pointList.size(); ++j) {
if (i == j) continue;
bool isInConstellation = false;
//bool notAlreadyContained = true;
for (int k = 0; k < cliqueIdx.size(); ++k) {
dist = getManhattenDist4D(pointList[cliqueIdx[k]], pointList[j]);
//std::cout << "Dist: " << j << "-" << cliqueIdx[k] << ": " << dist << std::endl;
if (dist < 4 &&
j != cliqueIdx[k] &&
usedPoints[j] < 1) {
//std::cout << "\t MatchDist: " << j << "-" << cliqueIdx[k] << ": " << dist << std::endl;
// these two point form a constelation
isInConstellation = true;
break;
}
}
if (isInConstellation) {
//std::cout << "Adding " << j << " to clique " << numConst << std::endl;
cliqueIdx.push_back(j);
usedPoints[j] = numConst;
j = 0; // start over
// DEBUG
//for (auto s : cliqueIdx) {
// std::cout << "[" << s << "]" << " ";
//}
//std::cout << std::endl;
//std::cin.get();
}
}
cliqueListIdx.push_back(cliqueIdx);
cliqueIdx.erase(cliqueIdx.begin(), cliqueIdx.end());
}
++numConst;
}
//std::cout << "=====================" << std::endl;
numConst = 0;
for (auto c : cliqueListIdx) {
if (c.size() > 2) ++numConst;
for (auto s : c) {
std::cout << "[" << s << "]" << " ";
}
std::cout << std::endl;
}
std::cout << "Num Constellations: " << cliqueListIdx.size() << std::endl;
// 169: too low
// 567: too high (counted all longly single points as well)
return 0;
}
/******************************
* INPUT HELPER FUNCTIONS *
******************************/
ll getManhattenDist4D(std::array<ll, 4> a, std::array<ll, 4> b)
{
ll dist;
dist = abs(a[0] - b[0]) + abs(a[1] - b[1]) + abs(a[2] - b[2]) + abs(a[3] - b[3]);
return dist;
}
std::list<std::string> getInputPerLines(std::string fileName) {
std::list<std::string> lines;
std::string line;
// Open File
std::ifstream in(fileName);
if (!in.is_open() || !in.good()) {
std::cout << "Failed to open input" << std::endl;
lines.push_back(std::string()); // empty string
return lines;
}
// Create Vector of lines
while (getline(in, line)) {
lines.push_back(line);
}
in.close();
return lines;
} | 25.655172 | 99 | 0.560753 | ATRI17Z |
62ab40755157d2e700c4399719c09d5a7e757660 | 1,704 | cpp | C++ | test/unit/math/opencl/indexing_rev_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/opencl/indexing_rev_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | test/unit/math/opencl/indexing_rev_test.cpp | LaudateCorpus1/math | 990a66b3cccd27a5fd48626360bb91093a48278b | [
"BSD-3-Clause"
] | null | null | null | #ifdef STAN_OPENCL
#ifndef STAN_TEST_SKIP_REQUIRING_OPENCL_INT64_BASE_ATOMIC
#include <stan/math/opencl/indexing_rev.hpp>
#include <stan/math/opencl/copy.hpp>
#include <test/unit/util.hpp>
#include <test/unit/math/expect_near_rel.hpp>
#include <gtest/gtest.h>
#include <algorithm>
TEST(indexing_rev, indexing_rev_small) {
Eigen::MatrixXd res(3, 3);
res << 1, 2, 3, 4, 5, 6, 7, 8, 9;
Eigen::MatrixXi idx(3, 3);
idx << 1, 2, 1, 0, 1, 2, 1, 1, 1;
Eigen::MatrixXd adj = Eigen::MatrixXd::Zero(3, 1);
Eigen::MatrixXd correct(3, 1);
correct << 4, 33, 8;
stan::math::matrix_cl<double> res_cl(res);
stan::math::matrix_cl<int> idx_cl(idx);
stan::math::matrix_cl<double> adj_cl(adj);
stan::math::indexing_rev(adj_cl, idx_cl, res_cl);
EXPECT_NEAR_REL(stan::math::from_matrix_cl(adj_cl), correct);
}
TEST(indexing_rev, indexing_rev_large) {
int N = 377;
// different sizes of adj ensure all three kernels are tested regardless of
// the OpenCL device
for (int M = 1; M < 1e6; M *= 2) {
Eigen::MatrixXd res = Eigen::MatrixXd::Random(N, N);
Eigen::MatrixXi idx(N, N);
for (int i = 0; i < N * N; i++) {
idx(i) = std::abs(Eigen::MatrixXi::Random(1, 1)(0)) % M;
}
Eigen::MatrixXd adj = Eigen::MatrixXd::Zero(M, 1);
Eigen::MatrixXd correct = adj;
for (int i = 0; i < N * N; i++) {
correct(idx(i)) += res(i);
}
stan::math::matrix_cl<double> res_cl(res);
stan::math::matrix_cl<int> idx_cl(idx);
stan::math::matrix_cl<double> adj_cl(adj);
stan::math::indexing_rev(adj_cl, idx_cl, res_cl);
EXPECT_NEAR_REL(stan::math::from_matrix_cl(adj_cl), correct);
}
}
#endif // STAN_TEST_SKIP_REQUIRING_OPENCL_INT64_BASE_ATOMIC
#endif
| 32.769231 | 77 | 0.661385 | LaudateCorpus1 |
62ade6f1df319792c79f00f6e4b4194a8d8b2d7c | 1,015 | cpp | C++ | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | acm.hdu.edu.cn/2005/main.cpp | hunterMG/Algorithm | 9435cec56ecf39c1e48725dc9fe06d8d6eacdb09 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstdio>
#include <cmath>
#include <cstring>
using namespace std;
int main()
{
int m[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31};
int y,mon,d;
char date[10];// 1985/1/20
while(~scanf("%s", date)){
getchar();
m[2] = 28;
y = (date[0]-'0')*1000+(date[1]-'0')*100+(date[2]-'0')*10+date[3]-'0';
if(date[6] == '/'){
mon = date[5]-'0';
if(strlen(date) == 8) d = date[7]-'0';
else d = (date[7]-'0')*10 +date[8]-'0';
}else{
mon = (date[5]-'0')*10+date[6]-'0';
if(strlen(date) == 9) d = date[8]-'0';
else d = (date[8]-'0')*10 +date[9]-'0';
}
if( y%400==0 || (y%4==0 && y%100!=0))
m[2] = 29;
if(mon == 1){
printf("%d\n", d);
}else{
int i=1;
while(i<mon){
d += m[i];
i++;
}
printf("%d\n", d);
}
}
return 0;
}
| 25.375 | 78 | 0.375369 | hunterMG |
62aeed594fe92bef8551993c5dc8aa8ecbee66a4 | 1,025 | cpp | C++ | chapter7/class2.cpp | kingmax/cpp | b0c3abcfc77094421d906695a4ac167463a43b92 | [
"Apache-2.0"
] | null | null | null | chapter7/class2.cpp | kingmax/cpp | b0c3abcfc77094421d906695a4ac167463a43b92 | [
"Apache-2.0"
] | null | null | null | chapter7/class2.cpp | kingmax/cpp | b0c3abcfc77094421d906695a4ac167463a43b92 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <string>
#include <vector>
using namespace std;
class Screen
{
public:
typedef std::string::size_type pos;
//Constructor
Screen() = default;
Screen(pos ht, pos wd, char c) : height(ht), width(wd),
contents(ht * wd, c) {}
//Methods
char get() const
{
return contents[cursor];
}
inline char get(pos ht, pos wd) const;
Screen &move(pos r, pos c);
//mutable
void some_member() const;
private:
pos cursor = 0;
pos height = 0, width = 0;
std::string contents;
//mutable data member
mutable size_t access_ctr; //can change in const!!
};
void Screen::some_member() const
{
++access_ctr; //can change in const object!!!
}
inline Screen &Screen::move(pos r, pos c)
{
pos row = r * width;
cursor = row + c;
return *this;
}
inline char Screen::get(pos ht, pos wd) const
{
pos row = ht * width;
return contents[row + wd];
}
class Window_mgr
{
private:
std::vector<Screen> screens{Screen(24, 80, ' ')};
};
int main()
{
return 0;
} | 15.769231 | 58 | 0.632195 | kingmax |
62b355299e738802da25d86381eeab9604199668 | 1,680 | cpp | C++ | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | 5 | 2018-10-07T11:13:18.000Z | 2021-11-18T13:57:27.000Z | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | null | null | null | baremetal/Darwin/DarwinSerial.cpp | cmarrin/placid | deb5a5301de98011a3c2b312b068b325b5191c17 | [
"MIT"
] | 1 | 2018-12-07T18:20:17.000Z | 2018-12-07T18:20:17.000Z | /*-------------------------------------------------------------------------
This source file is a part of Placid
For the latest info, see http:www.marrin.org/
Copyright (c) 2018-2019, Chris Marrin
All rights reserved.
Use of this source code is governed by the MIT license that can be
found in the LICENSE file.
-------------------------------------------------------------------------*/
#include "bare.h"
#include "bare/Serial.h"
#include "bare/GPIO.h"
#include "bare/InterruptManager.h"
#include "bare/Timer.h"
#include <iostream>
#include <unistd.h>
#include <errno.h>
#include <util.h>
#include <termios.h>
//#define USE_PTY
using namespace bare;
#ifdef USE_PTY
static int master;
static int slave;
#endif
void Serial::init(uint32_t baudrate)
{
#ifdef USE_PTY
struct termios tty;
tty.c_iflag = (tcflag_t) 0;
tty.c_lflag = (tcflag_t) 0;
tty.c_cflag = CS8;
tty.c_oflag = (tcflag_t) 0;
char buf[256];
auto e = openpty(&master, &slave, buf, &tty, nullptr);
if(0 > e) {
::printf("Error: %s\n", strerror(errno));
return;
}
::printf("Slave PTY: %s\n", buf);
fflush(stdout);
#endif
}
Serial::Error Serial::read(uint8_t& c)
{
#ifdef USE_PTY
return (::read(master, &c, 1) == -1) ? Error::Fail : Error::OK;
#else
c = getchar();
return Error::OK;
#endif
}
bool Serial::rxReady()
{
return true;
}
Serial::Error Serial::write(uint8_t c)
{
#ifdef USE_PTY
::write(master, &c, 1);
#else
if (c != '\r') {
std::cout.write(reinterpret_cast<const char*>(&c), 1);
}
#endif
return Error::OK;
}
void Serial::handleInterrupt()
{
}
void Serial::clearInput()
{
}
| 18.26087 | 75 | 0.574405 | cmarrin |
62b445c9a6c11810df1ff6cde9a5f65e11b3515a | 2,106 | cc | C++ | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 20 | 2020-06-28T03:55:40.000Z | 2022-03-08T06:00:31.000Z | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | null | null | null | src/shapes/quad.cc | BlurryLight/DiRender | 1ea55ff8a10bb76993ce9990b200ee8ed173eb3e | [
"MIT"
] | 1 | 2020-06-29T08:47:21.000Z | 2020-06-29T08:47:21.000Z | //
// Created by panda on 2021/2/28.
//
#include "quad.h"
using namespace DR;
Quad::Quad(observer_ptr<Transform> LocalToWorld,
observer_ptr<Transform> WorldToObject, Point3f a, Point3f b,
Point3f c, bool reverse)
: Shape(LocalToWorld, WorldToObject, reverse)
// clang-format off
/*
* (2)c ------- d(3)
* / \ /
* / \ /
* /------/
* a(0) b(1)
* index: 0 1 2
* index: 1 3 2
*/
// clang-format on
{
vec3 ad = (b - a) + (c - a);
Point3f d = a + ad;
std::vector<Point3f> vertices{a, b, c, d};
int nVertices = 4;
int nTriangles = 2;
std::vector<DR::uint> vertexIndices{0, 1, 2, 1, 3, 2};
Normal3f normal = reverse ? (c - a).cross(b - a) : (b - a).cross(c - a);
normal = normal.normalize();
std::vector<Normal3f> normals(4, normal);
std::vector<Point2f> uvs{{0, 0}, {0, 1}, {1, 0}, {1, 1}};
std::vector<int> faceIndices(nTriangles, 0);
auto mesh_ptr = std::make_shared<TriangleMesh>(
LocalToWorld, nTriangles, nVertices, vertexIndices.data(),
vertices.data(), normals.data(), uvs.data(), faceIndices.data());
this->tris_[0] = std::make_unique<Triangle>(LocalToWorld, WorldToObject,
reverse, mesh_ptr, 0);
this->tris_[1] = std::make_unique<Triangle>(LocalToWorld, WorldToObject,
reverse, mesh_ptr, 1);
}
Bounds3 Quad::ObjectBounds() const {
return Bounds3::Union(tris_[0]->ObjectBounds(), tris_[1]->ObjectBounds());
}
Bounds3 Quad::WorldBounds() const {
return Bounds3::Union(tris_[0]->WorldBounds(), tris_[1]->WorldBounds());
}
bool Quad::Intersect(const Ray &ray, float *time, Intersection *isect) const {
if (tris_[0]->Intersect(ray, time, isect))
return true;
return tris_[1]->Intersect(ray, time, isect);
}
float Quad::Area() const { return tris_[0]->Area() + tris_[1]->Area(); }
std::pair<Intersection, float> Quad::sample() const {
// naive sampler
int index = get_random_float() > 0.5 ? 0 : 1;
return tris_[index]->sample();
}
| 34.52459 | 78 | 0.581671 | BlurryLight |
62bb221b2319ebc04c68b74a53c08295f08adc42 | 1,358 | cpp | C++ | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 25 | 2019-05-20T08:07:39.000Z | 2021-08-17T11:25:02.000Z | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | null | null | null | halfnetwork/HalfNetwork/HalfNetwork/Src/ReactorPool.cpp | cjwcjswo/com2us_cppNetStudy_work | 3aab26cfd2e9bf1544fa41a0f2694d81167b2584 | [
"MIT"
] | 17 | 2019-07-07T12:20:16.000Z | 2022-01-11T08:27:44.000Z | #include <string>
#include <ace/Singleton.h>
#include "HalfNetworkType.h"
#include "ReactorPool.h"
namespace HalfNetwork
{
/////////////////////////////////////////
// ReactorTask
/////////////////////////////////////////
ReactorTask::ReactorTask()
{
this->reactor(ACE_Reactor::instance());
}
ReactorTask::~ReactorTask()
{
this->reactor(NULL);
}
bool ReactorTask::Open(uint8 poolSize)
{
int properPoolSize = poolSize;
if (0 == properPoolSize)
properPoolSize = 1;
m_poolSize = properPoolSize;
return (-1 != this->activate(THR_NEW_LWP|THR_JOINABLE, m_poolSize));
}
void ReactorTask::Close()
{
ACE_Reactor::instance()->end_reactor_event_loop();
this->wait();
ACE_Reactor::instance()->reset_reactor_event_loop();
}
uint8 ReactorTask::GetPoolSize()
{
return m_poolSize;
}
int ReactorTask::svc()
{
ACE_Reactor::instance()->owner(ACE_Thread::self());
ACE_Reactor::instance()->run_reactor_event_loop();
return 0;
}
/////////////////////////////////////////
// ReactorPool
/////////////////////////////////////////
bool ReactorPool::Open(uint8 poolSize)
{
return _task.Open(poolSize);
}
void ReactorPool::Close()
{
_task.Close();
}
uint8 ReactorPool::GetPoolSize()
{
return _task.GetPoolSize();
}
} // namespace HalfNetwork | 20.268657 | 71 | 0.576583 | cjwcjswo |
62bb84d5245fc5ce5e44203f63e6a63308b2f546 | 3,324 | cc | C++ | HeterogeneousCore/SonicTriton/test/TritonImageProducer.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 1 | 2018-03-14T16:25:31.000Z | 2018-03-14T16:25:31.000Z | HeterogeneousCore/SonicTriton/test/TritonImageProducer.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 3 | 2020-02-19T08:33:16.000Z | 2020-03-13T10:02:19.000Z | HeterogeneousCore/SonicTriton/test/TritonImageProducer.cc | tklijnsma/cmssw | d7f103c459dd195eaa651ce0c30e4bd4bfd0fe43 | [
"Apache-2.0"
] | 1 | 2018-09-12T13:30:34.000Z | 2018-09-12T13:30:34.000Z | #include "HeterogeneousCore/SonicCore/interface/SonicEDProducer.h"
#include "HeterogeneousCore/SonicTriton/interface/TritonClient.h"
#include "FWCore/ParameterSet/interface/ConfigurationDescriptions.h"
#include "FWCore/ParameterSet/interface/ParameterSetDescription.h"
#include "FWCore/Framework/interface/MakerMacros.h"
#include <sstream>
#include <fstream>
#include <string>
#include <vector>
#include <map>
template <typename Client>
class TritonImageProducer : public SonicEDProducer<Client> {
public:
//needed because base class has dependent scope
using typename SonicEDProducer<Client>::Input;
using typename SonicEDProducer<Client>::Output;
explicit TritonImageProducer(edm::ParameterSet const& cfg)
: SonicEDProducer<Client>(cfg), topN_(cfg.getParameter<unsigned>("topN")) {
//for debugging
this->setDebugName("TritonImageProducer");
//load score list
std::string imageListFile(cfg.getParameter<std::string>("imageList"));
std::ifstream ifile(imageListFile);
if (ifile.is_open()) {
std::string line;
while (std::getline(ifile, line)) {
imageList_.push_back(line);
}
} else {
throw cms::Exception("MissingFile") << "Could not open image list file: " << imageListFile;
}
}
void acquire(edm::Event const& iEvent, edm::EventSetup const& iSetup, Input& iInput) override {
// create an npix x npix x ncol image w/ arbitrary color value
iInput.resize(client_.nInput() * client_.batchSize(), 0.5f);
}
void produce(edm::Event& iEvent, edm::EventSetup const& iSetup, Output const& iOutput) override {
//check the results
findTopN(iOutput);
}
~TritonImageProducer() override = default;
static void fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
Client::fillPSetDescription(desc);
desc.add<unsigned>("topN", 5);
desc.add<std::string>("imageList");
//to ensure distinct cfi names
descriptions.addWithDefaultLabel(desc);
}
private:
using SonicEDProducer<Client>::client_;
void findTopN(const std::vector<float>& scores, unsigned n = 5) const {
auto dim = client_.nOutput();
for (unsigned i0 = 0; i0 < client_.batchSize(); i0++) {
//match score to type by index, then put in largest-first map
std::map<float, std::string, std::greater<float>> score_map;
for (unsigned i = 0; i < std::min((unsigned)dim, (unsigned)imageList_.size()); ++i) {
score_map.emplace(scores[i0 * dim + i], imageList_[i]);
}
//get top n
std::stringstream msg;
msg << "Scores for image " << i0 << ":\n";
unsigned counter = 0;
for (const auto& item : score_map) {
msg << item.second << " : " << item.first << "\n";
++counter;
if (counter >= topN_)
break;
}
edm::LogInfo(client_.debugName()) << msg.str();
}
}
unsigned topN_;
std::vector<std::string> imageList_;
};
using TritonImageProducerSync = TritonImageProducer<TritonClientSync>;
using TritonImageProducerAsync = TritonImageProducer<TritonClientAsync>;
using TritonImageProducerPseudoAsync = TritonImageProducer<TritonClientPseudoAsync>;
DEFINE_FWK_MODULE(TritonImageProducerSync);
DEFINE_FWK_MODULE(TritonImageProducerAsync);
DEFINE_FWK_MODULE(TritonImageProducerPseudoAsync);
| 36.933333 | 99 | 0.702467 | tklijnsma |
62bdaeffef0d5c0a033cefe99c63556843f15e5e | 3,249 | cc | C++ | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | 12 | 2016-12-01T02:49:35.000Z | 2020-11-23T14:32:24.000Z | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | null | null | null | server/dal/group_dao_impl.cc | nebula-im/imengine | c3e0867ecfa7c7bd9f42cb37754ed54c08e8b459 | [
"Apache-2.0"
] | 6 | 2018-01-25T03:42:07.000Z | 2020-11-03T04:19:21.000Z | /*
* Copyright (c) 2016, https://github.com/nebula-im/imengine
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "dal/group_dao_impl.h"
GroupDAO& GroupDAO::GetInstance() {
static GroupDAOImpl impl;
return impl;
}
int GroupDAOImpl::CheckExists(const std::string& creator_user_id, uint64_t client_group_id) {
return DoStorageQuery("nebula_engine",
[&](std::string& query_string) {
folly::format(&query_string, "SELECT id FROM groups WHERE creator_user_id='{}' AND client_group_id={} LIMIT 1",
creator_user_id,
client_group_id);
},
[&](MysqlResultSet& answ) -> int {
return BREAK;
});
}
int64_t GroupDAOImpl::Create(GroupDO& group) {
return DoStorageInsertID("nebula_engine",
[&](std::string& query_string) {
QueryParam p;
p.AddParam(group.group_id.c_str());
p.AddParam(group.creator_user_id.c_str());
p.AddParam(&group.client_group_id);
p.AddParamEsc(group.title.c_str());
p.AddParamEsc(group.avatar.c_str());
p.AddParamEsc(group.topic.c_str());
p.AddParamEsc(group.about.c_str());
p.AddParam(&group.created_at);
p.AddParam(&group.updated_at);
MakeQueryString("INSERT INTO groups "
"(group_id,creator_user_id,client_group_id,title,avatar,topic,about,status,created_at,updated_at) "
"VALUES "
"(:1,:2,:3,:4,:5,:6,:7,1,:8,:9)",
&p,
&query_string);
});
}
int GroupDAOImpl::GetGroup(const std::string& group_id, GroupDO& group) {
return DoStorageQuery("nebula_engine",
[&](std::string& query_string) {
folly::format(&query_string, "SELECT id FROM groups WHERE group_id='{}' LIMIT 1",
group_id);
},
[&](MysqlResultSet& answ) -> int {
group.app_id = 1;
// ...
return BREAK;
});
}
| 45.125 | 148 | 0.480148 | nebula-im |
62bdb0d602368a1aba7f31194b7bf570985447e3 | 459 | hpp | C++ | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | 3 | 2015-08-19T19:29:28.000Z | 2016-11-15T07:41:06.000Z | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | null | null | null | src/keyhook.hpp | agrippa1994/node-win32-keyhook | 3b3892c2f20c5821878d7d720f1dc671e7c0cbc3 | [
"MIT"
] | null | null | null | #ifndef KEYHOOK_HPP
#define KEYHOOK_HPP
#include <string>
#include <functional>
typedef std::function<bool()> KeyPressedCallback;
bool isKeyRegistered(const std::string& key);
bool registerKey(const std::string& key, KeyPressedCallback callback);
bool unregisterKey(const std::string& key);
bool initializeKeyhook();
bool destroyKeyhook();
void setKeyboardHookedCallback(std::function<void(bool)> callback);
void unsetKeyboardHookedCallback();
#endif | 20.863636 | 70 | 0.79085 | agrippa1994 |
4983f3da929285e5e562d39b82dab15d29ca6a1b | 4,966 | cpp | C++ | third_party/virtualbox/src/VBox/HostServices/SharedOpenGL/crserverlib/server_getteximage.cpp | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 521 | 2019-03-29T15:44:08.000Z | 2022-03-22T09:46:19.000Z | third_party/virtualbox/src/VBox/HostServices/SharedOpenGL/crserverlib/server_getteximage.cpp | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 30 | 2019-06-04T17:00:49.000Z | 2021-09-08T20:44:19.000Z | third_party/virtualbox/src/VBox/HostServices/SharedOpenGL/crserverlib/server_getteximage.cpp | Fimbure/icebox-1 | 0b81992a53e1b410955ca89bdb6f8169d6f2da86 | [
"MIT"
] | 99 | 2019-03-29T16:04:13.000Z | 2022-03-28T16:59:34.000Z | /* Copyright (c) 2001, Stanford University
* All rights reserved
*
* See the file LICENSE.txt for information on redistributing this software.
*/
#include "chromium.h"
#include "cr_error.h"
#include "cr_mem.h"
#include "cr_pixeldata.h"
#include "server_dispatch.h"
#include "server.h"
void SERVER_DISPATCH_APIENTRY
crServerDispatchGetTexImage(GLenum target, GLint level, GLenum format,
GLenum type, GLvoid * pixels)
{
GLsizei width, height, depth, size;
GLvoid *buffer = NULL;
#ifdef CR_ARB_pixel_buffer_object
if (crStateIsBufferBound(&cr_server.StateTracker, GL_PIXEL_PACK_BUFFER_ARB))
{
GLvoid *pbo_offset;
/*pixels are actually a pointer to location of 8byte network pointer in hgcm buffer
regardless of guest/host bitness we're using only 4lower bytes as there're no
pbo>4gb (yet?)
*/
pbo_offset = (GLvoid*) ((uintptr_t) *((GLint*)pixels));
cr_server.head_spu->dispatch_table.GetTexImage(target, level, format, type, pbo_offset);
return;
}
#endif
cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(target, level, GL_TEXTURE_WIDTH, &width);
cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(target, level, GL_TEXTURE_HEIGHT, &height);
cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(target, level, GL_TEXTURE_DEPTH, &depth);
size = crTextureSize(format, type, width, height, depth);
#if 0
{
CRContext *ctx = crStateGetCurrent();
CRTextureObj *tobj;
CRTextureLevel *tl;
GLint id;
crDebug("GetTexImage: %d, %i, %d, %d", target, level, format, type);
crDebug("===StateTracker===");
crDebug("Current TU: %i", ctx->texture.curTextureUnit);
if (target==GL_TEXTURE_2D)
{
tobj = ctx->texture.unit[ctx->texture.curTextureUnit].currentTexture2D;
CRASSERT(tobj);
tl = &tobj->level[0][level];
crDebug("Texture %i(hw %i), w=%i, h=%i", tobj->id, tobj->hwid, tl->width, tl->height, tl->depth);
}
else
{
crDebug("Not 2D tex");
}
crDebug("===GPU===");
cr_server.head_spu->dispatch_table.GetIntegerv(GL_ACTIVE_TEXTURE, &id);
crDebug("Current TU: %i", id);
if (target==GL_TEXTURE_2D)
{
cr_server.head_spu->dispatch_table.GetIntegerv(GL_TEXTURE_BINDING_2D, &id);
crDebug("Texture: %i, w=%i, h=%i, d=%i", id, width, height, depth);
}
}
#endif
if (size && (buffer = crCalloc(size))) {
/* Note, the other pixel PACK parameters (default values) should
* be OK at this point.
*/
cr_server.head_spu->dispatch_table.PixelStorei(GL_PACK_ALIGNMENT, 1);
cr_server.head_spu->dispatch_table.GetTexImage(target, level, format, type, buffer);
crServerReturnValue( buffer, size );
crFree(buffer);
}
else {
/* need to return _something_ to avoid blowing up */
GLuint dummy = 0;
crServerReturnValue( (GLvoid *) &dummy, sizeof(dummy) );
}
}
#if CR_ARB_texture_compression
void SERVER_DISPATCH_APIENTRY
crServerDispatchGetCompressedTexImageARB(GLenum target, GLint level,
GLvoid *img)
{
GLint size;
GLvoid *buffer=NULL;
#ifdef CR_ARB_pixel_buffer_object
if (crStateIsBufferBound(&cr_server.StateTracker, GL_PIXEL_PACK_BUFFER_ARB))
{
GLvoid *pbo_offset;
pbo_offset = (GLvoid*) ((uintptr_t) *((GLint*)img));
cr_server.head_spu->dispatch_table.GetCompressedTexImageARB(target, level, pbo_offset);
return;
}
#endif
cr_server.head_spu->dispatch_table.GetTexLevelParameteriv(target, level, GL_TEXTURE_COMPRESSED_IMAGE_SIZE, &size);
if (size && (buffer = crCalloc(size))) {
/* XXX the pixel PACK parameter should be OK at this point */
cr_server.head_spu->dispatch_table.GetCompressedTexImageARB(target, level, buffer);
crServerReturnValue( buffer, size );
crFree(buffer);
}
else {
/* need to return _something_ to avoid blowing up */
GLuint dummy = 0;
crServerReturnValue( (GLvoid *) &dummy, sizeof(dummy) );
}
}
#endif /* CR_ARB_texture_compression */
void SERVER_DISPATCH_APIENTRY crServerDispatchGetPolygonStipple( GLubyte * mask )
{
#ifdef CR_ARB_pixel_buffer_object
if (crStateIsBufferBound(&cr_server.StateTracker, GL_PIXEL_PACK_BUFFER_ARB))
{
GLvoid *pbo_offset;
pbo_offset = (GLubyte*) ((uintptr_t) *((GLint*)mask));
cr_server.head_spu->dispatch_table.GetPolygonStipple((GLubyte *)pbo_offset);
}
else
#endif
{
GLubyte local_mask[128];
memset(local_mask, 0, sizeof(local_mask));
cr_server.head_spu->dispatch_table.GetPolygonStipple( local_mask );
crServerReturnValue( &(local_mask[0]), 128*sizeof(GLubyte) );
}
}
| 31.630573 | 118 | 0.649013 | Fimbure |
498b2cb79f7cb8217759663ca39f872e44498c66 | 477 | cpp | C++ | cpps/02/types.cpp | ch1huizong/lang | 904d18b9364033af07933d38fd3f2e136a3cba2c | [
"MIT"
] | null | null | null | cpps/02/types.cpp | ch1huizong/lang | 904d18b9364033af07933d38fd3f2e136a3cba2c | [
"MIT"
] | null | null | null | cpps/02/types.cpp | ch1huizong/lang | 904d18b9364033af07933d38fd3f2e136a3cba2c | [
"MIT"
] | null | null | null | #include <iostream>
// T: 类型定义语法
typedef int int_32;
typedef unsigned int un_32;
using machine_32 = int;
using machine_64 = long;
int main() {
int_32 a = 10;
un_32 b = 65;
printf("a = %d\n", a);
printf("b = %d\n", b);
printf("sizeof(machine_32) = %d\n", sizeof(machine_32));
printf("sizeof(machine_64) = %d\n", sizeof(machine_64));
auto v = a + b; // 类型取决于右边
printf("v = %d\n", v);
decltype(b) j = 2; // j是b类型
printf("j = %d\n", j);
return 0;
}
| 17.035714 | 58 | 0.584906 | ch1huizong |
498b77b42868a1c0ed27bca3ae3f5c81e461a29a | 1,133 | cpp | C++ | platforms/leetcode/0116_rotate_list.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/leetcode/0116_rotate_list.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | platforms/leetcode/0116_rotate_list.cpp | idfumg/algorithms | 06f85c5a1d07a965df44219b5a6bf0d43a129256 | [
"MIT"
] | null | null | null | #include "../../template.hpp"
using i32 = std::int32_t;
using i64 = std::int64_t;
//const i32 INF = 1000000000 + 7;
const i32 fastio_ = ([](){std::ios_base::sync_with_stdio(0); std::cin.tie(0);return 0;})();
i32 getLength(ListNode* head) {
if (not head) return 0;
return 1 + getLength(head->next);
}
ListNode* rotateRight(ListNode* head) {
ListNode* node = head;
while (node and node->next and node->next->next) {
node = node->next;
}
ListNode* tmp = exchange(node->next, nullptr);
tmp->next = head;
head = tmp;
return head;
}
ListNode* sol(ListNode* head, i32 k) {
if (not head) return {};
k %= getLength(head);
while (k--) {
head = rotateRight(head);
}
return head;
}
ListNode* sol(const vi& arr, const int k) {
ListNode* head = make_list(arr);
ListNode* ans = sol(head, k);
return ans;
}
ostream& operator<<(ostream& os, ListNode* head) { print_list2(head); return os; }
int main() { TimeMeasure _;
cout << sol({1,2,3,4,5}, 2) << endl; // 4,5,1,2,3
cout << sol({0,1,2}, 4) << endl; // 2,0,1
cout << sol({}, 0) << endl; // []
}
| 24.630435 | 91 | 0.580759 | idfumg |
498ba48a20f7569d7ea878890b12a5fba546d518 | 787 | cpp | C++ | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | NAMESPACES in C++/namespace.cpp | anjali9811/Programming-in-Cpp | 02e80e045a7fb20f8970fcdae68c08bdf27f95b8 | [
"Apache-2.0"
] | null | null | null | #include<iostream>
using namespace std;
/*program to explain the concept of namespaces
namespaces consists of a set of identifiers which are local to that particular name space.Also namespaces are like the lastname of a 2 persons having different names.
Like we can differentiate 2persons with smae first names using their last names(Which are different) in the same way to avoid name collisions in c++, we use
namespaces.
To access members of a namespace outside it, we have to use scope resolution operator.
'using' keyword actually loads the particular namespace into the golbal namespace or global scope.
Each program has a un-named or anynymous namespace.
*/
#include "one.cpp"
#include "two.cpp"
int main()
{
one::x=20;
one::display();
two::x=30;
two::display();
}
| 26.233333 | 166 | 0.76493 | anjali9811 |
498d73819a96ddf8ea1759cbfd7076d67af9f7cd | 3,150 | hh | C++ | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 19 | 2018-04-23T09:30:48.000Z | 2022-03-06T21:35:18.000Z | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 22 | 2017-11-27T23:39:25.000Z | 2019-08-09T08:56:57.000Z | src/Zynga/Framework/StorableObject/V1/Base.hh | chintan-j-patel/zynga-hacklang-framework | d9893b8873e3c8c7223772fd3c94d2531760172a | [
"MIT"
] | 28 | 2017-11-16T20:53:56.000Z | 2021-01-04T11:13:17.000Z | <?hh // strict
namespace Zynga\Framework\StorableObject\V1;
use JsonSerializable;
use Zynga\Framework\StorableObject\V1\Interfaces\StorableObjectInterface;
use
Zynga\Framework\StorableObject\V1\Exceptions\MissingKeyFromImportDataException
;
use Zynga\Framework\StorableObject\V1\Exceptions\UnsupportedTypeException;
use
Zynga\Framework\StorableObject\V1\Exceptions\PropertyUnavailableException
;
use
Zynga\Framework\StorableObject\V1\Exceptions\ExpectedFieldCountMismatchException
;
use Zynga\Framework\StorableObject\V1\SupportedTypes;
use Zynga\Framework\StorableObject\V1\Interfaces\ImportInterface;
use Zynga\Framework\StorableObject\V1\Interfaces\ExportInterface;
use Zynga\Framework\StorableObject\V1\Interfaces\FieldsInterface;
use Zynga\Framework\StorableObject\V1\Object\Importer;
use Zynga\Framework\StorableObject\V1\Object\Exporter;
use Zynga\Type\V1\Interfaces\TypeInterface;
use Zynga\Framework\StorableObject\V1\Fields;
use Zynga\Framework\StorableObject\V1\Fields\Generic as FieldsGeneric;
use Zynga\Framework\Exception\V1\Exception;
abstract class Base implements StorableObjectInterface, JsonSerializable {
private bool $_isRequired;
private ?bool $_isDefaultValue;
public function __construct() {
// --
// As hack requires you to not use $this-><func> until the init is overwith
// we can make the assumption the default value is going to be set for the
// object
// --
$this->_isRequired = false;
$this->_isDefaultValue = null;
}
public function fields(): FieldsInterface {
$fields = new Fields($this);
return $fields;
}
public function import(): ImportInterface {
$importer = new Importer($this);
return $importer;
}
public function export(): ExportInterface {
$exporter = new Exporter($this);
return $exporter;
}
public function setIsRequired(bool $isRequired): bool {
$this->_isRequired = $isRequired;
return true;
}
public function getIsRequired(): bool {
return $this->_isRequired;
}
public function setIsDefaultValue(bool $tf): bool {
$this->_isDefaultValue = $tf;
return true;
}
public function isDefaultValue(): (bool, Vector<string>) {
$defaultFields = Vector {};
if ($this->_isDefaultValue !== null) {
return tuple($this->_isDefaultValue, $defaultFields);
}
$fields = $this->fields()->getForObject();
foreach ($fields as $fieldName => $field) {
list($f_isRequired, $f_isDefaultValue) =
FieldsGeneric::getIsRequiredAndIsDefaultValue($field);
// echo json_encode(array(get_class($this), $fieldName, $f_isDefaultValue)) . "\n";
if ($f_isDefaultValue === true) {
$defaultFields[] = $fieldName;
}
}
$isDefaultValue = true;
// --
// if any of the fields or child fields are not the default,
// we are okay marking this object as not default.
// --
if ($defaultFields->count() != $fields->count()) {
$isDefaultValue = false;
}
return tuple($isDefaultValue, $defaultFields);
}
public function jsonSerialize(): mixed {
return $this->export()->asMap()->toArray();
}
}
| 26.25 | 89 | 0.713333 | chintan-j-patel |
499065902e136fd401a2fcbc4826c7116b0293b3 | 828 | cpp | C++ | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | lectures/7-IntroToRecursion/code/towersHanoi/src/towers.cpp | tofergregg/cs106X-website-spring-2017 | 1c1f4bab672248a77bdb881e818dee49b48c0070 | [
"MIT"
] | null | null | null | #include <fstream>
#include <iostream>
#include <iomanip>
#include "console.h"
#include "timer.h"
#include "hashset.h"
#include "lexicon.h"
#include "queue.h"
#include "set.h"
#include "vector.h"
#include "grid.h"
#include "filelib.h"
#include "gwindow.h"
#include "gobjects.h"
#include "simpio.h"
#include "ghanoi.h"
using namespace std;
static const int N = 5;
void findSolution(int n, char source, char target, char aux) {
// All about that base
if(n == 1) {
moveSingleDisk(source, target);
// Recursive case
} else {
findSolution(n - 1, source, aux, target);
moveSingleDisk(source, target);
findSolution(n - 1, aux, target, source);
}
}
int main() {
cout << "Towers of Hanoi" << endl;
initHanoiDisplay(N);
findSolution(N, 'a', 'c', 'b');
return 0;
}
| 19.714286 | 62 | 0.628019 | tofergregg |
4991dc9486f61adbf45deba82b13fd0f99c3d4f9 | 321 | cpp | C++ | Source Code/SIMFECompiler.cpp | kaiky25/SIMFECompiler | 8088113a7d555f9c334c166e3a4629b9e5078f49 | [
"MIT"
] | null | null | null | Source Code/SIMFECompiler.cpp | kaiky25/SIMFECompiler | 8088113a7d555f9c334c166e3a4629b9e5078f49 | [
"MIT"
] | null | null | null | Source Code/SIMFECompiler.cpp | kaiky25/SIMFECompiler | 8088113a7d555f9c334c166e3a4629b9e5078f49 | [
"MIT"
] | null | null | null | // SIMFECompiler.cpp
// SIMFECompiler
// Created by Kaê Angeli Coutinho
// MIT license
// Included dependencies
#include "SIMFECompilerFunctions.h"
// Compiler lifecycle
int main(int argumentsCount, char ** arguments)
{
// Compiles the given SIM source code
return compileSIMSourceCode(argumentsCount,arguments);
}
| 18.882353 | 55 | 0.76947 | kaiky25 |
49927a325be1a2e72019019e98d47a8d4244f018 | 7,116 | cpp | C++ | libraries/shared/src/LogHandler.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | null | null | null | libraries/shared/src/LogHandler.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | null | null | null | libraries/shared/src/LogHandler.cpp | mnafees/hifi | d8f0cfa89a1fdf7339bac6af984e940df6265006 | [
"Apache-2.0"
] | null | null | null | //
// LogHandler.cpp
// libraries/shared/src
//
// Created by Stephen Birarda on 2014-10-28.
// Migrated from Logging.cpp created on 6/11/13
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
#include "LogHandler.h"
#include <mutex>
#ifdef Q_OS_WIN
#include <windows.h>
#endif
#include <QtCore/QCoreApplication>
#include <QtCore/QDateTime>
#include <QtCore/QDebug>
#include <QtCore/QMutexLocker>
#include <QtCore/QThread>
#include <QtCore/QTimer>
QMutex LogHandler::_mutex;
LogHandler& LogHandler::getInstance() {
static LogHandler staticInstance;
return staticInstance;
}
LogHandler::LogHandler() {
// when the log handler is first setup we should print our timezone
QString timezoneString = "Time zone: " + QDateTime::currentDateTime().toString("t");
printMessage(LogMsgType::LogInfo, QMessageLogContext(), timezoneString);
}
LogHandler::~LogHandler() {
flushRepeatedMessages();
printMessage(LogMsgType::LogDebug, QMessageLogContext(), "LogHandler shutdown.");
}
const char* stringForLogType(LogMsgType msgType) {
switch (msgType) {
case LogInfo:
return "INFO";
case LogDebug:
return "DEBUG";
case LogWarning:
return "WARNING";
case LogCritical:
return "CRITICAL";
case LogFatal:
return "FATAL";
case LogSuppressed:
return "SUPPRESS";
default:
return "UNKNOWN";
}
}
// the following will produce 11/18 13:55:36
const QString DATE_STRING_FORMAT = "MM/dd hh:mm:ss";
// the following will produce 11/18 13:55:36.999
const QString DATE_STRING_FORMAT_WITH_MILLISECONDS = "MM/dd hh:mm:ss.zzz";
void LogHandler::setTargetName(const QString& targetName) {
QMutexLocker lock(&_mutex);
_targetName = targetName;
}
void LogHandler::setShouldOutputProcessID(bool shouldOutputProcessID) {
QMutexLocker lock(&_mutex);
_shouldOutputProcessID = shouldOutputProcessID;
}
void LogHandler::setShouldOutputThreadID(bool shouldOutputThreadID) {
QMutexLocker lock(&_mutex);
_shouldOutputThreadID = shouldOutputThreadID;
}
void LogHandler::setShouldDisplayMilliseconds(bool shouldDisplayMilliseconds) {
QMutexLocker lock(&_mutex);
_shouldDisplayMilliseconds = shouldDisplayMilliseconds;
}
void LogHandler::flushRepeatedMessages() {
QMutexLocker lock(&_mutex);
for(auto& message: _repeatedMessages) {
if (message.messageCount > 1) {
QString repeatMessage = QString("%1 repeated log entries matching \"%2\" - Last entry: \"%3\"")
.arg(message.messageCount - 1)
.arg(message.regexp.pattern())
.arg(message.lastMessage);
QMessageLogContext emptyContext;
lock.unlock();
printMessage(LogSuppressed, emptyContext, repeatMessage);
lock.relock();
}
message.messageCount = 0;
}
}
QString LogHandler::printMessage(LogMsgType type, const QMessageLogContext& context, const QString& message) {
QMutexLocker lock(&_mutex);
if (message.isEmpty()) {
return QString();
}
if (type == LogDebug) {
// for debug messages, check if this matches any of our regexes for repeated log messages
for (auto& repeatRegex : _repeatedMessages) {
if (repeatRegex.regexp.indexIn(message) != -1) {
// If we've printed the first one then return out.
if (repeatRegex.messageCount++ == 0) {
break;
}
repeatRegex.lastMessage = message;
return QString();
}
}
}
if (type == LogDebug) {
// see if this message is one we should only print once
for (auto& onceOnly : _onetimeMessages) {
if (onceOnly.regexp.indexIn(message) != -1) {
if (onceOnly.messageCount++ == 0) {
// we have a match and haven't yet printed this message.
break;
} else {
// We've already printed this message, don't print it again.
return QString();
}
}
}
}
// log prefix is in the following format
// [TIMESTAMP] [DEBUG] [PID] [TID] [TARGET] logged string
const QString* dateFormatPtr = &DATE_STRING_FORMAT;
if (_shouldDisplayMilliseconds) {
dateFormatPtr = &DATE_STRING_FORMAT_WITH_MILLISECONDS;
}
QString prefixString = QString("[%1] [%2] [%3]").arg(QDateTime::currentDateTime().toString(*dateFormatPtr),
stringForLogType(type), context.category);
if (_shouldOutputProcessID) {
prefixString.append(QString(" [%1]").arg(QCoreApplication::applicationPid()));
}
if (_shouldOutputThreadID) {
size_t threadID = (size_t)QThread::currentThreadId();
prefixString.append(QString(" [%1]").arg(threadID));
}
if (!_targetName.isEmpty()) {
prefixString.append(QString(" [%1]").arg(_targetName));
}
// for [qml] console.* messages include an abbreviated source filename
if (context.category && context.file && !strcmp("qml", context.category)) {
if (const char* basename = strrchr(context.file, '/')) {
prefixString.append(QString(" [%1]").arg(basename+1));
}
}
QString logMessage = QString("%1 %2\n").arg(prefixString, message.split('\n').join('\n' + prefixString + " "));
fprintf(stdout, "%s", qPrintable(logMessage));
#ifdef Q_OS_WIN
// On windows, this will output log lines into the Visual Studio "output" tab
OutputDebugStringA(qPrintable(logMessage));
#endif
return logMessage;
}
void LogHandler::verboseMessageHandler(QtMsgType type, const QMessageLogContext& context, const QString& message) {
getInstance().printMessage((LogMsgType) type, context, message);
}
void LogHandler::setupRepeatedMessageFlusher() {
static std::once_flag once;
std::call_once(once, [&] {
// setup our timer to flush the verbose logs every 5 seconds
QTimer* logFlushTimer = new QTimer(this);
connect(logFlushTimer, &QTimer::timeout, this, &LogHandler::flushRepeatedMessages);
logFlushTimer->start(VERBOSE_LOG_INTERVAL_SECONDS * 1000);
});
}
const QString& LogHandler::addRepeatedMessageRegex(const QString& regexString) {
// make sure we setup the repeated message flusher, but do it on the LogHandler thread
QMetaObject::invokeMethod(this, "setupRepeatedMessageFlusher");
QMutexLocker lock(&_mutex);
RepeatedMessage repeatRecord;
repeatRecord.regexp = QRegExp(regexString);
_repeatedMessages.push_back(repeatRecord);
return regexString;
}
const QString& LogHandler::addOnlyOnceMessageRegex(const QString& regexString) {
QMutexLocker lock(&_mutex);
OnceOnlyMessage onetimeMessage;
onetimeMessage.regexp = QRegExp(regexString);
_onetimeMessages.push_back(onetimeMessage);
return regexString;
}
| 32.345455 | 115 | 0.657392 | mnafees |
49943a09d854cd6ab0ddb0b87fc8edf1c5ba6e6e | 767 | cpp | C++ | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | 1 | 2020-10-21T07:53:54.000Z | 2020-10-21T07:53:54.000Z | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | null | null | null | Sorting/Optimised_BubbleSort.cpp | VanshMaheshwari30/DS-Algo | d47710387d78ed418a229b3a021ce37c9fcd949a | [
"MIT"
] | 1 | 2020-10-20T09:11:34.000Z | 2020-10-20T09:11:34.000Z | #include <bits/stdc++.h>
using namespace std;
void bubblesort(int a[],int n)
{
for (int i=0; i<n-1; i++)
{
bool swapped = false;
for (int j=0; j<n-i-1; j++)
{
if (a[j]>a[j+1])
{
swap(a[j],a[j+1]);
swapped = true;
}
}
if (swapped == false)
break;
}
}
int main(void)
{
int arr[10],i,ans;
cout << "Enter 10 elements in array: " << endl;
for (int i=0; i<10; i++)
cin >> arr[i];
cout << "Original Array is: ";
for (int i=0; i<10; i++)
cout << arr[i] << " ";
cout << "\n";
bubblesort(arr,10);
cout << "Array after sorting is: ";
for (int i=0; i<10; i++)
cout << arr[i] << " ";
}
| 20.72973 | 51 | 0.411995 | VanshMaheshwari30 |
49956ef1a27cdf020ddfc3932a92ea4d081df966 | 1,611 | cpp | C++ | oneEngine/oneGame/source/after/after-common.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 8 | 2017-12-08T02:59:31.000Z | 2022-02-02T04:30:03.000Z | oneEngine/oneGame/source/after/after-common.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 2 | 2021-04-16T03:44:42.000Z | 2021-08-30T06:48:44.000Z | oneEngine/oneGame/source/after/after-common.cpp | jonting/1Engine | f22ba31f08fa96fe6405ebecec4f374138283803 | [
"BSD-3-Clause"
] | 1 | 2021-04-16T02:09:54.000Z | 2021-04-16T02:09:54.000Z |
#include "physical/liscensing.cxx" // Include liscense info
#include "engine/utils/CDeveloperConsole.h"
#include "engine-common/lua/LuaSys.h"
#include "engine-common/lua/Lua_Console.h"
#include "engine-common/engine-common.h"
#include "engine-common/engine-common-scenes.h"
#include "after-common.h"
#include "after/scenes/gmsceneCharacterViewer.h"
#include "after-editor/scenes/gmsceneParticleEditor.h"
#include "after-editor/scenes/gmsceneLipsyncEditor.h"
#include "after/physics/water/Water.h"
#include "after/physics/wind/WindMotion.h"
//===============================================================================================//
// GameInitialize
//
// After the main engine components have been started, this function is called.
// This calls EngineCommonInitialize first, then performs its own actions.
// It adds game specific bindings to the console, Lua system, and other systems.
//===============================================================================================//
int GameInitialize ( void )
{
// Engine
EngineCommonInitialize();
// Scene registration
EngineCommon::RegisterScene<gmsceneCharacterViewer>( "test" );
EngineCommon::RegisterScene<gmsceneParticleEditor>( "pce" );
EngineCommon::RegisterScene<gmsceneLipsyncEditor>( "lse" );
//===============================================================================================//
// PLACE YOUR CUSTOM ENGINE MODULES BELOW HERE
//===============================================================================================//
// create testers
new CAfterWaterTester();
new CWindMotion();
return 0;
} | 36.613636 | 100 | 0.581006 | jonting |
499884591bc69d37dac296592b1491123427b87d | 12,848 | cpp | C++ | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 9 | 2018-11-19T10:15:29.000Z | 2021-08-30T11:52:07.000Z | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Gui/albaGUICrossSplitter.cpp | IOR-BIC/ALBA | b574968b05d9a3a2756dd2ac61d015a0d20232a4 | [
"Apache-2.0",
"BSD-3-Clause"
] | 3 | 2018-06-10T22:56:29.000Z | 2019-12-12T06:22:56.000Z | /*=========================================================================
Program: ALBA (Agile Library for Biomedical Applications)
Module: albaGUICrossSplitter
Authors: Silvano Imboden
Copyright (c) BIC
All rights reserved. See Copyright.txt or
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "albaDefines.h"
//----------------------------------------------------------------------------
// NOTE: Every CPP file in the ALBA must include "albaDefines.h" as first.
// This force to include Window,wxWidgets and VTK exactly in this order.
// Failing in doing this will result in a run-time error saying:
// "Failure#0: The value of ESP was not properly saved across a function call"
//----------------------------------------------------------------------------
#include "albaDecl.h"
#include "albaGUICrossSplitter.h"
//----------------------------------------------------------------------------
// albaGUICrossSplitter
//----------------------------------------------------------------------------
BEGIN_EVENT_TABLE(albaGUICrossSplitter,albaGUIPanel)
EVT_SIZE(albaGUICrossSplitter::OnSize)
EVT_LEFT_DOWN(albaGUICrossSplitter::OnLeftMouseButtonDown)
EVT_LEFT_UP(albaGUICrossSplitter::OnLeftMouseButtonUp)
EVT_MOTION(albaGUICrossSplitter::OnMouseMotion)
EVT_LEAVE_WINDOW(albaGUICrossSplitter::OnMouseMotion)
END_EVENT_TABLE()
//----------------------------------------------------------------------------
albaGUICrossSplitter::albaGUICrossSplitter(wxWindow* parent,wxWindowID id)
: albaGUIPanel(parent, id)
//----------------------------------------------------------------------------
{
m_ViewPanel1 = new wxPanel(this,1,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel2 = new wxPanel(this,2,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel3 = new wxPanel(this,3,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_ViewPanel4 = new wxPanel(this,4,wxDefaultPosition,wxDefaultSize,wxSUNKEN_BORDER);
m_Maximized = false;
m_FocusedPanel = m_ViewPanel1;
m_CursorNS = new wxCursor(wxCURSOR_SIZENS);
m_CursorWE = new wxCursor(wxCURSOR_SIZEWE);
m_CursorNSWE = new wxCursor(wxCURSOR_SIZING);
m_Pen = new wxPen(*wxBLACK, 2, wxSOLID);
m_With = m_Height = 100;
m_XPos = m_YPos = m_Margin = 20;
m_Dragging = drag_none;
m_RelXPos = m_RelYPos = 0.5,
Split(VA_FOUR);
}
//----------------------------------------------------------------------------
albaGUICrossSplitter::~albaGUICrossSplitter()
//----------------------------------------------------------------------------
{
delete m_CursorNS;
delete m_CursorWE;
delete m_CursorNSWE;
delete m_Pen;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnSize(wxSizeEvent &event)
//----------------------------------------------------------------------------
{
wxPanel::OnSize(event);
albaYield();
if (m_With == -1 )
{
return;
}
GetClientSize(&m_With,&m_Height);
m_XPos = m_RelXPos * m_With;
m_YPos = m_RelYPos * m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Split(CrossSplitterModes mode)
//----------------------------------------------------------------------------
{
m_Maximized = false;
m_Mode = mode;
switch(m_Mode)
{
case VA_ONE:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(false);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
break;
case VA_TWO_VERT:
case VA_TWO_HORZ:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
break;
case VA_THREE_UP:
case VA_THREE_DOWN:
case VA_THREE_LEFT:
case VA_THREE_RIGHT:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(true);
m_ViewPanel4->Show(false);
break;
case VA_FOUR:
m_ViewPanel1->Show(true);
m_ViewPanel2->Show(true);
m_ViewPanel3->Show(true);
m_ViewPanel4->Show(true);
break;
}
m_RelXPos = 0.5;
m_RelYPos = 0.5;
m_XPos = m_With * m_RelXPos;
m_YPos = m_Height * m_RelYPos;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetSplitPos(int x,int y)
//----------------------------------------------------------------------------
{
if (m_XPos < m_Margin) m_XPos = m_Margin;
if (m_XPos > m_With - m_Margin) m_XPos = m_With - m_Margin;
if (m_YPos < m_Margin) m_YPos = m_Margin;
if (m_YPos > m_Height - m_Margin) m_YPos = m_Height - m_Margin;
m_XPos = x;
m_YPos = y;
m_RelXPos = (x * 1.0 )/m_With;
m_RelYPos = (y * 1.0 )/m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetSplitPosRel(float x,float y)
//----------------------------------------------------------------------------
{
m_RelXPos = x;
m_RelYPos = y;
m_XPos = x * m_With;
m_YPos = y * m_Height;
OnLayout();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLeftMouseButtonDown(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
CaptureMouse();
m_Dragging = HitTest(event);
if(m_Dragging == 0) return;
int x = event.GetX();
int y = event.GetY();
DrawTracker(x,y);
m_OldXPos = x;
m_OldYPos = y;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLeftMouseButtonUp(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
if(m_Dragging != drag_none)
{
DrawTracker(m_OldXPos,m_OldYPos);
int x = event.GetX();
int y = event.GetY();
switch(m_Dragging)
{
case drag_y:
SetSplitPos(m_XPos,y);
break;
case drag_x:
SetSplitPos(x,m_YPos);
break;
case drag_xy:
SetSplitPos(x,y);
break;
}
m_Dragging = drag_none;
}
ReleaseMouse();
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnMouseMotion(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
if (m_Dragging == drag_none )
{
switch(HitTest(event))
{
case drag_y:
SetCursor(*m_CursorNS);
break;
case drag_x:
SetCursor(*m_CursorWE);
break;
case drag_xy:
SetCursor(*m_CursorNSWE);
break;
case drag_none:
SetCursor(*wxSTANDARD_CURSOR);
break;
}
}
else
{
int x = event.GetX();
int y = event.GetY();
DrawTracker(m_OldXPos,m_OldYPos);
DrawTracker(x,y);
m_OldXPos = x;
m_OldYPos = y;
}
if( event.Leaving() )
{
SetCursor(*wxSTANDARD_CURSOR);
}
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::OnLayout()
//----------------------------------------------------------------------------
{
if (m_XPos < m_Margin) m_XPos = m_Margin;
if (m_XPos > m_With - m_Margin) m_XPos = m_With - m_Margin;
if (m_YPos < m_Margin) m_YPos = m_Margin;
if (m_YPos > m_Height - m_Margin) m_YPos = m_Height - m_Margin;
int m = 3;
int w = m_With -m;
int h = m_Height -m;
int x1 = 0;
int x2 = m_XPos + m;
int y1 = 0;
int y2 = m_YPos + m;
int w1 = m_XPos - m;
int w2 = w - m_XPos -m;
int h1 = m_YPos - m;
int h2 = h - m_YPos -m;
if(this->m_Maximized)
{
this->m_FocusedPanel->Move(x1, y1);
this->m_FocusedPanel->SetSize(w,h);
}
else
{
switch(m_Mode)
{
case VA_ONE:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h);
break;
case VA_TWO_VERT:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h);
break;
case VA_TWO_HORZ:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h1);
m_ViewPanel2->Move(x1,y2);
m_ViewPanel2->SetSize(w,h2);
break;
case VA_THREE_UP:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w,h1);
m_ViewPanel2->Move(x1, y2);
m_ViewPanel2->SetSize(w1,h2);
m_ViewPanel3->Move(x2, y2);
m_ViewPanel3->SetSize(w2,h2);
break;
case VA_THREE_DOWN:
m_ViewPanel1->Move(x1, y2);
m_ViewPanel1->SetSize(w,h2);
m_ViewPanel2->Move(x1, y1);
m_ViewPanel2->SetSize(w1,h1);
m_ViewPanel3->Move(x2, y1);
m_ViewPanel3->SetSize(w2,h1);
break;
case VA_THREE_LEFT:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h1);
m_ViewPanel3->Move(x2, y2);
m_ViewPanel3->SetSize(w2,h2);
break;
case VA_THREE_RIGHT:
m_ViewPanel1->Move(x2, y1);
m_ViewPanel1->SetSize(w2,h);
m_ViewPanel2->Move(x1, y1);
m_ViewPanel2->SetSize(w1,h1);
m_ViewPanel3->Move(x1, y2);
m_ViewPanel3->SetSize(w1,h2);
break;
case VA_FOUR:
m_ViewPanel1->Move(x1, y1);
m_ViewPanel1->SetSize(w1,h1);
m_ViewPanel2->Move(x2, y1);
m_ViewPanel2->SetSize(w2,h1);
m_ViewPanel3->Move(x1, y2);
m_ViewPanel3->SetSize(w1,h2);
m_ViewPanel4->Move(x2, y2);
m_ViewPanel4->SetSize(w2,h2);
break;
}
}
m_ViewPanel1->Layout();
m_ViewPanel2->Layout();
m_ViewPanel3->Layout();
m_ViewPanel4->Layout();
this->Refresh();
}
//----------------------------------------------------------------------------
CrossSplitterDragModes albaGUICrossSplitter::HitTest(wxMouseEvent &event)
//----------------------------------------------------------------------------
{
wxCoord x = (wxCoord)event.GetX(),
y = (wxCoord)event.GetY();
if ( abs(m_XPos-x) < 5 && abs(m_YPos-y) < 5 && m_Mode >= VA_THREE_UP) return drag_xy;
if ( abs(m_XPos-x) < 5 ) return drag_x;
if ( abs(m_YPos-y) < 5 ) return drag_y;
return drag_none;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::DrawTracker(int x, int y)
//----------------------------------------------------------------------------
{
int m = 3;
int x1, y1;
int x2, y2;
if (x < m_Margin) x = m_Margin;
if (x > m_With - m_Margin) x = m_With - m_Margin;
if (y < m_Margin) y = m_Margin;
if (y > m_Height - m_Margin) y = m_Height - m_Margin;
wxScreenDC screenDC;
screenDC.SetLogicalFunction(wxINVERT);
screenDC.SetPen(*m_Pen);
screenDC.SetBrush(*wxTRANSPARENT_BRUSH);
if ( m_Dragging == 1 || m_Dragging == 3 )
{
x1 = x; y1 = m;
x2 = x; y2 = m_Height-m;
ClientToScreen(&x1, &y1);
ClientToScreen(&x2, &y2);
screenDC.DrawLine(x1, y1, x2, y2);
}
if ( m_Dragging == 2 || m_Dragging == 3 )
{
x1 = m; y1 = y;
x2 = m_With-m; y2 = y;
ClientToScreen(&x1, &y1);
ClientToScreen(&x2, &y2);
screenDC.DrawLine(x1, y1, x2, y2);
}
screenDC.SetLogicalFunction(wxCOPY);
screenDC.SetPen(wxNullPen);
screenDC.SetBrush(wxNullBrush);
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Put(wxWindow* w,int i)
//----------------------------------------------------------------------------
{
w->Reparent(this);
switch(i)
{
case 1:
if (m_ViewPanel1) delete m_ViewPanel1;
m_ViewPanel1 = w;
m_ViewPanel1->Layout();
break;
case 2:
if (m_ViewPanel2) delete m_ViewPanel2;
m_ViewPanel2 = w;
m_ViewPanel2->Layout();
break;
case 3:
if (m_ViewPanel3) delete m_ViewPanel3;
m_ViewPanel3 = w;
m_ViewPanel3->Layout();
break;
case 4:
if (m_ViewPanel4) delete m_ViewPanel4;
m_ViewPanel4 = w;
m_ViewPanel4->Layout();
break;
};
w->Show(true);
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::SetFocusedPanel(wxWindow* w)
//----------------------------------------------------------------------------
{
this->m_FocusedPanel = w;
}
//----------------------------------------------------------------------------
void albaGUICrossSplitter::Maximize()
//----------------------------------------------------------------------------
{
m_Maximized = !m_Maximized;
if(m_Maximized)
{
m_ViewPanel1->Show(false);
m_ViewPanel2->Show(false);
m_ViewPanel3->Show(false);
m_ViewPanel4->Show(false);
this->m_FocusedPanel->Show(true);
OnLayout();
}
else
{
Split(m_Mode);
OnLayout();
}
this->Layout();
}
| 28.052402 | 94 | 0.511753 | IOR-BIC |
499a092274a9ba88a44457476a8d309f521ab901 | 10,748 | cpp | C++ | ADCore/ADApp/pluginSrc/NDPluginGather.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | null | null | null | ADCore/ADApp/pluginSrc/NDPluginGather.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | 11 | 2015-12-04T14:48:19.000Z | 2020-04-03T10:05:30.000Z | ADCore/ADApp/pluginSrc/NDPluginGather.cpp | jerryjiahaha/areaDetector | a0ebc33a94a3cccffb4c9489d4b8e8ff33bf4231 | [
"MIT"
] | 4 | 2015-11-11T10:49:39.000Z | 2017-03-14T09:50:04.000Z | /*
* NDPluginGather.cpp
*
* A plugin that subscribes to callbacks from multiple ports, not just a single port
* Author: Mark Rivers
*
* February 27. 2017.
*/
#include <stdlib.h>
#include <stdio.h>
#include <epicsTypes.h>
#include <epicsMessageQueue.h>
#include <epicsThread.h>
#include <epicsTime.h>
#include <iocsh.h>
#include <asynDriver.h>
#include <epicsExport.h>
#include "NDPluginDriver.h"
#include "NDPluginGather.h"
static const char *driverName="NDPluginGather";
/** Constructor for NDPluginGather; most parameters are simply passed to NDPluginDriver::NDPluginDriver.
*
* \param[in] portName The name of the asyn port driver to be created.
* \param[in] queueSize The number of NDArrays that the input queue for this plugin can hold when
* NDPluginDriverBlockingCallbacks=0. Larger queues can decrease the number of dropped arrays,
* at the expense of more NDArray buffers being allocated from the underlying driver's NDArrayPool.
* \param[in] blockingCallbacks Initial setting for the NDPluginDriverBlockingCallbacks flag.
* 0=callbacks are queued and executed by the callback thread; 1 callbacks execute in the thread
* of the driver doing the callbacks.
* \param[in] maxPorts Maximum number of ports that this plugin can connected to for callbacks
* \param[in] maxBuffers The maximum number of NDArray buffers that the NDArrayPool for this driver is
* allowed to allocate. Set this to -1 to allow an unlimited number of buffers.
* \param[in] maxMemory The maximum amount of memory that the NDArrayPool for this driver is
* allowed to allocate. Set this to -1 to allow an unlimited amount of memory.
* \param[in] priority The thread priority for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags.
* \param[in] stackSize The stack size for the asyn port driver thread if ASYN_CANBLOCK is set in asynFlags.
*/
NDPluginGather::NDPluginGather(const char *portName, int queueSize, int blockingCallbacks,
int maxPorts,
int maxBuffers, size_t maxMemory,
int priority, int stackSize)
/* Invoke the base class constructor */
: NDPluginDriver(portName, queueSize, blockingCallbacks,
"", 0, maxPorts, maxBuffers, maxMemory,
asynInt32Mask | asynFloat64Mask | asynGenericPointerMask,
asynInt32Mask | asynFloat64Mask | asynGenericPointerMask,
ASYN_MULTIDEVICE, 1, priority, stackSize, 1),
maxPorts_(maxPorts)
{
int i;
NDGatherNDArraySource_t *pArraySrc;
//static const char *functionName = "NDPluginGather";
/* Set the plugin type string */
setStringParam(NDPluginDriverPluginType, "NDPluginGather");
if (maxPorts_ < 1) maxPorts_ = 1;
NDArraySrc_ = (NDGatherNDArraySource_t *)calloc(sizeof(NDGatherNDArraySource_t), maxPorts_);
pArraySrc = NDArraySrc_;
for (i=0; i<maxPorts_; i++, pArraySrc++) {
/* Create asynUser for communicating with NDArray port */
pArraySrc->pasynUserGenericPointer = pasynManager->createAsynUser(0, 0);
pArraySrc->pasynUserGenericPointer->userPvt = this;
pArraySrc->pasynUserGenericPointer->reason = NDArrayData;
}
}
extern "C" {static void driverCallback(void *drvPvt, asynUser *pasynUser, void *genericPointer)
{
NDPluginDriver *pNDPluginDriver = (NDPluginDriver *)drvPvt;
pNDPluginDriver->driverCallback(pasynUser, genericPointer);
}}
/**
* \param[in] pArray The NDArray from the callback.
*/
void NDPluginGather::processCallbacks(NDArray *pArray)
{
/* This function is called with the mutex already locked. It unlocks it during long calculations when private
* structures don't need to be protected.
*/
//static const char *functionName = "processCallbacks";
/* Call the base class method */
NDPluginDriver::beginProcessCallbacks(pArray);
NDPluginDriver::endProcessCallbacks(pArray, true, true);
}
/** Register or unregister to receive asynGenericPointer (NDArray) callbacks from the driver.
* Note: this function must be called with the lock released, otherwise a deadlock can occur
* in the call to cancelInterruptUser.
* \param[in] enableCallbacks 1 to enable callbacks, 0 to disable callbacks */
asynStatus NDPluginGather::setArrayInterrupt(int enableCallbacks)
{
asynStatus status = asynSuccess;
int i;
NDGatherNDArraySource_t *pArraySrc = NDArraySrc_;
static const char *functionName = "setArrayInterrupt";
for (i=0; i<maxPorts_; i++, pArraySrc++) {
if (enableCallbacks && pArraySrc->connectedToArrayPort && !pArraySrc->asynGenericPointerInterruptPvt) {
status = pArraySrc->pasynGenericPointer->registerInterruptUser(
pArraySrc->asynGenericPointerPvt, pArraySrc->pasynUserGenericPointer,
::driverCallback, this, &pArraySrc->asynGenericPointerInterruptPvt);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s::%s ERROR: Can't register for interrupt callbacks on detector port: %s\n",
driverName, functionName, pArraySrc->pasynUserGenericPointer->errorMessage);
return(status);
}
}
if (!enableCallbacks && pArraySrc->connectedToArrayPort && pArraySrc->asynGenericPointerInterruptPvt) {
status = pArraySrc->pasynGenericPointer->cancelInterruptUser(pArraySrc->asynGenericPointerPvt,
pArraySrc->pasynUserGenericPointer, pArraySrc->asynGenericPointerInterruptPvt);
pArraySrc->asynGenericPointerInterruptPvt = NULL;
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s::%s ERROR: Can't unregister for interrupt callbacks on detector port: %s\n",
driverName, functionName, pArraySrc->pasynUserGenericPointer->errorMessage);
return(status);
}
}
}
return(asynSuccess);
}
/** Connect this plugin to an NDArray port driver; disconnect from any existing driver first, register
* for callbacks if enabled. */
asynStatus NDPluginGather::connectToArrayPort(void)
{
asynStatus status;
asynInterface *pasynInterface;
int enableCallbacks;
char arrayPort[20];
int arrayAddr;
int i;
NDGatherNDArraySource_t *pArraySrc = NDArraySrc_;
static const char *functionName = "connectToArrayPort";
getIntegerParam(NDPluginDriverEnableCallbacks, &enableCallbacks);
for (i=0; i<maxPorts_; i++, pArraySrc++) {
getStringParam(i, NDPluginDriverArrayPort, sizeof(arrayPort), arrayPort);
getIntegerParam(i, NDPluginDriverArrayAddr, &arrayAddr);
/* If we are currently connected to an array port cancel interrupt request */
if (pArraySrc->connectedToArrayPort) {
status = setArrayInterrupt(0);
}
/* Disconnect the array port from our asynUser. Ignore error if there is no device
* currently connected. */
pasynManager->disconnect(pArraySrc->pasynUserGenericPointer);
pArraySrc->connectedToArrayPort = false;
/* Connect to the array port driver if the arrayPort string is not zero-length */
if (strlen(arrayPort) == 0) continue;
status = pasynManager->connectDevice(pArraySrc->pasynUserGenericPointer, arrayPort, arrayAddr);
if (status != asynSuccess) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s::%s Error calling pasynManager->connectDevice to array port %s address %d, status=%d, error=%s\n",
driverName, functionName, arrayPort, arrayAddr, status, pArraySrc->pasynUserGenericPointer->errorMessage);
return (status);
}
/* Find the asynGenericPointer interface in that driver */
pasynInterface = pasynManager->findInterface(pArraySrc->pasynUserGenericPointer, asynGenericPointerType, 1);
if (!pasynInterface) {
asynPrint(this->pasynUserSelf, ASYN_TRACE_ERROR,
"%s::connectToPort ERROR: Can't find asynGenericPointer interface on array port %s address %d\n",
driverName, arrayPort, arrayAddr);
return(asynError);
}
pArraySrc->pasynGenericPointer = (asynGenericPointer *)pasynInterface->pinterface;
pArraySrc->asynGenericPointerPvt = pasynInterface->drvPvt;
pArraySrc->connectedToArrayPort = true;
}
/* Enable or disable interrupt callbacks */
status = setArrayInterrupt(enableCallbacks);
return(status);
}
/** Configuration command */
extern "C" int NDGatherConfigure(const char *portName, int queueSize, int blockingCallbacks,
int maxPorts,
int maxBuffers, size_t maxMemory,
int priority, int stackSize)
{
NDPluginGather *pPlugin = new NDPluginGather(portName, queueSize, blockingCallbacks, maxPorts,
maxBuffers, maxMemory, priority, stackSize);
return pPlugin->start();
}
/* EPICS iocsh shell commands */
static const iocshArg initArg0 = { "portName",iocshArgString};
static const iocshArg initArg1 = { "frame queue size",iocshArgInt};
static const iocshArg initArg2 = { "blocking callbacks",iocshArgInt};
static const iocshArg initArg3 = { "maxPorts",iocshArgInt};
static const iocshArg initArg4 = { "maxBuffers",iocshArgInt};
static const iocshArg initArg5 = { "maxMemory",iocshArgInt};
static const iocshArg initArg6 = { "priority",iocshArgInt};
static const iocshArg initArg7 = { "stackSize",iocshArgInt};
static const iocshArg * const initArgs[] = {&initArg0,
&initArg1,
&initArg2,
&initArg3,
&initArg4,
&initArg5,
&initArg6,
&initArg7};
static const iocshFuncDef initFuncDef = {"NDGatherConfigure",8,initArgs};
static void initCallFunc(const iocshArgBuf *args)
{
NDGatherConfigure(args[0].sval, args[1].ival, args[2].ival,
args[3].ival, args[4].ival, args[5].ival,
args[6].ival, args[7].ival);
}
extern "C" void NDGatherRegister(void)
{
iocshRegister(&initFuncDef,initCallFunc);
}
extern "C" {
epicsExportRegistrar(NDGatherRegister);
}
| 45.159664 | 128 | 0.66217 | jerryjiahaha |
49a1b7ec4fa673672e81db01df7232b8ebfd7996 | 586 | cc | C++ | userFiles/ctrl/body/articulations/specific_art/Yaw_Torso_Art.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/ctrl/body/articulations/specific_art/Yaw_Torso_Art.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null | userFiles/ctrl/body/articulations/specific_art/Yaw_Torso_Art.cc | mharding01/augmented-neuromuscular-RT-running | 7e1ef00d3fdf9cfa9d59fc4f3a6a0e6dd792a834 | [
"MIT"
] | null | null | null |
#include "Yaw_Torso_Art.hh"
/*! \brief constructor
*
* \param[in] inputs controller inputs
* \param[in] ctrl_index indexes of the controller
*/
Yaw_Torso_Art::Yaw_Torso_Art(CtrlInputs *inputs, MotorCtrlIndex *ctrl_index): Articulation(inputs, ctrl_index, YAW_TORSO_ART, TORSO_BODY)
{
joint_id = ctrl_index->get_inv_index(CtrlIndex::TorsoYaw);
q_min = -50.0 * DEG_TO_RAD;
q_max = 50.0 * DEG_TO_RAD;
}
/*! \brief destructor
*/
Yaw_Torso_Art::~Yaw_Torso_Art()
{
}
/*! \brief add soft limit contribution
*/
void Yaw_Torso_Art::add_Qq_soft_lim()
{
apply_Qq_soft(150.0);
}
| 18.903226 | 137 | 0.726962 | mharding01 |
49a26ebd0efe4aae8ed9bfd592c74ef0d25b2d7c | 12,041 | cxx | C++ | panda/src/physx/physxJoint.cxx | kestred/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | 3 | 2018-03-09T12:07:29.000Z | 2021-02-25T06:50:25.000Z | panda/src/physx/physxJoint.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | panda/src/physx/physxJoint.cxx | Sinkay/panda3d | 16bfd3750f726a8831771b81649d18d087917fd5 | [
"PHP-3.01",
"PHP-3.0"
] | null | null | null | // Filename: physxJoint.cxx
// Created by: enn0x (02Oct09)
//
////////////////////////////////////////////////////////////////////
//
// PANDA 3D SOFTWARE
// Copyright (c) Carnegie Mellon University. All rights reserved.
//
// All use of this software is subject to the terms of the revised BSD
// license. You should have received a copy of this license along
// with this source code in a file named "LICENSE."
//
////////////////////////////////////////////////////////////////////
#include "physxJoint.h"
#include "physxManager.h"
#include "physxActor.h"
#include "physxScene.h"
#include "physxCylindricalJoint.h"
#include "physxDistanceJoint.h"
#include "physxFixedJoint.h"
#include "physxPointInPlaneJoint.h"
#include "physxPointOnLineJoint.h"
#include "physxPrismaticJoint.h"
#include "physxPulleyJoint.h"
#include "physxRevoluteJoint.h"
#include "physxSphericalJoint.h"
#include "physxD6Joint.h"
TypeHandle PhysxJoint::_type_handle;
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::release
// Access: Published
// Description:
////////////////////////////////////////////////////////////////////
void PhysxJoint::
release() {
nassertv(_error_type == ET_ok);
unlink();
ptr()->getScene().releaseJoint(*ptr());
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::factory
// Access: Public
// Description:
////////////////////////////////////////////////////////////////////
PhysxJoint *PhysxJoint::
factory(NxJointType shapeType) {
switch (shapeType) {
case NX_JOINT_PRISMATIC:
return new PhysxPrismaticJoint();
case NX_JOINT_REVOLUTE:
return new PhysxRevoluteJoint();
case NX_JOINT_CYLINDRICAL:
return new PhysxCylindricalJoint();
case NX_JOINT_SPHERICAL:
return new PhysxSphericalJoint();
case NX_JOINT_POINT_ON_LINE:
return new PhysxPointOnLineJoint();
case NX_JOINT_POINT_IN_PLANE:
return new PhysxPointInPlaneJoint();
case NX_JOINT_DISTANCE:
return new PhysxDistanceJoint();
case NX_JOINT_PULLEY:
return new PhysxPulleyJoint();
case NX_JOINT_FIXED:
return new PhysxFixedJoint();
case NX_JOINT_D6:
return new PhysxD6Joint();
}
physx_cat.error() << "Unknown joint type.\n";
return NULL;
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_name
// Access: Published
// Description: Sets a name string for this object. The name can
// be retrieved again with get_name().
// This is for debugging and is not used by the
// physics engine.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_name(const char *name) {
nassertv(_error_type == ET_ok);
_name = name ? name : "";
ptr()->setName(_name.c_str());
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_name
// Access: Published
// Description: Returns the name string.
////////////////////////////////////////////////////////////////////
const char *PhysxJoint::
get_name() const {
nassertr(_error_type == ET_ok, "");
return ptr()->getName();
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_actor
// Access: Published
// Description: Retrieves the actor which this joint is associated
// with.
////////////////////////////////////////////////////////////////////
PhysxActor *PhysxJoint::
get_actor(unsigned int idx) const {
nassertr_always(idx < 2, NULL);
nassertr(_error_type == ET_ok, NULL);
NxActor *actorPtr[2];
ptr()->getActors(&actorPtr[0], &actorPtr[1]);
return (PhysxActor *)(actorPtr[idx]->userData);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_scene
// Access: Published
// Description: Retrieves the scene which this joint is associated
// with.
////////////////////////////////////////////////////////////////////
PhysxScene *PhysxJoint::
get_scene() const {
nassertr(_error_type == ET_ok, NULL);
return (PhysxScene *)(ptr()->getScene().userData);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_global_anchor
// Access: Published
// Description: Sets the point where the two actors are attached,
// specified in global coordinates.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_global_anchor(const LPoint3f &anchor) {
nassertv(_error_type == ET_ok);
ptr()->setGlobalAnchor(PhysxManager::point3_to_nxVec3(anchor));
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_global_anchor
// Access: Published
// Description: Retrieves the joint anchor.
////////////////////////////////////////////////////////////////////
LPoint3f PhysxJoint::
get_global_anchor() const {
nassertr(_error_type == ET_ok, LPoint3f::zero());
return PhysxManager::nxVec3_to_point3(ptr()->getGlobalAnchor());
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_global_axis
// Access: Published
// Description: Sets the direction of the joint's primary axis,
// specified in global coordinates.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_global_axis(const LVector3f &axis) {
nassertv(_error_type == ET_ok);
ptr()->setGlobalAxis(PhysxManager::vec3_to_nxVec3(axis));
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_global_axis
// Access: Published
// Description: Retrieves the joint axis.
////////////////////////////////////////////////////////////////////
LVector3f PhysxJoint::
get_global_axis() const {
nassertr(_error_type == ET_ok, LVector3f::zero());
return PhysxManager::nxVec3_to_vec3(ptr()->getGlobalAxis());
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_breakable
// Access: Published
// Description: Sets the maximum force magnitude that the joint
// is able to withstand without breaking.
//
// If the joint force rises above this threshold, the
// joint breaks, and becomes disabled.
//
// There are two values, one for linear forces, and
// one for angular forces. Both values are used
// directly as a value for the maximum impulse
// tolerated by the joint constraints.
//
// Both force values are NX_MAX_REAL by default.
// This setting makes the joint unbreakable. The values
// should always be nonnegative.
//
// The distinction between maxForce and maxTorque is
// dependent on how the joint is implemented
// internally, which may not be obvious. For example
// what appears to be an angular degree of freedom may
// be constrained indirectly by a linear constraint.
//
// So in most practical applications the user should
// set both maxTorque and maxForce to low values.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_breakable(float maxForce, float maxTorque) {
nassertv(_error_type == ET_ok);
ptr()->setBreakable(maxForce, maxTorque);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_use_acceleration_spring
// Access: Published
// Description: Switch between acceleration and force based spring.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_use_acceleration_spring(bool value) {
nassertv(_error_type == ET_ok);
ptr()->setUseAccelerationSpring(value);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_use_acceleration_spring
// Access: Published
// Description: Checks whether acceleration spring is used.
////////////////////////////////////////////////////////////////////
bool PhysxJoint::
get_use_acceleration_spring() const {
nassertr(_error_type == ET_ok, false);
return ptr()->getUseAccelerationSpring();
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_solver_extrapolation_factor
// Access: Published
// Description: Sets the solver extrapolation factor.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_solver_extrapolation_factor(float factor) {
nassertv(_error_type == ET_ok);
ptr()->setSolverExtrapolationFactor(factor);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::get_solver_extrapolation_factor
// Access: Published
// Description: Retrieves the solver extrapolation factor.
////////////////////////////////////////////////////////////////////
float PhysxJoint::
get_solver_extrapolation_factor() const {
nassertr(_error_type == ET_ok, false);
return ptr()->getSolverExtrapolationFactor();
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::set_limit_point
// Access: Published
// Description: Sets the limit point.
// The point is specified in the global coordinate
// frame.
//
// All types of joints may be limited with the same
// system: You may elect a point attached to one of
// the two actors to act as the limit point. You may
// also specify several planes attached to the other
// actor.
//
// The points and planes move together with the actor
// they are attached to.
//
// The simulation then makes certain that the pair
// of actors only move relative to each other so that
// the limit point stays on the positive side of all
// limit planes.
//
// The default limit point is (0,0,0) in the local
// frame of actor2. Calling this deletes all existing
// limit planes
////////////////////////////////////////////////////////////////////
void PhysxJoint::
set_limit_point(const LPoint3f &pos, bool isOnActor2) {
nassertv(_error_type == ET_ok);
ptr()->setLimitPoint(PhysxManager::point3_to_nxVec3(pos), isOnActor2);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::add_limit_plane
// Access: Published
// Description: Adds a limit plane.
// The parameters are given in global coordinates.
// The plane is affixed to the actor that does not
// have the limit point.
//
// The normal of the plane points toward the positive
// side of the plane, and thus toward the limit point.
// If the normal points away from the limit point at
// the time of this call, the method returns false
// and the limit plane is ignored.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
add_limit_plane(const LVector3f &normal, const LPoint3f &pointInPlane, float restitution) {
nassertv(_error_type == ET_ok);
ptr()->addLimitPlane(PhysxManager::vec3_to_nxVec3(normal),
PhysxManager::point3_to_nxVec3(pointInPlane),
restitution);
}
////////////////////////////////////////////////////////////////////
// Function: PhysxJoint::purge_limit_planes
// Access: Published
// Description: Deletes all limit planes added to the joint.
////////////////////////////////////////////////////////////////////
void PhysxJoint::
purge_limit_planes() {
nassertv(_error_type == ET_ok);
ptr()->purgeLimitPlanes();
}
| 34.501433 | 91 | 0.526867 | kestred |
49a453d03a599b1ca3ddfa363aeaafcebe546ad4 | 366 | cc | C++ | tcpp/minion2/minion/system/minlib/tests/test_reader_1.cc | Behrouz-Babaki/TCPP-chuffed | d832b44690914ef4b73d71bc7e565efb98e42937 | [
"MIT"
] | 1 | 2021-09-09T13:03:02.000Z | 2021-09-09T13:03:02.000Z | tcpp/minion2/minion/system/minlib/tests/test_reader_1.cc | Behrouz-Babaki/TCPP-chuffed | d832b44690914ef4b73d71bc7e565efb98e42937 | [
"MIT"
] | null | null | null | tcpp/minion2/minion/system/minlib/tests/test_reader_1.cc | Behrouz-Babaki/TCPP-chuffed | d832b44690914ef4b73d71bc7e565efb98e42937 | [
"MIT"
] | null | null | null | #include "minlib/LettingReader/inputfile_parse.h"
int main(void) {
SimpleMap<std::string, MultiDimCon<int, int>> lets;
readLettingStatements(lets, std::string("lettings1.txt"));
assert(lets.get(std::string("L")).arity() == 0);
assert(lets.get(std::string("L")).get(make_vec<int>()) == 1);
assert(lets.get(std::string("Mac")).get(make_vec<int>()) == 2);
} | 36.6 | 65 | 0.669399 | Behrouz-Babaki |
49a646f40e7e32094d7ee8470a1d9b27ee9537f2 | 6,940 | cpp | C++ | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | 1 | 2021-04-11T23:44:43.000Z | 2021-04-11T23:44:43.000Z | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | Source/Tools/alive_api/alive_api_test.cpp | THEONLYDarkShadow/alive_reversing | 680d87088023f2d5f2a40c42d6543809281374fb | [
"MIT"
] | null | null | null | #include "../AliveLibCommon/stdafx_common.h"
#include "alive_api.hpp"
#include "SDL.h"
#include "logger.hpp"
#include "AOTlvs.hpp"
#include <gmock/gmock.h>
#include "../AliveLibAE/DebugHelpers.hpp"
const std::string kAEDir = "C:\\GOG Games\\Abes Exoddus\\";
const std::string kAODir = "C:\\GOG Games\\Abes Oddysee\\";
const std::string kAETestLvl = "pv.lvl";
const std::vector<std::string> kAELvls =
{
"ba.lvl",
"bm.lvl",
"br.lvl",
"bw.lvl",
"cr.lvl",
"fd.lvl",
"mi.lvl",
"ne.lvl",
"pv.lvl",
"st.lvl",
"sv.lvl",
};
const std::vector<std::string> kAOLvls =
{
"c1.lvl",
"d1.lvl",
"d2.lvl",
"d7.lvl",
"e1.lvl",
"e2.lvl",
"f1.lvl",
"f2.lvl",
"f4.lvl",
"l1.lvl",
"r1.lvl",
"r2.lvl",
"r6.lvl",
"s1.lvl",
};
static std::string AEPath(const std::string& fileName)
{
return kAEDir + fileName;
}
static std::string AOPath(const std::string& fileName)
{
return kAODir + fileName;
}
TEST(alive_api, ExportPathBinaryToJsonAE)
{
auto ret = AliveAPI::ExportPathBinaryToJson("OutputAE.json", AEPath(kAETestLvl), 14);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ExportPathBinaryToJsonAO)
{
auto ret = AliveAPI::ExportPathBinaryToJson("OutputAO.json", AOPath("R1.LVL"), 19);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ImportPathJsonToBinaryAO)
{
auto ret = AliveAPI::ImportPathJsonToBinary("OutputAO.json", AOPath("R1.LVL"), "newAO.lvl", {});
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
const auto ogR1 = FS::ReadFile(AOPath("R1.LVL"));
ASSERT_NE(ogR1.size(), 0u);
const auto rewrittenR1 = FS::ReadFile("newAO.lvl");
ASSERT_NE(rewrittenR1.size(), 0u);
ASSERT_EQ(ogR1, rewrittenR1);
}
TEST(alive_api, ImportPathJsonToBinaryAE)
{
auto ret = AliveAPI::ImportPathJsonToBinary("OutputAE.json", AEPath(kAETestLvl), "newAE.lvl", {});
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
const auto ogLVL = FS::ReadFile(AEPath(kAETestLvl));
ASSERT_NE(ogLVL.size(), 0u);
const auto rewrittenLVL = FS::ReadFile("newAE.lvl");
ASSERT_NE(rewrittenLVL.size(), 0u);
if (ogLVL != rewrittenLVL)
{
AliveAPI::DebugDumpTlvs("old/", AEPath(kAETestLvl), 14);
AliveAPI::DebugDumpTlvs("new/", "newAE.lvl", 14);
}
ASSERT_EQ(ogLVL, rewrittenLVL);
}
TEST(alive_api, EnumeratePathsAO)
{
auto ret = AliveAPI::EnumeratePaths(AOPath("R1.LVL"));
ASSERT_EQ(ret.pathBndName, "R1PATH.BND");
const std::vector<int> paths {15, 16, 18, 19};
ASSERT_EQ(ret.paths, paths);
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
}
TEST(alive_api, ReSaveAllPathsAO)
{
for (const auto& lvl : kAOLvls)
{
auto ret = AliveAPI::EnumeratePaths(AOPath(lvl));
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
for (int path : ret.paths)
{
const std::string jsonName = "OutputAO_" + lvl + "_" + std::to_string(path) + ".json";
LOG_INFO("Save " << jsonName);
auto exportRet = AliveAPI::ExportPathBinaryToJson(jsonName, AOPath(lvl), path);
ASSERT_EQ(exportRet.mResult, AliveAPI::Error::None);
const std::string lvlName = "OutputAO_" + lvl + "_" + std::to_string(path) + ".lvl";
LOG_INFO("Resave " << lvlName);
auto importRet = AliveAPI::ImportPathJsonToBinary(jsonName, AOPath(lvl), lvlName, {});
ASSERT_EQ(importRet.mResult, AliveAPI::Error::None);
const auto originalLvlBytes = FS::ReadFile(AOPath(lvl));
ASSERT_NE(originalLvlBytes.size(), 0u);
const auto resavedLvlBytes = FS::ReadFile(lvlName);
ASSERT_NE(resavedLvlBytes.size(), 0u);
if (originalLvlBytes != resavedLvlBytes)
{
AliveAPI::DebugDumpTlvs("old/", AOPath(lvl), path);
AliveAPI::DebugDumpTlvs("new/", lvlName, path);
}
ASSERT_EQ(originalLvlBytes, resavedLvlBytes);
}
}
}
TEST(alive_api, ReSaveAllPathsAE)
{
for (const auto& lvl : kAELvls)
{
auto ret = AliveAPI::EnumeratePaths(AEPath(lvl));
ASSERT_EQ(ret.mResult, AliveAPI::Error::None);
for (int path : ret.paths)
{
const std::string jsonName = "OutputAE_" + lvl + "_" + std::to_string(path) + ".json";
LOG_INFO("Save " << jsonName);
auto exportRet = AliveAPI::ExportPathBinaryToJson(jsonName, AEPath(lvl), path);
ASSERT_EQ(exportRet.mResult, AliveAPI::Error::None);
const std::string lvlName = "OutputAE_" + lvl + "_" + std::to_string(path) + ".lvl";
LOG_INFO("Resave " << lvlName);
auto importRet = AliveAPI::ImportPathJsonToBinary(jsonName, AEPath(lvl), lvlName, {});
ASSERT_EQ(importRet.mResult, AliveAPI::Error::None);
const auto originalLvlBytes = FS::ReadFile(AEPath(lvl));
ASSERT_NE(originalLvlBytes.size(), 0u);
const auto resavedLvlBytes = FS::ReadFile(lvlName);
ASSERT_NE(resavedLvlBytes.size(), 0u);
if (originalLvlBytes != resavedLvlBytes)
{
AliveAPI::DebugDumpTlvs("old/", AEPath(lvl), path);
AliveAPI::DebugDumpTlvs("new/", lvlName, path);
}
ASSERT_EQ(originalLvlBytes, resavedLvlBytes);
}
}
}
// Get version
// Upgrade
TEST(alive_api, tlv_reflection)
{
TypesCollection types(Game::AO);
AO::Path_Hoist tlv = {};
std::unique_ptr<TlvObjectBase> pHoist = types.MakeTlvAO(AO::TlvTypes::Hoist_3, &tlv, 99);
auto obj = pHoist->InstanceToJson(types);
pHoist->InstanceFromJson(types, obj);
pHoist->StructureToJson();
ASSERT_EQ(pHoist->InstanceNumber(), 99);
}
/*
TEST(json_upgrade, upgrade_rename_structure)
{
AliveAPI::JsonUpgradeResult r = AliveAPI::UpgradePathJson("rename_field.json");
ASSERT_EQ(r.mResult, AliveAPI::UpgradeError::None);
}
*/
class ArgsAdapter
{
public:
ArgsAdapter(int argc, char* argv[])
{
for (int i = 0; i < argc; i++)
{
mArgs.push_back(argv[i]);
}
}
void Add(const std::string& arg)
{
mArgs.push_back(arg);
}
int ArgC() const
{
return static_cast<int>(mArgs.size());
}
std::unique_ptr<char*[]> ArgV() const
{
auto ptr = std::make_unique<char* []>(mArgs.size());
int i = 0;
for (const auto& arg : mArgs)
{
ptr[i++] = const_cast<char*>(arg.c_str());
}
return ptr;
}
private:
std::vector<std::string> mArgs;
};
int main(int argc, char* argv[])
{
ArgsAdapter args(argc, argv);
args.Add("--gtest_catch_exceptions=0");
int newArgc = args.ArgC();
auto newArgv = args.ArgV();
::testing::InitGoogleTest(&newArgc, newArgv.get());
const auto ret = RUN_ALL_TESTS();
return ret;
}
| 27.109375 | 102 | 0.606916 | THEONLYDarkShadow |
49a8388d6bb64f90c4eed1c6618d095dab18b3da | 20,600 | cc | C++ | libhwsec-foundation/crypto/aes.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | libhwsec-foundation/crypto/aes.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | libhwsec-foundation/crypto/aes.cc | Toromino/chromiumos-platform2 | 97e6ba18f0e5ab6723f3448a66f82c1a07538d87 | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2021 The Chromium OS Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "libhwsec-foundation/crypto/aes.h"
#include <limits>
#include <optional>
#include "libhwsec-foundation/crypto/secure_blob_util.h"
#include <base/logging.h>
#include <base/notreached.h>
#include <crypto/scoped_openssl_types.h>
#include <openssl/err.h>
#include <openssl/evp.h>
namespace hwsec_foundation {
size_t GetAesBlockSize() {
return EVP_CIPHER_block_size(EVP_aes_256_cbc());
}
bool PasskeyToAesKey(const brillo::SecureBlob& passkey,
const brillo::SecureBlob& salt,
unsigned int rounds,
brillo::SecureBlob* key,
brillo::SecureBlob* iv) {
if (salt.size() != PKCS5_SALT_LEN) {
LOG(ERROR) << "Bad salt size.";
return false;
}
const EVP_CIPHER* cipher = EVP_aes_256_cbc();
brillo::SecureBlob aes_key(EVP_CIPHER_key_length(cipher));
brillo::SecureBlob local_iv(EVP_CIPHER_iv_length(cipher));
// Convert the passkey to a key
if (!EVP_BytesToKey(cipher, EVP_sha1(), salt.data(), passkey.data(),
passkey.size(), rounds, aes_key.data(),
local_iv.data())) {
LOG(ERROR) << "Failure converting bytes to key";
return false;
}
key->swap(aes_key);
if (iv) {
iv->swap(local_iv);
}
return true;
}
bool AesEncryptDeprecated(const brillo::SecureBlob& plaintext,
const brillo::SecureBlob& key,
const brillo::SecureBlob& iv,
brillo::SecureBlob* ciphertext) {
return AesEncryptSpecifyBlockMode(
plaintext, 0, plaintext.size(), key, iv,
PaddingScheme::kPaddingCryptohomeDefaultDeprecated, BlockMode::kCbc,
ciphertext);
}
bool AesDecryptDeprecated(const brillo::SecureBlob& ciphertext,
const brillo::SecureBlob& key,
const brillo::SecureBlob& iv,
brillo::SecureBlob* plaintext) {
return AesDecryptSpecifyBlockMode(
ciphertext, 0, ciphertext.size(), key, iv,
PaddingScheme::kPaddingCryptohomeDefaultDeprecated, BlockMode::kCbc,
plaintext);
}
bool AesGcmDecrypt(const brillo::SecureBlob& ciphertext,
const std::optional<brillo::SecureBlob>& ad,
const brillo::SecureBlob& tag,
const brillo::SecureBlob& key,
const brillo::SecureBlob& iv,
brillo::SecureBlob* plaintext) {
if (ciphertext.empty()) {
NOTREACHED() << "Empty ciphertext passed to AesGcmDecrypt.";
return false;
}
if (tag.size() != kAesGcmTagSize) {
NOTREACHED() << "Wrong tag size passed to AesGcmDecrypt: " << tag.size()
<< ", expected " << kAesGcmTagSize << ".";
return false;
}
if (key.size() != kAesGcm256KeySize) {
NOTREACHED() << "Wrong key size passed to AesGcmDecrypt: " << key.size()
<< ", expected " << kAesGcm256KeySize << ".";
return false;
}
if (iv.size() != kAesGcmIVSize) {
NOTREACHED() << "Wrong iv size passed to AesGcmDecrypt: " << iv.size()
<< ", expected " << kAesGcmIVSize << ".";
return false;
}
crypto::ScopedEVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == nullptr) {
LOG(ERROR) << "Failed to create cipher ctx.";
return false;
}
if (EVP_DecryptInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr, nullptr,
nullptr) != 1) {
LOG(ERROR) << "Failed to init decrypt.";
return false;
}
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, kAesGcmIVSize,
nullptr) != 1) {
LOG(ERROR) << "Failed to set iv size.";
return false;
}
if (EVP_DecryptInit_ex(ctx.get(), nullptr, nullptr, key.data(), iv.data()) !=
1) {
LOG(ERROR) << "Failed to add key and iv to decrypt operation.";
return false;
}
if (ad.has_value()) {
if (ad.value().empty()) {
NOTREACHED() << "Empty associated data passed to AesGcmDecrypt.";
return false;
}
int out_size = 0;
if (EVP_DecryptUpdate(ctx.get(), nullptr, &out_size, ad.value().data(),
ad.value().size()) != 1) {
LOG(ERROR) << "Failed to add additional authentication data.";
return false;
}
if (out_size != ad.value().size()) {
LOG(ERROR) << "Failed to process entire ad.";
return false;
}
}
brillo::SecureBlob result;
result.resize(ciphertext.size());
int output_size = 0;
if (EVP_DecryptUpdate(ctx.get(), result.data(), &output_size,
ciphertext.data(), ciphertext.size()) != 1) {
LOG(ERROR) << "Failed to decrypt the plaintext.";
return false;
}
if (output_size != ciphertext.size()) {
LOG(ERROR) << "Failed to process entire ciphertext.";
return false;
}
uint8_t* tag_ptr = const_cast<uint8_t*>(tag.data());
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_TAG, tag.size(),
tag_ptr) != 1) {
LOG(ERROR) << "Failed to set the tag.";
return false;
}
output_size = 0;
int ret_val = EVP_DecryptFinal_ex(ctx.get(), nullptr, &output_size);
bool success = output_size == 0 && ret_val > 0;
if (success) {
*plaintext = result;
}
return success;
}
bool AesGcmEncrypt(const brillo::SecureBlob& plaintext,
const std::optional<brillo::SecureBlob>& ad,
const brillo::SecureBlob& key,
brillo::SecureBlob* iv,
brillo::SecureBlob* tag,
brillo::SecureBlob* ciphertext) {
if (plaintext.empty()) {
NOTREACHED() << "Empty plaintext passed to AesGcmEncrypt.";
return false;
}
if (key.size() != kAesGcm256KeySize) {
NOTREACHED() << "Wrong key size passed to AesGcmEncrypt: " << key.size()
<< ", expected " << kAesGcm256KeySize << ".";
return false;
}
iv->resize(kAesGcmIVSize);
GetSecureRandom(iv->data(), kAesGcmIVSize);
crypto::ScopedEVP_CIPHER_CTX ctx(EVP_CIPHER_CTX_new());
if (ctx.get() == nullptr) {
LOG(ERROR) << "Failed to create context.";
return false;
}
if (EVP_EncryptInit_ex(ctx.get(), EVP_aes_256_gcm(), nullptr, nullptr,
nullptr) != 1) {
LOG(ERROR) << "Failed to init aes-gcm-256.";
return false;
}
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_SET_IVLEN, kAesGcmIVSize,
nullptr) != 1) {
LOG(ERROR) << "Failed to set IV length.";
return false;
}
if (EVP_EncryptInit_ex(ctx.get(), nullptr, nullptr, key.data(), iv->data()) !=
1) {
LOG(ERROR) << "Failed to init key and iv.";
return false;
}
if (ad.has_value()) {
if (ad.value().empty()) {
NOTREACHED() << "Empty associated data passed to AesGcmEncrypt.";
return false;
}
int out_size = 0;
if (EVP_EncryptUpdate(ctx.get(), nullptr, &out_size, ad.value().data(),
ad.value().size()) != 1) {
LOG(ERROR) << "Failed to add additional authentication data.";
return false;
}
if (out_size != ad.value().size()) {
LOG(ERROR) << "Failed to process entire ad.";
return false;
}
}
brillo::SecureBlob result;
result.resize(plaintext.size());
int processed_bytes = 0;
if (EVP_EncryptUpdate(ctx.get(), result.data(), &processed_bytes,
plaintext.data(), plaintext.size()) != 1) {
LOG(ERROR) << "Failed to encrypt plaintext.";
return false;
}
if (plaintext.size() != processed_bytes) {
LOG(ERROR) << "Did not process the entire plaintext.";
return false;
}
int unused_output_length;
if (EVP_EncryptFinal_ex(ctx.get(), nullptr, &unused_output_length) != 1) {
LOG(ERROR) << "Failed to finalize encryption.";
return false;
}
tag->resize(kAesGcmTagSize);
if (EVP_CIPHER_CTX_ctrl(ctx.get(), EVP_CTRL_GCM_GET_TAG, kAesGcmTagSize,
tag->data()) != 1) {
LOG(ERROR) << "Failed to retrieve tag.";
return false;
}
*ciphertext = result;
return true;
}
// This is the reverse operation of AesEncryptSpecifyBlockMode above. See that
// method for a description of how padding and block_mode affect the crypto
// operations. This method automatically removes and verifies the padding, so
// plain_text (on success) will contain the original data.
//
// Note that a call to AesDecryptSpecifyBlockMode needs to have the same padding
// and block_mode as the corresponding encrypt call. Changing the block mode
// will drastically alter the decryption. And an incorrect PaddingScheme will
// result in the padding verification failing, for which the method call fails,
// even if the key and initialization vector were correct.
bool AesDecryptSpecifyBlockMode(const brillo::SecureBlob& encrypted,
unsigned int start,
unsigned int count,
const brillo::SecureBlob& key,
const brillo::SecureBlob& iv,
PaddingScheme padding,
BlockMode block_mode,
brillo::SecureBlob* plain_text) {
if ((start > encrypted.size()) || ((start + count) > encrypted.size()) ||
((start + count) < start)) {
return false;
}
brillo::SecureBlob local_plain_text(count);
if (local_plain_text.size() >
static_cast<unsigned int>(std::numeric_limits<int>::max())) {
// EVP_DecryptUpdate takes a signed int
return false;
}
int final_size = 0;
int decrypt_size = local_plain_text.size();
const EVP_CIPHER* cipher;
switch (block_mode) {
case BlockMode::kCbc:
cipher = EVP_aes_256_cbc();
break;
case BlockMode::kEcb:
cipher = EVP_aes_256_ecb();
break;
case BlockMode::kCtr:
cipher = EVP_aes_256_ctr();
break;
default:
LOG(ERROR) << "Invalid block mode specified: "
<< static_cast<int>(block_mode);
return false;
}
if (key.size() != static_cast<unsigned int>(EVP_CIPHER_key_length(cipher))) {
LOG(ERROR) << "Invalid key length of " << key.size() << ", expected "
<< EVP_CIPHER_key_length(cipher);
return false;
}
// ECB ignores the IV, so only check the IV length if we are using a different
// block mode.
if ((block_mode != BlockMode::kEcb) &&
(iv.size() != static_cast<unsigned int>(EVP_CIPHER_iv_length(cipher)))) {
LOG(ERROR) << "Invalid iv length of " << iv.size() << ", expected "
<< EVP_CIPHER_iv_length(cipher);
return false;
}
crypto::ScopedEVP_CIPHER_CTX decryption_context(EVP_CIPHER_CTX_new());
if (!decryption_context) {
LOG(ERROR) << "Failed to allocate EVP_CIPHER_CTX";
return false;
}
EVP_DecryptInit_ex(decryption_context.get(), cipher, nullptr, key.data(),
iv.data());
if (padding == PaddingScheme::kPaddingNone) {
EVP_CIPHER_CTX_set_padding(decryption_context.get(), 0);
}
// Make sure we're not pointing into an empty buffer or past the end.
const unsigned char* encrypted_buf = NULL;
if (start < encrypted.size())
encrypted_buf = &encrypted[start];
if (!EVP_DecryptUpdate(decryption_context.get(), local_plain_text.data(),
&decrypt_size, encrypted_buf, count)) {
LOG(ERROR) << "DecryptUpdate failed";
return false;
}
// In the case of local_plain_text being full, we must avoid trying to
// point past the end of the buffer when calling EVP_DecryptFinal_ex().
unsigned char* final_buf = NULL;
if (static_cast<unsigned int>(decrypt_size) < local_plain_text.size())
final_buf = &local_plain_text[decrypt_size];
if (!EVP_DecryptFinal_ex(decryption_context.get(), final_buf, &final_size)) {
unsigned long err = ERR_get_error(); // NOLINT openssl types
ERR_load_ERR_strings();
ERR_load_crypto_strings();
LOG(ERROR) << "DecryptFinal Error: " << err << ": "
<< ERR_lib_error_string(err) << ", "
<< ERR_func_error_string(err) << ", "
<< ERR_reason_error_string(err);
return false;
}
final_size += decrypt_size;
if (padding == PaddingScheme::kPaddingCryptohomeDefaultDeprecated) {
if (final_size < SHA_DIGEST_LENGTH) {
LOG(ERROR) << "Plain text was too small.";
return false;
}
final_size -= SHA_DIGEST_LENGTH;
SHA_CTX sha_context;
unsigned char md_value[SHA_DIGEST_LENGTH];
SHA1_Init(&sha_context);
SHA1_Update(&sha_context, local_plain_text.data(), final_size);
SHA1_Final(md_value, &sha_context);
const unsigned char* md_ptr = local_plain_text.data();
md_ptr += final_size;
if (brillo::SecureMemcmp(md_ptr, md_value, SHA_DIGEST_LENGTH)) {
LOG(ERROR) << "Digest verification failed.";
return false;
}
}
local_plain_text.resize(final_size);
plain_text->swap(local_plain_text);
return true;
}
// AesEncryptSpecifyBlockMode encrypts the bytes in plain_text using AES,
// placing the output into encrypted. Aside from range constraints (start and
// count) and the key and initialization vector, this method has two parameters
// that control how the ciphertext is generated and are useful in encrypting
// specific types of data in hwsec_foundation.
//
// First, padding specifies whether and how the plaintext is padded before
// encryption. The three options, described in the PaddingScheme enumeration
// are used as such:
// - PaddingScheme::kPaddingNone is used to mix the user's passkey (derived
// from the
// password) into the encrypted blob storing the vault keyset when the TPM
// is used. This is described in more detail in the README file. There is
// no padding in this case, and the size of plain_text needs to be a
// multiple of the AES block size (16 bytes).
// - PaddingScheme::kPaddingStandard uses standard PKCS padding, which is the
// default for
// OpenSSL.
// - PaddingScheme::kPaddingCryptohomeDefaultDeprecated appends a SHA1 hash of
// the plaintext
// in plain_text before passing it to OpenSSL, which still uses PKCS padding
// so that we do not have to re-implement block-multiple padding ourselves.
// This padding scheme allows us to strongly verify the plaintext on
// decryption, which is essential when, for example, test decrypting a nonce
// to test whether a password was correct (we do this in user_session.cc).
// This padding is now deprecated and a standard integrity checking
// algorithm such as AES-GCM should be used instead.
//
// The block mode switches between ECB and CBC. Generally, CBC is used for most
// AES crypto that we perform, since it is a better mode for us for data that is
// larger than the block size. We use ECB only when mixing the user passkey
// into the TPM-encrypted blob, since we only encrypt a single block of that
// data.
bool AesEncryptSpecifyBlockMode(const brillo::SecureBlob& plain_text,
unsigned int start,
unsigned int count,
const brillo::SecureBlob& key,
const brillo::SecureBlob& iv,
PaddingScheme padding,
BlockMode block_mode,
brillo::SecureBlob* encrypted) {
// Verify that the range is within the data passed
if ((start > plain_text.size()) || ((start + count) > plain_text.size()) ||
((start + count) < start)) {
return false;
}
if (count > static_cast<unsigned int>(std::numeric_limits<int>::max())) {
// EVP_EncryptUpdate takes a signed int
return false;
}
// First set the output size based on the padding scheme. No padding means
// that the input needs to be a multiple of the block size, and the output
// size is equal to the input size. Standard padding means we should allocate
// up to a full block additional for the PKCS padding. Cryptohome default
// means we should allocate a full block additional for the PKCS padding and
// enough for a SHA1 hash.
unsigned int block_size = GetAesBlockSize();
unsigned int needed_size = count;
switch (padding) {
case PaddingScheme::kPaddingCryptohomeDefaultDeprecated:
// The AES block size and SHA digest length are not enough for this to
// overflow, as needed_size is initialized to count, which must be <=
// INT_MAX, but needed_size is itself an unsigned. The block size and
// digest length are fixed by the algorithm.
needed_size += block_size + SHA_DIGEST_LENGTH;
break;
case PaddingScheme::kPaddingStandard:
needed_size += block_size;
break;
case PaddingScheme::kPaddingNone:
if (count % block_size) {
LOG(ERROR) << "Data size (" << count << ") was not a multiple "
<< "of the block size (" << block_size << ")";
return false;
}
break;
default:
LOG(ERROR) << "Invalid padding specified";
return false;
break;
}
brillo::SecureBlob cipher_text(needed_size);
// Set the block mode
const EVP_CIPHER* cipher;
switch (block_mode) {
case BlockMode::kCbc:
cipher = EVP_aes_256_cbc();
break;
case BlockMode::kEcb:
cipher = EVP_aes_256_ecb();
break;
case BlockMode::kCtr:
cipher = EVP_aes_256_ctr();
break;
default:
LOG(ERROR) << "Invalid block mode specified";
return false;
}
if (key.size() != static_cast<unsigned int>(EVP_CIPHER_key_length(cipher))) {
LOG(ERROR) << "Invalid key length of " << key.size() << ", expected "
<< EVP_CIPHER_key_length(cipher);
return false;
}
// ECB ignores the IV, so only check the IV length if we are using a different
// block mode.
if ((block_mode != BlockMode::kEcb) &&
(iv.size() != static_cast<unsigned int>(EVP_CIPHER_iv_length(cipher)))) {
LOG(ERROR) << "Invalid iv length of " << iv.size() << ", expected "
<< EVP_CIPHER_iv_length(cipher);
return false;
}
// Initialize the OpenSSL crypto context
crypto::ScopedEVP_CIPHER_CTX encryption_context(EVP_CIPHER_CTX_new());
if (!encryption_context) {
LOG(ERROR) << "Failed to allocate EVP_CIPHER_CTX";
return false;
}
EVP_EncryptInit_ex(encryption_context.get(), cipher, nullptr, key.data(),
iv.data());
if (padding == PaddingScheme::kPaddingNone) {
EVP_CIPHER_CTX_set_padding(encryption_context.get(), 0);
}
// First, encrypt the plain_text data
unsigned int current_size = 0;
int encrypt_size = 0;
// Make sure we're not pointing into an empty buffer or past the end.
const unsigned char* plain_buf = NULL;
if (start < plain_text.size())
plain_buf = &plain_text[start];
if (!EVP_EncryptUpdate(encryption_context.get(), &cipher_text[current_size],
&encrypt_size, plain_buf, count)) {
LOG(ERROR) << "EncryptUpdate failed";
return false;
}
current_size += encrypt_size;
encrypt_size = 0;
// Next, if the padding uses the hwsec_foundation default scheme, encrypt a
// SHA1 hash of the preceding plain_text into the output data
if (padding == PaddingScheme::kPaddingCryptohomeDefaultDeprecated) {
SHA_CTX sha_context;
unsigned char md_value[SHA_DIGEST_LENGTH];
SHA1_Init(&sha_context);
SHA1_Update(&sha_context, &plain_text[start], count);
SHA1_Final(md_value, &sha_context);
if (!EVP_EncryptUpdate(encryption_context.get(), &cipher_text[current_size],
&encrypt_size, md_value, sizeof(md_value))) {
LOG(ERROR) << "EncryptUpdate failed";
return false;
}
current_size += encrypt_size;
encrypt_size = 0;
}
// In the case of cipher_text being full, we must avoid trying to
// point past the end of the buffer when calling EVP_EncryptFinal_ex().
unsigned char* final_buf = NULL;
if (static_cast<unsigned int>(current_size) < cipher_text.size())
final_buf = &cipher_text[current_size];
// Finally, finish the encryption
if (!EVP_EncryptFinal_ex(encryption_context.get(), final_buf,
&encrypt_size)) {
LOG(ERROR) << "EncryptFinal failed";
return false;
}
current_size += encrypt_size;
cipher_text.resize(current_size);
encrypted->swap(cipher_text);
return true;
}
} // namespace hwsec_foundation
| 35.826087 | 80 | 0.637621 | Toromino |
49a89792602e67ef169ad5931e18c36d24956944 | 9,971 | cpp | C++ | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 2 | 2021-07-19T12:03:39.000Z | 2021-07-22T18:37:45.000Z | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | null | null | null | components/modules/ds3231/ds3231.cpp | thmalmeida/agro_mesh | fbce39d2e08d02495ecd3b55b2e826449b9dc3b7 | [
"MIT"
] | 1 | 2021-07-08T09:07:10.000Z | 2021-07-08T09:07:10.000Z | #include "ds3231.hpp"
//Registers
#define REG_SEC 0x00
#define REG_MIN 0x01
#define REG_HOUR 0x02
#define REG_DOW 0x03
#define REG_DATE 0x04
#define REG_MON 0x05
#define REG_YEAR 0x06
#define REG_CON 0x0e
#define REG_STATUS 0x0f
#define REG_AGING 0x10
#define REG_TEMPM 0x11
#define REG_TEMPL 0x12
//Alarm 1 registers
#define REG_ALARM1_SEC 0x07
#define REG_ALARM1_MIN 0x08
#define REG_ALARM1_HOUR 0x09
#define REG_ALARM1_DATE 0x0A
//Alarm 2 regiters
#define REG_ALARM2_MIN 0x0B
#define REG_ALARM2_HOUR 0x0C
#define REG_ALARM2_DATE 0x0D
//Bits
#define BIT_AMPM 5 //1: PM | 0: AM
#define BIT_1224 6 //1: 12 | 0: 24
#define BIT_CENTURY 7
//Control register bits
#define BIT_EOSC 7
#define BIT_BBSQW 6
#define BIT_CONV 5
#define BIT_RS2 4
#define BIT_RS1 3
#define BIT_INTCN 2
#define BIT_A2IE 1
#define BIT_A1IE 0
//Status register bits
#define BIT_OSF 7
#define BIT_EN32kHz 3 //1: enable /0: disable
#define BIT_BSY 2
#define BIT_A2F 1 //1: Alarm 2 match
#define BIT_A1F 0 //1: Alarm 1 match
#define DS3231_ADDR 0b01101000 // 0x68 >> 1
DS3231::DS3231(I2C_Master *i2c, uint8_t time_mode /* = FORMAT_24H */)
: _i2c(i2c), _time_mode(time_mode)
{}
bool DS3231::probe() noexcept
{
return _i2c->probe(DS3231_ADDR);
}
void DS3231::begin(){
_set_bit_reg(REG_HOUR, BIT_1224, _time_mode);
enableAlarm1Int(false);
enableAlarm2Int(false);
enableInterrupt(false);
}
void DS3231::setDateTime(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
//_encode(dateTime->dayOfWeek()),
1,
_encode(dateTime->getDay()),
_encode(dateTime->getMonth()),
_encode((uint8_t)(dateTime->getYear()-2000))
};
_send(REG_SEC,date,7);
}
void DS3231::getDateTime(DateTime* dateTime)
{
uint8_t date[7];
_receive(REG_SEC, date, 7);
dateTime->setDateTime((uint16_t)_decodeY(date[6])+2000,
_decode(date[5]),
_decode(date[4]),
_decodeH(date[2]),
_decode(date[1]),
_decode(date[0]));
}
void DS3231::setTime(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour())
};
_send(REG_SEC,date,3);
}
void DS3231::getTime(DateTime* dateTime)
{
uint8_t date[3];
_receive(REG_SEC,date,3);
dateTime->setTime(_decodeH(date[2]),
_decode(date[1]),
_decode(date[0]));
}
void DS3231::setDate(DateTime *dateTime)
{
uint8_t date[] = {_encode(dateTime->getDay()),
_encode(dateTime->getMonth()),
_encode((uint8_t)(dateTime->getYear()-2000))
};
_send(REG_DATE,date,3);
}
void DS3231::getDate(DateTime *dateTime)
{
uint8_t date[3];
_receive(REG_DATE,date,3);
dateTime->setDate((uint16_t)(_decodeY(date[2])+2000),
_decode(date[1]),
_decode(date[0])
);
}
void DS3231::setTimeMode(uint8_t mode)
{
_set_bit_reg(REG_HOUR,6,mode);
}
uint8_t DS3231::getTimeMode()
{
return _get_bit_reg(REG_HOUR,6);
}
void DS3231::setDOW(uint8_t dow)
{
_send(REG_DOW,dow);
}
uint8_t DS3231::getDOW()
{
return _receive(REG_DOW);
}
void DS3231::enable32kHz(bool enable)
{
_set_bit_reg(REG_STATUS, BIT_EN32kHz, enable);
}
void DS3231::enableInterrupt(uint8_t enable /*= true*/)
{
_set_bit_reg(REG_CON, BIT_INTCN, enable);
}
void DS3231::enableSQWRate(DS3231SQWrate rate, uint8_t enable /*= true*/)
{
if(enable)
enableInterrupt(false);
_set_bit_reg(REG_CON, BIT_BBSQW, enable);
switch(rate){
case SQW_RATE_1K:
_set_bit_reg(REG_CON,BIT_RS2,false);
_set_bit_reg(REG_CON,BIT_RS1,true);
break;
case SQW_RATE_4K:
_set_bit_reg(REG_CON,BIT_RS2,true);
_set_bit_reg(REG_CON,BIT_RS1,false);
break;
case SQW_RATE_8K:
_set_bit_reg(REG_CON,BIT_RS2,true);
_set_bit_reg(REG_CON,BIT_RS1,true);
break;
default: /* SQW_RATE_1 */
_set_bit_reg(REG_CON,BIT_RS2,false);
_set_bit_reg(REG_CON,BIT_RS1,false);
break;
}
}
void DS3231::enableAlarm2Int(bool enable /*= true*/)
{
_set_bit_reg(REG_CON,BIT_A2IE,enable);
}
void DS3231::enableAlarm1Int(bool enable /*= true*/)
{
_set_bit_reg(REG_CON,BIT_A1IE,enable);
}
uint8_t DS3231::clearAlarmFlags()
{
uint8_t alarms = _receive(REG_STATUS) & ((1<<BIT_A2F)|(1<<BIT_A1F));
_set_bit_reg(REG_STATUS, BIT_A2F, false);
_set_bit_reg(REG_STATUS, BIT_A1F, false);
return alarms;
}
void DS3231::configAlarm2(DS3231Alarm2Config type_alarm, DateTime *dateTime /* = NULL */)
{
switch(type_alarm){
case PER_MINUTE:
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7);
_set_bit_reg(REG_ALARM2_MIN, 7);
break;
case MINUTES_MATCH:
_send(REG_ALARM2_MIN, _encode(dateTime->getMinute()));
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
break;
case HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour())};
_send(REG_ALARM2_MIN, data, 2);
_set_bit_reg(REG_ALARM2_DATE, 7);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
}
break;
case DATE_HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->getDay())};
_send(REG_ALARM2_MIN, data, 3);
_set_bit_reg(REG_ALARM2_DATE, 7, false);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
_set_bit_reg(REG_ALARM2_DATE, 6, false);
}
break;
case DAY_HOUR_MIN_MATCH:
{
uint8_t data[] = {_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->dayOfWeek())};
_send(REG_ALARM2_MIN, data, 3);
_set_bit_reg(REG_ALARM2_DATE, 7, false);
_set_bit_reg(REG_ALARM2_HOUR, 7, false);
_set_bit_reg(REG_ALARM2_MIN, 7, false);
_set_bit_reg(REG_ALARM2_DATE, 6, true);
}
break;
default:
break;
}
}
void DS3231::configAlarm1(DS3231Alarm1Config type_alarm, DateTime *dateTime /* = NULL */)
{
switch(type_alarm){
case PER_SECOND:
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7);
_set_bit_reg(REG_ALARM1_SEC, 7);
break;
case SECONDS_MATCH:
_send(REG_ALARM1_SEC, _encode(dateTime->getSecond()));
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
break;
case MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute())};
_send(REG_ALARM1_SEC, data, 2);
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
}
break;
case HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour())};
_send(REG_ALARM1_SEC, data, 3);
_set_bit_reg(REG_ALARM1_DATE, 7);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
}
break;
case DATE_HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->getDay())};
_send(REG_ALARM1_SEC,data, 4);
_set_bit_reg(REG_ALARM1_DATE, 7, false);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
_set_bit_reg(REG_ALARM1_DATE, 6, false);
}
break;
case DAY_HOUR_MIN_SEC_MATCH:
{
uint8_t data[] = {_encode(dateTime->getSecond()),
_encode(dateTime->getMinute()),
_encode(dateTime->getHour()),
_encode(dateTime->dayOfWeek())};
_send(REG_ALARM1_SEC,data, 4);
_set_bit_reg(REG_ALARM1_DATE, 7, false);
_set_bit_reg(REG_ALARM1_HOUR, 7, false);
_set_bit_reg(REG_ALARM1_MIN, 7, false);
_set_bit_reg(REG_ALARM1_SEC, 7, false);
_set_bit_reg(REG_ALARM1_DATE, 6);
}
break;
default:
break;
}
}
void DS3231::startConvTemp()
{
if(_get_bit_reg(REG_CON, BIT_CONV))
return;
_set_bit_reg(REG_CON, BIT_CONV);
}
float DS3231::getTemp()
{
uint8_t data[2];
_receive(REG_TEMPM, data, 2);
return (float)data[0] + ((data[1] >> 6) * 0.25f);
}
/* Private */
void DS3231::_send(uint8_t reg, uint8_t* data, size_t length)
{
_i2c->write(DS3231_ADDR, reg, data, length, true);
}
void DS3231::_send(uint8_t reg,uint8_t data)
{
_i2c->write(DS3231_ADDR, reg, data, true);
}
void DS3231::_receive(uint8_t reg,uint8_t* data, size_t length)
{
_i2c->read(DS3231_ADDR, reg, data, length, true);
}
uint8_t DS3231::_receive(uint8_t reg)
{
uint8_t data;
_i2c->read(DS3231_ADDR, reg, &data, true);
return data;
}
void DS3231::_set_bit_reg(uint8_t reg, uint8_t bit, bool value /* = true*/)
{
uint8_t r = _receive(reg);
r &= ~(1 << bit);
r |= (value << bit);
_send(reg, r);
}
uint8_t DS3231::_get_bit_reg(uint8_t reg, uint8_t bit)
{
return (_receive(reg) >> bit) & 1;
}
uint8_t DS3231::_decode(uint8_t value)
{
uint8_t decoded = value & 127;
decoded = (decoded & 15) + 10 * ((decoded & (15 << 4)) >> 4);
return decoded;
}
uint8_t DS3231::_decodeH(uint8_t value)
{
if (value & 128)
value = (value & 15) + (12 * ((value & 32) >> 5));
else
value = (value & 15) + (10 * ((value & 48) >> 4));
return value;
}
uint8_t DS3231::_decodeY(uint8_t value)
{
return (value & 15) + 10 * ((value & (15 << 4)) >> 4);
}
uint8_t DS3231::_encode(uint8_t value)
{
return ((value / 10) << 4) + (value % 10);
}
| 23.627962 | 90 | 0.664627 | thmalmeida |
49aaf4ac7f6b7fb8effddf07d0272531622de3f5 | 6,437 | cpp | C++ | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | 4 | 2016-12-16T16:42:41.000Z | 2017-01-27T23:49:33.000Z | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | null | null | null | AGNES.cpp | Quanhaoli2641/MachineLearningVoter | 244ed7dd18d0c497a903e3ada5fe3f9aa4ec18c7 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include "AGNES.h"
#include <iostream>
#include "Silhouette.h"
using namespace std;
using namespace Silhouette;
namespace AGNES {
UnsupervisedNode* UnsupervisedNode::getChild1 (){return child1;}
UnsupervisedNode* UnsupervisedNode::getChild2 (){return child2;}
void UnsupervisedNode::modChild1 (UnsupervisedNode* n){child1 = n;}
void UnsupervisedNode::modChild2 (UnsupervisedNode* n){child2 = n;}
// Initializes the Distance matrix with values
void initializeDistMatrix (vector<vector<float>>& distMatrix, vector<vector<float>>& unlabeledData) {
// For every data set in the data set holder
// Or in another perspective: generate the rows of the matrices
for (int k = 0; k < unlabeledData.size(); k++) {
vector<float> inV;
inV.clear();
// and generate the columns of the matrices
for (int l = 0; l < unlabeledData.size(); l++) {
inV.push_back(0);
}
distMatrix.push_back(inV);
}
// For every row
for (int i = 0; i < unlabeledData.size(); i++) {
// and every column
for (int j = 0; j < unlabeledData.size(); j++) {
// Gets the Euclidean distance between two data sets
distMatrix[i][j] = getDistance(unlabeledData[i], unlabeledData[j]);
}
}
}
// Initializes the vector of unsupervised node clusters
// with values obtained from a file
void initializeNodesVector (vector<UnsupervisedNode*>& vNodes, vector<vector<float>>& unlabeledData) {
// For every value in the vector of datasets
for (int i = 0; i < unlabeledData.size(); i++) {
// create a Node pointer pointing to a Unsupervised Node with the data set
UnsupervisedNode* n = new UnsupervisedNode (unlabeledData[i]);
// and add it to the vector of unsupervised node clusters
vNodes.push_back(n);
}
}
// Finds the smallest distance between two datasets
// inside the distance matrix
pair<int, int> findMinDistCluster (vector<vector<float>>& distMatrix) {
// initialize a minimum value with the largest float value
float min = MAXFLOAT;
pair<int, int> indices (0,0);
// look at every row
for (int i = 0; i < distMatrix.size(); i++) {
// look at every column
for (int j = 0; j < distMatrix.size(); j++) {
// if the indices arent the same
// because if they were, it would just return itself
if (i != j) {
// if the distance is smaller than the minimum
if (distMatrix[i][j] < min) {
// reassign value
min = distMatrix[i][j];
// save the indices
indices.first = i;
indices.second = j;
}
}
}
}
// return the indices
return indices;
}
// Modify the matrix to update its values
void modMatrix (vector<vector<float>>& distMatrix, int index1, int index2) {
// Since a new cluster will be created, it's closest distance must be updated
// Luckily since it's members already have distances
// Find the smallest distance from one of its members to other clusters
// And use that value as the minimum distance
for (int i = 0; i < distMatrix.size(); i++) {
// Compares the smaller of the two values and saves the smaller of the two
// at the end of the matrix row
if (distMatrix[i][index1] > distMatrix[i][index2]) {
distMatrix[i].push_back(distMatrix[i][index2]);
}
else {
distMatrix[i].push_back(distMatrix[i][index1]);
}
// Remove the two data values from every row
// Or the column of these two data sets
distMatrix[i].erase(distMatrix[i].begin()+index1);
distMatrix[i].erase(distMatrix[i].begin()+index2-1);
}
// Remove the rows of these two data sets
distMatrix.erase(distMatrix.begin()+index1);
if (index2 > index1) distMatrix.erase(distMatrix.begin()+index2-1);
else distMatrix.erase(distMatrix.begin()+index2);
vector<float> newRow;
newRow.clear();
// Insert a new row into the matrix holding it's smallest distance values
// to other clusters
for (int j = 0; j < distMatrix.size(); j++) {
newRow.push_back(distMatrix[j][distMatrix.size()-1]);
}
newRow.push_back(0);
distMatrix.push_back(newRow);
}
// Update the vector of clusters
void modVNodes (vector<UnsupervisedNode*>& vNodes, int index1, int index2) {
// Create a new cluster
UnsupervisedNode* n = new UnsupervisedNode();
// that holds the previous clusters
n->modChild1(vNodes[index1]);
n->modChild2(vNodes[index2]);
// Remove the clusters from the vector of clusters
vNodes.erase(vNodes.begin()+index1);
if (index2 > index1) vNodes.erase(vNodes.begin()+index2-1);
else vNodes.erase(vNodes.begin()+index2);
// and put the new cluster in the vector of clusters
vNodes.push_back(n);
}
// Generate the unsupervised tree for the agglomerate nesting cluster
UnsupervisedNode* genTree (vector<vector<float>>& distMatrix, vector<UnsupervisedNode*>& nodes) {
// Return a stump if there is nothing to create with
if (nodes.size() == 0 || distMatrix.size() == 0) return nullptr;
// Until there is only one giant cluster
while (nodes.size() > 1) {
cout << "Number of current clusters: " << nodes.size() << ", still processing..." << endl;
// Find the smallest distance pair
pair<int,int> t = findMinDistCluster(distMatrix);
// Combine the two clusters into one
modVNodes(nodes, t.first, t.second);
// and fix the distance matrix to reflect this combination
modMatrix(distMatrix, t.first, t.second);
}
// Return the head of the tree
return nodes[0];
}
}
| 41.262821 | 106 | 0.5762 | Quanhaoli2641 |
49ae7cf017d7df0da7d85bfc9677fe387b4dd2d2 | 550 | cpp | C++ | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | src/limit.cpp | henrikt-ma/cadical | 58331fd078cb5f76bae52e25de0e34c6a7dd4c1d | [
"MIT"
] | null | null | null | #include "internal.hpp"
namespace CaDiCaL {
Limit::Limit () { memset (this, 0, sizeof *this); }
bool Internal::terminating () {
if (termination) {
LOG ("termination forced");
return true;
}
if (lim.conflict >= 0 && stats.conflicts >= lim.conflict) {
LOG ("conflict limit %ld reached", lim.conflict);
return true;
}
if (lim.decision >= 0 && stats.decisions >= lim.decision) {
LOG ("decision limit %ld reached", lim.decision);
return true;
}
return false;
}
Inc::Inc () { memset (this, 0, sizeof *this); }
};
| 21.153846 | 61 | 0.616364 | henrikt-ma |
49b21525f89fdb60466b3d2d7515bfc68fda09a4 | 4,985 | cpp | C++ | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | 1 | 2017-10-28T07:39:29.000Z | 2017-10-28T07:39:29.000Z | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | null | null | null | src/WinTrek/Slideshow.cpp | nikodemak/Allegiance | 9c24c6c80bf3939a8095aa40e2f85c1d3adc20fc | [
"MIT"
] | null | null | null | #include "pch.h"
#include "slideshow.h"
//////////////////////////////////////////////////////////////////////////////
//
// Training Screen
//
//////////////////////////////////////////////////////////////////////////////
void Slideshow::CleanUpTimers (void)
{
if (m_bInTimer)
{
// if a timer event had already been fired, then we need to remove it now
ITimerEventSource* pTimer = GetEngineWindow()->GetTimer ();
pTimer->RemoveSink (m_pEventSink);
m_bInTimer = false;
}
}
void Slideshow::StopSound (void)
{
// check to see if there is a sound already playing
if (static_cast<ISoundInstance*> (m_pSoundInstance))
if (m_pSoundInstance->IsPlaying () == S_OK)
{
m_pSoundInstance->GetFinishEventSource ()->RemoveSink(m_pEventSink);
m_pSoundInstance->Stop (true);
}
}
Slideshow::Slideshow (Modeler* pmodeler, const ZString& strNamespace) :
m_bNextSlide (false),
m_bInTimer (false)
{
// create the wrap image
m_pWrapImage = new WrapImage(Image::GetEmpty());
m_pImage = new GroupImage(new PickImage (this), m_pWrapImage);
// create a namespace for exporting information
TRef<INameSpace> pTrainingDataNameSpace = pmodeler->CreateNameSpace ("SlideshowData", pmodeler->GetNameSpace ("gamepanes"));
// Load the members from MDL
TRef<INameSpace> pNameSpace = pmodeler->GetNameSpace(strNamespace);
CastTo(m_pSlideList, pNameSpace->FindMember("slides"));
pmodeler->UnloadNameSpace(strNamespace);
// create a delegate for myself
m_pEventSink = IEventSink::CreateDelegate(this);
// make the keyboard inputs come to us
m_pkeyboardInputOldFocus = GetEngineWindow()->GetFocus();
GetEngineWindow()->SetFocus(IKeyboardInput::CreateDelegate(this));
// set the flag to indicate we are in a slideshow
m_bIsInSlideShow = true;
// start with the first slide
m_pSlideList->GetFirst();
NextSlide ();
}
Slideshow::~Slideshow (void)
{
// set the flag to indicate we are no longer in a slideshow
m_bIsInSlideShow = false;
// clean up timers so nothing fires an event at us when we're gone
CleanUpTimers ();
// stop sounds so nothing fires an event at us when we're gone
StopSound ();
// reset the focus for inputs
GetEngineWindow()->SetFocus(m_pkeyboardInputOldFocus);
}
// do the work
void Slideshow::NextSlide (void)
{
// stop any playing sounds
StopSound ();
// clean up any existing timers
CleanUpTimers ();
// check to see if there are any more slides to show
if (m_pSlideList->GetCurrent() != NULL)
{
// get the image and sound id for the slide
TRef<IObjectPair> pPair;
CastTo (pPair, m_pSlideList->GetCurrent());
//TRef<Image> pImage = Image::Cast((Value*)pPair->GetFirst ());
TRef<Image> pImage = Image::Cast (static_cast<Value*> (pPair->GetFirst ()));
SoundID soundID = static_cast<SoundID> (GetNumber (pPair->GetSecond ()));
// advance to the next slide
m_pSlideList->GetNext();
// set the image to the next image in the list
m_pWrapImage->SetImage (pImage);
// start the sound
m_pSoundInstance = GetWindow ()->StartSound (soundID);
// wait for the sound to finish
m_pSoundInstance->GetFinishEventSource ()->AddSink (m_pEventSink);
}
else
{
// get out of the slideshow
Dismiss ();
}
}
void Slideshow::Dismiss (void)
{
}
// UI Events
bool Slideshow::OnEvent (IEventSource* pEventSource)
{
// get the timer event source
ITimerEventSource* pTimer = GetEngineWindow()->GetTimer ();
// XXX something strange, in that timers are not passing the event source in,
// so I am assuming that if there is an event source, then it is from the
// current sound ending.
if (pEventSource)
{
// delay one second before processing the event
pTimer->AddSink (m_pEventSink, 1.0f);
m_bInTimer = true;
}
else
{
// skip to the next slide on the next update
m_bNextSlide = true;
pTimer->RemoveSink (m_pEventSink);
m_bInTimer = false;
}
return false;
}
void Slideshow::Picked (void)
{
NextSlide ();
}
// Screen Methods
Image* Slideshow::GetImage (void)
{
return m_pImage;
}
void Slideshow::OnFrame (void)
{
if (m_bNextSlide)
{
m_bNextSlide = false;
NextSlide ();
}
}
bool Slideshow::m_bIsInSlideShow = false;
bool Slideshow::IsInSlideShow (void)
{
return m_bIsInSlideShow;
}
//////////////////////////////////////////////////////////////////////////////
//
// IKeyboardInput
//
//////////////////////////////////////////////////////////////////////////////
bool Slideshow::OnKey(IInputProvider* pprovider, const KeyState& ks, bool& fForceTranslate)
{
if (ks.bDown)
NextSlide();
return false;
}
| 26.801075 | 131 | 0.604614 | nikodemak |
49bdc478f03d5b57259e07de05882e47c3e581e7 | 3,224 | hpp | C++ | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 3 | 2022-01-25T19:31:17.000Z | 2022-01-25T21:10:39.000Z | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | 20 | 2021-12-17T14:58:00.000Z | 2022-02-05T21:25:35.000Z | logger/logger.hpp | mlohry/maDGiCart-CH | 36723e992449fce670d17279b606f54d4b5b5545 | [
"MIT"
] | null | null | null | #pragma once
#include <chrono>
#include <fstream>
#include <map>
#include <memory>
#include <sstream>
#include <string>
#include <vector>
#include <boost/log/sinks/sync_frontend.hpp>
#include <boost/log/sinks/text_file_backend.hpp>
#include <boost/log/sinks/text_ostream_backend.hpp>
#include "typedefs.hpp"
enum class LogLevel { trace, debug, info, warning, error, fatal };
class Logger {
public:
static Logger& get()
{
static Logger S;
return S;
}
void disable();
void enable();
void initLogFile(std::string file, LogLevel lvl = LogLevel::trace);
const std::string& logFilename() const { return log_filename_; }
void closeLogFile();
void setLogLevel(LogLevel lvl);
void updateLog();
void setTimeMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
void setResidualMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
void setSolutionMonitor(const std::vector<std::pair<std::string, double>>& name_value_pairs);
const std::vector<std::pair<std::string, double>> getTimeMonitor() const { return time_status_; }
const std::vector<std::pair<std::string, double>> getResidualMonitor() const { return residual_status_; }
const std::vector<std::pair<std::string, double>> getSolutionMonitor() const { return solution_status_; }
void Message(const std::string& str, LogLevel lvl);
void TraceMessage(std::string str);
void DebugMessage(std::string str);
void InfoMessage(std::string str);
void WarningMessage(std::string str);
void ErrorMessage(std::string str);
void FatalMessage(std::string str);
void WarningAssert(bool, const std::string&);
void FatalAssert(bool, const std::string&);
void logDeviceMemoryTransfer(const std::string& description);
void closeDeviceMemoryTransferLog();
class Timer {
public:
Timer(const std::string& msg, const LogLevel log_level);
virtual ~Timer();
real_t elapsed();
protected:
const std::chrono::time_point<std::chrono::high_resolution_clock> start_;
const std::string msg_;
const LogLevel log_level_;
bool elapsed_called_;
};
Timer timer(const std::string& msg, const LogLevel log_level = LogLevel::trace) { return Timer(msg, log_level); }
private:
Logger();
~Logger() = default;
static std::string makeBanner();
const std::string banner_;
std::string log_filename_;
int_t n_update_calls_;
bool initialized_;
bool auto_flush_;
bool log_level_overridden_ = false;
std::unique_ptr<std::ofstream> memlog_;
int_t n_device_to_host_copies_ = 0;
std::vector<std::pair<std::string, double>> time_status_;
std::vector<std::pair<std::string, double>> residual_status_;
std::vector<std::pair<std::string, double>> solution_status_;
boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_file_backend>> g_file_sink_;
boost::shared_ptr<boost::log::sinks::synchronous_sink<boost::log::sinks::text_ostream_backend>> g_console_sink_;
};
| 31.607843 | 115 | 0.675248 | mlohry |
49bf32d72e49ffdf422e633e13f056b21921b048 | 28,035 | cpp | C++ | multimedia/dshow/filterus/dexter/tldb/tldbobj.cpp | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | multimedia/dshow/filterus/dexter/tldb/tldbobj.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | multimedia/dshow/filterus/dexter/tldb/tldbobj.cpp | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //@@@@AUTOBLOCK+============================================================;
//
// 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.
//
// File: tldbobj.cpp
//
// Copyright (c) Microsoft Corporation. All Rights Reserved.
//
//@@@@AUTOBLOCK-============================================================;
#include <streams.h>
#include "stdafx.h"
#include "tldb.h"
#include <strsafe.h>
const int OUR_MAX_STREAM_SIZE = 2048; // chosen at random
long CAMTimelineObj::m_nStaticGenID = 0;
//############################################################################
//
//############################################################################
CAMTimelineObj::CAMTimelineObj( TCHAR *pName, LPUNKNOWN pUnk, HRESULT * phr )
: CUnknown( pName, pUnk )
, m_rtStart( 0 )
, m_rtStop( 0 )
, m_bMuted( FALSE )
, m_bLocked( FALSE )
, m_rtDirtyStart( -1 )
, m_rtDirtyStop( -1 )
, m_pUserData( NULL )
, m_nUserDataSize( 0 )
, m_UserID( 0 )
, m_SubObjectGuid( GUID_NULL )
, m_nGenID( 0 )
{
m_UserName[0] = 0;
m_ClassID = GUID_NULL;
// bad logic since we don't init globals
//
static bool SetStatic = false;
if( !SetStatic )
{
SetStatic = true;
m_nStaticGenID = 0;
}
_BumpGenID( );
}
//############################################################################
//
//############################################################################
CAMTimelineObj::~CAMTimelineObj( )
{
_Clear( );
}
//############################################################################
// clear all the memory this object allocated for it's subobject and data
//############################################################################
void CAMTimelineObj::_Clear( )
{
_ClearSubObject( );
if( m_pUserData )
{
delete [] m_pUserData;
m_pUserData = NULL;
}
m_nUserDataSize = 0;
}
//############################################################################
// clear out the subobject and anything it had in it.
//############################################################################
void CAMTimelineObj::_ClearSubObject( )
{
m_pSubObject.Release( );
m_SubObjectGuid = GUID_NULL;
m_pSetter.Release( );
}
//############################################################################
// return the interfaces we support
//############################################################################
STDMETHODIMP CAMTimelineObj::NonDelegatingQueryInterface(REFIID riid, void **ppv)
{
if( riid == IID_IAMTimelineObj )
{
return GetInterface( (IAMTimelineObj*) this, ppv );
}
if( riid == IID_IAMTimelineNode )
{
return GetInterface( (IAMTimelineNode*) this, ppv );
}
return CUnknown::NonDelegatingQueryInterface( riid, ppv );
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetStartStop2(REFTIME * pStart, REFTIME * pStop)
{
REFERENCE_TIME p1;
REFERENCE_TIME p2;
HRESULT hr = GetStartStop( &p1, &p2 );
*pStart = RTtoDouble( p1 );
*pStop = RTtoDouble( p2 );
return hr;
}
STDMETHODIMP CAMTimelineObj::GetStartStop(REFERENCE_TIME * pStart, REFERENCE_TIME * pStop)
{
CheckPointer( pStart, E_POINTER );
CheckPointer( pStop, E_POINTER );
*pStart = m_rtStart;
*pStop = m_rtStop;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetStartStop2(REFTIME Start, REFTIME Stop)
{
if( ( Start == -1 ) && ( Stop == -1 ) )
{
return NOERROR;
}
// see how long we are
//
REFERENCE_TIME diff = m_rtStop - m_rtStart;
REFERENCE_TIME p1 = DoubleToRT( Start );
REFERENCE_TIME p2 = DoubleToRT( Stop );
// if they didn't give the start time
//
if( Start == -1 )
{
p1 = p2 - diff;
}
// if they didn't give the stop time
//
if( Stop == -1 )
{
p2 = p1 + diff;
}
HRESULT hr = SetStartStop( p1, p2 );
return hr;
}
STDMETHODIMP CAMTimelineObj::SetStartStop(REFERENCE_TIME Start, REFERENCE_TIME Stop)
{
if( ( Start == -1 ) && ( Stop == -1 ) )
{
return NOERROR;
}
CComPtr< IAMTimelineObj > pRefHolder( this );
// is this object already in the tree? Don't add and remove it if it is NOT.
//
CComPtr< IAMTimelineObj > pParent;
XGetParent( &pParent );
REFERENCE_TIME p1 = Start;
REFERENCE_TIME p2 = Stop;
// if they didn't give the start time
//
if( Start == -1 )
{
p1 = m_rtStart;
}
else if( Start < 0 )
{
return E_INVALIDARG;
}
// if they didn't give the stop time
//
if( Stop == -1 )
{
p2 = m_rtStop;
} else if( Stop < 0 )
{
return E_INVALIDARG;
}
// if stop time is less than Start
//
if( Start > Stop )
{
return E_INVALIDARG;
}
// if we're time based, not priority based, we need to remove this
// object from the tree first, in case we change the start times to
// something weird
//
if( !HasPriorityOverTime( ) && pParent )
{
XRemoveOnlyMe( );
}
m_rtStart = p1;
m_rtStop = p2;
SetDirtyRange( m_rtStart, m_rtStop );
// if prioriity is more important, then we're done
//
if( HasPriorityOverTime( ) || !pParent )
{
return NOERROR;
}
HRESULT hr = 0;
CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pParentNode( pParent );
hr = pParentNode->XAddKidByTime( m_TimelineType, pRefHolder );
return hr;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetSubObject(IUnknown* *ppVal)
{
CheckPointer( ppVal, E_POINTER );
*ppVal = m_pSubObject;
if( *ppVal )
{
(*ppVal)->AddRef( );
}
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetSubObjectLoaded(BOOL * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = ( m_pSubObject != NULL );
return NOERROR;
}
//############################################################################
// set the COM object that this timeline object holds. This can be used instead
// of a GUID to the COM object.
//############################################################################
// why will people be calling us to tell us what our sub object is?
// 1: we don't already have one, so we need to fill in our com
// pointer and GUID, and sub-object data. Problem is, only sometimes
// will we want sub-object data, depending on what type of node we are.
// how do we tell?
// 2: we already have a sub-object, but want to clear it out. We can call
// a clear method, then pretend it's #1 above.
//
STDMETHODIMP CAMTimelineObj::SetSubObject(IUnknown* newVal)
{
// if they're the same, return
//
if( newVal == m_pSubObject )
{
return NOERROR;
}
GUID incomingGuid = _GetObjectGuid( newVal );
if( incomingGuid == GUID_NULL )
{
DbgLog((LOG_TRACE, 2, TEXT("SetSubObject: CLSID doesn't exist." )));
}
else
{
m_SubObjectGuid = incomingGuid;
}
// blow out the cache
//
_BumpGenID( );
// dirty ourselves for our duration
//
SetDirtyRange( m_rtStart, m_rtStop );
m_pSubObject = newVal;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetSubObjectGUID(GUID newVal)
{
// if they're the same, return
//
if( newVal == m_SubObjectGuid )
{
return NOERROR;
}
// wipe out what used to be here, since we're setting a new object.
//
_ClearSubObject( );
// blow out the cache
//
_BumpGenID( );
// ??? should we wipe out user data, too?
m_SubObjectGuid = newVal;
SetDirtyRange( m_rtStart, m_rtStop );
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetSubObjectGUID(GUID * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = m_SubObjectGuid;
return NOERROR;
}
STDMETHODIMP CAMTimelineObj::SetSubObjectGUIDB(BSTR newVal)
{
GUID NewGuid = GUID_NULL;
HRESULT hr = CLSIDFromString( newVal, &NewGuid );
if( FAILED( hr ) )
{
return hr;
}
hr = SetSubObjectGUID( NewGuid );
return hr;
}
STDMETHODIMP CAMTimelineObj::GetSubObjectGUIDB(BSTR * pVal)
{
HRESULT hr;
WCHAR * TempVal = NULL;
hr = StringFromCLSID( m_SubObjectGuid, &TempVal );
if( FAILED( hr ) )
{
return hr;
}
*pVal = SysAllocString( TempVal );
CoTaskMemFree( TempVal );
if( !(*pVal) ) return E_OUTOFMEMORY;
return NOERROR;
}
//############################################################################
// ask what our type is.
//############################################################################
STDMETHODIMP CAMTimelineObj::GetTimelineType(TIMELINE_MAJOR_TYPE * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = m_TimelineType;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetTimelineType(TIMELINE_MAJOR_TYPE newVal)
{
// don't care if they're the same
//
if( newVal == m_TimelineType )
{
return NOERROR;
}
// can't set the type, once it's been set
//
if( m_TimelineType != 0 )
{
DbgLog((LOG_TRACE, 2, TEXT("SetTimelineType: Timeline type already set." )));
return E_INVALIDARG;
}
SetDirtyRange( m_rtStart, m_rtStop );
m_TimelineType = newVal;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetUserID(long * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = m_UserID;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetUserID(long newVal)
{
m_UserID = newVal;
SetDirtyRange( m_rtStart, m_rtStop );
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetUserName(BSTR * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = SysAllocString( m_UserName );
if( !(*pVal) ) return E_OUTOFMEMORY;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetUserName(BSTR newVal)
{
if (newVal == NULL) {
m_UserName[0] = 0;
} else {
HRESULT hr = StringCchCopy( m_UserName, 256, newVal );
if( FAILED( hr ) )
{
return hr;
}
}
SetDirtyRange( m_rtStart, m_rtStop );
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetPropertySetter(IPropertySetter **ppSetter)
{
CheckPointer(ppSetter, E_POINTER);
*ppSetter = m_pSetter;
if (*ppSetter)
(*ppSetter)->AddRef();
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetPropertySetter(IPropertySetter *pSetter)
{
m_pSetter = pSetter;
// !!! _GiveSubObjectData(); if sub object instantiated, give it props now?
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetUserData(BYTE * pData, long * pSize)
{
// somebody was fooling us
//
if( !pData && !pSize )
{
return E_POINTER;
}
CheckPointer( pSize, E_POINTER );
*pSize = m_nUserDataSize;
// they just want the size
//
if( !pData )
{
return NOERROR;
}
// if passed in size isn't what we expect it to be... ???
CopyMemory( pData, m_pUserData, m_nUserDataSize );
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetUserData(BYTE * pData, long Size)
{
// somebody was fooling us
//
if( Size == 0 )
{
return NOERROR;
}
SetDirtyRange( m_rtStart, m_rtStop );
if( m_pUserData )
{
delete [] m_pUserData;
m_pUserData = NULL;
}
BYTE * pNewData = new BYTE[Size];
if( !pNewData )
{
DbgLog((LOG_TRACE, 2, TEXT("SetUserData: memory allocation failed." )));
return E_OUTOFMEMORY;
}
m_pUserData = pNewData;
CopyMemory( m_pUserData, pData, Size );
m_nUserDataSize = Size;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetMuted(BOOL * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = FALSE;
// if the parent is muted, so are we
CComPtr< IAMTimelineObj > pObj;
HRESULT hr = XGetParent(&pObj);
if (hr == S_OK && pObj)
pObj->GetMuted(pVal);
if (m_bMuted)
*pVal = TRUE;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetMuted(BOOL newVal)
{
// drived class should override
//
//DbgLog((LOG_TRACE,2,TEXT("SetMuted: Derived class should implement?" )));
m_bMuted = newVal;
return S_OK;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetLocked(BOOL * pVal)
{
CheckPointer( pVal, E_POINTER );
*pVal = m_bLocked;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetLocked(BOOL newVal)
{
// drived class should override
//
//DbgLog((LOG_TRACE,2,TEXT("SetLocked: Derived class should implement?" )));
m_bLocked = newVal;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetDirtyRange2
(REFTIME * pStart, REFTIME * pStop)
{
REFERENCE_TIME p1 = DoubleToRT( *pStart );
REFERENCE_TIME p2 = DoubleToRT( *pStop );
HRESULT hr = GetDirtyRange( &p1, &p2 );
*pStart = RTtoDouble( p1 );
*pStop = RTtoDouble( p2 );
return hr;
}
STDMETHODIMP CAMTimelineObj::GetDirtyRange
(REFERENCE_TIME * pStart, REFERENCE_TIME * pStop)
{
CheckPointer( pStart, E_POINTER );
CheckPointer( pStop, E_POINTER );
*pStart = m_rtDirtyStart;
*pStop = m_rtDirtyStop;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::SetDirtyRange2
(REFTIME Start, REFTIME Stop )
{
REFERENCE_TIME p1 = DoubleToRT( Start );
REFERENCE_TIME p2 = DoubleToRT( Stop );
HRESULT hr = SetDirtyRange( p1, p2 );
return hr;
}
STDMETHODIMP CAMTimelineObj::SetDirtyRange
(REFERENCE_TIME Start, REFERENCE_TIME Stop )
{
// need to do different things, depending on what our major type is.
// every C++ class should need to override this.
DbgLog((LOG_TRACE, 2, TEXT("SetDirtyRange: Derived class should implement." )));
return E_NOTIMPL; // okay
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::ClearDirty
( )
{
m_rtDirtyStart = -1;
m_rtDirtyStop = -1;
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::Remove()
{
// if this thing isn't in the tree already, don't do anything
//
IAMTimelineObj * pParent = 0;
XGetParentNoRef( &pParent );
if( !pParent )
{
return NOERROR;
}
return XRemoveOnlyMe( );
}
STDMETHODIMP CAMTimelineObj::RemoveAll()
{
// if this thing isn't in the tree already, don't do anything
//
IAMTimelineObj * pParent = 0;
XGetParentNoRef( &pParent );
if( !pParent )
{
return NOERROR;
}
return XRemove( );
}
//############################################################################
// complicated function. Must copy everything, including the sub-object,
//############################################################################
HRESULT CAMTimelineObj::CopyDataTo( IAMTimelineObj * pSrc, REFERENCE_TIME TimelineTime )
{
HRESULT hr = 0;
// these functions cannot fail
//
pSrc->SetStartStop( m_rtStart, m_rtStop );
pSrc->SetTimelineType( m_TimelineType );
pSrc->SetUserID( m_UserID );
pSrc->SetSubObjectGUID( m_SubObjectGuid );
pSrc->SetMuted( m_bMuted );
pSrc->SetLocked( m_bLocked );
pSrc->SetDirtyRange( m_rtStart, m_rtStop );
// these functions can bomb on allocating memory
//
hr = pSrc->SetUserData( m_pUserData, m_nUserDataSize );
if( FAILED( hr ) )
{
return hr;
}
BSTR bName = SysAllocString (m_UserName);
if (bName)
{
hr = pSrc->SetUserName( bName);
SysFreeString(bName);
}
else
{
hr = E_OUTOFMEMORY;
}
if( FAILED( hr ) )
{
return hr;
}
// if we have any properties in the property setter, the new object
// needs them too.
//
if( !m_pSetter )
{
hr = pSrc->SetPropertySetter( NULL );
}
else
{
// clone our property setter and give it to the new
// !!! these times are wrong.
CComPtr< IPropertySetter > pNewSetter;
hr = m_pSetter->CloneProps( &pNewSetter, TimelineTime - m_rtStart, m_rtStop - m_rtStart );
ASSERT( !FAILED( hr ) );
if( FAILED( hr ) )
{
return hr;
}
hr = pSrc->SetPropertySetter( pNewSetter );
}
if( FAILED( hr ) )
{
return hr;
}
if( m_pSubObject )
{
// how to create a copy of a COM object
//
CComPtr< IStream > pMemStream;
CreateStreamOnHGlobal( NULL, TRUE, &pMemStream );
if( !pMemStream )
{
return E_OUTOFMEMORY;
}
CComQIPtr< IPersistStream, &IID_IPersistStream > pPersistStream( m_pSubObject );
if( pPersistStream )
{
CComPtr< IUnknown > pNewSubObject;
hr = pPersistStream->Save( pMemStream, TRUE );
ASSERT( !FAILED( hr ) );
if( FAILED( hr ) )
{
return hr;
}
hr = pMemStream->Commit( 0 );
if( FAILED( hr ) )
{
return hr;
}
LARGE_INTEGER li;
li.QuadPart = 0;
hr = pMemStream->Seek( li, STREAM_SEEK_SET, NULL );
if( FAILED( hr ) )
{
return hr;
}
OleLoadFromStream( pMemStream, IID_IUnknown, (void**) &pNewSubObject );
if( !pNewSubObject )
{
return E_OUTOFMEMORY;
}
hr = pSrc->SetSubObject( pNewSubObject );
}
}
return hr;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetTimelineNoRef( IAMTimeline ** ppResult )
{
HRESULT hr = 0;
CheckPointer( ppResult, E_POINTER );
*ppResult = NULL;
CComPtr< IAMTimelineGroup > pGroup;
hr = GetGroupIBelongTo( &pGroup );
if( FAILED( hr ) )
{
return hr;
}
hr = pGroup->GetTimeline( ppResult );
// don't hold a reference to it
//
if( *ppResult )
{
(*ppResult)->Release( );
}
return hr;
}
//############################################################################
// try to find the subobject's GUID, only called by SetSubObject.
//############################################################################
GUID CAMTimelineObj::_GetObjectGuid( IUnknown * pObject )
{
GUID guid;
HRESULT hr = 0;
// ask IPersist for it
CComQIPtr< IPersist, &IID_IPersist > pPersist( pObject );
if( pPersist )
{
hr = pPersist->GetClassID( &guid );
return guid;
}
// ask IPersistStorage for it
CComQIPtr< IPersistStorage, &IID_IPersistStorage > pPersistStorage( pObject );
if( pPersistStorage )
{
hr = pPersistStorage->GetClassID( &guid );
return guid;
}
// oh darn, ask IPersistPropertyBag?
//
CComQIPtr< IPersistPropertyBag, &IID_IPersistPropertyBag > pPersistPropBag( pObject );
if( pPersistPropBag )
{
hr = pPersistPropBag->GetClassID( &guid );
return guid;
}
// DARN!
//
return GUID_NULL;
}
//############################################################################
//
//############################################################################
HRESULT CAMTimelineObj::GetGenID( long * pVal )
{
CheckPointer( pVal, E_POINTER );
*pVal = m_nGenID;
return NOERROR;
}
//############################################################################
// fix up the times to align on our group's frame rate
//############################################################################
STDMETHODIMP CAMTimelineObj::FixTimes2( REFTIME * pStart, REFTIME * pStop )
{
REFERENCE_TIME p1 = 0;
if( pStart )
{
p1 = DoubleToRT( *pStart );
}
REFERENCE_TIME p2 = 0;
if( pStop )
{
p2 = DoubleToRT( *pStop );
}
HRESULT hr = FixTimes( &p1, &p2 );
if( pStart )
{
*pStart = RTtoDouble( p1 );
}
if( pStop )
{
*pStop = RTtoDouble( p2 );
}
return hr;
}
//############################################################################
// These parameters are IN/OUT. It fixes up what was passed in.
//############################################################################
STDMETHODIMP CAMTimelineObj::FixTimes
( REFERENCE_TIME * pStart, REFERENCE_TIME * pStop )
{
REFERENCE_TIME Start = 0;
REFERENCE_TIME Stop = 0;
if( pStart )
{
Start = *pStart;
}
if( pStop )
{
Stop = *pStop;
}
CComPtr< IAMTimelineGroup > pGroup;
HRESULT hr = 0;
hr = GetGroupIBelongTo( &pGroup );
if( !pGroup )
{
return E_NOTINTREE;
}
double FPS = TIMELINE_DEFAULT_FPS;
pGroup->GetOutputFPS( &FPS );
LONGLONG f = Time2Frame( Start, FPS );
REFERENCE_TIME NewStart = Frame2Time( f, FPS );
f = Time2Frame( Stop, FPS );
REFERENCE_TIME NewStop = Frame2Time( f, FPS );
if( pStart )
{
*pStart = NewStart;
}
if( pStop )
{
*pStop = NewStop;
}
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetGroupIBelongTo( IAMTimelineGroup ** ppGroup )
{
CheckPointer( ppGroup, E_POINTER );
*ppGroup = NULL;
HRESULT hr = 0;
// since we never use bumping of refcounts in here, don't use a CComPtr
//
IAMTimelineObj * p = this; // okay not CComPtr
long HaveParent;
while( 1 )
{
CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pNode( p );
HaveParent = 0;
hr = pNode->XHaveParent( &HaveParent );
if( HaveParent == 0 )
{
break;
}
pNode->XGetParentNoRef( &p );
}
CComQIPtr< IAMTimelineGroup, &IID_IAMTimelineGroup > pGroup( p );
if( !pGroup )
{
return E_NOINTERFACE;
}
*ppGroup = pGroup;
(*ppGroup)->AddRef( );
return NOERROR;
}
//############################################################################
//
//############################################################################
STDMETHODIMP CAMTimelineObj::GetEmbedDepth( long * pVal )
{
CheckPointer( pVal, E_POINTER );
*pVal = 0;
HRESULT hr = 0;
// since we never use bumping of refcounts in here, don't use a CComPtr
//
IAMTimelineObj * p = this; // okay not CComPtr
long HaveParent;
while( 1 )
{
CComQIPtr< IAMTimelineNode, &IID_IAMTimelineNode > pNode( p );
HaveParent = 0;
hr = pNode->XHaveParent( &HaveParent );
if( HaveParent == 0 )
{
break;
}
(*pVal)++;
pNode->XGetParentNoRef( &p );
}
return NOERROR;
}
//############################################################################
//
//############################################################################
void CAMTimelineObj::_BumpGenID( )
{
// bump by a # to account for things who want to fiddle with secret
// things in the graph cache. Don't change this.
m_nStaticGenID = m_nStaticGenID + 10;
m_nGenID = m_nStaticGenID;
}
| 25.673077 | 99 | 0.442911 | npocmaka |
49c295ebfb66665055fce5546a6c9de1b1185948 | 9,696 | hpp | C++ | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | 2 | 2017-01-13T09:20:58.000Z | 2019-06-28T15:27:13.000Z | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | null | null | null | include/tao/algorithm/selection/min_max_element.hpp | tao-cpp/algorithm | 156655aed1c522a3386cb82fb4aa2b3a302ee7e8 | [
"MIT"
] | 2 | 2017-05-31T12:05:26.000Z | 2019-10-13T22:36:32.000Z | //! \file tao/algorithm/selection/min_max_element.hpp
// Tao.Algorithm
//
// Copyright (c) 2016-2021 Fernando Pelliccioni.
//
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_
#define TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_
#include <algorithm>
#include <iterator>
#include <utility>
#include <tao/algorithm/concepts.hpp>
#include <tao/algorithm/integers.hpp>
#include <tao/algorithm/type_attributes.hpp>
namespace tao { namespace algorithm {
// --------------------------------------------
template <ForwardIterator I>
using min_max_ret_elem = std::pair<I, DistanceType<I>>;
template <ForwardIterator I>
using min_max_ret = std::pair<min_max_ret_elem<I>, min_max_ret_elem<I>>;
template <ForwardIterator I>
ValueType<I> const& operator*(min_max_ret_elem<I> const& p) {
return *p.first;
}
template <StrictWeakOrdering R>
struct min_max {
R r;
template <Regular T>
requires(Domain<R, T>)
T const& min(T const& x, T const& y) const {
if (r(y, x)) return y;
return x;
}
template <Regular T>
requires(Domain<R, T>)
T const& max(T const& x, T const& y) const {
if (r(y, x)) return x;
return y;
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> construct(T const& x, T const& y) const {
if (r(y, x)) return {y, x};
return {x, y};
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> combine(std::pair<T, T> const& x, pair<T, T> const& y) const {
return { min(x.first, y.first), max(x.second, y.second) };
}
template <Regular T>
requires(Domain<R, T>)
std::pair<T, T> combine(std::pair<T, T> const& x, T const& val) const {
if (r(val, x.first)) return {val, x.second};
if (r(val, x.second)) return x;
return {x.first, val};
}
};
template <StrictWeakOrdering R>
struct compare_dereference {
R r;
template <Iterator I>
requires(Readable<I> && Domain<R, ValueType<I>>)
bool operator()(I const& x, I const& y) const {
return r(*x, *y);
}
};
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element_even_length(I f, I l, R r) {
// precondition: distance(f, l) % 2 == 0 &&
// readable_bounded_range(f, l)
// postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
if (f == l) return {l, l};
I prev = f;
min_max<compare_dereference<R>> op{r};
auto result = op.construct(prev, ++f);
while (++f != l) {
prev = f;
result = op.combine(result, op.construct(prev, ++f));
}
return result;
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<I, I> min_max_element_n_basis(I f, DistanceType<I> n, R r) {
//precondition: readable_counted_range(f, n)
//postcondition: result.first == stable_sort_copy_n(f, n, r)[0] &&
// result.second == stable_sort_copy_n(f, n, r)[n - 1]
if (zero(n)) return {f, f};
if (one(n)) return {f, f};
auto m = 2 * half(n);
min_max<compare_dereference<R>> op{r};
I prev = f;
++f;
auto result = op.construct(prev, f);
++f;
DistanceType<I> i = 2;
while (i != m) {
prev = f;
++i; ++f;
result = op.combine(result, op.construct(prev, f));
++i; ++f;
}
if (i != n) {
// return op.combine(result, {f, f});
return op.combine(result, f);
}
return result;
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element(I f, I l, R r, std::forward_iterator_tag) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
I prev = f;
if (f == l || ++f == l) return {prev, prev};
min_max<compare_dereference<R>> op{r};
auto result = op.construct(prev, f);
while (++f != l) {
prev = f;
// if (++f == l) return op.combine(result, {prev, prev});
if (++f == l) return op.combine(result, prev);
result = op.combine(result, op.construct(prev, f));
}
return result;
}
template <RandomAccessIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
std::pair<I, I> min_max_element(I f, I l, R r, std::random_access_iterator_tag) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
auto n = std::distance(f, l);
return min_max_element_n_basis(f, n, r);
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
inline
auto min_max_element(I f, I l, R r) {
//precondition: readable_bounded_range(f, l)
//postcondition: result.first == stable_sort_copy(f, l, r)[0] &&
// result.second == stable_sort_copy(f, l, r)[distance(f, l) - 1]
return min_max_element(f, l, r, IteratorCategory<I>{});
}
template <ForwardIterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
min_max_ret<I> min_max_element_n(I f, DistanceType<I> n, R r) {
//precondition: readable_counted_range(f, n)
//postcondition: result.first == stable_sort_copy_n(f, n, r)[0] &&
// result.second == stable_sort_copy_n(f, n, r)[n - 1]
if (zero(n)) return {{f, n}, {f, n}};
if (one(n)) return {{f, n}, {f, n}};
min_max<compare_dereference<R>> op{r};
min_max_ret_elem<I> prev{f, n}; //I prev = f;
++f;
auto result = op.construct(prev, min_max_ret_elem<I>{f, n - 1});
++f;
DistanceType<I> i = 2;
auto m = 2 * half(n);
while (i != m) {
prev = min_max_ret_elem<I>{f, n - i};
++i; ++f;
result = op.combine(result, op.construct(prev, min_max_ret_elem<I>{f, n - i}));
++i; ++f;
}
if (i != n) {
// return op.combine(result, {min_max_ret_elem<I>{f, n - i}, min_max_ret_elem<I>{f, n - i}});
return op.combine(result, min_max_ret_elem<I>{f, n - i});
}
return result;
}
template <Iterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<ValueType<I>, ValueType<I>> min_max_value_nonempty(I f, I l, R r) {
using T = ValueType<I>;
min_max<R> op{r};
T val = std::move(*f);
if (++f == l) return {val, val};
auto result = op.construct(val, *f);
while (++f != l) {
val = std::move(*f);
// if (++f == l) return op.combine(result, {val, val});
if (++f == l) return op.combine(result, val);
result = op.combine(result, op.construct(val, *f));
}
return result;
}
template <Iterator I, StrictWeakOrdering R>
requires(Readable<I> && Domain<R, ValueType<I>>)
pair<ValueType<I>, ValueType<I>> min_max_value(I f, I l, R r) {
using T = ValueType<I>;
// if (f == l) return {supremum(r), infimum(r)};
if (f == l) return {supremum<T>, infimum<T>};
return min_max_value_nonempty(f, l, r);
}
// TODO(fernando): create min_max_value_n
// TODO(fernando): create min_max_value even vesion
}} /*tao::algorithm*/
#include <tao/algorithm/concepts_undef.hpp>
#endif /*TAO_ALGORITHM_SELECTION_MIN_MAX_ELEMENT_HPP_*/
#ifdef DOCTEST_LIBRARY_INCLUDED
#include <tao/benchmark/instrumented.hpp>
using namespace tao::algorithm;
using namespace std;
TEST_CASE("[min_max_element] testing min_max_element selection algorithm, instrumented, random access") {
using T = instrumented<int>;
vector<T> a = {3, 6, 2, 1, 4, 5, 1, 6, 2, 3}; //do it with random number of elements...
instrumented<int>::initialize(0);
auto p = tao::algorithm::min_max_element(begin(a), end(a), less<>());
double* count_p = instrumented<int>::counts;
// ceil(3/2 * 2) - 2
CHECK(count_p[instrumented_base::comparison] <= (3 * a.size()) / 2 - 2);
// for (size_t i = 0; i < instrumented_base::number_ops; ++i) {
// std::cout << instrumented_base::counter_names[i] << ": "
// << count_p[i]
// << std::endl;
// }
// CHECK(1 == 0);
}
TEST_CASE("[min_max_element] testing min_max_element selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_element(begin(a), end(a), std::less<>());
CHECK(p.first == next(begin(a), 3));
CHECK(p.second == next(begin(a), 6));
}
TEST_CASE("[min_max_element] testing min_max_element_n selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_element_n(begin(a), a.size(), std::less<>());
CHECK(p.first.first == next(begin(a), 3));
CHECK(p.second.first == next(begin(a), 6));
CHECK(p.first.second == a.size() - 3);
CHECK(p.second.second == a.size() - 6);
}
TEST_CASE("[min_max_element] testing min_max_value selection algorithm, random access") {
using T = int;
vector<T> a = {3, 6, 2, 1, 4, 5, 6, 2, 3};
auto p = tao::algorithm::min_max_value(begin(a), end(a), std::less<>());
CHECK(p.first == *next(begin(a), 3));
CHECK(p.second == *next(begin(a), 6));
}
#endif /*DOCTEST_LIBRARY_INCLUDED*/
| 31.076923 | 105 | 0.60066 | tao-cpp |
49c3f1b17fe1f3975a0f1b60e8cd4b01fe5a00f1 | 10,582 | cpp | C++ | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | depends/work/build/i686-w64-mingw32/qt/5.9.7-f2560c1efa6/qtbase/tests/auto/network/access/qnetworkcachemetadata/tst_qnetworkcachemetadata.cpp | GrinCash/Grinc-core | 1377979453ba84082f70f9c128be38e57b65a909 | [
"MIT"
] | null | null | null | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtTest/QtTest>
#include <qabstractnetworkcache.h>
#define EXAMPLE_URL "http://user:pass@www.example.com/#foo"
class tst_QNetworkCacheMetaData : public QObject
{
Q_OBJECT
private slots:
void qnetworkcachemetadata_data();
void qnetworkcachemetadata();
void expirationDate_data();
void expirationDate();
void isValid_data();
void isValid();
void lastModified_data();
void lastModified();
void operatorEqual_data();
void operatorEqual();
void operatorEqualEqual_data();
void operatorEqualEqual();
void rawHeaders_data();
void rawHeaders();
void saveToDisk_data();
void saveToDisk();
void url_data();
void url();
void stream();
};
// Subclass that exposes the protected functions.
class SubQNetworkCacheMetaData : public QNetworkCacheMetaData
{
public:};
void tst_QNetworkCacheMetaData::qnetworkcachemetadata_data()
{
}
void tst_QNetworkCacheMetaData::qnetworkcachemetadata()
{
QNetworkCacheMetaData data;
QCOMPARE(data.expirationDate(), QDateTime());
QCOMPARE(data.isValid(), false);
QCOMPARE(data.lastModified(), QDateTime());
QCOMPARE(data.operator!=(QNetworkCacheMetaData()), false);
QNetworkCacheMetaData metaData;
QCOMPARE(data.operator=(metaData), QNetworkCacheMetaData());
QCOMPARE(data.operator==(QNetworkCacheMetaData()), true);
QCOMPARE(data.rawHeaders(), QNetworkCacheMetaData::RawHeaderList());
QCOMPARE(data.saveToDisk(), true);
QCOMPARE(data.url(), QUrl());
data.setExpirationDate(QDateTime());
data.setLastModified(QDateTime());
data.setRawHeaders(QNetworkCacheMetaData::RawHeaderList());
data.setSaveToDisk(false);
data.setUrl(QUrl());
}
void tst_QNetworkCacheMetaData::expirationDate_data()
{
QTest::addColumn<QDateTime>("expirationDate");
QTest::newRow("null") << QDateTime();
QTest::newRow("now") << QDateTime::currentDateTime();
}
// public QDateTime expirationDate() const
void tst_QNetworkCacheMetaData::expirationDate()
{
QFETCH(QDateTime, expirationDate);
SubQNetworkCacheMetaData data;
data.setExpirationDate(expirationDate);
QCOMPARE(data.expirationDate(), expirationDate);
}
Q_DECLARE_METATYPE(QNetworkCacheMetaData)
void tst_QNetworkCacheMetaData::isValid_data()
{
QTest::addColumn<QNetworkCacheMetaData>("data");
QTest::addColumn<bool>("isValid");
QNetworkCacheMetaData metaData;
QTest::newRow("null") << metaData << false;
QNetworkCacheMetaData data1;
data1.setUrl(QUrl(EXAMPLE_URL));
QTest::newRow("valid-1") << data1 << true;
QNetworkCacheMetaData data2;
QNetworkCacheMetaData::RawHeaderList headers;
headers.append(QNetworkCacheMetaData::RawHeader("foo", "Bar"));
data2.setRawHeaders(headers);
QTest::newRow("valid-2") << data2 << true;
QNetworkCacheMetaData data3;
data3.setLastModified(QDateTime::currentDateTime());
QTest::newRow("valid-3") << data3 << true;
QNetworkCacheMetaData data4;
data4.setExpirationDate(QDateTime::currentDateTime());
QTest::newRow("valid-4") << data4 << true;
QNetworkCacheMetaData data5;
data5.setSaveToDisk(false);
QTest::newRow("valid-5") << data5 << true;
}
// public bool isValid() const
void tst_QNetworkCacheMetaData::isValid()
{
QFETCH(QNetworkCacheMetaData, data);
QFETCH(bool, isValid);
QCOMPARE(data.isValid(), isValid);
}
void tst_QNetworkCacheMetaData::lastModified_data()
{
QTest::addColumn<QDateTime>("lastModified");
QTest::newRow("null") << QDateTime();
QTest::newRow("now") << QDateTime::currentDateTime();
}
// public QDateTime lastModified() const
void tst_QNetworkCacheMetaData::lastModified()
{
QFETCH(QDateTime, lastModified);
SubQNetworkCacheMetaData data;
data.setLastModified(lastModified);
QCOMPARE(data.lastModified(), lastModified);
}
void tst_QNetworkCacheMetaData::operatorEqual_data()
{
QTest::addColumn<QNetworkCacheMetaData>("other");
QTest::newRow("null") << QNetworkCacheMetaData();
QNetworkCacheMetaData data;
data.setUrl(QUrl(EXAMPLE_URL));
QNetworkCacheMetaData::RawHeaderList headers;
headers.append(QNetworkCacheMetaData::RawHeader("foo", "Bar"));
data.setRawHeaders(headers);
data.setLastModified(QDateTime::currentDateTime());
data.setExpirationDate(QDateTime::currentDateTime());
data.setSaveToDisk(false);
QTest::newRow("valid") << data;
}
// public QNetworkCacheMetaData& operator=(QNetworkCacheMetaData const& other)
void tst_QNetworkCacheMetaData::operatorEqual()
{
QFETCH(QNetworkCacheMetaData, other);
QNetworkCacheMetaData data = other;
QCOMPARE(data, other);
}
void tst_QNetworkCacheMetaData::operatorEqualEqual_data()
{
QTest::addColumn<QNetworkCacheMetaData>("a");
QTest::addColumn<QNetworkCacheMetaData>("b");
QTest::addColumn<bool>("operatorEqualEqual");
QTest::newRow("null") << QNetworkCacheMetaData() << QNetworkCacheMetaData() << true;
QNetworkCacheMetaData data1;
data1.setUrl(QUrl(EXAMPLE_URL));
QTest::newRow("valid-1-1") << data1 << QNetworkCacheMetaData() << false;
QTest::newRow("valid-1-2") << data1 << data1 << true;
QNetworkCacheMetaData data2;
QNetworkCacheMetaData::RawHeaderList headers;
headers.append(QNetworkCacheMetaData::RawHeader("foo", "Bar"));
data2.setRawHeaders(headers);
QTest::newRow("valid-2-1") << data2 << QNetworkCacheMetaData() << false;
QTest::newRow("valid-2-2") << data2 << data2 << true;
QTest::newRow("valid-2-3") << data2 << data1 << false;
QNetworkCacheMetaData data3;
data3.setLastModified(QDateTime::currentDateTime());
QTest::newRow("valid-3-1") << data3 << QNetworkCacheMetaData() << false;
QTest::newRow("valid-3-2") << data3 << data3 << true;
QTest::newRow("valid-3-3") << data3 << data1 << false;
QTest::newRow("valid-3-4") << data3 << data2 << false;
QNetworkCacheMetaData data4;
data4.setExpirationDate(QDateTime::currentDateTime());
QTest::newRow("valid-4-1") << data4 << QNetworkCacheMetaData() << false;
QTest::newRow("valid-4-2") << data4 << data4 << true;
QTest::newRow("valid-4-3") << data4 << data1 << false;
QTest::newRow("valid-4-4") << data4 << data2 << false;
QTest::newRow("valid-4-5") << data4 << data3 << false;
QNetworkCacheMetaData data5;
data5.setSaveToDisk(false);
QTest::newRow("valid-5-1") << data5 << QNetworkCacheMetaData() << false;
QTest::newRow("valid-5-2") << data5 << data5 << true;
QTest::newRow("valid-5-3") << data5 << data1 << false;
QTest::newRow("valid-5-4") << data5 << data2 << false;
QTest::newRow("valid-5-5") << data5 << data3 << false;
QTest::newRow("valid-5-6") << data5 << data4 << false;
}
// public bool operator==(QNetworkCacheMetaData const& other) const
void tst_QNetworkCacheMetaData::operatorEqualEqual()
{
QFETCH(QNetworkCacheMetaData, a);
QFETCH(QNetworkCacheMetaData, b);
QFETCH(bool, operatorEqualEqual);
QCOMPARE(a == b, operatorEqualEqual);
}
Q_DECLARE_METATYPE(QNetworkCacheMetaData::RawHeaderList)
void tst_QNetworkCacheMetaData::rawHeaders_data()
{
QTest::addColumn<QNetworkCacheMetaData::RawHeaderList>("rawHeaders");
QTest::newRow("null") << QNetworkCacheMetaData::RawHeaderList();
QNetworkCacheMetaData::RawHeaderList headers;
headers.append(QNetworkCacheMetaData::RawHeader("foo", "Bar"));
QTest::newRow("valie") << headers;
}
// public QNetworkCacheMetaData::RawHeaderList rawHeaders() const
void tst_QNetworkCacheMetaData::rawHeaders()
{
QFETCH(QNetworkCacheMetaData::RawHeaderList, rawHeaders);
SubQNetworkCacheMetaData data;
data.setRawHeaders(rawHeaders);
QCOMPARE(data.rawHeaders(), rawHeaders);
}
void tst_QNetworkCacheMetaData::saveToDisk_data()
{
QTest::addColumn<bool>("saveToDisk");
QTest::newRow("false") << false;
QTest::newRow("true") << true;
}
// public bool saveToDisk() const
void tst_QNetworkCacheMetaData::saveToDisk()
{
QFETCH(bool, saveToDisk);
SubQNetworkCacheMetaData data;
data.setSaveToDisk(saveToDisk);
QCOMPARE(data.saveToDisk(), saveToDisk);
}
void tst_QNetworkCacheMetaData::url_data()
{
QTest::addColumn<QUrl>("url");
QTest::addColumn<QUrl>("expected");
QTest::newRow("null") << QUrl() << QUrl();
QTest::newRow("valid") << QUrl(EXAMPLE_URL) << QUrl("http://user@www.example.com/");
}
// public QUrl url() const
void tst_QNetworkCacheMetaData::url()
{
QFETCH(QUrl, url);
QFETCH(QUrl, expected);
SubQNetworkCacheMetaData data;
data.setUrl(url);
QCOMPARE(data.url(), expected);
}
void tst_QNetworkCacheMetaData::stream()
{
QNetworkCacheMetaData data;
data.setUrl(QUrl(EXAMPLE_URL));
QNetworkCacheMetaData::RawHeaderList headers;
headers.append(QNetworkCacheMetaData::RawHeader("foo", "Bar"));
data.setRawHeaders(headers);
data.setLastModified(QDateTime::currentDateTime());
data.setExpirationDate(QDateTime::currentDateTime());
data.setSaveToDisk(false);
QBuffer buffer;
buffer.open(QIODevice::ReadWrite);
QDataStream stream(&buffer);
stream << data;
buffer.seek(0);
QNetworkCacheMetaData data2;
stream >> data2;
QCOMPARE(data2, data);
}
QTEST_MAIN(tst_QNetworkCacheMetaData)
#include "tst_qnetworkcachemetadata.moc"
| 31.777778 | 88 | 0.702797 | GrinCash |
49c46305a00bba9ecb9ecd673e6d0cdb50a7ab77 | 5,680 | cpp | C++ | webkit/port/platform/chromium/DragDataChromium.cpp | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | 1 | 2016-05-08T15:35:17.000Z | 2016-05-08T15:35:17.000Z | webkit/port/platform/chromium/DragDataChromium.cpp | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | webkit/port/platform/chromium/DragDataChromium.cpp | bluebellzhy/chromium | 008c4fef2676506869a0404239da31e83fd6ccc7 | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. 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.
*/
// Modified from Apple's version to not directly call any windows methods as
// they may not be available to us in the multiprocess
#include "config.h"
#include "DragData.h"
#if PLATFORM(WIN_OS)
#include "ClipboardWin.h"
#include "ClipboardUtilitiesWin.h"
#include "WCDataObject.h"
#else
#include "Clipboard.h" // This and ClipboardWin.h should be ClipboardChromium.h
#endif
#include "DocumentFragment.h"
#include "KURL.h"
#include "PlatformString.h"
#include "markup.h"
#undef LOG
#include "base/file_util.h"
#include "base/string_util.h"
#include "net/base/base64.h"
#include "webkit/glue/glue_util.h"
#include "webkit/glue/webdropdata.h"
#include "webkit/glue/webkit_glue.h"
namespace {
bool containsHTML(const WebDropData& drop_data) {
std::wstring html;
return drop_data.cf_html.length() > 0
|| drop_data.text_html.length() > 0;
}
}
namespace WebCore {
PassRefPtr<Clipboard> DragData::createClipboard(ClipboardAccessPolicy policy) const
{
// TODO(darin): Invent ClipboardChromium and use that instead.
#if PLATFORM(WIN_OS)
WCDataObject* data;
WCDataObject::createInstance(&data);
RefPtr<ClipboardWin> clipboard = ClipboardWin::create(true, data, policy);
// The clipboard keeps a reference to the WCDataObject, so we can release
// our reference to it.
data->Release();
return clipboard.release();
#else
return PassRefPtr<Clipboard>(0);
#endif
}
bool DragData::containsURL() const
{
return m_platformDragData->url.is_valid();
}
String DragData::asURL(String* title) const
{
if (!m_platformDragData->url.is_valid())
return String();
// |title| can be NULL
if (title)
*title = webkit_glue::StdWStringToString(m_platformDragData->url_title);
return webkit_glue::StdStringToString(m_platformDragData->url.spec());
}
bool DragData::containsFiles() const
{
return !m_platformDragData->filenames.empty();
}
void DragData::asFilenames(Vector<String>& result) const
{
for (size_t i = 0; i < m_platformDragData->filenames.size(); ++i)
result.append(webkit_glue::StdWStringToString(m_platformDragData->filenames[i]));
}
bool DragData::containsPlainText() const
{
return !m_platformDragData->plain_text.empty();
}
String DragData::asPlainText() const
{
return webkit_glue::StdWStringToString(
m_platformDragData->plain_text);
}
bool DragData::containsColor() const
{
return false;
}
bool DragData::canSmartReplace() const
{
// Mimic the situations in which mac allows drag&drop to do a smart replace.
// This is allowed whenever the drag data contains a 'range' (ie.,
// ClipboardWin::writeRange is called). For example, dragging a link
// should not result in a space being added.
return !m_platformDragData->cf_html.empty() &&
!m_platformDragData->plain_text.empty() &&
!m_platformDragData->url.is_valid();
}
bool DragData::containsCompatibleContent() const
{
return containsPlainText() || containsURL()
|| ::containsHTML(*m_platformDragData)
|| containsColor();
}
PassRefPtr<DocumentFragment> DragData::asFragment(Document* doc) const
{
/*
* Order is richest format first. On OSX this is:
* * Web Archive
* * Filenames
* * HTML
* * RTF
* * TIFF
* * PICT
*/
// TODO(tc): Disabled because containsFilenames is hardcoded to return
// false. We need to implement fragmentFromFilenames when this is
// re-enabled in Apple's win port.
//if (containsFilenames())
// if (PassRefPtr<DocumentFragment> fragment = fragmentFromFilenames(doc, m_platformDragData))
// return fragment;
#if PLATFORM(WIN_OS)
// fragmentFromCF_HTML comes from ClipboardUtilitiesWin.
if (!m_platformDragData->cf_html.empty()) {
RefPtr<DocumentFragment> fragment = fragmentFromCF_HTML(doc,
webkit_glue::StdWStringToString(m_platformDragData->cf_html));
return fragment;
}
#endif
if (!m_platformDragData->text_html.empty()) {
String url;
RefPtr<DocumentFragment> fragment = createFragmentFromMarkup(doc,
webkit_glue::StdWStringToString(m_platformDragData->text_html), url);
return fragment;
}
return 0;
}
Color DragData::asColor() const
{
return Color();
}
}
| 30.374332 | 102 | 0.71162 | bluebellzhy |
49c47e8ccc1f031844436950f924c1d2ac308f50 | 3,550 | cpp | C++ | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | src/executors/groupby.cpp | dhruvarya/simple-ra | 2cb3930d5fe75a96c335a55d788d697016d282d4 | [
"MIT"
] | null | null | null | #include "global.h"
/**
* @brief
* SYNTAX: R <- GROUP BY <attr> FROM relation_name RETURN MIN|MAX|SUM|AVG(attr)
*/
bool syntacticParseGROUP()
{
logger.log("syntacticParseGROUP");
if (tokenizedQuery.size() != 9 || tokenizedQuery[3] != "BY" || tokenizedQuery[7] != "RETURN" || tokenizedQuery[5] != "FROM")
{
cout << "SYNTAX ERROR" << endl;
return false;
}
parsedQuery.queryType = GROUP;
parsedQuery.groupResultRelationName = tokenizedQuery[0];
parsedQuery.groupRelationName = tokenizedQuery[6];
parsedQuery.groupColumnName = tokenizedQuery[4];
parsedQuery.groupOperation = tokenizedQuery[8].substr(0, 3);
if (parsedQuery.groupOperation != "MAX" && parsedQuery.groupOperation != "AVG" && parsedQuery.groupOperation != "MIN" && parsedQuery.groupOperation != "SUM")
{
cout << "SYNTAX:ERROR" << endl;
return false;
}
string temp = tokenizedQuery[8];
temp = temp.substr(4, temp.length() - 5);
parsedQuery.groupOperationColumn = temp;
return true;
}
bool semanticParseGROUP()
{
logger.log("semanticParseGROUP");
if (tableCatalogue.isTable(parsedQuery.groupResultRelationName))
{
cout << "SEMANTIC ERROR: Resultant relation already exists" << endl;
return false;
}
if (!tableCatalogue.isTable(parsedQuery.groupRelationName))
{
cout << "SEMANTIC ERROR: Relation doesn't exist" << endl;
return false;
}
Table table = *tableCatalogue.getTable(parsedQuery.groupRelationName);
if (!table.isColumn(parsedQuery.groupColumnName))
{
cout << "SEMANTIC ERROR: Column doesn't exist in relation";
return false;
}
if (!table.isColumn(parsedQuery.groupOperationColumn))
{
cout << "SEMANTIC ERROR: Column doesn't exist in relation";
return false;
}
return true;
}
void executeGROUP()
{
logger.log("executeGROUP");
vector<string> columns = {parsedQuery.groupColumnName, parsedQuery.groupOperation + parsedQuery.groupOperationColumn};
Table *resultantTable = new Table(parsedQuery.groupResultRelationName, columns);
Table table = *tableCatalogue.getTable(parsedQuery.groupRelationName);
table.sortTable(parsedQuery.groupColumnName, 0, 10);
Cursor cursor = table.getCursor();
int groupColumnIndex = table.getColumnIndex(parsedQuery.groupColumnName);
int groupOperationIndex = table.getColumnIndex(parsedQuery.groupOperationColumn);
vector<int> row = cursor.getNext();
vector<int> res(2);
int min_val = INT_MAX, max_val = INT_MIN, cnt = 0, sum = 0;
int cur_val = -1;
while (!row.empty())
{
if(cur_val != -1 && cur_val != row[groupColumnIndex]) {
res[0] = cur_val;
if(parsedQuery.groupOperation == "MAX") {
res[1] = max_val;
} else if(parsedQuery.groupOperation == "MIN") {
res[1] = min_val;
} else if(parsedQuery.groupOperation == "SUM") {
res[1] = sum;
} else {
res[1] = sum/cnt;
}
resultantTable->writeRow(res);
min_val = INT_MAX, max_val = INT_MIN, cnt = 0, sum = 0;
}
cur_val = row[groupColumnIndex];
max_val = max(max_val, row[groupOperationIndex]);
min_val = min(min_val, row[groupOperationIndex]);
sum += row[groupOperationIndex];
cnt++;
row = cursor.getNext();
}
resultantTable->blockify();
tableCatalogue.insertTable(resultantTable);
return;
} | 34.803922 | 161 | 0.63493 | dhruvarya |
49c4c1d39143ea3b3aea9024c7036f3e08ee1f53 | 4,289 | cpp | C++ | UVa 10511 - Councilling/sample/10511 - Councilling.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2020-11-24T03:17:21.000Z | 2020-11-24T03:17:21.000Z | UVa 10511 - Councilling/sample/10511 - Councilling.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | null | null | null | UVa 10511 - Councilling/sample/10511 - Councilling.cpp | tadvi/uva | 0ac0cbdf593879b4fb02a3efc09adbb031cb47d5 | [
"MIT"
] | 1 | 2021-04-11T16:22:31.000Z | 2021-04-11T16:22:31.000Z | #include <stdio.h>
#include <string.h>
#include <queue>
#include <map>
#include <iostream>
#include <sstream>
using namespace std;
struct Node {
int x, y, v;// x->y, v
int next;
} edge[500005];
int e, head[5000], dis[5000], prev[5000], record[5000];
void addEdge(int x, int y, int v) {
edge[e].x = x, edge[e].y = y, edge[e].v = v;
edge[e].next = head[x], head[x] = e++;
edge[e].x = y, edge[e].y = x, edge[e].v = 0;
edge[e].next = head[y], head[y] = e++;
}
int maxflow(int s, int t) {
int flow = 0;
int i, j, x, y;
while(1) {
memset(dis, 0, sizeof(dis));
dis[s] = 0xffff; // oo
queue<int> Q;
Q.push(s);
while(!Q.empty()) {
x = Q.front();
Q.pop();
for(i = head[x]; i != -1; i = edge[i].next) {
y = edge[i].y;
if(dis[y] == 0 && edge[i].v > 0) {
prev[y] = x, record[y] = i;
dis[y] = min(dis[x], edge[i].v);
Q.push(y);
}
}
if(dis[t]) break;
}
if(dis[t] == 0) break;
flow += dis[t];
for(x = t; x != s; x = prev[x]) {
int ri = record[x];
edge[ri].v -= dis[t];
edge[ri^1].v += dis[t];
}
}
return flow;
}
char s[1005][100], buf[105];
string pstr[5000], cstr[5000], mstr[5000];
int main() {
int t;
scanf("%d", &t);
while(getchar() != '\n');
while(getchar() != '\n');
int i, j;
while(t--) {
int n = 0;
map<string, int> party, club, man;
int pz, cz, mz;
pz = 0, cz = 0, mz = 0;
while(gets(s[n]) && s[n][0]) {
int x = 0, idx = 0;
for(i = 0; s[n][i]; ) {
while(s[n][i] == ' ') i++;
idx = 0;
while(s[n][i] && s[n][i] != ' ')
buf[idx++] = s[n][i++];
buf[idx] = '\0';
if(x == 0) {
man[buf] = ++mz;
mstr[mz] = buf;
} else if(x == 1) {
if(party.find(buf) == party.end()) {
party[buf] = ++pz;
pstr[pz] = buf;
}
} else {
if(club.find(buf) == club.end()) {
club[buf] = ++cz;
cstr[cz] = buf;
}
}
x++;
}
n++;
}
//<maxflow>
e = 0;
memset(head, -1, sizeof(head));
//</maxflow>
int manN, clubN, partyN;
for(j = 0; j < n; j++) {
int x = 0, idx = 0;
for(i = 0; s[j][i]; ) {
while(s[j][i] == ' ') i++;
idx = 0;
while(s[j][i] && s[j][i] != ' ')
buf[idx++] = s[j][i++];
buf[idx] = '\0';
if(x == 0) {
manN = man[buf];
} else if(x == 1) {
partyN = party[buf];
addEdge(cz+manN, cz+mz+partyN, 1);
} else {
clubN = club[buf];
addEdge(clubN, cz+manN, 1);
}
x++;
}
}
for(i = 1; i <= club.size(); i++)
addEdge(0, i, 1);
int source = 0, sink = cz+mz+pz+1;
for(i = 1; i <= pz; i++)
addEdge(cz+mz+i, sink, (cz-1)/2);
int f = maxflow(source, sink);
if(f != cz) {
puts("Impossible.");
} else {
for(i = 1; i <= cz; i++) {
for(j = head[i]; j != -1; j = edge[j].next) {
if(edge[j].v == 0) {
printf("%s %s\n", mstr[edge[j].y-cz].c_str(), cstr[edge[j].x].c_str());
break;
}
}
}
}
if(t)
puts("");
}
return 0;
}
/*
source(0) - club - people - party - sink
2
fred dinosaur jets jetsons
john rhinocerous jets rockets
mary rhinocerous jetsons rockets
ruth platypus rockets
fred dinosaur jets jetsons
john rhinocerous jets rockets
mary rhinocerous jetsons rockets
ruth platypus rockets
*/
| 28.403974 | 95 | 0.358592 | tadvi |
49cc3d5ab65230e5f951f35388e76e4101d80aae | 5,121 | cpp | C++ | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 93 | 2015-01-11T03:10:17.000Z | 2022-01-27T15:53:35.000Z | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 6 | 2016-01-10T11:11:50.000Z | 2019-10-31T05:23:58.000Z | src/blocks/falling.cpp | BonemealPioneer/Mineserver | 0d0d9af02c3a76aab057798511683fed85e76463 | [
"BSD-3-Clause"
] | 35 | 2015-01-11T04:08:30.000Z | 2022-02-11T10:17:20.000Z | /*
Copyright (c) 2011, The Mineserver Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Mineserver Project 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 BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include "mineserver.h"
#include "map.h"
#include "plugin.h"
#include "logger.h"
#include "protocol.h"
#include "physics.h"
#include "falling.h"
bool BlockFalling::affectedBlock(int block) const
{
if (block == BLOCK_SAND || block == BLOCK_SLOW_SAND || block == BLOCK_GRAVEL)
return true;
return false;
}
std::string printfify(const char *fmt, ...)
{
if(fmt)
{
va_list args;
char buf[4096];
va_start(args, fmt);
vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
return buf;
}
else
return fmt;
}
void BlockFalling::onNeighbourBroken(User* user, int16_t, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
this->onNeighbourMove(user, 0, x, y, z, direction, map);
}
bool BlockFalling::onPlace(User* user, int16_t newblock, int32_t x, int16_t y, int32_t z, int map, int8_t direction)
{
uint8_t oldblock;
uint8_t oldmeta;
if (!ServerInstance->map(map)->getBlock(x, y, z, &oldblock, &oldmeta))
{
revertBlock(user, x, y, z, map);
return true;
}
/* Check block below allows blocks placed on top */
if (!this->isBlockStackable(oldblock))
{
revertBlock(user, x, y, z, map);
return true;
}
/* move the x,y,z coords dependent upon placement direction */
if (!this->translateDirection(&x, &y, &z, map, direction))
{
revertBlock(user, x, y, z, map);
return true;
}
if (this->isUserOnBlock(x, y, z, map))
{
revertBlock(user, x, y, z, map);
return true;
}
if (!this->isBlockEmpty(x, y, z, map))
{
revertBlock(user, x, y, z, map);
return true;
}
ServerInstance->map(map)->setBlock(x, y, z, (char)newblock, 0);
ServerInstance->map(map)->sendBlockChange(x, y, z, newblock, 0);
applyPhysics(user, x, y, z, map);
return false;
}
void BlockFalling::onNeighbourMove(User* user, int16_t, int32_t x, int16_t y, int32_t z, int8_t direction, int map)
{
uint8_t block;
uint8_t meta;
if(!ServerInstance->map(map)->getBlock(x, y, z, &block, &meta))
return;
if (affectedBlock(block))
{
applyPhysics(user, x, y, z, map);
}
}
void BlockFalling::applyPhysics(User* user, int32_t x, int16_t y, int32_t z, int map)
{
uint8_t fallblock, block;
uint8_t fallmeta, meta;
if (!ServerInstance->map(map)->getBlock(x, y, z, &fallblock, &fallmeta))
{
return;
}
if (ServerInstance->map(map)->getBlock(x, y - 1, z, &block, &meta))
{
switch (block)
{
case BLOCK_AIR:
case BLOCK_WATER:
case BLOCK_STATIONARY_WATER:
case BLOCK_LAVA:
case BLOCK_STATIONARY_LAVA:
case BLOCK_SNOW:
break;
default:
return;
break;
}
// Destroy original block
ServerInstance->map(map)->sendBlockChange(x, y, z, BLOCK_AIR, 0);
ServerInstance->map(map)->setBlock(x, y, z, BLOCK_AIR, 0);
y--;
//Spawn an entity for the falling block
const int chunk_x = blockToChunk(x);
const int chunk_z = blockToChunk(z);
const ChunkMap::const_iterator it = ServerInstance->map(map)->chunks.find(Coords(chunk_x, chunk_z));
if (it == ServerInstance->map(map)->chunks.end())
return;
uint32_t EID = Mineserver::generateEID();
uint8_t object = 70; //type == Falling object
Packet pkt = Protocol::spawnObject(EID,object, (x<<5)+16, ((y+1)<<5)+16, (z<<5)+16, fallblock|(fallmeta<<0x10));
it->second->sendPacket(pkt);
//Add to physics loop
ServerInstance->physics(map)->addFallSimulation(fallblock,vec(x, y, z), EID);
this->notifyNeighbours(x, y + 1, z, map, "onNeighbourMove", user, fallblock, BLOCK_BOTTOM);
}
}
| 28.608939 | 117 | 0.68717 | BonemealPioneer |
49ccef0babe7b01c7fd08cefd81424f3f13cd36f | 17,808 | cpp | C++ | src/demos/irrlicht/demo_IRR_decomposition.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | src/demos/irrlicht/demo_IRR_decomposition.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | src/demos/irrlicht/demo_IRR_decomposition.cpp | lucasw/chrono | e79d8c761c718ecb4c796725cff37026f357da8c | [
"BSD-3-Clause"
] | null | null | null | // =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All rights reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Alessandro Tasora
// =============================================================================
//
// A small interactive editor to test the convex decomposition settings.
//
// =============================================================================
#include <cstdlib>
#include "chrono/physics/ChSystemNSC.h"
#include "chrono/core/ChRealtimeStep.h"
#include "chrono/collision/ChConvexDecomposition.h"
#include "chrono_irrlicht/ChVisualSystemIrrlicht.h"
#include "chrono_irrlicht/ChIrrMeshTools.h"
#include <irrlicht.h>
// Use the namespaces of Chrono
using namespace chrono;
using namespace chrono::collision;
using namespace chrono::geometry;
using namespace chrono::irrlicht;
// Use the main namespace of Irrlicht
using namespace irr;
// to make things easier (it's a test..) introduce global variables.
scene::IAnimatedMesh* modelMesh;
scene::IAnimatedMeshSceneNode* modelNode;
scene::ISceneNode* decompositionNode;
ChConvexDecompositionHACDv2 mydecompositionHACDv2;
int hacd_maxhullcount;
int hacd_maxhullmerge;
int hacd_maxhullvertexes;
double hacd_concavity;
double hacd_smallclusterthreshold;
double hacd_fusetolerance;
// LOAD A TRIANGLE MESH USING IRRLICHT IMPORTERS
//
void LoadModel(ChVisualSystemIrrlicht* vis, const char* filename) {
if (modelNode)
modelNode->remove();
modelNode = 0;
if (decompositionNode)
decompositionNode->remove();
decompositionNode = 0;
// Load a mesh using the Irrlicht I/O conversion
// from mesh file formats.
modelMesh = vis->GetSceneManager()->getMesh(filename);
modelNode = vis->GetSceneManager()->addAnimatedMeshSceneNode(modelMesh);
modelNode->setMaterialFlag(irr::video::EMF_NORMALIZE_NORMALS, true);
}
void DecomposeModel(ChVisualSystemIrrlicht* vis) {
if (decompositionNode)
decompositionNode->remove();
decompositionNode = 0;
if (!modelNode)
return;
decompositionNode = vis->GetSceneManager()->addEmptySceneNode();
// Convert the Irrlicht mesh into a Chrono::Engine mesh.
ChTriangleMeshSoup chmesh;
// modelNode->getMesh();
fillChTrimeshFromIrlichtMesh(&chmesh, modelNode->getMesh()); // modelMesh->getMesh(0));
// Perform the convex decomposition using the desired parameters.
mydecompositionHACDv2.Reset();
mydecompositionHACDv2.AddTriangleMesh(chmesh);
mydecompositionHACDv2.SetParameters(hacd_maxhullcount, hacd_maxhullmerge, hacd_maxhullvertexes,
(float)hacd_concavity, (float)hacd_smallclusterthreshold,
(float)hacd_fusetolerance);
mydecompositionHACDv2.ComputeConvexDecomposition();
// Visualize the resulting convex decomposition by creating many
// colored meshes, each per convex hull.
for (unsigned int j = 0; j < mydecompositionHACDv2.GetHullCount(); j++) {
scene::SMesh* mmesh = new scene::SMesh();
// Get the j-th convex hull as a ChTriangleMesh.
ChTriangleMeshSoup chmesh_hull;
mydecompositionHACDv2.GetConvexHullResult(j, chmesh_hull);
video::SColor clr(255, 20 + (int)(140. * ChRandom()), 20 + (int)(140. * ChRandom()),
20 + (int)(140. * ChRandom()));
// Convert the j-th convex hull from a ChTriangleMesh to an Irrlicht mesh.
fillIrlichtMeshFromChTrimesh(mmesh, &chmesh_hull, clr);
// Add Irrlicht mesh to the scene, as a scene node.
scene::SAnimatedMesh* Amesh = new scene::SAnimatedMesh();
Amesh->addMesh(mmesh);
mmesh->drop();
scene::IAnimatedMeshSceneNode* piece_node =
vis->GetSceneManager()->addAnimatedMeshSceneNode(Amesh, decompositionNode);
piece_node->getMaterial(0).EmissiveColor.set(255, 40, 40, 50); // 255, 50, 50, 50);
// piece_node->getMaterial(0).AmbientColor.set(255,30,30,30);//100, 0,0,0);
piece_node->getMaterial(0).DiffuseColor.set(255, clr.getRed(), clr.getGreen(),
clr.getBlue()); // 255, 50, 50, 50);
// piece_node->getMaterial(0).Lighting = true;
piece_node->setMaterialFlag(irr::video::EMF_NORMALIZE_NORMALS, true);
scene::IAnimatedMeshSceneNode* piece_node2 =
vis->GetSceneManager()->addAnimatedMeshSceneNode(Amesh, decompositionNode);
piece_node2->getMaterial(0).Lighting = true;
piece_node2->getMaterial(0).Wireframe = true;
piece_node2->getMaterial(0).Thickness = 2;
}
modelNode->setVisible(false);
}
void SaveHullsWavefront(ChVisualSystemIrrlicht* vis, const char* filename) {
// Save the convex decomposition to a
// file using the .obj fileformat.
try {
ChStreamOutAsciiFile decomposed_objfile(filename);
mydecompositionHACDv2.WriteConvexHullsAsWavefrontObj(decomposed_objfile);
} catch (const ChException&) {
vis->GetGUIEnvironment()->addMessageBox(L"Save file error", L"Impossible to write into file.");
}
}
void SaveHullsChulls(ChVisualSystemIrrlicht* vis, const char* filename) {
// Save the convex decomposition to a
// file using the .obj fileformat.
try {
ChStreamOutAsciiFile decomposed_objfile(filename);
mydecompositionHACDv2.WriteConvexHullsAsChullsFile(decomposed_objfile);
} catch (const ChException&) {
vis->GetGUIEnvironment()->addMessageBox(L"Save file error", L"Impossible to write into file.");
}
}
// Define a MyEventReceiver class which will be used to manage input
// from the GUI graphical user interface (the interface will
// be created with the basic -yet flexible- platform
// independent toolset of Irrlicht).
class MyEventReceiver : public IEventReceiver {
public:
MyEventReceiver(ChVisualSystemIrrlicht* vsys) : vis(vsys) {
vis->GetDevice()->setEventReceiver(this);
// create menu
gui::IGUIContextMenu* menu = vis->GetGUIEnvironment()->addMenu();
menu->addItem(L"File", -1, true, true);
menu->addItem(L"View", -1, true, true);
gui::IGUIContextMenu* submenu;
submenu = menu->getSubMenu(0);
submenu->addItem(L"Load OBJ mesh...", 90);
submenu->addItem(L"Load STEP model...", 95, false);
submenu->addItem(L"Save convex hulls (.obj)", 91);
submenu->addItem(L"Save convex hulls (.chulls)", 96);
submenu->addSeparator();
submenu->addItem(L"Quit", 92);
submenu = menu->getSubMenu(1);
submenu->addItem(L"View model", 93);
submenu->addItem(L"View decomposition", 94);
text_algo_type =
vis->GetGUIEnvironment()->addStaticText(L"HACDv2 algorithm", core::rect<s32>(510, 35, 650, 50), false);
// ..add a GUI
edit_hacd_maxhullcount = vis->GetGUIEnvironment()->addEditBox(
irr::core::stringw((int)hacd_maxhullcount).c_str(), core::rect<s32>(510, 60, 650, 75), true, 0, 121);
text_hacd_maxhullcount =
vis->GetGUIEnvironment()->addStaticText(L"Max. hull count ", core::rect<s32>(650, 60, 750, 75), false);
// ..add a GUI
edit_hacd_maxhullmerge = vis->GetGUIEnvironment()->addEditBox(
irr::core::stringw((int)hacd_maxhullmerge).c_str(), core::rect<s32>(510, 85, 650, 100), true, 0, 122);
text_hacd_maxhullmerge =
vis->GetGUIEnvironment()->addStaticText(L"Max. hull merge ", core::rect<s32>(650, 85, 750, 100), false);
// ..add a GUI
edit_hacd_maxhullvertexes = vis->GetGUIEnvironment()->addEditBox(
irr::core::stringw((int)hacd_maxhullvertexes).c_str(), core::rect<s32>(510, 110, 650, 125), true, 0, 123);
text_hacd_maxhullvertexes = vis->GetGUIEnvironment()->addStaticText(L"Max. vertexes per hull",
core::rect<s32>(650, 110, 750, 125), false);
// ..add a GUI
edit_hacd_concavity = vis->GetGUIEnvironment()->addEditBox(irr::core::stringw(hacd_concavity).c_str(),
core::rect<s32>(510, 135, 650, 150), true, 0, 124);
text_hacd_concavity = vis->GetGUIEnvironment()->addStaticText(L"Max. concavity (0..1)",
core::rect<s32>(650, 135, 750, 150), false);
// ..add a GUI
edit_hacd_smallclusterthreshold = vis->GetGUIEnvironment()->addEditBox(
irr::core::stringw(hacd_smallclusterthreshold).c_str(), core::rect<s32>(510, 160, 650, 175), true, 0, 125);
text_hacd_smallclusterthreshold = vis->GetGUIEnvironment()->addStaticText(
L"Small cluster threshold", core::rect<s32>(650, 160, 750, 175), false);
// ..add a GUI
edit_hacd_fusetolerance = vis->GetGUIEnvironment()->addEditBox(
irr::core::stringw(hacd_fusetolerance).c_str(), core::rect<s32>(510, 185, 650, 200), true, 0, 126);
text_hacd_fusetolerance = vis->GetGUIEnvironment()->addStaticText(L"Vertex fuse tolerance",
core::rect<s32>(650, 185, 750, 200), false);
// .. add buttons..
button_decompose = vis->GetGUIEnvironment()->addButton(core::rect<s32>(510, 210, 650, 225), 0, 106,
L"Decompose", L"Perform convex decomposition");
text_hacd_maxhullcount->setVisible(true);
edit_hacd_maxhullcount->setVisible(true);
text_hacd_maxhullmerge->setVisible(true);
edit_hacd_maxhullmerge->setVisible(true);
text_hacd_maxhullvertexes->setVisible(true);
edit_hacd_maxhullvertexes->setVisible(true);
text_hacd_concavity->setVisible(true);
edit_hacd_concavity->setVisible(true);
text_hacd_smallclusterthreshold->setVisible(true);
edit_hacd_smallclusterthreshold->setVisible(true);
text_hacd_fusetolerance->setVisible(true);
edit_hacd_fusetolerance->setVisible(true);
}
bool OnEvent(const SEvent& event) {
// check if user moved the sliders with mouse..
if (event.EventType == EET_GUI_EVENT) {
s32 id = event.GUIEvent.Caller->getID();
gui::IGUIEnvironment* env = vis->GetGUIEnvironment();
switch (event.GUIEvent.EventType) {
case gui::EGET_MENU_ITEM_SELECTED: {
// a menu item was clicked
gui::IGUIContextMenu* menu = (gui::IGUIContextMenu*)event.GUIEvent.Caller;
id = menu->getItemCommandId(menu->getSelectedItem());
switch (id) {
case 90:
env->addFileOpenDialog(L"Load a mesh file, in .OBJ/.X/.MAX format", true, 0, 80);
break;
case 95:
env->addFileOpenDialog(L"Load a 3D CAD model, in STEP format", true, 0, 85);
break;
case 91:
env->addFileOpenDialog(L"Save decomposed convex hulls in .obj 3D format", true, 0, 81);
break;
case 96:
env->addFileOpenDialog(L"Save decomposed convex hulls in .chulls 3D format", true, 0, 86);
break;
case 92: // File -> Quit
vis->GetDevice()->closeDevice();
break;
case 93:
if (modelNode)
modelNode->setVisible(true);
if (decompositionNode)
decompositionNode->setVisible(false);
break;
case 94:
if (modelNode)
modelNode->setVisible(false);
if (decompositionNode)
decompositionNode->setVisible(true);
break;
}
break;
}
case gui::EGET_FILE_SELECTED: {
// load the model file, selected in the file open dialog
gui::IGUIFileOpenDialog* dialog = (gui::IGUIFileOpenDialog*)event.GUIEvent.Caller;
switch (id) {
case 80:
LoadModel(vis, core::stringc(dialog->getFileName()).c_str());
break;
case 85:
// LoadStepModel(app, core::stringc(dialog->getFileName()).c_str() );
break;
case 81:
SaveHullsWavefront(vis, core::stringc(dialog->getFileName()).c_str());
break;
case 86:
SaveHullsChulls(vis, core::stringc(dialog->getFileName()).c_str());
break;
}
} break;
case gui::EGET_EDITBOX_ENTER: {
// load the model file, selected in the file open dialog
gui::IGUIEditBox* medit = (gui::IGUIEditBox*)event.GUIEvent.Caller;
switch (id) {
case 122:
hacd_maxhullmerge = std::atoi(irr::core::stringc(medit->getText()).c_str());
medit->setText(irr::core::stringw(hacd_maxhullmerge).c_str());
break;
case 123:
hacd_maxhullvertexes = std::atoi(irr::core::stringc(medit->getText()).c_str());
medit->setText(irr::core::stringw(hacd_maxhullvertexes).c_str());
break;
case 124:
hacd_concavity = std::atof(irr::core::stringc(medit->getText()).c_str());
medit->setText(irr::core::stringw(hacd_concavity).c_str());
break;
case 125:
hacd_smallclusterthreshold = std::atof(irr::core::stringc(medit->getText()).c_str());
medit->setText(irr::core::stringw(hacd_smallclusterthreshold).c_str());
break;
case 126:
hacd_fusetolerance = std::atof(irr::core::stringc(medit->getText()).c_str());
medit->setText(irr::core::stringw(hacd_fusetolerance).c_str());
break;
}
} break;
case gui::EGET_BUTTON_CLICKED: {
switch (id) {
case 106:
DecomposeModel(vis);
return true;
default:
return false;
}
break;
}
default:
break;
}
}
return false;
}
private:
ChVisualSystemIrrlicht* vis;
gui::IGUIButton* button_decompose;
gui::IGUIStaticText* text_algo_type;
gui::IGUIStaticText* text_hacd_maxhullcount;
gui::IGUIEditBox* edit_hacd_maxhullcount;
gui::IGUIStaticText* text_hacd_maxhullmerge;
gui::IGUIEditBox* edit_hacd_maxhullmerge;
gui::IGUIStaticText* text_hacd_maxhullvertexes;
gui::IGUIEditBox* edit_hacd_maxhullvertexes;
gui::IGUIStaticText* text_hacd_concavity;
gui::IGUIEditBox* edit_hacd_concavity;
gui::IGUIStaticText* text_hacd_smallclusterthreshold;
gui::IGUIEditBox* edit_hacd_smallclusterthreshold;
gui::IGUIStaticText* text_hacd_fusetolerance;
gui::IGUIEditBox* edit_hacd_fusetolerance;
};
//
// This is the program which is executed
//
int main(int argc, char* argv[]) {
GetLog() << "Copyright (c) 2017 projectchrono.org\nChrono version: " << CHRONO_VERSION << "\n\n";
// 1- Create a ChronoENGINE physical system: all bodies and constraints
// will be handled by this ChSystemNSC object.
ChSystemNSC sys;
// Initial settings
modelMesh = 0;
modelNode = 0;
decompositionNode = 0;
hacd_maxhullcount = 512;
hacd_maxhullmerge = 256;
hacd_maxhullvertexes = 64;
hacd_concavity = 0.2;
hacd_smallclusterthreshold = 0.0;
hacd_fusetolerance = 1e-9;
// Create the Irrlicht visualization system
auto vis = chrono_types::make_shared<ChVisualSystemIrrlicht>();
sys.SetVisualSystem(vis);
vis->SetWindowSize(800, 600);
vis->SetWindowTitle("Convex decomposition of a mesh");
vis->Initialize();
vis->AddLogo();
vis->AddSkyBox();
vis->AddCamera(ChVector<>(0, 1.5, -2));
vis->AddLight(ChVector<>(30, 100, 30), 200, ChColor(0.7f, 0.7f, 0.7f));
vis->AddLight(ChVector<>(30, -80, -30), 130, ChColor(0.7f, 0.8f, 0.8f));
// Create a custom event receiver for a GUI
MyEventReceiver receiver(vis.get());
vis->AddUserEventReceiver(&receiver);
// Simulation loop
while (vis->Run()) {
vis->BeginScene();
vis->DrawAll();
vis->EndScene();
}
return 0;
}
| 42.299287 | 120 | 0.574629 | lucasw |
49d0ad93f2733814bcdc3a2c80701f0e72f223dc | 2,033 | cpp | C++ | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | basic-window/main.cpp | coltonhurst/learning-sdl | e629a24b851a6b409266e2514f1b94bc162f85d3 | [
"MIT"
] | null | null | null | #include <SDL2/SDL.h>
#include <iostream>
const int WINDOW_HEIGHT = 640;
const int WINDOW_WIDTH = 480;
// Starting point.
int main(int argc, const char * argv[])
{
// Create the window & screen surface.
// We render to the window & the surface is "contained" by the window.
SDL_Window* window = nullptr;
SDL_Surface* screenSurface = nullptr;
// Initiate SDL. If an error occurs, stop & print the error.
if (SDL_Init(SDL_INIT_VIDEO) < 0)
{
std::cout << "SDL could not be initialized. SDL_Error: " << SDL_GetError() << std::endl;
}
else
{
// Create the window.
window = SDL_CreateWindow("Window Title",
SDL_WINDOWPOS_UNDEFINED,
SDL_WINDOWPOS_UNDEFINED,
WINDOW_HEIGHT,
WINDOW_WIDTH,
SDL_WINDOW_OPENGL);
// If the window can't be created, print the error.
if (window == nullptr)
{
std::cout << "The window couldn't be created. SDL_Error: " << SDL_GetError() << std::endl;
}
else
{
// Get the window's surface.
screenSurface = SDL_GetWindowSurface(window);
// Make the screen surface white.
SDL_FillRect(screenSurface, nullptr, SDL_MapRGB(screenSurface->format, 0xFF, 0xFF, 0xFF));
// Update the surface.
SDL_UpdateWindowSurface(window);
SDL_Event event;
bool quit = false;
// Event loop.
while (!quit) {
while (SDL_PollEvent(&event) != 0) {
if (event.type == SDL_QUIT)
{
quit = true;
}
}
}
}
}
// Destroy the window.
SDL_DestroyWindow( window );
// Quit SDL.
SDL_Quit();
return 0;
}
| 29.042857 | 102 | 0.487949 | coltonhurst |
49d1f5e89dd6a3655548bc676cfc8ac33df047a3 | 3,185 | cpp | C++ | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | Programmation-II/src/Project 013 (The Tortoise and the Hare)/Main.cpp | EpsilonsQc/Programmation-I | 34ec0cd60f3c51faf1ea5ba03b7b95e1c9d96986 | [
"MIT"
] | null | null | null | // The Tortoise and the Hare
// Main.cpp (Main function | Program execution begins and ends there)
/*
EXERCICE 8.12 PSEUDOCODE
- utilisation de nombre aléatoire pour recréation de la simulation
- créer un array de 70 cases
- chacune des 70 cases représente une position le long du parcours de course
- la ligne d'arrivée est à la case 70
- le premier a atteindre la case 70 reçois : "pail of fresh carrots and lettuce"
- Le parcours serpente le long d'une montagne glissante, donc parfois les prétendants perdent du terrain.
- Il y a une horloge qui tic-tac une fois par seconde.
- Le programme doit utiliser les fonctions "moveTortoise" et "moveHare" pour ajuster la position des animaux selon les règles de la Figure 8.18
- Ces fonctions doivent utiliser des pointeurs passe-par-référence pour modifier la position de la tortue et du lièvre.
- Utilisez des variables pour garder une trace des positions des animaux (les numéros de position vont de 1 à 70).
- Commencer chaque animal à la position 1 (c'est-à-dire la "starting gate")
- Si un animal glisse à gauche avant la case 1, déplacez l'animal vers la case 1.
PERCENTAGE (FIG 8.18)
- Générez les pourcentages de la Figure 8.18 en produisant un entier aléatoire i dans la plage 1 <= i <= 10
- Pour la tortue, effectuez une :
> "fast plod" quand 1 <= i <= 5 (50%) actual move : 3 case a droite
> "slip" quand 6 <= i <= 7 (20%) actual move : 6 case a GAUCHE
> "slow plod" quand 8 <= i <= 10 (30%) actual move : 1 case a droite
- Utilisez une technique similaire pour déplacer le lièvre :
> "sleep" quand 1 <= i <= 2 (20%) actual move : ne bouge pas
> "big hop" quand 3 <= i <= 4 (20%) actual move : 9 case a droite
> "big slip" quand 5 <= i <= 5 (10%) actual move : 12 case a GAUCHE
> "small hop" quand 6 <= i <= 8 (30%) actual move : 1 case a droite
> "small slip" quand 9 <= i <= 10 (20%) actual move : 2 case a GAUCHE
BEGIN THE RACE BY DISPLAYING :
BANG !!!!!
AND THEY'RE OFF !!!!!
- Pour chaque tick de l'horloge (c'est-à-dire chaque itération d'une boucle), affichez une ligne à 70 positions indiquant la lettre "T" en position de tortue (tortoise) et la lettre "H" en position de lièvre (hare).
- Parfois, les concurrents atterrissent sur la même case. Dans ce cas, la tortue mord le lièvre et votre programme devrait afficher "OUCH!!!" commençant à cette position.
- Toutes les positions autres que le "T" , le "H" ou "OUCH!!!" (en cas d'égalité) doit être vide.
WINNING
- Après avoir affiché chaque ligne, testez si l'un ou l'autre des animaux a atteint ou dépassé la case 70.
- Si c'est le cas, affichez le gagnant et terminer la simulation.
- Si la tortue gagne, affichez "TORTOISE WINS!!! YAY!!!" | "LA TORTUE GAGNE!!! YAY!!!"
- Si le lièvre gagne, affichez "Hare wins. Yuch." | "Le lièvre gagne. Yuch."
- Si les deux animaux gagnent sur le même tic d'horloge, afficher "It's a tie."
- Si aucun animal ne gagne, refaites la boucle pour simuler le prochain tic-tac de l'horloge.
*/
#include <iostream>
using namespace std;
int main()
{
system("pause");
return 0;
}
| 49.765625 | 216 | 0.6854 | EpsilonsQc |
49d7145725729878d437d073cf0594dbd68d839c | 4,490 | hh | C++ | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | 1 | 2021-09-13T17:06:34.000Z | 2021-09-13T17:06:34.000Z | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | null | null | null | include/hcore/exception.hh | ecrc/hcorepp | 5192f7334518e3b7fbffa8e2f56301f77c777c55 | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) 2017-2021, King Abdullah University of Science and Technology
// (KAUST). All rights reserved.
// SPDX-License-Identifier: BSD-3-Clause. See the accompanying LICENSE file.
#ifndef HCORE_EXCEPTION_HH
#define HCORE_EXCEPTION_HH
#include <string>
#include <cstdio>
#include <cstdarg>
#include <exception>
namespace hcore {
class Error : public std::exception {
public:
Error() : std::exception()
{
}
Error(const std::string& what_arg) : std::exception(), what_arg_(what_arg)
{
}
Error(
const std::string& what_arg, const char* function) : std::exception(),
what_arg_(what_arg + ", function " + function + ".")
{
}
Error(
const std::string& what_arg,
const char* function, const char* file, int line) : std::exception(),
what_arg_(what_arg
+ ", function " + function
+ ", file " + file
+ ", line " + std::to_string(line) + ".")
{
}
virtual const char* what() const noexcept override
{
return what_arg_.c_str();
}
private:
std::string what_arg_;
};
namespace internal {
// throws hcore::Error if condition is true called by hcore_error_if macro
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line)
{
if (condition) {
throw Error(condition_string, function, file, line);
}
}
// throws hcore::Error if condition is true called by hcore_error_if_msg macro
// and uses printf-style format for error message
// condition_string is ignored, but differentiates this from other version.
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line, const char* format, ...)
__attribute__((format(printf, 6, 7)));
inline void throw_if(
bool condition, const char* condition_string,
const char* function, const char* file, int line, const char* format, ...)
{
if (condition) {
char bufffer[80];
va_list v;
va_start(v, format);
vsnprintf(bufffer, sizeof(bufffer), format, v);
va_end(v);
throw Error(bufffer, function, file, line);
}
}
// internal helper function; aborts if condition is true
// uses printf-style format for error message
// called by hcore_error_if_msg macro
inline void abort_if(
bool condition,
const char* function, const char* file, int line, const char* format, ...)
__attribute__((format(printf, 5, 6)));
inline void abort_if(
bool condition,
const char* function, const char* file, int line, const char* format, ...)
{
if (condition) {
char bufffer[80];
va_list v;
va_start(v, format);
vsnprintf(bufffer, sizeof(bufffer), format, v);
va_end(v);
fprintf(stderr,
"HCORE assertion failed: (%s), function %s, file %s, line %d.\n",
bufffer, function, file, line);
abort();
}
}
} // namespace internal
} // namespace hcore
#if defined(HCORE_ERROR_NDEBUG) || \
(defined(HCORE_ERROR_ASSERT) && defined(NDEBUG))
// HCORE does no error checking, and thus errors maybe either handled by
// - BLAS++ and LAPACK++, or
// - Lower level BLAS and LAPACK via xerbla
#define hcore_error_if(condition) ((void)0)
#define hcore_error_if_msg(condition, ...) ((void)0)
#elif defined(HCORE_ERROR_ASSERT)
// HCORE aborts on error (similar to C/C++ assert)
#define hcore_error_if(condition) \
hcore::internal::abort_if( \
condition, __func__, __FILE__, __LINE__, "%s", #condition)
#define hcore_error_if_msg(condition, ...) \
hcore::internal::abort_if( \
condition, __func__, __FILE__, __LINE__, __VA_ARGS__)
#else
// HCORE throws errors (default)
// internal macro to get string #condition; throws hcore::Error if condition
// is true. Example: hcore_error_if(a < b)
#define hcore_error_if(condition) \
hcore::internal::throw_if( \
condition, #condition, __func__, __FILE__, __LINE__)
// internal macro takes condition and printf-style format for error message.
// throws Error if condition is true.
// example: hcore_error_if_msg(a < b, "a %d < b %d", a, b);
#define hcore_error_if_msg(condition, ...) \
hcore::internal::throw_if( \
condition, #condition, __func__, __FILE__, __LINE__, __VA_ARGS__)
#endif
#endif // HCORE_EXCEPTION_HH
| 32.536232 | 80 | 0.647216 | ecrc |
49d7d85fa62b54de41eae6e91cb4a45db28dba88 | 3,180 | cpp | C++ | tr-game-server/src/main.cpp | SolidLeon/Overheat | 62074b613d4f692bc36e44930b677c5dc1205f88 | [
"OpenSSL"
] | 3 | 2017-09-11T09:06:57.000Z | 2019-11-12T03:06:37.000Z | tr-game-server/src/main.cpp | SolidLeon/Overheat | 62074b613d4f692bc36e44930b677c5dc1205f88 | [
"OpenSSL"
] | null | null | null | tr-game-server/src/main.cpp | SolidLeon/Overheat | 62074b613d4f692bc36e44930b677c5dc1205f88 | [
"OpenSSL"
] | null | null | null | //FIXME: If you get a compiler error that the type uintX_t is not defined, include the "types.h" in the corresoponding header file.
#include <iostream>
#include <string>
#include "server.h"
//#include "crypto.h"
#include "DBMgr.h"
#include "ThreadUtils.h"
#include <pthread.h>
using namespace std;
pthread_mutex_t gMutex;
bool server_running = true;
#ifndef _WIN32
#define Sleep(x) sleep(x/1000)
#endif
//#include "PacketBuffer.h"
void* game_auth_gg_main(void* param);
void* game_auth1_main(void* param);
void* game_auth2_main(void* param);
void HexOut(uint8_t* data, size_t len)
{
for(int i = 0; i < len; i++)
{
if(i%0x10==0) {
printf("\n%04X: ", i);
}
printf("%02X ", data[i]);
}
printf("\n");
for(int i = 0; i < len; i++)
{
if(i%0x10==0) {
printf("\n%04X: ", i);
}
if((data[i] >= 'A' && data[i] <= 'Z') || (data[i]>='a' && data[i]<='z') || (data[i]>='0' && data[i]<='9'))
printf("%c", data[i]);
else
printf(".");
}
printf("\n\n");
}
int main (int argc, char * const argv[])
{
printf(" ==============================================================================\r\n");
printf(" Overheat \r\n");
printf(" Auth Game Server \r\n\r\n");
printf(" Version 0.4 http://overheat.com/ \r\n");
printf(" ==============================================================================\r\n");
//printf(">> Load Crypto...\n");
//tr::crypto::CCryptMgr::instance();
printf(">> Load Database Driver...\n");
try { tr::util::DBMgr::create( "127.0.0.1", 8889, "root", "root", "tabuladb" ); } catch(const char* ex) { printf("Could not load Database: %s\n", ex); return 1; }
printf(">> Database loaded OK\n");
printf("\n");
pthread_t pt1, pt2, pt3;
if( Thread::New(&pt1, game_auth_gg_main, NULL)) printf(">> Game Auth GG Thread started\n");
else printf("Could not start Game Auth GG Thread!\n");
Sleep(1000);
if( Thread::New(&pt2, game_auth1_main, NULL)) printf(">> Game Auth 1 Thread started\n");
else printf("Could not start Game Auth 1 Thread!\n");
Sleep(1000);
if( Thread::New(&pt3, game_auth2_main, NULL)) printf(">> Game Auth 2 Thread started\n");
else printf("Could not start Game Auth 2 Thread!\n");
Sleep(1000);
Thread::Join(pt1);
Thread::Join(pt2);
Thread::Join(pt3);
return 0;
}
void* game_auth_gg_main(void* param)
{
tr::net::CGameServer gs = tr::net::CGameServer::load_by_id(53);
tr::net::CServer server(tr::net::CServer::AUTH_GG, gs);
server.start();
return 0;
}
void* game_auth1_main(void* param)
{
tr::net::CGameServer gs = tr::net::CGameServer::load_by_id(53);
tr::net::CServer server(tr::net::CServer::AUTH_GG_FIRST, gs);
server.start();
return 0;
}
void* game_auth2_main(void* param)
{
tr::net::CGameServer gs = tr::net::CGameServer::load_by_id(53);
tr::net::CServer server(tr::net::CServer::AUTH_GAMING, gs);
server.start();
return 0;
} | 29.174312 | 163 | 0.536792 | SolidLeon |
49d7d8f2724c252c81e0e4ffadee4979028d3186 | 198 | cpp | C++ | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | target/classes/top.chenqwwq/acwing/content/_56/C.cpp | CheNbXxx/_leetcode | d49786b376d7cf17e099af7dcda1a47866f7e194 | [
"Apache-2.0"
] | null | null | null | //
// Created by chenqwwq on 2022/6/18.
//
#include "stdc++.h"
#include "common.h"
#include "iostream"
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
} | 12.375 | 36 | 0.641414 | CheNbXxx |
49da17727538a27dae3335702b0ad6fd299602d8 | 40 | cpp | C++ | cpp/src/main/models/GlobalRankingScoreIterator.cpp | rpalovics/Alpenglow | 63472ce667d517d6c7f47c9d0559861392fca3f9 | [
"Apache-2.0"
] | 28 | 2017-07-23T22:47:44.000Z | 2022-03-12T15:11:13.000Z | cpp/src/main/models/GlobalRankingScoreIterator.cpp | proto-n/Alpenglow | 7a15d5c57b511787379f095e7310e67423159fa0 | [
"Apache-2.0"
] | 4 | 2017-05-10T10:23:17.000Z | 2019-05-23T14:07:09.000Z | cpp/src/main/models/GlobalRankingScoreIterator.cpp | proto-n/Alpenglow | 7a15d5c57b511787379f095e7310e67423159fa0 | [
"Apache-2.0"
] | 9 | 2017-05-04T09:20:58.000Z | 2021-12-14T08:19:01.000Z | #include "GlobalRankingScoreIterator.h"
| 20 | 39 | 0.85 | rpalovics |
49e74d6552b220e5d1b1fcfdb1bc0f6b4c4c8843 | 1,715 | hh | C++ | StRoot/StDbLib/StDbTableFactory.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | 2 | 2018-12-24T19:37:00.000Z | 2022-02-28T06:57:20.000Z | StRoot/StDbLib/StDbTableFactory.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | StRoot/StDbLib/StDbTableFactory.hh | xiaohaijin/RHIC-STAR | a305cb0a6ac15c8165bd8f0d074d7075d5e58752 | [
"MIT"
] | null | null | null | /***************************************************************************
*
* $Id: StDbTableFactory.hh,v 1.1 2001/01/22 18:38:01 porter Exp $
*
* Author: R. Jeff Porter
***************************************************************************
*
* Description: Simple place holder for creating DB tables;
* Eventually can depend on which database.
*
***************************************************************************
*
* $Log: StDbTableFactory.hh,v $
* Revision 1.1 2001/01/22 18:38:01 porter
* Update of code needed in next year running. This update has little
* effect on the interface (only 1 method has been changed in the interface).
* Code also preserves backwards compatibility so that old versions of
* StDbLib can read new table structures.
* -Important features:
* a. more efficient low-level table structure (see StDbSql.cc)
* b. more flexible indexing for new systems (see StDbElememtIndex.cc)
* c. environment variable override KEYS for each database
* d. StMessage support & clock-time logging diagnostics
* -Cosmetic features
* e. hid stl behind interfaces (see new *Impl.* files) to again allow rootcint access
* f. removed codes that have been obsolete for awhile (e.g. db factories)
* & renamed some classes for clarity (e.g. tableQuery became StDataBaseI
* and mysqlAccessor became StDbSql)
*
*
**************************************************************************/
#ifndef STDBTABLEFACTORY_HH
#define STDBTABLEFACTORY_HH
class StDbTable;
class StDbTableFactory {
public:
virtual ~StDbTableFactory() {};
virtual StDbTable* newDbTable(const char* dbName, const char* tabName);
};
#endif
| 36.489362 | 89 | 0.587172 | xiaohaijin |
49e8bb7742522cd602eb35a5fabf30f00d3f530d | 479 | cpp | C++ | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | TotalInsanity/Source/TotalInsanity/Player/TIShootEffect.cpp | APBerg/TotalInsanity | 35950d2dd8ea196b5a76f968033a63990aa50bd8 | [
"MIT"
] | null | null | null | // Copyright Adam Berg 2017
#include "TIShootEffect.h"
// Sets default values
ATIShootEffect::ATIShootEffect()
{
// Set this actor to call Tick() every frame. You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
}
// Called when the game starts or when spawned
void ATIShootEffect::BeginPlay()
{
Super::BeginPlay();
}
// Called every frame
void ATIShootEffect::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
}
| 17.107143 | 115 | 0.730689 | APBerg |
49e9501641183e601d40851df1fc9954e5359dd4 | 2,206 | cpp | C++ | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | source/component/Ray.cpp | xzrunner/editopgraph | 1201c71285b417f8e4cbf2146f3acbd5b50aff61 | [
"MIT"
] | null | null | null | #include "editopgraph/component/Ray.h"
#include "editopgraph/CompHelper.h"
#include "editopgraph/ParamImpl.h"
#include "editopgraph/Context.h"
#include <painting3/PerspCam.h>
#include <painting3/Viewport.h>
namespace editopgraph
{
namespace comp
{
void Ray::Execute(const std::shared_ptr<dag::Context>& ctx)
{
m_vals.resize(1, nullptr);
auto start_pos = m_start_pos;
auto end_pos = m_end_pos;
auto p_start = CompHelper::GetInputParam(*this, 0);
auto p_end = CompHelper::GetInputParam(*this, 1);
if (p_start)
{
switch (p_start->Type())
{
case ParamType::Camera:
{
auto cam = std::static_pointer_cast<CameraParam>(p_start)->GetCamera();
auto cam_type = cam->TypeID();
if (cam_type == pt0::GetCamTypeID<pt3::PerspCam>()) {
start_pos = std::dynamic_pointer_cast<pt3::PerspCam>(cam)->GetPos();
}
}
break;
case ParamType::Float3:
start_pos = std::static_pointer_cast<Float3Param>(p_start)->GetValue();
break;
}
}
if (p_end)
{
switch (p_end->Type())
{
case ParamType::ScreenPos:
{
if (ctx)
{
auto _ctx = std::static_pointer_cast<Context>(ctx);
auto cam = _ctx->GetCamera();
auto cam_type = cam->TypeID();
if (cam_type == pt0::GetCamTypeID<pt3::PerspCam>())
{
auto p_cam = std::dynamic_pointer_cast<pt3::PerspCam>(cam);
auto pos = std::static_pointer_cast<ScreenPosParam>(p_end)->GetPos();
sm::vec3 ray_dir = _ctx->GetViewport().TransPos3ScreenToDir(
sm::vec2(static_cast<float>(pos.x), static_cast<float>(pos.y)), *p_cam);
end_pos = start_pos + ray_dir;
}
}
}
break;
case ParamType::Float3:
end_pos = std::static_pointer_cast<Float3Param>(p_end)->GetValue();
break;
}
}
sm::Ray ray(start_pos, end_pos - start_pos);
m_vals[0] = std::make_shared<RayParam>(ray);
}
}
} | 28.649351 | 96 | 0.549864 | xzrunner |
49ea73bb180ed7b921c79412bc93739f35930059 | 3,887 | cpp | C++ | setbench/setbench/macrobench/concurrency_control/vll.cpp | cmuparlay/flock | afdcfe55cdd7507c2a19a6e0b30f3115e183cd58 | [
"MIT"
] | 19 | 2022-01-29T02:44:30.000Z | 2022-03-29T15:52:51.000Z | setbench/setbench/macrobench/concurrency_control/vll.cpp | cmuparlay/flock | afdcfe55cdd7507c2a19a6e0b30f3115e183cd58 | [
"MIT"
] | null | null | null | setbench/setbench/macrobench/concurrency_control/vll.cpp | cmuparlay/flock | afdcfe55cdd7507c2a19a6e0b30f3115e183cd58 | [
"MIT"
] | 1 | 2022-02-22T05:58:11.000Z | 2022-02-22T05:58:11.000Z | #include "vll.h"
#include "txn.h"
#include "table.h"
#include "row.h"
#include "row_vll.h"
#include "ycsb_query.h"
#include "ycsb.h"
#include "wl.h"
#include "catalog.h"
#include "mem_alloc.h"
#if CC_ALG == VLL
void
VLLMan::init() {
_txn_queue_size = 0;
_txn_queue = NULL;
_txn_queue_tail = NULL;
}
void
VLLMan::vllMainLoop(txn_man * txn, base_query * query) {
ycsb_query * m_query = (ycsb_query *) query;
// access the indexes. This is not in the critical section
for (int rid = 0; rid < m_query->request_cnt; rid ++) {
ycsb_request * req = &m_query->requests[rid];
ycsb_wl * wl = (ycsb_wl *) txn->get_wl();
int part_id = wl->key_to_part( req->key );
Index * index = wl->the_index;
itemid_t * item;
item = txn->index_read(index, req->key, part_id);
row_t * row = ((row_t *)item->location);
// the following line adds the read/write sets to txn->accesses
txn->get_row(row, req->rtype);
int cs = row->manager->get_cs();
}
bool done = false;
while (!done) {
txn_man * front_txn = NULL;
uint64_t t5 = get_sys_clock();
pthread_mutex_lock(&_mutex);
uint64_t tt5 = get_sys_clock() - t5;
INC_STATS(txn->get_thd_id(), debug5, tt5);
TxnQEntry * front = _txn_queue;
if (front)
front_txn = front->txn;
// only one worker thread can execute the txn.
if (front_txn && front_txn->vll_txn_type == VLL_Blocked) {
front_txn->vll_txn_type = VLL_Free;
pthread_mutex_unlock(&_mutex);
execute(front_txn, query);
finishTxn( front_txn, front);
} else {
// _mutex will be unlocked in beginTxn()
TxnQEntry * entry = NULL;
int ok = beginTxn(txn, query, entry);
if (ok == 2) {
execute(txn, query);
finishTxn(txn, entry);
}
assert(ok == 1 || ok == 2);
done = true;
}
}
return;
}
int
VLLMan::beginTxn(txn_man * txn, base_query * query, TxnQEntry *& entry) {
int ret = -1;
if (_txn_queue_size >= TXN_QUEUE_SIZE_LIMIT)
ret = 3;
txn->vll_txn_type = VLL_Free;
assert(WORKLOAD == YCSB);
for (int rid = 0; rid < txn->row_cnt; rid ++ ) {
access_t type = txn->accesses[rid]->type;
if (txn->accesses[rid]->orig_row->manager->insert_access(type))
txn->vll_txn_type = VLL_Blocked;
}
entry = getQEntry();
LIST_PUT_TAIL(_txn_queue, _txn_queue_tail, entry);
if (txn->vll_txn_type == VLL_Blocked)
ret = 1;
else
ret = 2;
pthread_mutex_unlock(&_mutex);
return ret;
}
void
VLLMan::execute(txn_man * txn, base_query * query) {
RC rc;
uint64_t t3 = get_sys_clock();
ycsb_query * m_query = (ycsb_query *) query;
ycsb_wl * wl = (ycsb_wl *) txn->get_wl();
Catalog * schema = wl->the_table->get_schema();
uint64_t average;
for (int rid = 0; rid < txn->row_cnt; rid ++) {
row_t * row = txn->accesses[rid]->orig_row;
access_t type = txn->accesses[rid]->type;
if (type == RD) {
for (int fid = 0; fid < schema->get_field_cnt(); fid++) {
char * data = row->get_data();
uint64_t fval = *(uint64_t *)(&data[fid * 100]);
}
} else {
assert(type == WR);
for (int fid = 0; fid < schema->get_field_cnt(); fid++) {
char * data = row->get_data();
*(uint64_t *)(&data[fid * 100]) = 0;
}
}
}
uint64_t tt3 = get_sys_clock() - t3;
INC_STATS(txn->get_thd_id(), debug3, tt3);
}
void
VLLMan::finishTxn(txn_man * txn, TxnQEntry * entry) {
pthread_mutex_lock(&_mutex);
for (int rid = 0; rid < txn->row_cnt; rid ++ ) {
access_t type = txn->accesses[rid]->type;
txn->accesses[rid]->orig_row->manager->remove_access(type);
}
LIST_REMOVE_HT(entry, _txn_queue, _txn_queue_tail);
pthread_mutex_unlock(&_mutex);
txn->release();
mem_allocator.free(txn, 0);
}
TxnQEntry *
VLLMan::getQEntry() {
TxnQEntry * entry = (TxnQEntry *) mem_allocator.alloc(sizeof(TxnQEntry), 0);
entry->prev = NULL;
entry->next = NULL;
entry->txn = NULL;
return entry;
}
void
VLLMan::returnQEntry(TxnQEntry * entry) {
mem_allocator.free(entry, sizeof(TxnQEntry));
}
#endif
| 25.077419 | 77 | 0.651145 | cmuparlay |
49ea851c70299bbff10f905532cb0e031348f97d | 14,636 | cpp | C++ | src/geometry/surface.cpp | dillonhuff/scg | 21d004ce37c0e0e3650e373726d7e8bac51fffa4 | [
"MIT"
] | 14 | 2018-05-10T16:40:38.000Z | 2020-01-09T06:36:09.000Z | src/geometry/surface.cpp | dillonhuff/scg | 21d004ce37c0e0e3650e373726d7e8bac51fffa4 | [
"MIT"
] | 1 | 2019-10-26T13:08:56.000Z | 2019-10-26T13:08:56.000Z | src/geometry/surface.cpp | dillonhuff/scg | 21d004ce37c0e0e3650e373726d7e8bac51fffa4 | [
"MIT"
] | 2 | 2020-11-28T17:36:45.000Z | 2021-05-30T14:32:05.000Z | #include "geometry/surface.h"
#include "geometry/triangular_mesh_utils.h"
#include "geometry/vtk_debug.h"
namespace gca {
bool surfaces_share_edge(const surface& l,
const surface& r) {
auto ind1 = l.index_list();
auto ind2 = r.index_list();
return share_edge(ind1, ind2, l.get_parent_mesh());
}
bool surfaces_share_edge(const unsigned i,
const unsigned j,
const std::vector<surface>& surfaces) {
auto ind1 = surfaces[i].index_list();
auto ind2 = surfaces[j].index_list();
return share_edge(ind1, ind2, surfaces[i].get_parent_mesh());
}
bool surfaces_share_edge(const unsigned i,
const unsigned j,
const std::vector<surface*>& surfaces) {
auto ind1 = surfaces[i]->index_list();
auto ind2 = surfaces[j]->index_list();
return share_edge(ind1, ind2, surfaces[i]->get_parent_mesh());
}
std::vector<index_t> surface_vertexes(const surface& s) {
vector<index_t> inds;
for (auto i : s.index_list()) {
triangle_t t = s.get_parent_mesh().triangle_vertices(i);
inds.push_back(t.v[0]);
inds.push_back(t.v[1]);
inds.push_back(t.v[2]);
}
sort(begin(inds), end(inds));
return inds;
}
bool orthogonal_flat_surfaces(const surface* l, const surface* r) {
point l_orient = l->face_orientation(l->front());
point r_orient = r->face_orientation(r->front());
double theta = angle_between(l_orient, r_orient);
return within_eps(theta, 90, 0.1);
}
bool parallel_flat_surfaces(const surface* l, const surface* r) {
point l_orient = l->face_orientation(l->front());
point r_orient = r->face_orientation(r->front());
double theta = angle_between(l_orient, r_orient);
return within_eps(theta, 180, 0.1);
}
std::vector<surface> outer_surfaces(const triangular_mesh& part) {
// cout << "# of triangles in the part = " << part.face_indexes().size() << endl;
auto const_orient_face_indices = const_orientation_regions(part);
vector<surface> surfaces;
// cout << "# of const orientation regions = " << const_orient_face_indices.size() << endl;
for (auto f : const_orient_face_indices) {
surface s(&part, f);
// cout << "Region normal = " << normal(s) << endl;
// cout << "# of triangles in region = " << s.index_list().size() << endl;
//vtk_debug_highlight_inds(f, part);
DBG_ASSERT(f.size() > 0);
bool is_outer = is_outer_surface(f, part);
// cout << "Is outer = " << is_outer << endl;
if (is_outer) {
surfaces.push_back(surface(&part, f));
}
}
return surfaces;
}
surface merge_surfaces(const std::vector<surface>& surfaces) {
DBG_ASSERT(surfaces.size() > 0);
vector<index_t> inds;
for (auto s : surfaces) {
concat(inds, s.index_list());
}
return surface(&(surfaces.front().get_parent_mesh()), inds);
}
void remove_contained_surfaces(const std::vector<surface>& stable_surfaces,
std::vector<surface>& surfaces_to_cut) {
vector<index_t> stable_surface_inds;
for (auto s : stable_surfaces) {
concat(stable_surface_inds, s.index_list());
}
sort(begin(stable_surface_inds), end(stable_surface_inds));
delete_if(surfaces_to_cut,
[&stable_surface_inds](const surface& s)
{ return s.contained_by_sorted(stable_surface_inds); });
}
std::vector<surface>
merge_surface_groups(const std::vector<surface>& surfs,
const std::vector<std::vector<unsigned> >& groups) {
std::vector<surface> sfs;
for (auto group : groups) {
vector<surface> sg = select_indexes(surfs, group);
DBG_ASSERT(sg.size() == group.size());
sfs.push_back(merge_surfaces(sg));
}
return sfs;
}
// TODO: Eventually identify vertical holes and compensate for them
// TODO: Should this compensate for the fact that direction is not
//
bool vertical_contained_by(const surface& maybe_contained,
const surface& maybe_container) {
// vector<oriented_polygon> maybe_contained_outlines =
// mesh_bounds(maybe_contained.index_list(), maybe_contained.get_parent_mesh());
// if (maybe_contained_outlines.size() != 2) {
// cout << "More than 2 outlines" << endl;
// return false;
// }
auto contained_outline =
max_area_outline(maybe_contained.index_list(), maybe_contained.get_parent_mesh()); //maybe_contained_outlines.front();
// vector<oriented_polygon> maybe_container_outlines =
// mesh_bounds(maybe_container.index_list(), maybe_container.get_parent_mesh());
// if (maybe_container_outlines.size() != 2) {
// cout << "More than 2 outlines" << endl;
// return false;
// }
auto container_outline = max_area_outline(maybe_container.index_list(), maybe_container.get_parent_mesh()); //maybe_container_outlines.front();
return contains(container_outline, contained_outline);
}
boost::optional<surface>
part_outline_surface(std::vector<surface>* surfaces_to_cut,
const point n) {
cout << "Computing part outline surface" << endl;
vector<surface> vertical_surfs =
select(*surfaces_to_cut,
[n](const surface& s)
{ return s.orthogonal_to(n, 0.01); });
cout << "# of vertical surfaces in " << n << " = " << vertical_surfs.size() << endl;
vector<vector<unsigned>> merge_groups =
connected_components_by(vertical_surfs, [](const surface& l, const surface& r)
{ return surfaces_share_edge(l, r); });
if (merge_groups.size() == 1) {
return merge_surfaces(vertical_surfs);
} else {
cout << "More than 1 vertical component" << endl;
vector<surface> merged = merge_surface_groups(vertical_surfs, merge_groups);
vector<surface> outer_surfs =
partial_order_maxima(merged, [](const surface& l, const surface& r)
{ return vertical_contained_by(l, r); });
cout << "# of merged surfaces = " << merged.size() << endl;
cout << "# of outer surfaces = " << outer_surfs.size() << endl;
if (outer_surfs.size() == 1) {
return outer_surfs.front();
} else {
return boost::none;
}
}
return boost::none;
}
boost::optional<surface>
part_outline_surface(const triangular_mesh& m,
const point n) {
std::vector<surface> vertical_surfs =
connected_vertical_surfaces(m, n);
boost::optional<surface> outline =
part_outline_surface(&vertical_surfs, n);
return outline;
// vector<surface> surfs = surfaces_to_cut(m);
// return part_outline_surface(&surfs, n);
}
// TODO: Need to add normal vectors, how to match this with
// the code in make_fixture_plan?
boost::optional<oriented_polygon>
part_outline(std::vector<surface>* surfaces_to_cut) {
point n(0, 0, 1);
auto m = part_outline_surface(surfaces_to_cut, n);
if (m) {
vector<oriented_polygon> outlines =
mesh_bounds((*m).index_list(), (*m).get_parent_mesh());
if (outlines.size() == 2) {
vector<surface> vertical_surfs{*m};
remove_contained_surfaces(vertical_surfs, *surfaces_to_cut);
return outlines.front();
}
}
return boost::none;
}
std::vector<surface> surfaces_to_cut(const triangular_mesh& part) {
auto inds = part.face_indexes();
return surfaces_to_cut(inds, part);
}
std::vector<surface> surfaces_to_cut(const std::vector<index_t>& indexes,
const triangular_mesh& part) {
vector<index_t> inds = indexes;
double normal_degrees_delta = 30.0;
vector<vector<index_t>> delta_regions =
normal_delta_regions_greedy(inds, part, normal_degrees_delta);
vector<surface> surfaces;
for (auto r : delta_regions) {
surfaces.push_back(surface(&part, r));
}
return surfaces;
}
bool
share_edge(const std::vector<gca::edge>& edges,
const surface& l,
const surface& r) {
vector<gca::edge> l_es = edges;
delete_if(l_es,
[l](const gca::edge e) { return !(l.contains(e.l) && l.contains(e.r)); });
vector<gca::edge> r_es = edges;
delete_if(r_es,
[r](const gca::edge e) { return !(r.contains(e.l) && r.contains(e.r)); });
return intersection(l_es, r_es).size() > 0;
}
std::vector<surface_group>
convex_surface_groups(const std::vector<surface*>& surfaces) {
if (surfaces.size() == 0) { return {}; }
vector<gca::edge> conv_edges = convex_edges(surfaces.front()->get_parent_mesh());
cout << "# of convex edges = " << conv_edges.size() << endl;
auto ccs =
connected_components_by(surfaces,
[&conv_edges](const surface* l, const surface* r)
{ return share_edge(conv_edges, *l, *r); });
return ccs;
}
std::vector<surface>
constant_orientation_subsurfaces(const surface& surf) {
vector<index_t> inds = surf.index_list();
std::vector<std::vector<index_t> > regions =
normal_delta_regions(inds, surf.get_parent_mesh(), 3.0);
std::vector<surface> surfs;
for (auto r : regions) {
surfs.push_back(surface(&surf.get_parent_mesh(), r));
}
return surfs;
}
std::vector<surface>
inds_to_surfaces(const std::vector<std::vector<index_t>> regions,
const triangular_mesh& m) {
vector<surface> sfs;
for (auto r : regions) {
sfs.push_back(surface(&m, r));
}
return sfs;
}
std::vector<std::vector<index_t>>
surfaces_to_inds(const std::vector<surface>& surfs) {
std::vector<std::vector<index_t>> inds;
for (auto s : surfs) {
inds.push_back(s.index_list());
}
return inds;
}
std::vector<surface>
connected_vertical_surfaces(std::vector<index_t>& inds,
const triangular_mesh& m,
const point n) {
delete_if(inds, [m, n](const index_t i)
{ return !within_eps(angle_between(n, m.face_orientation(i)), 90, 2.0); });
vector<vector<index_t>> regions = connect_regions(inds, m);
return inds_to_surfaces(regions, m);
}
std::vector<surface>
connected_vertical_surfaces(const triangular_mesh& m, const point n) {
vector<index_t> inds = m.face_indexes();
return connected_vertical_surfaces(inds, m, n);
}
boost::optional<surface>
mesh_top_surface(const triangular_mesh& m, const point n) {
auto surfs = outer_surfaces(m);
cout << "Outer surfaces" << endl;
//vtk_debug_highlight_inds(surfs);
delete_if(surfs,
[n](const surface& s) { return !s.parallel_to(n, 1.0); });
cout << "Base surfaces = " << endl;
//vtk_debug_highlight_inds(surfs);
if (surfs.size() > 0) {
return merge_surfaces(surfs);
} else {
return boost::none;
}
}
std::vector<gca::edge>
shared_edges(const surface& r, const surface& l) {
return intersection(r.edges(), l.edges());
}
point normal(const surface& s) {
return s.face_orientation(s.front());
}
std::vector<gca::edge>
boundary_edges(const surface& s) {
std::vector<gca::edge> bound_edges;
for (auto e : s.get_parent_mesh().edges()) {
auto l_face_neighbors = s.get_parent_mesh().vertex_face_neighbors(e.l);
auto r_face_neighbors = s.get_parent_mesh().vertex_face_neighbors(e.r);
auto face_neighbors = intersection(l_face_neighbors, r_face_neighbors);
bool contains_some_neighbors = false;
bool contains_all_neighbors = true;
for (auto facet : face_neighbors) {
if (s.contains(facet)) {
contains_some_neighbors = true;
} else {
contains_all_neighbors = false;
}
}
if (contains_some_neighbors && !contains_all_neighbors) {
bound_edges.push_back(e);
}
}
return bound_edges;
}
plane surface_plane(const surface& s) {
triangle t = s.face_triangle(s.front());
return plane(t.normal, t.v1);
}
surface find_surface_by_normal(const std::vector<surface>& surfs,
const point n) {
auto r = find_if(begin(surfs), end(surfs),
[n](const surface& s)
{ return within_eps(angle_between(normal(s), n), 0, 1.0); });
DBG_ASSERT(r != end(surfs));
return *r;
}
std::vector<gca::edge>
orthogonal_boundary_edges(const surface& s,
const point n) {
vector<gca::edge> edges;
for (auto e : boundary_edges(s)) {
point ev = s.vertex(e.l) - s.vertex(e.r);
if (within_eps(angle_between(ev, n), 90.0, 1.0)) {
edges.push_back(e);
}
}
return edges;
}
double max_in_dir(const surface& mesh,
const point dir) {
return max_distance_along(mesh.vertex_list(), dir);
}
double min_in_dir(const surface& mesh,
const point dir) {
return min_distance_along(mesh.vertex_list(), dir);
}
point max_point_in_dir(const surface& mesh,
const point dir) {
return max_along(mesh.vertex_list(), dir);
}
point min_point_in_dir(const surface& mesh,
const point dir) {
return min_along(mesh.vertex_list(), dir);
}
bool share_orthogonal_valley_edge(const surface& l, const surface& r) {
vector<shared_edge> shared =
all_shared_edges(l.index_list(), r.index_list(), l.get_parent_mesh());
for (auto s : shared) {
if (is_valley_edge(s, l.get_parent_mesh()) &&
angle_eps(s, l.get_parent_mesh(), 90.0, 0.5)) {
return true;
}
}
return false;
}
std::vector<plane> max_area_basis(const std::vector<surface>& surfaces) {
DBG_ASSERT(surfaces.size() > 0);
vector<surface> sorted_part_surfaces = surfaces;
sort(begin(sorted_part_surfaces), end(sorted_part_surfaces),
[](const surface& l, const surface& r)
{ return l.surface_area() > r.surface_area(); });
vector<surface> basis =
take_basis(sorted_part_surfaces,
[](const surface& l, const surface& r)
{ return within_eps(angle_between(normal(l), normal(r)), 90, 2.0); },
2);
vector<plane> planes;
for (auto s : basis) {
cout << "surface normal = " << normal(s) << endl;
//vtk_debug_highlight_inds(s);
planes.push_back(plane(normal(s), s.face_triangle(s.front()).v1));
}
point third_vec = cross(planes[0].normal(), planes[1].normal());
const triangular_mesh& m = surfaces.front().get_parent_mesh();
point third_pt = max_point_in_dir(m, third_vec);
planes.push_back(plane(third_vec, third_pt));
return planes;
}
bool share_non_fully_concave_edge(const surface& l, const surface& r) {
vector<shared_edge> shared =
all_shared_edges(l.index_list(), r.index_list(), l.get_parent_mesh());
for (auto s : shared) {
if (is_valley_edge(s, l.get_parent_mesh())) {
return true;
} else if (angle_between_normals(s, l.get_parent_mesh()) < 70.0) {
return true;
}
}
return false;
}
}
| 31.140426 | 147 | 0.651544 | dillonhuff |
49ecb46ee50dbfe0409ac4c3e236191c2c1bb7cd | 3,734 | cpp | C++ | Codes/CodeForces/B/1436B.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Codes/CodeForces/B/1436B.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Codes/CodeForces/B/1436B.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | /*************************************************************************
SPDX-License-Identifier: MIT
Copyright (c) 2020 Qazi Fahim Farhan (@fahimfarhan)
May the CodeForces be with you!
************************************************************************/
/**
// ⢀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⣠⣤⣶⣶ ⠄⠄⠄⠄⠄⠄⢴⡶⣶⣶⣶⡒⣶⣶⣖⠢⡄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⢀⣠⣾⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⣠⣤⣶⣶ ⠄⠄⠄⠄⠄⠄⢠⣿⣋⣿⣿⣉⣿⣿⣯⣧⡰⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⢰⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⣿⣿⣹⣿⣿⣏⣿⣿⡗⣿⣿⠁⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣧⣀⣀⣾⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠟⡛⣉⣭⣭⣭⠌⠛⡻⢿⣿⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⡏⠉⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⣤⡌⣿⣷⣯⣭⣿⡆⣈⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⠀⠀⠀⠈⠛⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠿⠛⠉⠁⠀⣿ ⠄⠄⠄⠄⠄⠄⠄⢻⣿⣿⣿⣿⣿⣿⣿⣷⢛⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣧⡀⠀⠀⠀⠀⠙⠿⠿⠿⠻⠿⠿⠟⠿⠛⠉⠀⠀⠀⠀⠀⣸⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢻⣷⣽⣿⣿⣿⢿⠃⣼⣧⣀⠄⠄⠄⠄⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣿⣷⣄⠀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢀⣴⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⠄⠄⣛⣻⣿⠟⣀⡜⣻⢿⣿⣿⣶⣤⡀⠄⠄⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⠏⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠠⣴⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢠⣤⣀⣨⣥⣾⢟⣧⣿⠸⣿⣿⣿⣿⣿⣤⡀⠄⠄⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⡟⠀⠀⢰⣹⡆⠀⠀⠀⠀⠀⠀⣭⣷⠀⠀⠀⠸⣿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⠄⢟⣫⣯⡻⣋⣵⣟⡼⣛⠴⣫⣭⣽⣿⣷⣭⡻⣦⡀⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠈⠉⠀⠀⠤⠄⠀⠀⠀⠉⠁⠀⠀⠀⠀⢿⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⢰⣿⣿⣿⢏⣽⣿⢋⣾⡟⢺⣿⣿⣿⣿⣿⣿⣷⢹⣷⠄
// ⣿⣿⣿⣿⣿⣿⣿⣿⢾⣿⣷⠀⠀⠀⠀⡠⠤⢄⠀⠀⠀⠠⣿⣿⣷⠀⢸⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢣⣿⣿⣿⢸⣿⡇⣾⣿⠏⠉⣿⣿⣿⡇⣿⣿⡆
// ⣿⣿⣿⣿⣿⣿⣿⣿⡀⠉⠀⠀⠀⠀⠀⢄⠀⢀⠀⠀⠀⠀⠉⠉⠁⠀⠀⣿⣿⣿ ⠄⠄⠄⠄⠄⠄⠄⣿⣿⣿⢸⣿⣿⣿⠸⣿⡇⣿⣿⡆⣼⣿⣿⣿⡇⣿⣿⡇
// ⣿⣿⣿⣿⣿⣿⣿⣿⣧⠀⠀⠀⠀⠀⠀⠀⠈⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢹⣿⣿ ⠇⢀⠄⠄⠄⠄⠄⠘⣿⣿⡘⣿⣿⣷⢀⣿⣷⣿⣿⡿⠿⢿⣿⣿⡇⣩⣿⡇
// ⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿ ⣿⣿⠃⠄⠄⠄⠄⠄⠄⢻⣷⠙⠛⠋⣿⣿⣿⣿⣿⣷⣶⣿⣿⣿⡇⣿⣿⡇
*/
#include <iostream>
#include <climits> // this includes INT_MIN, INT_MAX, ... ...
// #include <sstream>
// #include <cstdio>
// #include <cmath>
// #include <cstring>
// #include <cctype>
// #include <string>
#include <vector>
// #include <list>
// #include <set>
// #include <unordered_set>
// #include <map>
// #include <unordered_map>
// #include <queue>
// #include <stack>
#include <algorithm>
// #include <functional>
#include <iomanip> // std::setprecision
using namespace std;
#define PI 2*acos(0)
//typedef long long int ll;
#define ll long long int
// other popular ones=> int64_t, uint64_t => use for 10^18
ll MOD = 1e9+7;
// int n,m;
vector<int> *g;
bool *isvisited;
void start() {}
void FastIO() {
// freopen("input.txt","r",stdin);
// freopen("output.txt","w",stdout);
/*
std::cout << std::fixed;
std::cout << std::setprecision(10);
cout << num1 << endl;
*/
ios_base::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
/*
---------- Interactive problems ---------
on each interactive questions' end, add `cout.flush()`
say, cout<<"some weirdo question";
cout<<"\n"; // end of question
cout.flush(); // <-- just like this
if still confusing, check out 1363D.cpp
*/
}
bool isPrime[1000];
vector<int> primes;
void preprocess() {
for(int i=0; i<1000; i++) { isPrime[i] = true; }
isPrime[0] = false; isPrime[1] = false;
for(int j=4; j<1000; j+=2) {
isPrime[j] = false;
}
for(int j=3; j<1000; j+=2) {
for(int i=2*j; i<1000; i+=j) {
isPrime[i] = false;
}
}
for(int i=0; i<1000; i++) {
if(isPrime[i]) { primes.push_back(i); }
}
}
int main(int argc, char const *argv[]){
/* code */
FastIO();
preprocess();
int t, n;
int **a;
cin>>t;
while (t--) {
cin>>n;
a = new int*[n+1];
for(int i=0; i<n; i++) { a[i] = new int[n+1]; }
int specialNumber = 0;
for(int i=n; i<1000; i++) {
if(isPrime[i]) {
int somePrime = i;
int x = n - 1;
int y = somePrime - x;
if(!isPrime[y]) {
specialNumber = y;
break;
}
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
if(i == j) {
a[i][j] = specialNumber;
}else{
a[i][j] = 1;
}
}
}
for(int i=0; i<n; i++) {
for(int j=0; j<n; j++) {
cout<<a[i][j]<<" ";
}cout<<"\n";
}
for(int i=0; i<n; i++) { delete[] a[i]; }
delete[] a;
}
return 0;
} | 23.192547 | 74 | 0.369041 | fahimfarhan |
49ee10a0eaea9ab4add5e5303cb60379b4cde470 | 10,973 | cc | C++ | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | tests/visqol_api_test.cc | bartvanerp/visqol | 9115ad9dbc29ae5f9cc5a55d2bb07befce2153cb | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC, Andrew Hines
//
// 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 "visqol_api.h"
#include "gtest/gtest.h"
#include "google/protobuf/stubs/status.h"
#include "audio_signal.h"
#include "commandline_parser.h"
#include "conformance.h"
#include "file_path.h"
#include "misc_audio.h"
#include "similarity_result.pb.h" // Generated by cc_proto_library rule
#include "visqol_config.pb.h" // Generated by cc_proto_library rule
namespace Visqol {
namespace {
const size_t kSampleRate = 48000;
const size_t kUnsupportedSampleRate = 44100;
const double kTolerance = 0.0001;
const char kContrabassoonRef[] =
"testdata/conformance_testdata_subset/contrabassoon48_stereo.wav";
const char kContrabassoonDeg[] =
"testdata/conformance_testdata_subset/contrabassoon48_stereo_24kbps_aac.wav";
const char kCleanSpeechRef[] =
"testdata/clean_speech/CA01_01.wav";
const char kCleanSpeechDeg[] =
"testdata/clean_speech/transcoded_CA01_01.wav";
const char kNoSampleRateErrMsg[] =
"INVALID_ARGUMENT:Audio info must be supplied for config.";
const char kNonExistantModelFile[] = "non_existant.txt";
const char kNonExistantModelFileErrMsg[] =
"INVALID_ARGUMENT:Failed to load the SVR model file: non_existant.txt";
const char kNon48kSampleRateErrMsg[] =
"INVALID_ARGUMENT:Currently, 48k is the only sample rate supported by "
"ViSQOL Audio. See README for details of overriding.";
// These values match the known version.
const double kContrabassoonVnsim = 0.90758;
const double kContrabassoonFvnsim[] = {
0.884680, 0.925437, 0.980274, 0.996635, 0.996060, 0.979772, 0.984409,
0.986112, 0.977326, 0.982975, 0.958038, 0.971650, 0.964743, 0.959870,
0.959018, 0.954554, 0.967928, 0.962373, 0.940116, 0.865323, 0.851010,
0.856138, 0.852182, 0.825574, 0.791404, 0.805591, 0.779993, 0.789653,
0.805530, 0.786122, 0.823594, 0.878549
};
const double kCA01_01AsAudio = 2.0003927800390828;
const double kPerfectScore = 5.0;
const double kCA01_01UnscaledPerfectScore = 4.456782;
/**
* Happy path test for the ViSQOL API with a model file specified.
*/
TEST(VisqolApi, happy_path_specified_model) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kConformanceContrabassoon24aac, sim_result.moslqo(), kTolerance);
ASSERT_NEAR(kContrabassoonVnsim, sim_result.vnsim(), kTolerance);
for (int i = 0; i < sim_result.fvnsim_size(); i++) {
ASSERT_NEAR(kContrabassoonFvnsim[i], sim_result.fvnsim(i), kTolerance);
}
}
/**
* Happy path test for the ViSQOL API with the default model file used.
*/
TEST(VisqolApi, happy_path_default_model) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kContrabassoonDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API without specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kConformanceContrabassoon24aac, sim_result.moslqo(), kTolerance);
ASSERT_NEAR(kContrabassoonVnsim, sim_result.vnsim(), kTolerance);
for (int i = 0; i < sim_result.fvnsim_size(); i++) {
ASSERT_NEAR(kContrabassoonFvnsim[i], sim_result.fvnsim(i), kTolerance);
}
}
/**
* Test calling the ViSQOL API without sample rate data for the input signals.
*/
TEST(VisqolApi, no_sample_rate_info) {
// Create the API with no sample rate data.
VisqolConfig config;
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(!result.ok());
ASSERT_EQ(kNoSampleRateErrMsg, result.ToString());
}
/**
* Test calling the ViSQOL API with an unsupported sample rate and the 'allow
* unsupported sample rates' override set to false.
*/
TEST(VisqolApi, unsupported_sample_rate_no_override) {
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kUnsupportedSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_FALSE(result.ok());
ASSERT_EQ(kNon48kSampleRateErrMsg, result.ToString());
}
/**
* Test calling the ViSQOL API with an unsupported sample rate and the 'allow
* unsupported sample rates' override set to true.
*/
TEST(VisqolApi, unsupported_sample_rate_with_override) {
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kUnsupportedSampleRate);
config.mutable_options()->set_allow_unsupported_sample_rates(true);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(result.ok());
}
/**
* Test calling the ViSQOL API with a model file specified that does not exist.
*/
TEST(VisqolApi, non_existant_mode_file) {
// Create the API with no sample rate data.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(kNonExistantModelFile);
VisqolApi visqol;
auto result = visqol.Create(config);
ASSERT_TRUE(!result.ok());
ASSERT_EQ(kNonExistantModelFileErrMsg, result.ToString());
}
/**
* Confirm that when running the ViSQOL API with speech mode disabled (even
* with the 'use unscaled mapping' bool set to true), the input files will be
* compared as audio.
*/
TEST(VisqolApi, speech_mode_disabled) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechDeg));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(false);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(true);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kCA01_01AsAudio, sim_result.moslqo(), kTolerance);
}
/**
* Test the ViSQOL API running in speech mode. Use the same file for both the
* reference and degraded signals and run in scaled mode. A perfect score of
* 5.0 is expected.
*/
TEST(VisqolApi, speech_mode_with_scaled_mapping) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(true);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(false);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kPerfectScore, sim_result.moslqo(), kTolerance);
}
/**
* Test the ViSQOL API running in speech mode. Use the same file for both the
* reference and degraded signals and run in unscaled mode. A score of 4.x is
* expected.
*/
TEST(VisqolApi, speech_mode_with_unscaled_mapping) {
// Build reference and degraded Spans.
AudioSignal ref_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
AudioSignal deg_signal = MiscAudio::LoadAsMono(FilePath(kCleanSpeechRef));
auto ref_data = ref_signal.data_matrix.ToVector();
auto deg_data = deg_signal.data_matrix.ToVector();
auto ref_span = absl::Span<double>(ref_data);
auto deg_span = absl::Span<double>(deg_data);
// Now call the API, specifying the model file location.
VisqolConfig config;
config.mutable_audio()->set_sample_rate(kSampleRate);
config.mutable_options()->set_svr_model_path(FilePath::currentWorkingDir() +
kDefaultAudioModelFile);
config.mutable_options()->set_use_speech_scoring(true);
config.mutable_options()->set_use_unscaled_speech_mos_mapping(true);
VisqolApi visqol;
auto create_status = visqol.Create(config);
ASSERT_TRUE(create_status.ok());
auto result = visqol.Measure(ref_span, deg_span);
ASSERT_TRUE(result.ok());
auto sim_result = result.ValueOrDie();
ASSERT_NEAR(kCA01_01UnscaledPerfectScore, sim_result.moslqo(), kTolerance);
}
} // namespace
} // namespace Visqol
| 37.707904 | 80 | 0.760868 | bartvanerp |
49ef9412b35915c185181db579fbfde345c49114 | 4,891 | cpp | C++ | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | ARPREC/arprec-2.2.13/src/div.cpp | paveloom-p/P3 | 57df3b6263db81685f137a7ed9428dbd3c1b4a5b | [
"Unlicense"
] | null | null | null | /*
* src/mpreal.cc
*
* This work was supported by the Director, Office of Science, Division
* of Mathematical, Information, and Computational Sciences of the
* U.S. Department of Energy under contract number DE-AC03-76SF00098.
*
* Copyright (c) 2002
*
*/
#include <arprec/mp_real.h>
#include "small_inline.h"
using std::cerr;
using std::endl;
void mp_real::mpdiv(const mp_real& a, const mp_real& b, mp_real& c, int prec_words)
{
/**
* This divides the MP number A by the MP number B to yield the MP
* quotient C. For extra high levels of precision, use MPDIVX.
* Debug output starts with debug_level = 8.
*
* The algorithm is by long division.
*/
int i, ia, ib, ij, is, i2, i3=0, j, j3, na, nb, nc, BreakLoop;
double rb, ss, t0, t1, t2, t[2];
double* d;
if (error_no != 0) {
if (error_no == 99) mpabrt();
zero(c);
return;
}
if (debug_level >= 8) {
print_mpreal("MPDIV a ", a);
print_mpreal("MPDIV b ", b);
}
ia = (a[1] >= 0 ? 1 : -1);
ib = (b[1] >= 0 ? 1 : -1);
na = std::min (int(std::abs(a[1])), prec_words);
nb = std::min (int(std::abs(b[1])), prec_words);
// Check if dividend is zero.
if (na == 0) {
zero(c);
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
if (nb == 1 && b[FST_M] == 1.) {
// Divisor is 1 or -1 -- result is A or -A.
c[1] = sign(na, ia * ib);
c[2] = a[2] - b[2];
for (i = FST_M; i < na+FST_M; ++i) c[i] = a[i];
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
// Check if divisor is zero.
if (nb == 0) {
if (MPKER[31] != 0) {
cerr << "*** MPDIV: Divisor is zero." << endl;
error_no = 31;
if (MPKER[error_no] == 2) mpabrt();
}
return;
}
//need the scratch space now...
d = new double[prec_words+9];
int d_add=0;
d++; d_add--;
// Initialize trial divisor and trial dividend.
t0 = mpbdx * b[3];
if (nb >= 2) t0 = t0 + b[4];
if (nb >= 3) t0 = t0 + mprdx * b[5];
rb = 1.0 / t0;
d[0] = d[1] = 0.0;
for (i = 2; i < na+2; ++i) d[i] = a[i+1];
for (/*i = na+2*/; i <= prec_words+7; ++i) d[i] = 0.0;
// Perform ordinary long division algorithm. First compute only the first
// NA words of the quotient.
for (j = 2; j <= na+1; ++j) {
t1 = mpbx2 * d[j-1] + mpbdx * d[j] + d[j+1];
t0 = AINT (rb * t1); // trial quotient, approx is ok.
j3 = j - 3;
i2 = std::min (nb, prec_words + 2 - j3) + 2;
ij = i2 + j3;
for (i = 3; i <= i2; ++i) {
i3 = i + j3;
t[0] = mp_two_prod(t0, b[i], t[1]);
d[i3-1] -= t[0]; // >= -(2^mpnbt-1), <= 2^mpnbt-1
d[i3] -= t[1];
}
// Release carry to avoid overflowing the exact integer capacity
// (2^52-1) of a floating point word in D.
if(!(j & (mp::mpnpr-1))) { // assume mpnpr is power of two
t2 = 0.0;
for(i=i3;i>j+1;i--) {
t1 = t2 + d[i];
t2 = int (t1 * mprdx); // carry <= 1
d[i] = t1 - t2 * mpbdx; // remainder of t1 * 2^(-mpnbt)
}
d[i] += t2;
}
d[j] += mpbdx * d[j-1];
d[j-1] = t0; // quotient
}
// Compute additional words of the quotient, as long as the remainder
// is nonzero.
BreakLoop = 0;
for (j = na+2; j <= prec_words+3; ++j) {
t1 = mpbx2 * d[j-1] + mpbdx * d[j];
if (j < prec_words + 3) t1 += d[j+1];
t0 = AINT (rb * t1); // trial quotient, approx is ok.
j3 = j - 3;
i2 = std::min (nb, prec_words + 2 - j3) + 2;
ij = i2 + j3;
ss = 0.0;
for (i = 3; i <= i2; ++i) {
i3 = i + j3;
t[0] = mp_two_prod(t0, b[i], t[1]);
d[i3-1] -= t[0]; // >= -(2^mpnbt-1), <= 2^mpnbt-1
d[i3] -= t[1];
//square to avoid cancellation when d[i3] or d[i3-1] are negative
ss += sqr (d[i3-1]) + sqr (d[i3]);
}
// Release carry to avoid overflowing the exact integer capacity
// (2^mpnbt-1) of a floating point word in D.
if(!(j & (mp::mpnpr-1))) { // assume mpnpr is power of two
t2 = 0.0;
for(i=i3;i>j+1;i--) {
t1 = t2 + d[i];
t2 = int (t1 * mprdx); // carry <= 1
d[i] = t1 - t2 * mpbdx; // remainder of t1 * 2^(-mpnbt)
}
d[i] += t2;
}
d[j] += mpbdx * d[j-1];
d[j-1] = t0;
if (ss == 0.0) {
BreakLoop = 1;
break;
}
if (ij <= prec_words+1) d[ij+3] = 0.0;
}
// Set sign and exponent, and fix up result.
if(!BreakLoop) j--;
d[j] = 0.0;
if (d[1] == 0.0) {
is = 1;
d--; d_add++;
} else {
is = 2;
d-=2; d_add+=2;
//for (i = j+1; i >= 3; --i) d[i] = d[i-2];
}
nc = std::min( (int(c[0])-FST_M-2), std::min (j-1, prec_words));
d[1] = ia+ib ? nc : -nc;//sign(nc, ia * ib);
d[2] = a[2] - b[2] + is - 2;
mpnorm(d, c, prec_words);
delete [] (d+d_add);
if (debug_level >= 8) print_mpreal("MPDIV O ", c);
return;
}
| 26.015957 | 83 | 0.491924 | paveloom-p |
49f4cbdf6382fce666081e78703ca70c4dd019a7 | 784 | cc | C++ | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 67 | 2015-03-30T19:56:16.000Z | 2022-03-11T13:52:17.000Z | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 5 | 2015-04-15T17:17:33.000Z | 2016-02-11T00:40:17.000Z | code/render/physics/physx/physxhinge.cc | gscept/nebula-trifid | e7c0a0acb05eedad9ed37a72c1bdf2d658511b42 | [
"BSD-2-Clause"
] | 34 | 2015-03-30T15:08:00.000Z | 2021-09-23T05:55:10.000Z | //------------------------------------------------------------------------------
// physics/physx/physxhinge.cc
// (C) 2016 Individual contributors, see AUTHORS file
//------------------------------------------------------------------------------
#include "stdneb.h"
#include "physics/physx/physxhinge.h"
#include "extensions/PxRevoluteJoint.h"
#include "physxutils.h"
#include "PxRigidDynamic.h"
#include "physxphysicsserver.h"
using namespace physx;
namespace PhysX
{
__ImplementClass(PhysX::PhysXHinge, 'PXHI', Physics::BaseHinge);
//------------------------------------------------------------------------------
/**
*/
PhysXHinge::PhysXHinge()
{
}
//------------------------------------------------------------------------------
/**
*/
PhysXHinge::~PhysXHinge()
{
}
} | 21.189189 | 80 | 0.423469 | gscept |
49f60a5116002e89286182579b4e0810935303c2 | 1,228 | cpp | C++ | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | 1 | 2021-07-16T19:59:39.000Z | 2021-07-16T19:59:39.000Z | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | gym/101992/E.cpp | albexl/codeforces-gym-submissions | 2a51905c50fcf5d7f417af81c4c49ca5217d0753 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#ifdef DGC
#include "debug.h"
#else
#define debug(...) 9715;
#endif
typedef long long ll;
typedef long double ld;
typedef complex<double> point;
#define F first
#define S second
const int mod = 1e9+7;
int dp[205][205][205];
void add(int &x, int y)
{
x += y;
if (x >= mod)
x -= mod;
}
int solve(int n, int k)
{
memset(dp, 0, sizeof dp);
dp[0][1][0] = 1;
dp[0][1][1] = mod-1;
for (int i = 0; i < n; ++i)
for (int j = 1; j <= k; ++j)
for (int g = 0; g <= n; ++g)
{
if (g) add(dp[i][j][g], dp[i][j][g-1]);
if (j < k && g > 0)
{
add(dp[i+1][j+1][0], dp[i][j][g]);
add(dp[i+1][j+1][g], mod-dp[i][j][g]);
}
int l = n-i - g;
if (l > 0)
{
add(dp[i+1][1][g], dp[i][j][g]);
add(dp[i+1][1][g+l], mod-dp[i][j][g]);
}
}
int ans = 0;
for (int j = 1; j <= k; ++j)
add(ans, dp[n][j][0]);
return ans;
}
int main()
{
#ifdef DGC
//freopen("b.out", "w", stdout);
#endif
freopen("permutations.in", "r", stdin);
ios_base::sync_with_stdio(0), cin.tie(0);
int t;
cin >> t;
while (t--)
{
int n, k;
cin >> n >> k;
int ans = solve(n, k);
add(ans, mod-solve(n, k-1));
cout << ans << "\n";
}
return 0;
} | 15.948052 | 43 | 0.491042 | albexl |
49f60d43e9221a504275798879416b7184455f33 | 1,496 | cpp | C++ | Codes/other-ojs/CoderByte/Min Window Substring.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 3 | 2019-07-20T07:26:31.000Z | 2020-08-06T09:31:09.000Z | Codes/other-ojs/CoderByte/Min Window Substring.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | null | null | null | Codes/other-ojs/CoderByte/Min Window Substring.cpp | fahimfarhan/legendary-coding-odyssey | 55289e05aa04f866201c607bed00c505cd9c4df9 | [
"MIT"
] | 4 | 2019-06-20T18:43:32.000Z | 2020-10-07T16:45:23.000Z | #include <bits/stdc++.h>
using namespace std;
string MinWindowSubstring(string strArr[]) {
// code goes here
string s1 = strArr[0];
string s2 = strArr[1];
int n = s1.size();
int k = s2.size();
bool mark[n];
for(int i=0; i<n; i++){ mark[i] = false; }
for(int i=0; i<k; i++){
for(int j=0; j<n; j++){
if(s2[i] == s1[j] ){ mark[j] = true; }
}
}
vector<int> v;
for(int i=0; i<n;i++){ if(mark[i]){ v.push_back(i); } }
string minimus = s1;
for(int i=0; i<n-1; i++){
for(int j=i+1; j<n; j++){
string temp =s1.substr(i,j);
string temp2 = temp;
bool b1 = true, b2 = false;
for(int l=0; l<k; l++){
if(!b1){ break; }
b2 = false;
for(int i1 = 0; i1 < temp.size(); i1++){
if(temp[i1] == s2[l]){
temp[i1] = 'A'; b2 = true; break;
}
}
if(b2 == false){ b1 = false; }
}
if(b1){
// candidate found!
if(temp2.size() < minimus.size() ){ minimus = ""; minimus = temp2; }
}
}
}
return minimus;
}
int main() {
// keep this function call here
/* Note: In C++ you first have to initialize an array and set
it equal to the stdin to test your code with arrays. */
string A[] = gets(stdin);
cout << MinWindowSubstring(A);
return 0;
}
| 23.375 | 82 | 0.439171 | fahimfarhan |
49fb38c602c085be86930fd73b24413649ccc5c3 | 1,010 | cpp | C++ | SPOJBR/BOMBA12.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | SPOJBR/BOMBA12.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | SPOJBR/BOMBA12.cpp | ggml1/Competitive-Programming | 1f5aa8f8d2f8addffd5a22c9ccd998f05b6faf79 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int N = 501;
const long long inf = 1e18;
int n, e, s, m;
vector<int> adj[3 * N];
long long dist[3 * N];
void bfs(int e){
queue<int> trr;
dist[e] = 0;
trr.push(e);
while(!trr.empty()){
int u = trr.front();
trr.pop();
for(auto k : adj[u]){
if(dist[k] == inf){
dist[k] = dist[u] + 1;
trr.push(k);
}
}
}
}
void cl(){
for(int i = 0; i < 3 * N; ++i){
dist[i] = inf;
}
}
inline int node(int x){
return 3 * x;
}
int main(){
ios::sync_with_stdio(0); cin.tie(0);
cin >> n >> e >> s >> m;
for(int i = 0; i < m; ++i){
int a, b, t; cin >> a >> b >> t;
if(t){
adj[node(a)].push_back(node(b) + 1);
} else{
adj[node(a) + 1].push_back(node(b) + 2);
adj[node(a) + 2].push_back(node(b));
}
}
cl();
bfs(node(e));
if(dist[node(s)] == inf && dist[node(s) + 1] == inf && dist[node(s) + 2] == inf) cout << "*" << endl;
else cout << min(dist[node(s)], min(dist[node(s) + 1], dist[node(s) + 2]));
return 0;
} | 15.30303 | 102 | 0.50198 | ggml1 |
b701a409556873b9c54a13de7d60f9f99952ce99 | 996 | cpp | C++ | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 4 | 2018-09-09T13:40:01.000Z | 2022-03-27T10:00:24.000Z | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 3 | 2016-04-02T05:59:43.000Z | 2020-06-27T11:30:40.000Z | src/HTGTweetViewWindow.cpp | HaikuArchives/HaikuTwitter | 61688f53de02820e801dd4126ff3c18b07fdd82f | [
"MIT"
] | 6 | 2017-04-05T20:00:48.000Z | 2020-10-26T08:35:11.000Z | /*
* Copyright 2010 Martin Hebnes Pedersen, martinhpedersen @ "google mail"
* All rights reserved. Distributed under the terms of the MIT License.
*/
#include "HTGTweetViewWindow.h"
HTGTweetViewWindow::HTGTweetViewWindow(BWindow *parent, BList *tweets)
: BWindow(BRect(300, 300, 615, 840), "Tweet Viewer", B_TITLED_WINDOW, B_NOT_H_RESIZABLE)
{
/*Set parent window (used for handeling messages)*/
this->parent = parent;
/*Set up timeline*/
theTimeLine = new HTGTimeLineView(TIMELINE_HDD, Bounds(), tweets);
this->AddChild(theTimeLine);
}
void
HTGTweetViewWindow::AddList(BList *tweets)
{
theTimeLine->AddList(tweets);
}
void
HTGTweetViewWindow::MessageReceived(BMessage *message)
{
switch (message->what) {
default:
be_app->PostMessage(message);
break;
}
}
bool
HTGTweetViewWindow::QuitRequested()
{
MessageReceived(new BMessage(TWEETVIEWWINDOW_CLOSED));
return true;
}
HTGTweetViewWindow::~HTGTweetViewWindow()
{
theTimeLine->RemoveSelf();
delete theTimeLine;
}
| 20.75 | 89 | 0.75 | HaikuArchives |
8e6616d984cafa0516321ef863e20b641c07371e | 489 | hpp | C++ | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | src/strong-types.hpp | tilnewman/castle-crawl | d9ce84eb0c29b640a1d78cca09ae2f267ba2a777 | [
"CC0-1.0"
] | null | null | null | #ifndef CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
#define CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
//
// strong-types.hpp
//
#include "strong-type.hpp"
namespace castlecrawl
{
// phantom tags
struct ArmorTag;
// strong types
using Armor_t = util::StrongType<int, ArmorTag>;
// user defined literals
inline Armor_t operator"" _armor(unsigned long long armor) { return Armor_t::make(armor); }
} // namespace castlecrawl
#endif // CASTLECRAWL_STRONG_TYPES_HPP_INCLUDED
| 21.26087 | 95 | 0.744376 | tilnewman |
8e68677527d44e93def4cc676de51ef99ce59be9 | 2,098 | cpp | C++ | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | Project/Kross-Engine/Source/Core/Manager/ShaderManager.cpp | Deklyn-Palmer/Kross-Engine-Game | 6ea927a4ef2407334ac3bcb5f80bf82bfe5648be | [
"Apache-2.0"
] | null | null | null | /*
* Author: Deklyn Palmer.
* Editors:
* - Deklyn Palmer.
*/
#include "ShaderManager.h"
namespace Kross
{
ShaderManager* ShaderManager::m_Instance = nullptr;
ShaderManager::~ShaderManager()
{
/* Destroy all the Shaders. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
Shader::OnDestroy(m_Instance->m_Shaders[i]);
m_Instance->m_Shaders[i] = nullptr;
}
/* Clean up Memory. */
m_Instance->m_Shaders.clear();
m_Instance->m_Shaders.~vector();
}
void ShaderManager::OnCreate()
{
if (!m_Instance)
{
m_Instance = KROSS_NEW ShaderManager();
}
}
void ShaderManager::OnDestroy()
{
if (m_Instance)
{
delete m_Instance;
}
}
void ShaderManager::AttachShader(Shader* shader)
{
/* Incase for some reason the Shader doesn't exist. Early out. */
if (!shader)
{
return;
}
/* Check for duplicates. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i] == shader)
{
return;
}
}
/* If no duplicate was found, add it. */
m_Instance->m_Shaders.push_back(shader);
}
void ShaderManager::DetachShader(Shader* shader)
{
/* Incase for some reason the Shader doesn't exist. Early out. */
if (!shader)
{
return;
}
/* Check for Shader. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i] == shader)
{
/* Remove the Shader. */
Shader::OnDestroy(shader);
m_Instance->m_Shaders.erase(m_Instance->m_Shaders.begin() + i);
return;
}
}
}
void ShaderManager::OnReloadShader(Shader* shader)
{
/* Reload the Shader. */
shader = Shader::OnReload(shader);
}
void ShaderManager::OnUpdateShaderVPMatrix(Matrix4 viewMatrix, Matrix4 projectionMatrix)
{
/* Update all Shaders View and Projection Matrix. */
for (int i = 0; i < m_Instance->m_Shaders.size(); i++)
{
if (m_Instance->m_Shaders[i]->GetType() == ShaderType::Standard)
{
m_Instance->m_Shaders[i]->SetUniform("u_View", viewMatrix);
m_Instance->m_Shaders[i]->SetUniform("u_Projection", projectionMatrix);
}
}
}
} | 20.772277 | 89 | 0.639657 | Deklyn-Palmer |
8e6c6fc56ab7225c02517e1a296bdceb1057876e | 15,399 | cpp | C++ | Glop/net/NetworkManager_test.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | 1 | 2016-06-28T18:19:30.000Z | 2016-06-28T18:19:30.000Z | Glop/net/NetworkManager_test.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | null | null | null | Glop/net/NetworkManager_test.cpp | zorbathut/glop | 762d4f1e070ce9c7180a161b521b05c45bde4a63 | [
"BSD-3-Clause"
] | null | null | null | #include <stdio.h>
#include <gtest/gtest.h>
#include "third_party/raknet/RakPeerInterface.h"
#include "third_party/raknet/RakNetworkFactory.h"
#include "NetworkManager.h"
#include "../System.h"
#include "../Thread.h"
#include <set>
using namespace std;
class GlopEnvironment : public testing::Environment {
public:
virtual void SetUp() {
System::Init();
}
};
testing::Environment* const global_env = testing::AddGlobalTestEnvironment(new GlopEnvironment);
class SendDataThread : public Thread {
public:
SendDataThread(NetworkManager* network_manager, GlopNetworkAddress gna, const string& data)
: network_manager_(network_manager),
gna_(gna),
data_(data) {
}
protected:
virtual void Run() {
network_manager_->SendData(gna_, data_);
}
private:
NetworkManager* network_manager_;
GlopNetworkAddress gna_;
const string& data_;
};
// Waits a short time for exactly num_hosts to be established
int WaitForHosts(vector<NetworkManager*> nm, int port, int index, int num_hosts) {
int t = system()->GetTime();
nm[index]->ClearHosts();
while (nm[index]->AvailableHosts().size() != num_hosts && t + 250 > system()->GetTime()) {
for (int i = 0; i < nm.size(); i++) {
nm[i]->Think();
}
system()->Sleep(1);
nm[index]->FindHosts(port);
}
return nm[index]->AvailableHosts().size();
}
int WaitForHosts(NetworkManager* nm, int port, int num_hosts) {
return WaitForHosts(vector<NetworkManager*>(1, nm), port, 0, num_hosts);
}
// Waits a short time and for exactly num_connections to be established
int WaitForConnections(vector<NetworkManager*> nm, int index, int num_connections) {
int t = system()->GetTime();
while (nm[index]->GetConnections().size() != num_connections && t + 250 > system()->GetTime()) {
for (int i = 0; i < nm.size(); i++) {
nm[i]->Think();
}
system()->Sleep(1);
}
return nm[index]->GetConnections().size();
}
int WaitForConnections(NetworkManager* nm, int num_connections) {
return WaitForConnections(vector<NetworkManager*>(1, nm), 0, num_connections);
}
// Waits a short time for num_messages messages to be received
vector<pair<GlopNetworkAddress, string> > WaitForData(NetworkManager* nm, int num_messages) {
int t = system()->GetTime();
vector<pair<GlopNetworkAddress, string> > ret;
while (ret.size() < num_messages && t + 250 > system()->GetTime()) {
nm->Think();
GlopNetworkAddress gna;
string data;
if (nm->ReceiveData(&gna, &data)) {
ret.push_back(pair<GlopNetworkAddress, string>(gna, data));
}
system()->Sleep(1);
}
return ret;
}
// Waits a short time for num_messages messages to be received from a certain person
vector<string> WaitForData(
NetworkManager* nm,
GlopNetworkAddress gna,
int num_messages) {
int t = system()->GetTime();
vector<string> ret;
// We'll wait up to 5 seconds here so that our large packets have lots of time to make it through.
while (ret.size() < num_messages && t + 5000 > system()->GetTime()) {
nm->Think();
string data;
if (nm->ReceiveData(gna, &data)) {
ret.push_back(data);
}
system()->Sleep(1);
}
return ret;
}
// Simply makes sure that a manager closes all of its open connections when it is destroyed.
TEST(NetTest, TestNetworkManagersConstructAndDeconstructProperly) {
{
NetworkManager host;
ASSERT_TRUE(host.Startup(65000));
}
{
NetworkManager host;
ASSERT_TRUE(host.Startup(65000));
}
}
// TODO: This test requires that the computer actually be connceted to a router, perhaps some sort
// of mock router can be created so this isn't required? Raknet would have to have support for this
// sort of thing.
TEST(NetTest, TestMultipleClientsCanConnectToASingleHost) {
NetworkManager host;
host.Startup(65000);
vector<NetworkManager*> clients(5);
for (int i = 0; i < 5; i++) {
clients[i] = new NetworkManager;
clients[i]->Startup(65001 + i);
}
host.StartHosting("foobar thundergun");
for (int i = 0; i < clients.size(); i++) {
ASSERT_EQ(1, WaitForHosts(clients, 65000, i, 1));
}
for (int i = 0; i < clients.size(); i++) {
clients[i]->Connect(clients[i]->AvailableHosts()[0].first);
ASSERT_EQ(1, WaitForConnections(clients, i, 1));
}
ASSERT_EQ(5, WaitForConnections(&host, 5));;
for (int i = 0; i < clients.size(); i++) {
delete clients[i];
}
}
TEST(NetTest, TestClientCanSendMultiplePacketsToHostThatAllArrive) {
NetworkManager host;
host.Startup(65000);
NetworkManager client;
client.Startup(65001);
host.StartHosting("A");
client.FindHosts(65000);
bool host_found = false;
int t = system()->GetTime();
while (!host_found && t + 2000 > system()->GetTime()) {
host.Think();
client.Think();
host_found = client.AvailableHosts().size() == 1;
}
ASSERT_TRUE(host_found) << "Unable to find host.";
vector<pair<GlopNetworkAddress, string> > hosts = client.AvailableHosts();
ASSERT_EQ("A", hosts[0].second);
client.Connect(client.AvailableHosts()[0].first);
ASSERT_EQ(1, WaitForConnections(&client, 1));
ASSERT_EQ(1, WaitForConnections(&host, 1));
GlopNetworkAddress host_gna = hosts[0].first;
client.SendData(host_gna, "foobar");
client.SendData(host_gna, "wingding");
client.SendData(host_gna, "thundergun");
bool data_available = false;
t = system()->GetTime();
while (!data_available && t + 2000 > system()->GetTime()) {
host.Think();
client.Think();
data_available = host.PendingData() == 3;
}
GlopNetworkAddress client_gna = host.GetConnections()[0];
GlopNetworkAddress client_message_gna;
string data;
set<string> data_set;
ASSERT_TRUE(host.ReceiveData(&client_message_gna, &data));
EXPECT_EQ(client_gna.first, client_message_gna.first);
EXPECT_EQ(client_gna.second, client_message_gna.second);
if (data == "foobar" || data == "wingding" || data == "thundergun") {
data_set.insert(data);
}
EXPECT_EQ(1, data_set.size()) << "Unexpected data received";
ASSERT_TRUE(host.ReceiveData(&client_message_gna, &data));
EXPECT_EQ(client_gna.first, client_message_gna.first);
EXPECT_EQ(client_gna.second, client_message_gna.second);
if (data == "foobar" || data == "wingding" || data == "thundergun") {
data_set.insert(data);
}
EXPECT_EQ(2, data_set.size()) << "Unexpected data received";
ASSERT_TRUE(host.ReceiveData(&client_message_gna, &data));
EXPECT_EQ(client_gna.first, client_message_gna.first);
EXPECT_EQ(client_gna.second, client_message_gna.second);
if (data == "foobar" || data == "wingding" || data == "thundergun") {
data_set.insert(data);
}
EXPECT_EQ(3, data_set.size()) << "Unexpected data received";
}
TEST(NetTest, TestClientCanSendVeryLargePacket) {
NetworkManager host;
host.Startup(65000);
NetworkManager client;
client.Startup(65001);
host.StartHosting("A");
client.FindHosts(65000);
bool host_found = false;
int t = system()->GetTime();
while (!host_found && t + 2000 > system()->GetTime()) {
host.Think();
client.Think();
host_found = client.AvailableHosts().size() == 1;
}
ASSERT_TRUE(host_found) << "Unable to find host.";
vector<pair<GlopNetworkAddress, string> > hosts = client.AvailableHosts();
ASSERT_EQ("A", hosts[0].second);
client.Connect(client.AvailableHosts()[0].first);
ASSERT_EQ(1, WaitForConnections(&client, 1));
ASSERT_EQ(1, WaitForConnections(&host, 1));
GlopNetworkAddress host_gna = hosts[0].first;
string large_data(10000000, 'X'); // 10 megs of 'X'
client.SendData(host_gna, large_data);
bool data_available = false;
GlopNetworkAddress client_gna = host.GetConnections()[0];
GlopNetworkAddress client_message_gna;
vector<string> v = WaitForData(&host, client_gna, 1);
ASSERT_EQ(1, v.size());
ASSERT_EQ(large_data.size(), v[0].size()) << "large_data size is " << large_data.size()
<< ", but only " << v[0].size() << " was received.";
for (int i = 0; i < large_data.size(); i++) {
// Don't want to check the whole string otherwise the error message would be a disaster
EXPECT_EQ(large_data[i], v[0][i]);
}
}
/* I think it would be good for send data to be reentrant. It isn't right now, but this would be a
test for it once it is.
TEST(NetTest, TestSendDataIsReentrant) {
NetworkManager host;
host.Startup(65000);
NetworkManager client;
client.Startup(65001);
host.StartHosting("A");
client.FindHosts(65000);
bool host_found = false;
int t = system()->GetTime();
while (!host_found && t + 2000 > system()->GetTime()) {
host.Think();
client.Think();
host_found = client.AvailableHosts().size() == 1;
}
ASSERT_TRUE(host_found) << "Unable to find host.";
vector<pair<GlopNetworkAddress, string> > hosts = client.AvailableHosts();
ASSERT_EQ("A", hosts[0].second);
client.Connect(client.AvailableHosts()[0].first);
ASSERT_EQ(1, WaitForConnections(&client, 1));
ASSERT_EQ(1, WaitForConnections(&host, 1));
int test_size = 1000000;
int num_threads = 5;
vector<Thread*> vt;
vector<string> vs;
for (int i = 0; i < num_threads; i++) {
vs.push_back(string(test_size, 'A' + i));
}
for (int i = 0; i < num_threads; i++) {
vt.push_back(
new SendDataThread(&client, client.AvailableHosts()[0].first, vs[i]));
}
for (int i = 0; i < num_threads; i++) {
vt[i]->Start();
}
for (int i = 0; i < num_threads; i++) {
vt[i]->Join();
}
bool data_available = false;
GlopNetworkAddress client_gna = host.GetConnections()[0];
vector<string> v = WaitForData(&host, client_gna, num_threads);
ASSERT_EQ(num_threads, v.size());
set<char> s;
for (int i = 0; i < v.size(); i++) {
s.insert(v[i][0]);
EXPECT_EQ(test_size, v[i].size());
bool all_equal = true;
for (int j = 0; j < v[i].size(); j++) {
if (v[i][j] != v[i][0]) {
all_equal = false;
break;
}
}
EXPECT_TRUE(all_equal) << "String didn't come through correctly.";
}
}
*/
TEST(NetTest, TestThatStartAndStopHostingWork) {
NetworkManager host;
host.Startup(65000);
NetworkManager client;
client.Startup(65001);
host.StartHosting("host");
ASSERT_EQ(1, WaitForHosts(&client, 65000, 1));
host.StopHosting();
ASSERT_EQ(0, WaitForHosts(&client, 65000, 0));
}
TEST(NetTest, TestMultiplePeersCanSeeEachOther) {
vector<NetworkManager*> c(3);
for (int i = 0; i < c.size(); i++) {
c[i] = new NetworkManager;
c[i]->Startup(65000 + i);
}
c[0]->StartHosting("0");
c[1]->StartHosting("1");
c[2]->StartHosting("2");
ASSERT_EQ(0, WaitForHosts(c, 65000, 0, 0));
ASSERT_EQ(1, WaitForHosts(c, 65001, 0, 1));
EXPECT_EQ("1", c[0]->AvailableHosts()[0].second);
ASSERT_EQ(1, WaitForHosts(c, 65002, 0, 1));
EXPECT_EQ("2", c[0]->AvailableHosts()[0].second);
ASSERT_EQ(1, WaitForHosts(c, 65000, 1, 1));
EXPECT_EQ("0", c[1]->AvailableHosts()[0].second);
ASSERT_EQ(0, WaitForHosts(c, 65001, 1, 0));
ASSERT_EQ(1, WaitForHosts(c, 65002, 1, 1));
EXPECT_EQ("2", c[1]->AvailableHosts()[0].second);
ASSERT_EQ(1, WaitForHosts(c, 65000, 2, 1));
EXPECT_EQ("0", c[2]->AvailableHosts()[0].second);
ASSERT_EQ(1, WaitForHosts(c, 65001, 2, 1));
EXPECT_EQ("1", c[2]->AvailableHosts()[0].second);
ASSERT_EQ(0, WaitForHosts(c, 65002, 2, 0));
for (int i = 0; i < c.size(); i++) {
delete c[i];
}
}
// Create a fully connected graph, then make sure everyone can send messages to everyone else.
TEST(NetTest, TestMultiplePeersCanCommunicateWithEachOther) {
vector<NetworkManager*> peer(5);
for (int i = 0; i < peer.size(); i++) {
peer[i] = new NetworkManager;
peer[i]->Startup(65000 + i);
char buf[16];
sprintf(buf, "%d", i);
string id(buf);
peer[i]->StartHosting(id);
}
// Make a completely connected graph
for (int i = 0; i < peer.size(); i++) {
for (int j = i + 1; j < peer.size(); j++) {
ASSERT_EQ(1, WaitForHosts(peer, 65000 + j, i, 1));
char buf[16];
sprintf(buf, "%d", j);
string id(buf);
EXPECT_EQ(id, peer[i]->AvailableHosts()[0].second);
peer[i]->Connect(peer[i]->AvailableHosts()[0].first);
EXPECT_EQ(j, WaitForConnections(peer, i, j));
}
}
for (int i = 0; i < peer.size(); i++) {
EXPECT_EQ(peer.size() - 1, WaitForConnections(peer, i, peer.size() - 1));
}
// Now each person sends a unique string to everyone else.
vector<string> data(peer.size());
data[0] = "aaaaaaaaaaaaaaaaaaaaa";
data[1] = "foobar thundergun";
data[2] = "1234567890!@#$^&*(),./;'[]";
data[3] = ".";
data[4] = "";
for (int i = 0; i < peer.size(); i++) {
vector<GlopNetworkAddress> connections = peer[i]->GetConnections();
for (int j = 0; j < connections.size(); j++) {
peer[i]->SendData(connections[j], data[i]);
}
}
for (int i = 0; i < peer.size(); i++) {
GlopNetworkAddress gna;
string message;
int count = 0;
vector<pair<GlopNetworkAddress, string> > messages = WaitForData(peer[i], peer.size() - 1);
EXPECT_EQ(peer.size() - 1, messages.size());
for (int j = 0; j < messages.size(); j++) {
// messages[j].first.second is the port that this messages was sent from, so that minus 65000
// will give us an index into data.
EXPECT_EQ(data[messages[j].first.second - 65000], messages[j].second);
}
}
for (int i = 0; i < peer.size(); i++) {
delete peer[i];
}
}
TEST(NetTest, TestMultiplePeersCanCommunicateWithEachOtherWithAlternateReceiveEvents) {
vector<NetworkManager*> peer(5);
for (int i = 0; i < peer.size(); i++) {
peer[i] = new NetworkManager;
peer[i]->Startup(65000 + i);
char buf[16];
sprintf(buf, "%d", i);
string id(buf);
peer[i]->StartHosting(id);
}
// Make a completely connected graph
for (int i = 0; i < peer.size(); i++) {
for (int j = i + 1; j < peer.size(); j++) {
ASSERT_EQ(1, WaitForHosts(peer, 65000 + j, i, 1));
char buf[16];
sprintf(buf, "%d", j);
string id(buf);
EXPECT_EQ(id, peer[i]->AvailableHosts()[0].second);
peer[i]->Connect(peer[i]->AvailableHosts()[0].first);
EXPECT_EQ(j, WaitForConnections(peer, i, j));
}
}
for (int i = 0; i < peer.size(); i++) {
EXPECT_EQ(peer.size() - 1, WaitForConnections(peer, i, peer.size() - 1));
}
// All the connections are on this machine, so rather than store all of the addresses, we just
// store this.
unsigned int local_host = peer[0]->AvailableHosts()[0].first.first;
// Now each person sends a unique string to everyone else.
vector<string> data(peer.size());
data[0] = "aaaaaaaaaaaaaaaaaaaaa";
data[1] = "foobar thundergun";
data[2] = "1234567890!@#$^&*(),./;'[]";
data[3] = ".";
data[4] = "";
for (int i = 0; i < peer.size(); i++) {
vector<GlopNetworkAddress> connections = peer[i]->GetConnections();
for (int j = 0; j < connections.size(); j++) {
peer[i]->SendData(connections[j], data[i]);
}
}
for (int i = 0; i < peer.size(); i++) {
for (int j = 0; j < peer.size(); j++) {
vector<string> messages =
WaitForData(peer[i], GlopNetworkAddress(local_host, 65000 + j), (i==j) ? 0 : 1);
if (i == j) {
EXPECT_EQ(0, messages.size());
} else {
EXPECT_EQ(1, messages.size());
if (messages.size() == 1) {
EXPECT_EQ(data[j], messages[0]);
}
}
}
}
for (int i = 0; i < peer.size(); i++) {
delete peer[i];
}
}
| 31.426531 | 100 | 0.643224 | zorbathut |
8e6ebf8886aec3a947ea44f3712847b1de5c43f1 | 1,436 | cc | C++ | compiler_gym/util/RunfilesPath.cc | mostafaelhoushi/CompilerGym | cf11c58333d263b3ebc5ece2110a429e9af499c1 | [
"MIT"
] | 562 | 2020-12-21T14:10:20.000Z | 2022-03-31T21:23:55.000Z | compiler_gym/util/RunfilesPath.cc | mostafaelhoushi/CompilerGym | cf11c58333d263b3ebc5ece2110a429e9af499c1 | [
"MIT"
] | 433 | 2020-12-22T03:40:41.000Z | 2022-03-31T18:16:17.000Z | compiler_gym/util/RunfilesPath.cc | mostafaelhoushi/CompilerGym | cf11c58333d263b3ebc5ece2110a429e9af499c1 | [
"MIT"
] | 88 | 2020-12-22T08:22:00.000Z | 2022-03-20T19:00:40.000Z | // Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.
#include "boost/filesystem.hpp"
namespace fs = boost::filesystem;
namespace compiler_gym::util {
// When running under bazel, the working directory is the root of the
// CompilerGym workspace. Back up one level so that we can reference other
// workspaces.
static const std::string kDefaultBase{"."};
fs::path getRunfilesPath(const std::string& relPath) {
const char* base = std::getenv("COMPILER_GYM_RUNFILES");
if (base) {
return fs::path(base) / relPath;
} else {
return fs::path(relPath);
}
}
fs::path getSiteDataPath(const std::string& relPath) {
// NOTE(cummins): This function has a matching implementation in the Python
// sources, compiler_gym.util.runfiles_path.get_site_data_path().
// Any change to behavior here must be reflected in the Python version.
const char* force = std::getenv("COMPILER_GYM_SITE_DATA");
if (force) {
return fs::path(force) / relPath;
}
const char* home = std::getenv("HOME");
if (home) {
return fs::path(home) / ".local/share/compiler_gym" / relPath;
} else {
// $HOME may not be set under testing conditions. In this case, use a
// throwaway directory.
return fs::temp_directory_path() / "compiler_gym" / relPath;
}
}
} // namespace compiler_gym::util
| 31.911111 | 77 | 0.704039 | mostafaelhoushi |
8e77c8b65e1a115502a7925c072aad85516edc19 | 1,212 | hpp | C++ | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | 1 | 2021-06-03T15:56:32.000Z | 2021-06-03T15:56:32.000Z | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | 1 | 2015-08-05T05:51:49.000Z | 2015-08-05T05:51:49.000Z | src/sip-0x/parser/tokens/messageheaders/TokenSIPMessageHeader_Accept_Encoding.hpp | zanfire/sip-0x | de38b3ff782d2a63b69d7f785e2bd9ce7674abd5 | [
"Apache-2.0"
] | null | null | null | #if !defined(SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__)
#define SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__
#include "parser/tokens/TokenAbstract.hpp"
#include "parser/tokens/Operators.hpp"
#include "parser/tokens/TokenRegex.hpp"
#include "parser/tokens/TokenSIPMethod.hpp"
#include "parser/tokens/messageheaders/TokenSIPMessageHeader_base.hpp"
namespace sip0x
{
namespace parser
{
// Accept-Encoding = "Accept-Encoding" HCOLON
// [ encoding *(COMMA encoding) ]
// encoding = codings *(SEMI accept-param)
// codings = content-coding / "*"
// content-coding = token
class TokenSIPMessageHeader_Accept_Encoding : public TokenSIPMessageHeader_base<Sequence<TokenDigits, TokenLWS, TokenSIPMethod>> {
protected:
public:
//
TokenSIPMessageHeader_Accept_Encoding() : TokenSIPMessageHeader_base("Accept-Encoding", "Accept\\-Encoding",
Sequence<TokenDigits, TokenLWS, TokenSIPMethod>
(
TokenDigits(),
TokenLWS(),
TokenSIPMethod()
)
)
{
}
};
}
}
#endif // SIP0X_PARSER_TOKENSIPMESSAGEHEADER_ACCEPT_ENCODING_HPP__
| 26.933333 | 134 | 0.685644 | zanfire |