text string | size int64 | token_count int64 |
|---|---|---|
///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2021.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
#include <test/test_uintwide_t_n_base.h>
auto test_uintwide_t_n_base::my_random_generator() -> std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647>&
{
static std::linear_congruential_engine<std::uint32_t, 48271, 0, 2147483647> my_generator; // NOLINT(cert-msc32-c,cert-msc51-cpp)
return my_generator;
}
| 610 | 252 |
//===--- CheckerRegistration.cpp - Registration for the Analyzer Checkers -===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines the registration function for the analyzer checkers.
//
//===----------------------------------------------------------------------===//
#include "clang/StaticAnalyzer/Frontend/AnalyzerHelpFlags.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/Frontend/FrontendDiagnostic.h"
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.h"
#include "clang/StaticAnalyzer/Core/CheckerManager.h"
#include "clang/StaticAnalyzer/Frontend/CheckerRegistry.h"
#include "clang/StaticAnalyzer/Frontend/FrontendActions.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/raw_ostream.h"
#include <memory>
using namespace clang;
using namespace ento;
void ento::printCheckerHelp(raw_ostream &out, CompilerInstance &CI) {
out << "OVERVIEW: Clang Static Analyzer Checkers List\n\n";
out << "USAGE: -analyzer-checker <CHECKER or PACKAGE,...>\n\n";
auto CheckerMgr = std::make_unique<CheckerManager>(
*CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(),
CI.getFrontendOpts().Plugins);
CheckerMgr->getCheckerRegistryData().printCheckerWithDescList(
*CI.getAnalyzerOpts(), out);
}
void ento::printEnabledCheckerList(raw_ostream &out, CompilerInstance &CI) {
out << "OVERVIEW: Clang Static Analyzer Enabled Checkers List\n\n";
auto CheckerMgr = std::make_unique<CheckerManager>(
*CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(),
CI.getFrontendOpts().Plugins);
CheckerMgr->getCheckerRegistryData().printEnabledCheckerList(out);
}
void ento::printCheckerConfigList(raw_ostream &out, CompilerInstance &CI) {
auto CheckerMgr = std::make_unique<CheckerManager>(
*CI.getAnalyzerOpts(), CI.getLangOpts(), CI.getDiagnostics(),
CI.getFrontendOpts().Plugins);
CheckerMgr->getCheckerRegistryData().printCheckerOptionList(
*CI.getAnalyzerOpts(), out);
}
void ento::printAnalyzerConfigList(raw_ostream &out) {
// FIXME: This message sounds scary, should be scary, but incorrectly states
// that all configs are super dangerous. In reality, many of them should be
// accessible to the user. We should create a user-facing subset of config
// options under a different frontend flag.
out << R"(
OVERVIEW: Clang Static Analyzer -analyzer-config Option List
The following list of configurations are meant for development purposes only, as
some of the variables they define are set to result in the most optimal
analysis. Setting them to other values may drastically change how the analyzer
behaves, and may even result in instabilities, crashes!
USAGE: -analyzer-config <OPTION1=VALUE,OPTION2=VALUE,...>
-analyzer-config OPTION1=VALUE, -analyzer-config OPTION2=VALUE, ...
OPTIONS:
)";
using OptionAndDescriptionTy = std::pair<StringRef, std::string>;
OptionAndDescriptionTy PrintableOptions[] = {
#define ANALYZER_OPTION(TYPE, NAME, CMDFLAG, DESC, DEFAULT_VAL) \
{ \
CMDFLAG, \
llvm::Twine(llvm::Twine() + "(" + \
(StringRef(#TYPE) == "StringRef" ? "string" : #TYPE ) + \
") " DESC \
" (default: " #DEFAULT_VAL ")").str() \
},
#define ANALYZER_OPTION_DEPENDS_ON_USER_MODE(TYPE, NAME, CMDFLAG, DESC, \
SHALLOW_VAL, DEEP_VAL) \
{ \
CMDFLAG, \
llvm::Twine(llvm::Twine() + "(" + \
(StringRef(#TYPE) == "StringRef" ? "string" : #TYPE ) + \
") " DESC \
" (default: " #SHALLOW_VAL " in shallow mode, " #DEEP_VAL \
" in deep mode)").str() \
},
#include "clang/StaticAnalyzer/Core/AnalyzerOptions.def"
#undef ANALYZER_OPTION
#undef ANALYZER_OPTION_DEPENDS_ON_USER_MODE
};
llvm::sort(PrintableOptions, [](const OptionAndDescriptionTy &LHS,
const OptionAndDescriptionTy &RHS) {
return LHS.first < RHS.first;
});
for (const auto &Pair : PrintableOptions) {
AnalyzerOptions::printFormattedEntry(out, Pair, /*InitialPad*/ 2,
/*EntryWidth*/ 30,
/*MinLineWidth*/ 70);
out << "\n\n";
}
}
| 5,102 | 1,537 |
/*********************************************************************************
* OKVIS - Open Keyframe-based Visual-Inertial SLAM
* Copyright (c) 2015, Autonomous Systems Lab / ETH Zurich
*
* 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 Autonomous Systems Lab / ETH Zurich nor the names of
* its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Created on: Jan 13, 2016
* Author: Stefan Leutenegger (s.leutenegger@imperial.ac.uk)
*********************************************************************************/
/**
* @file dataset_convertor.cpp
* @brief Source file for the VioParametersReader class.
* @author Stefan Leutenegger
* @author Andrea Nicastro
*/
#include <vector>
#include <map>
#include <memory>
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wnon-virtual-dtor"
#pragma GCC diagnostic ignored "-Woverloaded-virtual"
#include <ros/ros.h>
#include <ros/console.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
#include <rosbag/chunked_file.h>
#include <cv_bridge/cv_bridge.h>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/opencv.hpp>
#pragma GCC diagnostic pop
#include <message_filters/subscriber.h>
#include <message_filters/time_synchronizer.h>
#include <sensor_msgs/Image.h>
#include <sensor_msgs/image_encodings.h>
#include <sensor_msgs/Imu.h>
#include <geometry_msgs/TransformStamped.h>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/path.hpp>
using namespace boost::filesystem;
using std::vector;
using std::string;
using std::map;
using std::cout;
using std::endl;
using std::ofstream;
using std::shared_ptr;
const string RESET = "\033[0m";
const string BLACK = "0m";
const string RED = "1m";
const string GREEN = "2m";
const string BOLD = "\033[1;3";
const string REGULAR = "\033[0;3";
const string UNDERLINE = "\033[4;3";
const string BACKGROUND = "\033[4";
const int DOUBLE_PRECISION = 17;
// yaml parameters
const string SENSOR_LIST = "sensors";
const string CSVFILE = "data_file";
const string DATADIR = "data_dir";
const string SENSOR_TYPE = "type";
const string INFO = "info";
const string TOPIC = "topic";
const string NAME = "name";
const string CAMERA = "camera";
const string IMU = "imu";
const string VICON = "vicon";
///\todo: obsolete! delete
const string configDirectoryName = "/config/";
const string cam0DirectoryName = "/cam0";
const string cam1DirectoryName = "/cam1";
const string imuDirectoryName = "/imu0";
const string imuFileName = "imu0.csv";
std::ofstream imu_file_;
void signalHandler(int s)
{
imu_file_.close();
}
string colouredString(string str, string colour, string option)
{
return option + colour + str + RESET;
}
bool createDirs(string folderPath, map<string, map<string, string>> sensor_info)
{
path p(folderPath);
bool res = true;
if (exists(p)) {
cout << colouredString("\tCleaning previous dataset...", RED, REGULAR);
remove_all(p);
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
}
cout << colouredString("\tCreating dataset folder...", RED, REGULAR);
res = res && create_directories(p);
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
for (auto &iterator : sensor_info) {
std::stringstream sensor_folder;
sensor_folder << folderPath;
if (iterator.second.find(DATADIR) != iterator.second.end()) {
sensor_folder << "/" << iterator.second[DATADIR];
} else
sensor_folder << "/" << iterator.second[NAME];
path sensor_path(sensor_folder.str());
res = res && create_directories(sensor_path);
}
return res;
}
void writeCameraHeader(shared_ptr<ofstream> file)
{
*file << "#timestamp [ns]," << "filename" << endl;
}
void writeImuHeader(shared_ptr<ofstream> file)
{
*file << "#timestamp [ns]," << "w_S_x [rad s^-1]," << "w_S_y [rad s^-1],"
<< "w_S_z [rad s^-1]," << "a_S_x [m s^-2]," << "a_S_y [m s^-2],"
<< "a_S_z [m s^-2]" << endl;
}
void writeViconHeader(shared_ptr<ofstream> file)
{
*file << "#timestamp [ns]," << "p_S_x [m]," << "p_S_y [m]," << "p_S_z [m],"
<< "R_S_w []" << "R_S_x []," << "R_S_y []," << "R_S_z []" << endl;
}
void writeCSVHeaders(map<string, shared_ptr<ofstream>> &files,
const map<string, map<string, string>> &sensor_info)
{
for (auto iterator : sensor_info) {
if (iterator.second[SENSOR_TYPE].compare(CAMERA) == 0)
writeCameraHeader(files[iterator.first]);
else if (iterator.second[SENSOR_TYPE].compare(IMU) == 0)
writeImuHeader(files[iterator.first]);
else if (iterator.second[SENSOR_TYPE].compare(VICON) == 0)
writeViconHeader(files[iterator.first]);
}
}
map<string, shared_ptr<ofstream> > openFileStreams(
const string folder_path, map<string, map<string, string>> &sensor_info)
{
map<string, shared_ptr<ofstream>> topic2file_map;
for (auto &iterator : sensor_info) {
string topic = iterator.first;
string csv_file_path = folder_path + string("/") + iterator.second[CSVFILE];
ofstream *file = new ofstream(csv_file_path.c_str());
shared_ptr < ofstream > file_ptr(file);
topic2file_map.insert(
std::pair<string, shared_ptr<ofstream>>(topic, file_ptr));
}
writeCSVHeaders(topic2file_map, sensor_info);
return topic2file_map;
}
map<string, map<string, string> > sensorInfo(const ros::NodeHandle &nh)
{
cout << colouredString("\tRetrieving sensor list...", RED, REGULAR);
vector < string > sensor_list;
if (!nh.getParam(SENSOR_LIST, sensor_list)) {
std::stringstream msg;
msg << "FAIL! Missing \"" << SENSOR_LIST
<< "\" parameter. Check your yaml or launch file";
cout << colouredString(msg.str(), RED, BACKGROUND) << endl;
exit (EXIT_FAILURE);
}
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("\tRetrieving CSV filename...", RED, REGULAR);
string csv_filename;
if (!nh.getParam(CSVFILE, csv_filename)) {
std::stringstream msg;
msg << "FAIL! Missing \"" << CSVFILE
<< "\" parameter. Check your yaml or launch file";
cout << colouredString(msg.str(), RED, BACKGROUND) << endl;
exit (EXIT_FAILURE);
}
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("\tRetrieving sensor list...", RED, REGULAR);
map<string, map<string, string>> topic2info;
map < string, string > sensor_new_info;
for (string sensor : sensor_list) {
sensor_new_info.clear();
std::stringstream ss;
ss << INFO << "/" << sensor;
map < string, string > sensor_params;
if (!nh.getParam(ss.str(), sensor_params)) {
std::stringstream msg;
msg << "FAIL! Missing \"" << ss.str()
<< "\" parameter. Check your yaml or launch file";
cout << colouredString(msg.str(), RED, BACKGROUND) << endl;
exit (EXIT_FAILURE);
}
string topic = sensor_params[TOPIC];
string csv_file_path = sensor + string("/") + csv_filename;
sensor_new_info.insert(std::pair<string, string>(CSVFILE, csv_file_path));
if (sensor_params.find(DATADIR) != sensor_params.end()) {
string data_dir = sensor + string("/") + sensor_params[DATADIR];
sensor_new_info.insert(std::pair<string, string>(DATADIR, data_dir));
}
string sensor_type = sensor_params[SENSOR_TYPE];
sensor_new_info.insert(std::pair<string, string>(SENSOR_TYPE, sensor_type));
sensor_new_info.insert(std::pair<string, string>(NAME, sensor));
topic2info.insert(
std::pair<string, map<string, string>>(topic, sensor_new_info));
}
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
return topic2info;
}
void writeCSVCamera(shared_ptr<ofstream> file, ros::Time stamp)
{
std::stringstream ss;
ss << stamp.toNSec() << "," << stamp.toNSec() << ".png";
*file << ss.str() << endl;
}
void writeCSVImu(shared_ptr<ofstream> file, sensor_msgs::Imu::ConstPtr imu)
{
std::ostringstream ss;
ss << std::setprecision(DOUBLE_PRECISION) << imu->header.stamp.toNSec() << ","
<< imu->angular_velocity.x << "," << imu->angular_velocity.y << ","
<< imu->angular_velocity.z << "," << imu->linear_acceleration.x << ","
<< imu->linear_acceleration.y << "," << imu->linear_acceleration.z;
*file << ss.str() << endl;
}
void writeCSVVicon(shared_ptr<ofstream> file,
geometry_msgs::TransformStamped::ConstPtr vicon)
{
std::ostringstream ss;
ss << std::setprecision(DOUBLE_PRECISION) << vicon->header.stamp.toNSec()
<< "," << vicon->transform.translation.x << ","
<< vicon->transform.translation.y << "," << vicon->transform.translation.z
<< "," << vicon->transform.rotation.w << ","
<< vicon->transform.rotation.x << "," << vicon->transform.rotation.y
<< "," << vicon->transform.rotation.z;
*file << ss.str() << endl;
}
bool isTopicInMap(map<string, map<string, string> > &topic2info,
string topic_name)
{
bool res = false;
if (topic2info.find(topic_name) != topic2info.end()) {
res = true;
} else {
size_t first_slash = topic_name.find_first_of("/");
if (first_slash == 0) {
if (topic2info.find(topic_name.substr(1)) != topic2info.end()) {
res = true;
}
} else {
if (topic2info.find("/" + topic_name) != topic2info.end()) {
res = true;
}
}
}
return res;
}
bool findTopicInMap(map<string, map<string, string> > &topic2info,
string topic_name,
map<string, map<string, string> >::iterator &element)
{
element = topic2info.end();
bool res = false;
if (topic2info.find(topic_name) != topic2info.end()) {
element = topic2info.find(topic_name);
res = true;
} else {
size_t first_slash = topic_name.find_first_of("/");
if (first_slash == 0) {
if (topic2info.find(topic_name.substr(1)) != topic2info.end()) {
element = topic2info.find(topic_name.substr(1));
res = true;
}
} else {
if (topic2info.find("/" + topic_name) != topic2info.end()) {
element = topic2info.find("/" + topic_name);
res = true;
}
}
}
return res;
}
int main(int argc, char **argv)
{
cout << colouredString("Initializing ROS node:", RED, BOLD) << endl;
ros::init(argc, argv, "dataset_converter");
ros::NodeHandle nh;
cout << colouredString("DONE!", GREEN, BOLD) << endl;
cout << colouredString("Initializing sensor information:", RED, BOLD) << endl;
map<string, map<string, string>> topic2info_map = sensorInfo(nh);
cout << colouredString("DONE!", GREEN, BOLD) << endl;
cout << colouredString("Creating folders:", RED, BOLD) << endl;
string path(argv[1]);
size_t pos = path.find_last_of("/");
size_t pos_dot = path.find_last_of(".");
string bagname;
string bagpath;
if (pos == string::npos) {
cout
<< colouredString(
"Relative path are not supported. Use an absolute path instead."
"For example: roslaunch okvis_ros convert_datasert.launch bag:= /absolute/path/here",
RED, BOLD) << endl;
exit (EXIT_FAILURE);
} else {
bagname = path.substr(pos + 1, pos_dot - pos - 1);
bagpath = path.substr(0, pos + 1);
}
if (!createDirs(bagpath + bagname, topic2info_map)) {
cout << colouredString("FAILED!", RED, BACKGROUND);
exit (EXIT_FAILURE);
} else
cout << colouredString("DONE!", GREEN, BOLD) << endl;
cout << colouredString("Reading bag:", RED, BOLD) << endl;
rosbag::Bag bag;
cout << colouredString("\tOpening bag...", RED, REGULAR);
bag.open(argv[1], rosbag::bagmode::Read);
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("\tQuering topics bag...", RED, REGULAR);
vector < string > topic_list;
rosbag::View view(bag);
vector<const rosbag::ConnectionInfo *> bag_info = view.getConnections();
std::set < string > bag_topics;
for (const rosbag::ConnectionInfo *info : bag_info) {
string topic_name;
topic_name = info->topic;
if (isTopicInMap(topic2info_map, topic_name)) {
topic_list.push_back(topic_name);
}
}
view.addQuery(bag, rosbag::TopicQuery(topic_list));
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("\tOpening file streams...", RED, REGULAR);
map<string, shared_ptr<ofstream>> topic2file = openFileStreams(
bagpath + bagname, topic2info_map);
cout << colouredString("\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("\tParsing the bag...\n\t", RED, REGULAR);
double view_size = view.size();
double counter = 0;
for (auto bagIt : view) {
string topic = bagIt.getTopic();
map<string, map<string, string> >::iterator sensor_it;
findTopicInMap(topic2info_map, topic, sensor_it);
if (sensor_it == topic2info_map.end()) {
counter++;
std::printf("\r Progress: %.2f %%", 100.0 * counter / view_size);
continue;
}
string sens_type = sensor_it->second.find(SENSOR_TYPE)->second;
if (sens_type.compare(CAMERA) == 0) {
sensor_msgs::Image::ConstPtr image =
bagIt.instantiate<sensor_msgs::Image>();
cv_bridge::CvImagePtr cv_ptr;
cv_ptr = cv_bridge::toCvCopy(image, sensor_msgs::image_encodings::BGR8);
cv::Mat image_cv = cv_ptr->image;
std::stringstream ss;
ss << bagpath << bagname << "/" << sensor_it->second.find(DATADIR)->second
<< "/" << image->header.stamp.toNSec() << ".png";
cv::imwrite(ss.str(), image_cv);
writeCSVCamera(topic2file.find(sensor_it->first)->second,
image->header.stamp);
}
if (sens_type.compare(IMU) == 0) {
sensor_msgs::Imu::ConstPtr imuReading = bagIt
.instantiate<sensor_msgs::Imu>();
writeCSVImu(topic2file.find(sensor_it->first)->second, imuReading);
}
if (sens_type.compare(VICON) == 0) {
geometry_msgs::TransformStamped::ConstPtr viconReading = bagIt
.instantiate<geometry_msgs::TransformStamped>();
writeCSVVicon(topic2file.find(sensor_it->first)->second, viconReading);
}
counter++;
std::printf("\r Progress: %.2f %%", 100.0 * counter / view_size);
}
cout << colouredString("\n\t[DONE!]", GREEN, REGULAR) << endl;
cout << colouredString("DONE!", GREEN, BOLD) << endl;
cout << colouredString("Close file:", RED, BOLD) << endl;
for (auto it : topic2file) {
it.second->close();
}
cout << colouredString("DONE!", GREEN, BOLD) << endl;
ros::shutdown();
}
| 15,920 | 5,759 |
#include <cstdint>
#include <cstdio>
#include "FreeRTOS.h"
#include "task.h"
#include "config.hpp"
#include "L0_LowLevel/LPC40xx.h"
#include "L2_Utilities/debug_print.hpp"
#include "L2_Utilities/macros.hpp"
#include "L2_Utilities/rtos.hpp"
namespace
{
void LedToggle(void * parameters)
{
DEBUG_PRINT("Setting up task...");
DEBUG_PRINT("Retrieving delay amount from parameters...");
auto delay = rtos::RetrieveParameter(parameters);
DEBUG_PRINT("Initializing LEDs...");
LPC_IOCON->P1_1 &= ~(0b111);
LPC_IOCON->P1_8 &= ~(0b111);
LPC_GPIO1->DIR |= (1 << 1);
LPC_GPIO1->PIN &= ~(1 << 1);
LPC_GPIO1->DIR |= (1 << 8);
LPC_GPIO1->PIN |= (1 << 8);
DEBUG_PRINT("LEDs Initialized...");
DEBUG_PRINT("Toggling LEDs...");
// Loop blinks the LEDs back and forth at a rate that depends on the
// pvParameter's value.
while (true)
{
LPC_GPIO1->PIN ^= 0b0001'0000'0010;
vTaskDelay(delay);
}
}
constexpr uint32_t kButtonPinNumber = 14;
constexpr uint32_t kLedNumber = 15;
bool CheckSwitch3()
{
return (LPC_GPIO1->PIN & (1 << kButtonPinNumber));
}
void ButtonReader(void * parameters)
{
SJ2_USED(parameters);
DEBUG_PRINT("Setting up task...");
DEBUG_PRINT("Initializing LED3 and SW3...");
LPC_IOCON->P1_14 &= ~(0b111);
LPC_IOCON->P1_15 &= ~(0b111);
LPC_GPIO1->DIR &= ~(1 << kButtonPinNumber);
LPC_GPIO1->DIR |= (1 << kLedNumber);
LPC_GPIO1->PIN |= (1 << kLedNumber);
DEBUG_PRINT("LED3 and SW3 Initialized...");
DEBUG_PRINT("Press and release SW3 to toggle LED3 state...");
bool button_pressed = false;
// Loop detects when the button has been released and changes the LED state
// accordingly.
while (true)
{
if (CheckSwitch3())
{
button_pressed = true;
}
else if (!CheckSwitch3() && button_pressed)
{
LPC_GPIO1->PIN ^= (1 << kLedNumber);
button_pressed = false;
}
else
{
button_pressed = false;
}
vTaskDelay(50);
}
}
} // namespace
int main(void)
{
TaskHandle_t handle = NULL;
DEBUG_PRINT("Creating Tasks ...");
// See https://www.freertos.org/a00125.html for the xTaskCreate API
// See L2_Utilities/rtos.hpp for the rtos:: namespace utility functions
xTaskCreate(
LedToggle, // Make function LedToggle a task
"LedToggle", // Give this task the name "LedToggle"
rtos::StackSize(256), // Size of stack allocated to task
rtos::PassParameter(100), // Parameter to be passed to task
rtos::Priority::kLow, // Give this task low priority
&handle); // Reference to the task
xTaskCreate(
ButtonReader, // Make function ButtonReader a task
"ButtonReader", // Give this task the name "ButtonReader"
rtos::StackSize(256), // Size of stack allocated to task
rtos::kNoParameter, // Pass nothing to this task
rtos::Priority::kMedium, // Give this task medium priority
rtos::kNoHandle); // Do not supply a task handle
DEBUG_PRINT("Starting Scheduler ...");
vTaskStartScheduler();
return 0;
}
| 3,287 | 1,165 |
// Copyright Neil Groves 2009. Use, modification and
// distribution is subject to the Boost Software License, Version
// 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
//
// For more information, see http://www.boost.org/libs/range/
//
#ifndef BOOST_RANGE_ALGORITHM_SWAP_RANGES_HPP_INCLUDED
#define BOOST_RANGE_ALGORITHM_SWAP_RANGES_HPP_INCLUDED
#include <boost/assert.hpp>
#include <boost/concept_check.hpp>
#include <boost/iterator/iterator_categories.hpp>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/concepts.hpp>
#include <boost/range/iterator.hpp>
#include <algorithm>
namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
{
namespace range_detail
{
template<class Iterator1, class Iterator2>
void swap_ranges_impl(Iterator1 it1, Iterator1 last1,
Iterator2 it2, Iterator2 last2,
single_pass_traversal_tag,
single_pass_traversal_tag)
{
ignore_unused_variable_warning(last2);
for (; it1 != last1; ++it1, ++it2)
{
BOOST_ASSERT( it2 != last2 );
std::iter_swap(it1, it2);
}
}
template<class Iterator1, class Iterator2>
void swap_ranges_impl(Iterator1 it1, Iterator1 last1,
Iterator2 it2, Iterator2 last2,
random_access_traversal_tag,
random_access_traversal_tag)
{
ignore_unused_variable_warning(last2);
BOOST_ASSERT( last2 - it2 >= last1 - it1 );
std::swap_ranges(it1, last1, it2);
}
template<class Iterator1, class Iterator2>
void swap_ranges_impl(Iterator1 first1, Iterator1 last1,
Iterator2 first2, Iterator2 last2)
{
swap_ranges_impl(first1, last1, first2, last2,
BOOST_DEDUCED_TYPENAME iterator_traversal<Iterator1>::type(),
BOOST_DEDUCED_TYPENAME iterator_traversal<Iterator2>::type());
}
} // namespace range_detail
namespace range
{
/// \brief template function swap_ranges
///
/// range-based version of the swap_ranges std algorithm
///
/// \pre SinglePassRange1 is a model of the SinglePassRangeConcept
/// \pre SinglePassRange2 is a model of the SinglePassRangeConcept
template< class SinglePassRange1, class SinglePassRange2 >
inline SinglePassRange2&
swap_ranges(SinglePassRange1& range1, SinglePassRange2& range2)
{
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange1>));
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange2>));
mars_boost::range_detail::swap_ranges_impl(
mars_boost::begin(range1), mars_boost::end(range1),
mars_boost::begin(range2), mars_boost::end(range2));
return range2;
}
/// \overload
template< class SinglePassRange1, class SinglePassRange2 >
inline SinglePassRange2&
swap_ranges(const SinglePassRange1& range1, SinglePassRange2& range2)
{
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange1>));
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange2>));
mars_boost::range_detail::swap_ranges_impl(
mars_boost::begin(range1), mars_boost::end(range1),
mars_boost::begin(range2), mars_boost::end(range2));
return range2;
}
/// \overload
template< class SinglePassRange1, class SinglePassRange2 >
inline const SinglePassRange2&
swap_ranges(SinglePassRange1& range1, const SinglePassRange2& range2)
{
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<SinglePassRange1>));
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange2>));
mars_boost::range_detail::swap_ranges_impl(
mars_boost::begin(range1), mars_boost::end(range1),
mars_boost::begin(range2), mars_boost::end(range2));
return range2;
}
/// \overload
template< class SinglePassRange1, class SinglePassRange2 >
inline const SinglePassRange2&
swap_ranges(const SinglePassRange1& range1, const SinglePassRange2& range2)
{
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange1>));
BOOST_RANGE_CONCEPT_ASSERT((SinglePassRangeConcept<const SinglePassRange2>));
mars_boost::range_detail::swap_ranges_impl(
mars_boost::begin(range1), mars_boost::end(range1),
mars_boost::begin(range2), mars_boost::end(range2));
return range2;
}
} // namespace range
using range::swap_ranges;
} // namespace mars_boost {} namespace boost = mars_boost; namespace mars_boost
#endif // include guard
| 4,736 | 1,523 |
/*
* Copyright 1999-2019 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <alibabacloud/core/AlibabaCloud.h>
#include <alibabacloud/core/CommonClient.h>
#include <alibabacloud/core/location/LocationClient.h>
#include <alibabacloud/core/SimpleCredentialsProvider.h>
#include <ctime>
#include <algorithm>
#include <iomanip>
#include <sstream>
#include <alibabacloud/core/Utils.h>
namespace AlibabaCloud
{
namespace
{
const std::string SERVICE_NAME = "Common";
}
CommonClient::CommonClient(const Credentials &credentials,
const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
credentialsProvider_(
std::make_shared<SimpleCredentialsProvider>(credentials)),
signer_(std::make_shared<HmacSha1Signer>())
{
}
CommonClient::CommonClient(
const std::shared_ptr<CredentialsProvider> &credentialsProvider,
const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
credentialsProvider_(credentialsProvider),
signer_(std::make_shared<HmacSha1Signer>())
{
}
CommonClient::CommonClient(const std::string &accessKeyId,
const std::string &accessKeySecret,
const ClientConfiguration &configuration) : CoreClient(SERVICE_NAME, configuration),
credentialsProvider_(std::make_shared<SimpleCredentialsProvider>(accessKeyId,
accessKeySecret)),
signer_(std::make_shared<HmacSha1Signer>())
{
}
CommonClient::~CommonClient()
{
}
CommonClient::JsonOutcome CommonClient::makeRequest(const std::string &endpoint,
const CommonRequest &msg, HttpRequest::Method method) const
{
auto outcome = AttemptRequest(endpoint, msg, method);
if (outcome.isSuccess())
return JsonOutcome(std::string(outcome.result().body(),
outcome.result().bodySize()));
else
return JsonOutcome(outcome.error());
}
CommonClient::CommonResponseOutcome CommonClient::commonResponse(
const CommonRequest &request) const
{
auto outcome = makeRequest(request.domain(), request, request.httpMethod());
if (outcome.isSuccess())
return CommonResponseOutcome(CommonResponse(outcome.result()));
else
return CommonResponseOutcome(Error(outcome.error()));
}
void CommonClient::commonResponseAsync(const CommonRequest &request,
const CommonResponseAsyncHandler &handler,
const std::shared_ptr<const AsyncCallerContext> &context) const
{
auto fn = [this, request, handler, context]() {
handler(this, request, commonResponse(request), context);
};
asyncExecute(new Runnable(fn));
}
CommonClient::CommonResponseOutcomeCallable
CommonClient::commonResponseCallable(const CommonRequest &request) const
{
auto task = std::make_shared<std::packaged_task<CommonResponseOutcome()>>(
[this, request]() {
return this->commonResponse(request);
});
asyncExecute(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint,
const ServiceRequest &msg, HttpRequest::Method method) const
{
return buildHttpRequest(endpoint,
dynamic_cast<const CommonRequest &>(msg), method);
}
HttpRequest CommonClient::buildHttpRequest(const std::string &endpoint,
const CommonRequest &msg, HttpRequest::Method method) const
{
if (msg.requestPattern() == CommonRequest::RpcPattern)
return buildRpcHttpRequest(endpoint, msg, method);
else
return buildRoaHttpRequest(endpoint, msg, method);
}
HttpRequest CommonClient::buildRoaHttpRequest(const std::string &endpoint,
const CommonRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
if (msg.scheme().empty())
{
url.setScheme("https");
}
else
{
url.setScheme(msg.scheme());
}
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.headerParameters();
std::map<std::string, std::string> queryParams;
for (const auto &p : params)
{
if (!p.second.empty())
queryParams[p.first] = p.second;
}
if (!queryParams.empty())
{
std::stringstream queryString;
for (const auto &p : queryParams)
{
if (p.second.empty())
queryString << "&" << p.first;
else
queryString << "&" << p.first << "=" << p.second;
}
url.setQuery(queryString.str().substr(1));
}
HttpRequest request(url);
request.setMethod(method);
if (msg.connectTimeout() != kInvalidTimeout)
{
request.setConnectTimeout(msg.connectTimeout());
}
else
{
request.setConnectTimeout(configuration().connectTimeout());
}
if (msg.readTimeout() != kInvalidTimeout)
{
request.setReadTimeout(msg.readTimeout());
}
else
{
request.setReadTimeout(configuration().readTimeout());
}
if (msg.headerParameter("Accept").empty())
{
request.setHeader("Accept", "application/json");
}
else
{
request.setHeader("Accept", msg.headerParameter("Accept"));
}
std::stringstream ss;
ss << msg.contentSize();
request.setHeader("Content-Length", ss.str());
if (msg.headerParameter("Content-Type").empty())
{
request.setHeader("Content-Type", "application/octet-stream");
}
else
{
request.setHeader("Content-Type", msg.headerParameter("Content-Type"));
}
request.setHeader("Content-MD5",
ComputeContentMD5(msg.content(), msg.contentSize()));
request.setBody(msg.content(), msg.contentSize());
std::time_t t = std::time(nullptr);
std::stringstream date;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%a, %d %b %Y %T", std::gmtime(&t));
date << tmbuff << " GMT";
#else
date << std::put_time(std::gmtime(&t), "%a, %d %b %Y %T GMT");
#endif
request.setHeader("Date", date.str());
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client",
std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
request.setHeader("x-acs-region-id", configuration().regionId());
if (!credentials.sessionToken().empty())
request.setHeader("x-acs-security-token", credentials.sessionToken());
request.setHeader("x-acs-signature-method", signer_->name());
request.setHeader("x-acs-signature-nonce", GenerateUuid());
request.setHeader("x-acs-signature-version", signer_->version());
request.setHeader("x-acs-version", msg.version());
std::stringstream plaintext;
plaintext << HttpMethodToString(method) << "\n"
<< request.header("Accept") << "\n"
<< request.header("Content-MD5") << "\n"
<< request.header("Content-Type") << "\n"
<< request.header("Date") << "\n"
<< canonicalizedHeaders(request.headers());
if (!url.hasQuery())
plaintext << url.path();
else
plaintext << url.path() << "?" << url.query();
std::stringstream sign;
sign << "acs "
<< credentials.accessKeyId()
<< ":"
<< signer_->generate(plaintext.str(), credentials.accessKeySecret());
request.setHeader("Authorization", sign.str());
return request;
}
HttpRequest CommonClient::buildRpcHttpRequest(const std::string &endpoint,
const CommonRequest &msg, HttpRequest::Method method) const
{
const Credentials credentials = credentialsProvider_->getCredentials();
Url url;
if (msg.scheme().empty())
{
url.setScheme("https");
}
else
{
url.setScheme(msg.scheme());
}
url.setHost(endpoint);
url.setPath(msg.resourcePath());
auto params = msg.queryParameters();
std::map<std::string, std::string> queryParams;
for (const auto &p : params)
{
if (!p.second.empty())
queryParams[p.first] = p.second;
}
queryParams["AccessKeyId"] = credentials.accessKeyId();
queryParams["Format"] = "JSON";
queryParams["RegionId"] = configuration().regionId();
queryParams["SecurityToken"] = credentials.sessionToken();
queryParams["SignatureMethod"] = signer_->name();
queryParams["SignatureNonce"] = GenerateUuid();
queryParams["SignatureVersion"] = signer_->version();
std::time_t t = std::time(nullptr);
std::stringstream ss;
#if defined(__GNUG__) && __GNUC__ < 5
char tmbuff[26];
strftime(tmbuff, 26, "%FT%TZ", std::gmtime(&t));
ss << tmbuff;
#else
ss << std::put_time(std::gmtime(&t), "%FT%TZ");
#endif
queryParams["Timestamp"] = ss.str();
queryParams["Version"] = msg.version();
std::stringstream plaintext;
plaintext << HttpMethodToString(method)
<< "&"
<< UrlEncode(url.path())
<< "&"
<< UrlEncode(canonicalizedQuery(queryParams));
queryParams["Signature"] = signer_->generate(plaintext.str(),
credentials.accessKeySecret() + "&");
std::stringstream queryString;
for (const auto &p : queryParams)
queryString << "&" << p.first << "=" << UrlEncode(p.second);
url.setQuery(queryString.str().substr(1));
HttpRequest request(url);
if (msg.connectTimeout() != kInvalidTimeout)
{
request.setConnectTimeout(msg.connectTimeout());
}
else
{
request.setConnectTimeout(configuration().connectTimeout());
}
if (msg.readTimeout() != kInvalidTimeout)
{
request.setReadTimeout(msg.readTimeout());
}
else
{
request.setReadTimeout(configuration().readTimeout());
}
request.setMethod(method);
request.setHeader("Host", url.host());
request.setHeader("x-sdk-client",
std::string("CPP/").append(ALIBABACLOUD_VERSION_STR));
return request;
}
} // namespace AlibabaCloud
| 10,953 | 3,160 |
/*!
\file ray-inl.hpp
\author Sho Ikeda
Copyright (c) 2015-2018 Sho Ikeda
This software is released under the MIT License.
http://opensource.org/licenses/mit-license.php
*/
#ifndef NANAIRO_RAY_INL_HPP
#define NANAIRO_RAY_INL_HPP
#include "ray.hpp"
// Standard C++ library
#include <array>
#include <limits>
// Zisc
#include "zisc/math.hpp"
// Nanairo
#include "NanairoCore/nanairo_core_config.hpp"
#include "NanairoCore/Geometry/point.hpp"
#include "NanairoCore/Geometry/vector.hpp"
namespace nanairo {
/*!
\details
No detailed.
*/
inline
Ray::Ray() noexcept :
is_alive_{kFalse}
{
initialize();
}
/*!
\details
No detailed.
*/
inline
Ray::Ray(const Point3& origin, const Vector3& direction) noexcept :
origin_{origin},
direction_{direction},
is_alive_{kTrue}
{
initialize();
}
/*!
\details
No detailed.
*/
inline
const Vector3& Ray::direction() const noexcept
{
return direction_;
}
/*!
\details
No detailed.
*/
inline
bool Ray::isAlive() const noexcept
{
return is_alive_ == kTrue;
}
/*!
*/
inline
Ray Ray::makeRay(const Point3& origin, const Vector3& direction) noexcept
{
Ray ray{origin, direction};
return ray;
}
/*!
\details
No detailed.
*/
inline
const Point3& Ray::origin() const noexcept
{
return origin_;
}
/*!
\details
No detailed.
*/
inline
void Ray::setDirection(const Vector3& direction) noexcept
{
direction_ = direction;
}
/*!
\details
No detailed.
*/
inline
void Ray::setOrigin(const Point3& origin) noexcept
{
origin_ = origin;
}
/*!
\details
No detailed.
*/
inline
void Ray::setAlive(const bool is_alive) noexcept
{
is_alive_ = is_alive ? kTrue : kFalse;
}
/*!
*/
inline
void Ray::initialize() noexcept
{
// Avoid warnings
static_cast<void>(padding_);
}
} // namespace nanairo
#endif // NANAIRO_RAY_INL_HPP
| 1,844 | 713 |
/* A Bison parser, made by GNU Bison 2.5. */
/* Bison implementation for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2011 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
/* C LALR(1) parser skeleton written by Richard Stallman, by
simplifying the original so-called "semantic" parser. */
/* All symbols defined below should begin with yy or YY, to avoid
infringing on user name space. This should be done even for local
variables, as they might otherwise be expanded by user macros.
There are some unavoidable exceptions within include files to
define necessary library symbols; they are noted "INFRINGES ON
USER NAME SPACE" below. */
/* Identify Bison output. */
#define YYBISON 1
/* Bison version. */
#define YYBISON_VERSION "2.5"
/* Skeleton name. */
#define YYSKELETON_NAME "yacc.c"
/* Pure parsers. */
#define YYPURE 1
/* Push parsers. */
#define YYPUSH 0
/* Pull parsers. */
#define YYPULL 1
/* Using locations. */
#define YYLSP_NEEDED 0
/* Substitute the variable and function names. */
#define yyparse cssyyparse
#define yylex cssyylex
#define yyerror cssyyerror
#define yylval cssyylval
#define yychar cssyychar
#define yydebug cssyydebug
#define yynerrs cssyynerrs
/* Copy the first part of user declarations. */
/* Line 268 of yacc.c */
#line 1 "css/CSSGrammar.y"
/*
* Copyright (C) 2002-2003 Lars Knoll (knoll@kde.org)
* Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011, 2012, 2013 Apple Inc. All rights reserved.
* Copyright (C) 2006 Alexey Proskuryakov (ap@nypop.com)
* Copyright (C) 2008 Eric Seidel <eric@webkit.org>
* Copyright (C) 2012 Intel Corporation. All rights reserved.
*
* 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 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 "config.h"
#include "CSSPropertyNames.h"
#include "HTMLNames.h"
#include "core/css/CSSKeyframeRule.h"
#include "core/css/CSSKeyframesRule.h"
#include "core/css/parser/BisonCSSParser.h"
#include "core/css/CSSParserMode.h"
#include "core/css/CSSPrimitiveValue.h"
#include "core/css/CSSSelector.h"
#include "core/css/CSSSelectorList.h"
#include "core/css/MediaList.h"
#include "core/css/MediaQueryExp.h"
#include "core/css/StyleRule.h"
#include "core/css/StyleSheetContents.h"
#include "core/dom/Document.h"
#include "wtf/FastMalloc.h"
#include <stdlib.h>
#include <string.h>
using namespace WebCore;
using namespace HTMLNames;
#define YYMALLOC fastMalloc
#define YYFREE fastFree
#define YYENABLE_NLS 0
#define YYLTYPE_IS_TRIVIAL 1
#define YYMAXDEPTH 10000
#define YYDEBUG 0
#if YYDEBUG > 0
#define YYPRINT(File,Type,Value) if (isCSSTokenAString(Type)) YYFPRINTF(File, "%s", String((Value).string).utf8().data())
#endif
/* Line 268 of yacc.c */
#line 142 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp"
/* Enabling traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
/* Enabling verbose error messages. */
#ifdef YYERROR_VERBOSE
# undef YYERROR_VERBOSE
# define YYERROR_VERBOSE 1
#else
# define YYERROR_VERBOSE 0
#endif
/* Enabling the token table. */
#ifndef YYTOKEN_TABLE
# define YYTOKEN_TABLE 0
#endif
/* Tokens. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
/* Put the tokens into the symbol table, so that GDB and other debuggers
know about them. */
enum yytokentype {
TOKEN_EOF = 0,
LOWEST_PREC = 258,
UNIMPORTANT_TOK = 259,
WHITESPACE = 260,
SGML_CD = 261,
INCLUDES = 262,
DASHMATCH = 263,
BEGINSWITH = 264,
ENDSWITH = 265,
CONTAINS = 266,
STRING = 267,
IDENT = 268,
NTH = 269,
HEX = 270,
IDSEL = 271,
IMPORT_SYM = 272,
PAGE_SYM = 273,
MEDIA_SYM = 274,
SUPPORTS_SYM = 275,
FONT_FACE_SYM = 276,
CHARSET_SYM = 277,
NAMESPACE_SYM = 278,
VIEWPORT_RULE_SYM = 279,
INTERNAL_DECLS_SYM = 280,
INTERNAL_MEDIALIST_SYM = 281,
INTERNAL_RULE_SYM = 282,
INTERNAL_SELECTOR_SYM = 283,
INTERNAL_VALUE_SYM = 284,
INTERNAL_KEYFRAME_RULE_SYM = 285,
INTERNAL_KEYFRAME_KEY_LIST_SYM = 286,
INTERNAL_SUPPORTS_CONDITION_SYM = 287,
KEYFRAMES_SYM = 288,
WEBKIT_KEYFRAMES_SYM = 289,
TOPLEFTCORNER_SYM = 290,
TOPLEFT_SYM = 291,
TOPCENTER_SYM = 292,
TOPRIGHT_SYM = 293,
TOPRIGHTCORNER_SYM = 294,
BOTTOMLEFTCORNER_SYM = 295,
BOTTOMLEFT_SYM = 296,
BOTTOMCENTER_SYM = 297,
BOTTOMRIGHT_SYM = 298,
BOTTOMRIGHTCORNER_SYM = 299,
LEFTTOP_SYM = 300,
LEFTMIDDLE_SYM = 301,
LEFTBOTTOM_SYM = 302,
RIGHTTOP_SYM = 303,
RIGHTMIDDLE_SYM = 304,
RIGHTBOTTOM_SYM = 305,
ATKEYWORD = 306,
IMPORTANT_SYM = 307,
MEDIA_ONLY = 308,
MEDIA_NOT = 309,
MEDIA_AND = 310,
MEDIA_OR = 311,
SUPPORTS_NOT = 312,
SUPPORTS_AND = 313,
SUPPORTS_OR = 314,
REMS = 315,
CHS = 316,
QEMS = 317,
EMS = 318,
EXS = 319,
PXS = 320,
CMS = 321,
MMS = 322,
INS = 323,
PTS = 324,
PCS = 325,
DEGS = 326,
RADS = 327,
GRADS = 328,
TURNS = 329,
MSECS = 330,
SECS = 331,
HERTZ = 332,
KHERTZ = 333,
DIMEN = 334,
INVALIDDIMEN = 335,
PERCENTAGE = 336,
FLOATTOKEN = 337,
INTEGER = 338,
VW = 339,
VH = 340,
VMIN = 341,
VMAX = 342,
DPPX = 343,
DPI = 344,
DPCM = 345,
FR = 346,
URI = 347,
FUNCTION = 348,
ANYFUNCTION = 349,
CUEFUNCTION = 350,
NOTFUNCTION = 351,
DISTRIBUTEDFUNCTION = 352,
CALCFUNCTION = 353,
HOSTFUNCTION = 354,
HOSTCONTEXTFUNCTION = 355,
UNICODERANGE = 356
};
#endif
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
typedef union YYSTYPE
{
/* Line 293 of yacc.c */
#line 68 "css/CSSGrammar.y"
bool boolean;
char character;
int integer;
double number;
CSSParserString string;
StyleRuleBase* rule;
// The content of the three below HeapVectors are guaranteed to be kept alive by
// the corresponding m_parsedRules, m_floatingMediaQueryExpList, and m_parsedKeyFrames
// lists in BisonCSSParser.h.
WillBeHeapVector<RefPtrWillBeMember<StyleRuleBase> >* ruleList;
WillBeHeapVector<OwnPtrWillBeMember<MediaQueryExp> >* mediaQueryExpList;
WillBeHeapVector<RefPtrWillBeMember<StyleKeyframe> >* keyframeRuleList;
CSSParserSelector* selector;
Vector<OwnPtr<CSSParserSelector> >* selectorList;
CSSSelector::MarginBoxType marginBox;
CSSSelector::Relation relation;
MediaQuerySet* mediaList;
MediaQuery* mediaQuery;
MediaQuery::Restrictor mediaQueryRestrictor;
MediaQueryExp* mediaQueryExp;
CSSParserValue value;
CSSParserValueList* valueList;
StyleKeyframe* keyframe;
float val;
CSSPropertyID id;
CSSParserLocation location;
/* Line 293 of yacc.c */
#line 312 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp"
} YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define yystype YYSTYPE /* obsolescent; will be withdrawn */
# define YYSTYPE_IS_DECLARED 1
#endif
/* Copy the second part of user declarations. */
/* Line 343 of yacc.c */
#line 98 "css/CSSGrammar.y"
static inline int cssyyerror(void*, const char*)
{
return 1;
}
#if YYDEBUG > 0
static inline bool isCSSTokenAString(int yytype)
{
switch (yytype) {
case IDENT:
case STRING:
case NTH:
case HEX:
case IDSEL:
case DIMEN:
case INVALIDDIMEN:
case URI:
case FUNCTION:
case ANYFUNCTION:
case HOSTFUNCTION:
case HOSTCONTEXTFUNCTION:
case NOTFUNCTION:
case CALCFUNCTION:
case UNICODERANGE:
return true;
default:
return false;
}
}
#endif
inline static CSSParserValue makeOperatorValue(int value)
{
CSSParserValue v;
v.id = CSSValueInvalid;
v.isInt = false;
v.unit = CSSParserValue::Operator;
v.iValue = value;
return v;
}
inline static CSSParserValue makeIdentValue(CSSParserString string)
{
CSSParserValue v;
v.id = cssValueKeywordID(string);
v.isInt = false;
v.unit = CSSPrimitiveValue::CSS_IDENT;
v.string = string;
return v;
}
/* Line 343 of yacc.c */
#line 380 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp"
#ifdef short
# undef short
#endif
#ifdef YYTYPE_UINT8
typedef YYTYPE_UINT8 yytype_uint8;
#else
typedef unsigned char yytype_uint8;
#endif
#ifdef YYTYPE_INT8
typedef YYTYPE_INT8 yytype_int8;
#elif (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
typedef signed char yytype_int8;
#else
typedef short int yytype_int8;
#endif
#ifdef YYTYPE_UINT16
typedef YYTYPE_UINT16 yytype_uint16;
#else
typedef unsigned short int yytype_uint16;
#endif
#ifdef YYTYPE_INT16
typedef YYTYPE_INT16 yytype_int16;
#else
typedef short int yytype_int16;
#endif
#ifndef YYSIZE_T
# ifdef __SIZE_TYPE__
# define YYSIZE_T __SIZE_TYPE__
# elif defined size_t
# define YYSIZE_T size_t
# elif ! defined YYSIZE_T && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stddef.h> /* INFRINGES ON USER NAME SPACE */
# define YYSIZE_T size_t
# else
# define YYSIZE_T unsigned int
# endif
#endif
#define YYSIZE_MAXIMUM ((YYSIZE_T) -1)
#ifndef YY_
# if defined YYENABLE_NLS && YYENABLE_NLS
# if ENABLE_NLS
# include <libintl.h> /* INFRINGES ON USER NAME SPACE */
# define YY_(msgid) dgettext ("bison-runtime", msgid)
# endif
# endif
# ifndef YY_
# define YY_(msgid) msgid
# endif
#endif
/* Suppress unused-variable warnings by "using" E. */
#if ! defined lint || defined __GNUC__
# define YYUSE(e) ((void) (e))
#else
# define YYUSE(e) /* empty */
#endif
/* Identity function, used to suppress warnings about constant conditions. */
#ifndef lint
# define YYID(n) (n)
#else
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static int
YYID (int yyi)
#else
static int
YYID (yyi)
int yyi;
#endif
{
return yyi;
}
#endif
#if ! defined yyoverflow || YYERROR_VERBOSE
/* The parser invokes alloca or malloc; define the necessary symbols. */
# ifdef YYSTACK_USE_ALLOCA
# if YYSTACK_USE_ALLOCA
# ifdef __GNUC__
# define YYSTACK_ALLOC __builtin_alloca
# elif defined __BUILTIN_VA_ARG_INCR
# include <alloca.h> /* INFRINGES ON USER NAME SPACE */
# elif defined _AIX
# define YYSTACK_ALLOC __alloca
# elif defined _MSC_VER
# include <malloc.h> /* INFRINGES ON USER NAME SPACE */
# define alloca _alloca
# else
# define YYSTACK_ALLOC alloca
# if ! defined _ALLOCA_H && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# endif
# endif
# endif
# ifdef YYSTACK_ALLOC
/* Pacify GCC's `empty if-body' warning. */
# define YYSTACK_FREE(Ptr) do { /* empty */; } while (YYID (0))
# ifndef YYSTACK_ALLOC_MAXIMUM
/* The OS might guarantee only one guard page at the bottom of the stack,
and a page size can be as small as 4096 bytes. So we cannot safely
invoke alloca (N) if N exceeds 4096. Use a slightly smaller number
to allow for a few compiler-allocated temporary stack slots. */
# define YYSTACK_ALLOC_MAXIMUM 4032 /* reasonable circa 2006 */
# endif
# else
# define YYSTACK_ALLOC YYMALLOC
# define YYSTACK_FREE YYFREE
# ifndef YYSTACK_ALLOC_MAXIMUM
# define YYSTACK_ALLOC_MAXIMUM YYSIZE_MAXIMUM
# endif
# if (defined __cplusplus && ! defined EXIT_SUCCESS \
&& ! ((defined YYMALLOC || defined malloc) \
&& (defined YYFREE || defined free)))
# include <stdlib.h> /* INFRINGES ON USER NAME SPACE */
# ifndef EXIT_SUCCESS
# define EXIT_SUCCESS 0
# endif
# endif
# ifndef YYMALLOC
# define YYMALLOC malloc
# if ! defined malloc && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void *malloc (YYSIZE_T); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# ifndef YYFREE
# define YYFREE free
# if ! defined free && ! defined EXIT_SUCCESS && (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
void free (void *); /* INFRINGES ON USER NAME SPACE */
# endif
# endif
# endif
#endif /* ! defined yyoverflow || YYERROR_VERBOSE */
#if (! defined yyoverflow \
&& (! defined __cplusplus \
|| (defined YYSTYPE_IS_TRIVIAL && YYSTYPE_IS_TRIVIAL)))
/* A type that is properly aligned for any stack member. */
union yyalloc
{
yytype_int16 yyss_alloc;
YYSTYPE yyvs_alloc;
};
/* The size of the maximum gap between one aligned stack and the next. */
# define YYSTACK_GAP_MAXIMUM (sizeof (union yyalloc) - 1)
/* The size of an array large to enough to hold all stacks, each with
N elements. */
# define YYSTACK_BYTES(N) \
((N) * (sizeof (yytype_int16) + sizeof (YYSTYPE)) \
+ YYSTACK_GAP_MAXIMUM)
# define YYCOPY_NEEDED 1
/* Relocate STACK from its old location to the new one. The
local variables YYSIZE and YYSTACKSIZE give the old and new number of
elements in the stack, and YYPTR gives the new location of the
stack. Advance YYPTR to a properly aligned location for the next
stack. */
# define YYSTACK_RELOCATE(Stack_alloc, Stack) \
do \
{ \
YYSIZE_T yynewbytes; \
YYCOPY (&yyptr->Stack_alloc, Stack, yysize); \
Stack = &yyptr->Stack_alloc; \
yynewbytes = yystacksize * sizeof (*Stack) + YYSTACK_GAP_MAXIMUM; \
yyptr += yynewbytes / sizeof (*yyptr); \
} \
while (YYID (0))
#endif
#if defined YYCOPY_NEEDED && YYCOPY_NEEDED
/* Copy COUNT objects from FROM to TO. The source and destination do
not overlap. */
# ifndef YYCOPY
# if defined __GNUC__ && 1 < __GNUC__
# define YYCOPY(To, From, Count) \
__builtin_memcpy (To, From, (Count) * sizeof (*(From)))
# else
# define YYCOPY(To, From, Count) \
do \
{ \
YYSIZE_T yyi; \
for (yyi = 0; yyi < (Count); yyi++) \
(To)[yyi] = (From)[yyi]; \
} \
while (YYID (0))
# endif
# endif
#endif /* !YYCOPY_NEEDED */
/* YYFINAL -- State number of the termination state. */
#define YYFINAL 35
/* YYLAST -- Last index in YYTABLE. */
#define YYLAST 2129
/* YYNTOKENS -- Number of terminals. */
#define YYNTOKENS 122
/* YYNNTS -- Number of nonterminals. */
#define YYNNTS 139
/* YYNRULES -- Number of rules. */
#define YYNRULES 372
/* YYNRULES -- Number of states. */
#define YYNSTATES 708
/* YYTRANSLATE(YYLEX) -- Bison symbol number corresponding to YYLEX. */
#define YYUNDEFTOK 2
#define YYMAXUTOK 356
#define YYTRANSLATE(YYX) \
((unsigned int) (YYX) <= YYMAXUTOK ? yytranslate[YYX] : YYUNDEFTOK)
/* YYTRANSLATE[YYLEX] -- Bison symbol number corresponding to YYLEX. */
static const yytype_uint8 yytranslate[] =
{
0, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 120, 2, 121, 2, 2,
111, 108, 20, 114, 112, 118, 18, 117, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 17, 110,
2, 119, 116, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 19, 2, 109, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 113, 21, 107, 115, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 2, 2, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 22, 23, 24, 25, 26, 27, 28, 29,
30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, 56, 57, 58, 59,
60, 61, 62, 63, 64, 65, 66, 67, 68, 69,
70, 71, 72, 73, 74, 75, 76, 77, 78, 79,
80, 81, 82, 83, 84, 85, 86, 87, 88, 89,
90, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106
};
#if YYDEBUG
/* YYPRHS[YYN] -- Index of the first RHS symbol of rule number YYN in
YYRHS. */
static const yytype_uint16 yyprhs[] =
{
0, 0, 3, 7, 9, 11, 13, 15, 17, 19,
21, 23, 29, 35, 40, 45, 50, 56, 61, 66,
68, 71, 72, 74, 75, 78, 81, 83, 85, 87,
89, 91, 93, 95, 97, 98, 104, 107, 108, 112,
114, 116, 118, 120, 122, 124, 126, 128, 130, 131,
134, 137, 139, 142, 143, 147, 150, 152, 154, 156,
158, 160, 162, 164, 166, 169, 172, 173, 177, 184,
191, 198, 199, 202, 204, 206, 207, 211, 218, 223,
225, 231, 233, 239, 240, 243, 246, 249, 253, 255,
260, 264, 265, 267, 269, 272, 274, 279, 285, 286,
287, 289, 293, 302, 304, 315, 316, 317, 319, 321,
323, 325, 329, 334, 339, 344, 349, 355, 357, 364,
375, 386, 387, 391, 395, 405, 407, 409, 411, 414,
415, 420, 426, 432, 435, 441, 444, 446, 449, 450,
461, 464, 468, 471, 472, 474, 479, 480, 488, 490,
492, 494, 496, 498, 500, 502, 504, 506, 508, 510,
512, 514, 516, 518, 520, 521, 530, 531, 540, 543,
546, 549, 554, 556, 557, 559, 561, 563, 564, 565,
566, 576, 577, 579, 586, 588, 591, 595, 599, 601,
604, 607, 609, 612, 614, 617, 621, 624, 626, 632,
634, 636, 638, 641, 643, 645, 647, 649, 651, 654,
657, 662, 671, 677, 687, 691, 693, 695, 697, 699,
701, 703, 705, 707, 710, 714, 719, 727, 733, 740,
745, 752, 760, 767, 772, 779, 784, 791, 796, 803,
808, 812, 813, 815, 818, 820, 824, 829, 836, 845,
852, 857, 861, 865, 868, 869, 872, 876, 880, 885,
890, 892, 896, 899, 903, 906, 909, 912, 916, 919,
922, 925, 929, 932, 935, 938, 941, 944, 947, 950,
953, 955, 957, 959, 961, 963, 965, 967, 969, 971,
973, 975, 977, 979, 981, 983, 985, 987, 989, 991,
993, 995, 997, 999, 1001, 1003, 1005, 1007, 1009, 1011,
1013, 1018, 1022, 1027, 1029, 1032, 1036, 1040, 1044, 1048,
1049, 1051, 1057, 1062, 1064, 1068, 1072, 1074, 1080, 1085,
1087, 1089, 1093, 1097, 1100, 1103, 1106, 1110, 1114, 1120,
1124, 1127, 1130, 1134, 1140, 1144, 1148, 1152, 1157, 1160,
1163, 1164, 1168, 1172, 1176, 1178, 1180, 1182, 1184, 1186,
1188, 1190, 1192, 1193, 1194, 1195, 1198, 1201, 1204, 1207,
1208, 1211, 1214
};
/* YYRHS -- A `-1'-separated list of the rules' RHS. */
static const yytype_int16 yyrhs[] =
{
123, 0, -1, 139, 134, 140, -1, 127, -1, 124,
-1, 130, -1, 128, -1, 129, -1, 125, -1, 126,
-1, 131, -1, 32, 133, 141, 133, 0, -1, 35,
133, 186, 133, 0, -1, 36, 133, 187, 0, -1,
30, 204, 226, 0, -1, 34, 133, 233, 0, -1,
31, 133, 258, 162, 0, -1, 33, 133, 210, 0,
-1, 37, 133, 174, 0, -1, 5, -1, 132, 5,
-1, -1, 132, -1, -1, 134, 6, -1, 134, 5,
-1, 107, -1, 0, -1, 108, -1, 0, -1, 109,
-1, 0, -1, 110, -1, 0, -1, -1, 27, 133,
12, 133, 138, -1, 27, 246, -1, -1, 140, 143,
134, -1, 208, -1, 169, -1, 191, -1, 198, -1,
182, -1, 152, -1, 151, -1, 171, -1, 200, -1,
-1, 142, 141, -1, 142, 250, -1, 145, -1, 145,
146, -1, -1, 145, 148, 134, -1, 142, 251, -1,
208, -1, 191, -1, 198, -1, 169, -1, 182, -1,
171, -1, 200, -1, 152, -1, 142, 147, -1, 142,
250, -1, -1, 149, 22, 133, -1, 150, 154, 133,
258, 162, 138, -1, 150, 154, 133, 258, 162, 253,
-1, 28, 133, 153, 154, 133, 138, -1, -1, 13,
133, -1, 12, -1, 97, -1, -1, 17, 133, 233,
-1, 111, 133, 13, 133, 155, 136, -1, 111, 1,
259, 136, -1, 156, -1, 157, 133, 60, 133, 156,
-1, 133, -1, 133, 60, 133, 157, 133, -1, -1,
58, 133, -1, 59, 133, -1, 157, 133, -1, 159,
170, 158, -1, 160, -1, 160, 1, 257, 260, -1,
1, 257, 260, -1, -1, 163, -1, 161, -1, 164,
161, -1, 164, -1, 161, 112, 133, 258, -1, 164,
161, 112, 133, 258, -1, -1, -1, 133, -1, 166,
24, 133, -1, 168, 162, 206, 113, 165, 133, 144,
135, -1, 13, -1, 172, 25, 133, 174, 173, 113,
165, 133, 144, 135, -1, -1, -1, 178, -1, 175,
-1, 176, -1, 177, -1, 62, 133, 178, -1, 178,
63, 133, 178, -1, 176, 63, 133, 178, -1, 178,
64, 133, 178, -1, 177, 64, 133, 178, -1, 111,
133, 174, 136, 133, -1, 179, -1, 111, 1, 257,
259, 136, 133, -1, 111, 133, 13, 133, 17, 133,
233, 230, 136, 133, -1, 111, 133, 13, 133, 17,
133, 1, 259, 136, 133, -1, -1, 180, 38, 133,
-1, 180, 39, 133, -1, 181, 183, 167, 113, 165,
133, 258, 184, 135, -1, 13, -1, 12, -1, 185,
-1, 185, 189, -1, -1, 185, 186, 133, 258, -1,
185, 189, 253, 133, 258, -1, 187, 113, 133, 226,
135, -1, 188, 133, -1, 187, 112, 133, 188, 133,
-1, 202, 86, -1, 13, -1, 1, 260, -1, -1,
190, 23, 133, 192, 206, 113, 165, 204, 193, 135,
-1, 13, 133, -1, 13, 223, 133, -1, 223, 133,
-1, -1, 226, -1, 193, 194, 133, 226, -1, -1,
196, 195, 133, 113, 133, 226, 135, -1, 40, -1,
41, -1, 42, -1, 43, -1, 44, -1, 45, -1,
46, -1, 47, -1, 48, -1, 49, -1, 50, -1,
51, -1, 52, -1, 53, -1, 54, -1, 55, -1,
-1, 197, 26, 167, 113, 165, 204, 226, 135, -1,
-1, 199, 29, 167, 113, 165, 204, 226, 135, -1,
114, 133, -1, 115, 133, -1, 116, 133, -1, 117,
13, 117, 133, -1, 203, -1, -1, 118, -1, 114,
-1, 133, -1, -1, -1, -1, 205, 210, 207, 206,
113, 165, 204, 226, 135, -1, -1, 211, -1, 210,
207, 112, 133, 209, 211, -1, 213, -1, 211, 5,
-1, 211, 5, 213, -1, 211, 201, 213, -1, 21,
-1, 20, 21, -1, 13, 21, -1, 215, -1, 215,
216, -1, 216, -1, 212, 215, -1, 212, 215, 216,
-1, 212, 216, -1, 213, -1, 214, 133, 112, 133,
213, -1, 13, -1, 20, -1, 217, -1, 216, 217,
-1, 16, -1, 15, -1, 218, -1, 220, -1, 224,
-1, 18, 13, -1, 13, 133, -1, 19, 133, 219,
137, -1, 19, 133, 219, 221, 133, 222, 133, 137,
-1, 19, 133, 212, 219, 137, -1, 19, 133, 212,
219, 221, 133, 222, 133, 137, -1, 19, 225, 137,
-1, 119, -1, 7, -1, 8, -1, 9, -1, 10,
-1, 11, -1, 13, -1, 12, -1, 17, 13, -1,
17, 257, 13, -1, 17, 17, 257, 13, -1, 17,
17, 100, 133, 214, 133, 136, -1, 17, 17, 100,
225, 136, -1, 17, 99, 133, 214, 133, 136, -1,
17, 99, 225, 136, -1, 17, 98, 133, 14, 133,
136, -1, 17, 98, 133, 202, 88, 133, 136, -1,
17, 98, 133, 13, 133, 136, -1, 17, 98, 225,
136, -1, 17, 101, 133, 213, 133, 136, -1, 17,
101, 225, 136, -1, 17, 104, 133, 214, 133, 136,
-1, 17, 104, 225, 136, -1, 17, 105, 133, 214,
133, 136, -1, 17, 105, 225, 136, -1, 1, 257,
259, -1, -1, 228, -1, 227, 228, -1, 227, -1,
228, 110, 133, -1, 227, 228, 110, 133, -1, 229,
17, 133, 257, 233, 230, -1, 229, 17, 133, 257,
233, 230, 1, 259, -1, 229, 17, 133, 257, 1,
259, -1, 229, 1, 257, 259, -1, 1, 257, 259,
-1, 257, 13, 133, -1, 57, 133, -1, -1, 13,
133, -1, 231, 13, 133, -1, 111, 133, 136, -1,
111, 133, 231, 136, -1, 111, 133, 234, 136, -1,
236, -1, 233, 235, 236, -1, 233, 236, -1, 1,
257, 259, -1, 117, 133, -1, 112, 133, -1, 237,
133, -1, 203, 237, 133, -1, 12, 133, -1, 13,
133, -1, 84, 133, -1, 203, 84, 133, -1, 97,
133, -1, 106, 133, -1, 15, 133, -1, 120, 133,
-1, 238, 133, -1, 244, 133, -1, 121, 133, -1,
232, 133, -1, 88, -1, 87, -1, 86, -1, 70,
-1, 71, -1, 72, -1, 73, -1, 74, -1, 75,
-1, 76, -1, 77, -1, 78, -1, 79, -1, 80,
-1, 81, -1, 82, -1, 83, -1, 68, -1, 67,
-1, 69, -1, 65, -1, 66, -1, 89, -1, 90,
-1, 91, -1, 92, -1, 93, -1, 94, -1, 95,
-1, 96, -1, 98, 133, 233, 136, -1, 98, 133,
136, -1, 98, 133, 234, 136, -1, 237, -1, 203,
237, -1, 132, 114, 132, -1, 132, 118, 132, -1,
241, 20, 133, -1, 241, 117, 133, -1, -1, 5,
-1, 111, 133, 243, 241, 136, -1, 111, 133, 234,
136, -1, 239, -1, 243, 240, 239, -1, 243, 240,
242, -1, 242, -1, 103, 133, 243, 241, 136, -1,
103, 133, 234, 136, -1, 56, -1, 196, -1, 247,
252, 248, -1, 1, 257, 260, -1, 252, 138, -1,
252, 253, -1, 181, 247, -1, 190, 23, 247, -1,
197, 26, 247, -1, 172, 25, 1, 257, 260, -1,
199, 29, 247, -1, 150, 247, -1, 28, 247, -1,
257, 245, 247, -1, 1, 257, 260, 252, 253, -1,
249, 252, 110, -1, 249, 252, 253, -1, 168, 162,
110, -1, 1, 257, 260, 252, -1, 249, 252, -1,
168, 162, -1, -1, 113, 259, 135, -1, 19, 259,
137, -1, 256, 259, 136, -1, 111, -1, 98, -1,
103, -1, 99, -1, 101, -1, 100, -1, 102, -1,
104, -1, -1, -1, -1, 259, 1, -1, 259, 253,
-1, 259, 254, -1, 259, 255, -1, -1, 260, 1,
-1, 260, 254, -1, 260, 255, -1
};
/* YYRLINE[YYN] -- source line where rule number YYN was defined. */
static const yytype_uint16 yyrline[] =
{
0, 374, 374, 375, 376, 377, 378, 379, 380, 381,
382, 386, 392, 398, 404, 410, 420, 426, 433, 439,
440, 444, 445, 448, 450, 451, 455, 456, 460, 461,
465, 466, 470, 471, 474, 476, 481, 484, 486, 493,
494, 495, 496, 497, 498, 499, 500, 501, 505, 511,
516, 523, 524, 528, 529, 535, 541, 542, 543, 544,
545, 546, 547, 548, 552, 556, 563, 569, 576, 579,
585, 592, 593, 597, 598, 602, 605, 611, 617, 623,
627, 634, 637, 643, 646, 649, 655, 658, 665, 666,
670, 677, 680, 684, 688, 692, 699, 703, 710, 716,
722, 728, 731, 737, 741, 747, 754, 761, 762, 763,
764, 768, 774, 777, 783, 786, 792, 795, 796, 803,
817, 824, 830, 833, 839, 845, 846, 850, 851, 856,
860, 864, 871, 877, 881, 888, 891, 903, 909, 915,
929, 933, 938, 942, 949, 950, 954, 954, 962, 965,
968, 971, 974, 977, 980, 983, 986, 989, 992, 995,
998, 1001, 1004, 1007, 1013, 1019, 1026, 1033, 1041, 1042,
1043, 1044, 1053, 1054, 1058, 1059, 1063, 1069, 1076, 1082,
1088, 1094, 1099, 1104, 1111, 1112, 1113, 1124, 1137, 1138,
1139, 1143, 1146, 1151, 1156, 1161, 1166, 1174, 1178, 1185,
1190, 1197, 1198, 1204, 1211, 1222, 1223, 1224, 1228, 1238,
1246, 1251, 1257, 1262, 1268, 1274, 1277, 1280, 1283, 1286,
1289, 1295, 1296, 1300, 1313, 1326, 1341, 1350, 1358, 1368,
1372, 1382, 1392, 1409, 1413, 1428, 1431, 1441, 1445, 1455,
1461, 1464, 1465, 1466, 1469, 1473, 1477, 1484, 1501, 1508,
1514, 1520, 1527, 1536, 1537, 1541, 1545, 1552, 1555, 1558,
1564, 1568, 1573, 1580, 1586, 1589, 1595, 1596, 1597, 1598,
1600, 1601, 1602, 1603, 1604, 1605, 1607, 1608, 1609, 1612,
1616, 1617, 1618, 1619, 1620, 1621, 1622, 1623, 1624, 1625,
1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635,
1636, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649,
1653, 1656, 1659, 1665, 1666, 1670, 1673, 1676, 1679, 1684,
1686, 1690, 1695, 1701, 1705, 1710, 1715, 1719, 1722, 1729,
1730, 1734, 1738, 1744, 1745, 1749, 1750, 1751, 1752, 1756,
1759, 1760, 1761, 1768, 1771, 1772, 1773, 1777, 1780, 1781,
1785, 1791, 1797, 1801, 1804, 1804, 1804, 1804, 1804, 1804,
1804, 1804, 1807, 1812, 1817, 1819, 1820, 1821, 1822, 1825,
1827, 1828, 1829
};
#endif
#if YYDEBUG || YYERROR_VERBOSE || YYTOKEN_TABLE
/* YYTNAME[SYMBOL-NUM] -- String name of the symbol SYMBOL-NUM.
First, the terminals, then, starting at YYNTOKENS, nonterminals. */
static const char *const yytname[] =
{
"TOKEN_EOF", "error", "$undefined", "LOWEST_PREC", "UNIMPORTANT_TOK",
"WHITESPACE", "SGML_CD", "INCLUDES", "DASHMATCH", "BEGINSWITH",
"ENDSWITH", "CONTAINS", "STRING", "IDENT", "NTH", "HEX", "IDSEL", "':'",
"'.'", "'['", "'*'", "'|'", "IMPORT_SYM", "PAGE_SYM", "MEDIA_SYM",
"SUPPORTS_SYM", "FONT_FACE_SYM", "CHARSET_SYM", "NAMESPACE_SYM",
"VIEWPORT_RULE_SYM", "INTERNAL_DECLS_SYM", "INTERNAL_MEDIALIST_SYM",
"INTERNAL_RULE_SYM", "INTERNAL_SELECTOR_SYM", "INTERNAL_VALUE_SYM",
"INTERNAL_KEYFRAME_RULE_SYM", "INTERNAL_KEYFRAME_KEY_LIST_SYM",
"INTERNAL_SUPPORTS_CONDITION_SYM", "KEYFRAMES_SYM",
"WEBKIT_KEYFRAMES_SYM", "TOPLEFTCORNER_SYM", "TOPLEFT_SYM",
"TOPCENTER_SYM", "TOPRIGHT_SYM", "TOPRIGHTCORNER_SYM",
"BOTTOMLEFTCORNER_SYM", "BOTTOMLEFT_SYM", "BOTTOMCENTER_SYM",
"BOTTOMRIGHT_SYM", "BOTTOMRIGHTCORNER_SYM", "LEFTTOP_SYM",
"LEFTMIDDLE_SYM", "LEFTBOTTOM_SYM", "RIGHTTOP_SYM", "RIGHTMIDDLE_SYM",
"RIGHTBOTTOM_SYM", "ATKEYWORD", "IMPORTANT_SYM", "MEDIA_ONLY",
"MEDIA_NOT", "MEDIA_AND", "MEDIA_OR", "SUPPORTS_NOT", "SUPPORTS_AND",
"SUPPORTS_OR", "REMS", "CHS", "QEMS", "EMS", "EXS", "PXS", "CMS", "MMS",
"INS", "PTS", "PCS", "DEGS", "RADS", "GRADS", "TURNS", "MSECS", "SECS",
"HERTZ", "KHERTZ", "DIMEN", "INVALIDDIMEN", "PERCENTAGE", "FLOATTOKEN",
"INTEGER", "VW", "VH", "VMIN", "VMAX", "DPPX", "DPI", "DPCM", "FR",
"URI", "FUNCTION", "ANYFUNCTION", "CUEFUNCTION", "NOTFUNCTION",
"DISTRIBUTEDFUNCTION", "CALCFUNCTION", "HOSTFUNCTION",
"HOSTCONTEXTFUNCTION", "UNICODERANGE", "'}'", "')'", "']'", "';'", "'('",
"','", "'{'", "'+'", "'~'", "'>'", "'/'", "'-'", "'='", "'#'", "'%'",
"$accept", "stylesheet", "internal_rule", "internal_keyframe_rule",
"internal_keyframe_key_list", "internal_decls", "internal_value",
"internal_medialist", "internal_selector", "internal_supports_condition",
"space", "maybe_space", "maybe_sgml", "closing_brace",
"closing_parenthesis", "closing_square_bracket", "semi_or_eof",
"maybe_charset", "rule_list", "valid_rule", "before_rule", "rule",
"block_rule_body", "block_rule_list", "block_rule_recovery",
"block_valid_rule", "block_rule", "before_import_rule",
"import_rule_start", "import", "namespace", "maybe_ns_prefix",
"string_or_uri", "maybe_media_value", "media_query_exp",
"media_query_exp_list", "maybe_and_media_query_exp_list",
"maybe_media_restrictor", "valid_media_query", "media_query",
"maybe_media_list", "media_list", "mq_list", "at_rule_body_start",
"before_media_rule", "at_rule_header_end_maybe_space",
"media_rule_start", "media", "medium", "supports",
"before_supports_rule", "at_supports_rule_header_end",
"supports_condition", "supports_negation", "supports_conjunction",
"supports_disjunction", "supports_condition_in_parens",
"supports_declaration_condition", "before_keyframes_rule",
"keyframes_rule_start", "keyframes", "keyframe_name", "keyframes_rule",
"keyframe_rule_list", "keyframe_rule", "key_list", "key",
"keyframes_error_recovery", "before_page_rule", "page", "page_selector",
"declarations_and_margins", "margin_box", "$@1", "margin_sym",
"before_font_face_rule", "font_face", "before_viewport_rule", "viewport",
"combinator", "maybe_unary_operator", "unary_operator",
"maybe_space_before_declaration", "before_selector_list",
"at_rule_header_end", "at_selector_end", "ruleset",
"before_selector_group_item", "selector_list", "selector",
"namespace_selector", "simple_selector", "simple_selector_list",
"element_name", "specifier_list", "specifier", "class", "attr_name",
"attrib", "match", "ident_or_string", "pseudo_page", "pseudo",
"selector_recovery", "declaration_list", "decl_list", "declaration",
"property", "prio", "ident_list", "track_names_list", "expr",
"expr_recovery", "operator", "term", "unary_term", "function",
"calc_func_term", "calc_func_operator", "calc_maybe_space",
"calc_func_paren_expr", "calc_func_expr", "calc_function", "invalid_at",
"at_rule_recovery", "at_rule_header_recovery", "at_rule_end",
"regular_invalid_at_rule_header", "invalid_rule", "invalid_rule_header",
"at_invalid_rule_header_end", "invalid_block",
"invalid_square_brackets_block", "invalid_parentheses_block",
"opening_parenthesis", "error_location", "location_label",
"error_recovery", "rule_error_recovery", 0
};
#endif
# ifdef YYPRINT
/* YYTOKNUM[YYLEX-NUM] -- Internal token number corresponding to
token YYLEX-NUM. */
static const yytype_uint16 yytoknum[] =
{
0, 256, 257, 258, 259, 260, 261, 262, 263, 264,
265, 266, 267, 268, 269, 270, 271, 58, 46, 91,
42, 124, 272, 273, 274, 275, 276, 277, 278, 279,
280, 281, 282, 283, 284, 285, 286, 287, 288, 289,
290, 291, 292, 293, 294, 295, 296, 297, 298, 299,
300, 301, 302, 303, 304, 305, 306, 307, 308, 309,
310, 311, 312, 313, 314, 315, 316, 317, 318, 319,
320, 321, 322, 323, 324, 325, 326, 327, 328, 329,
330, 331, 332, 333, 334, 335, 336, 337, 338, 339,
340, 341, 342, 343, 344, 345, 346, 347, 348, 349,
350, 351, 352, 353, 354, 355, 356, 125, 41, 93,
59, 40, 44, 123, 43, 126, 62, 47, 45, 61,
35, 37
};
# endif
/* YYR1[YYN] -- Symbol number of symbol that rule YYN derives. */
static const yytype_uint16 yyr1[] =
{
0, 122, 123, 123, 123, 123, 123, 123, 123, 123,
123, 124, 125, 126, 127, 128, 129, 130, 131, 132,
132, 133, 133, 134, 134, 134, 135, 135, 136, 136,
137, 137, 138, 138, 139, 139, 139, 140, 140, 141,
141, 141, 141, 141, 141, 141, 141, 141, 142, 143,
143, 144, 144, 145, 145, 146, 147, 147, 147, 147,
147, 147, 147, 147, 148, 148, 149, 150, 151, 151,
152, 153, 153, 154, 154, 155, 155, 156, 156, 157,
157, 158, 158, 159, 159, 159, 160, 160, 161, 161,
161, 162, 162, 163, 163, 163, 164, 164, 165, 166,
167, 168, 169, 170, 171, 172, 173, 174, 174, 174,
174, 175, 176, 176, 177, 177, 178, 178, 178, 179,
179, 180, 181, 181, 182, 183, 183, 184, 184, 185,
185, 185, 186, 187, 187, 188, 188, 189, 190, 191,
192, 192, 192, 192, 193, 193, 195, 194, 196, 196,
196, 196, 196, 196, 196, 196, 196, 196, 196, 196,
196, 196, 196, 196, 197, 198, 199, 200, 201, 201,
201, 201, 202, 202, 203, 203, 204, 205, 206, 207,
208, 209, 210, 210, 211, 211, 211, 211, 212, 212,
212, 213, 213, 213, 213, 213, 213, 214, 214, 215,
215, 216, 216, 217, 217, 217, 217, 217, 218, 219,
220, 220, 220, 220, 220, 221, 221, 221, 221, 221,
221, 222, 222, 223, 224, 224, 224, 224, 224, 224,
224, 224, 224, 224, 224, 224, 224, 224, 224, 224,
225, 226, 226, 226, 226, 227, 227, 228, 228, 228,
228, 228, 229, 230, 230, 231, 231, 232, 232, 232,
233, 233, 233, 234, 235, 235, 236, 236, 236, 236,
236, 236, 236, 236, 236, 236, 236, 236, 236, 236,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
237, 237, 237, 237, 237, 237, 237, 237, 237, 237,
238, 238, 238, 239, 239, 240, 240, 240, 240, 241,
241, 242, 242, 243, 243, 243, 243, 244, 244, 245,
245, 246, 247, 248, 248, 249, 249, 249, 249, 249,
249, 249, 249, 250, 250, 250, 250, 251, 251, 251,
252, 253, 254, 255, 256, 256, 256, 256, 256, 256,
256, 256, 257, 258, 259, 259, 259, 259, 259, 260,
260, 260, 260
};
/* YYR2[YYN] -- Number of symbols composing right hand side of rule YYN. */
static const yytype_uint8 yyr2[] =
{
0, 2, 3, 1, 1, 1, 1, 1, 1, 1,
1, 5, 5, 4, 4, 4, 5, 4, 4, 1,
2, 0, 1, 0, 2, 2, 1, 1, 1, 1,
1, 1, 1, 1, 0, 5, 2, 0, 3, 1,
1, 1, 1, 1, 1, 1, 1, 1, 0, 2,
2, 1, 2, 0, 3, 2, 1, 1, 1, 1,
1, 1, 1, 1, 2, 2, 0, 3, 6, 6,
6, 0, 2, 1, 1, 0, 3, 6, 4, 1,
5, 1, 5, 0, 2, 2, 2, 3, 1, 4,
3, 0, 1, 1, 2, 1, 4, 5, 0, 0,
1, 3, 8, 1, 10, 0, 0, 1, 1, 1,
1, 3, 4, 4, 4, 4, 5, 1, 6, 10,
10, 0, 3, 3, 9, 1, 1, 1, 2, 0,
4, 5, 5, 2, 5, 2, 1, 2, 0, 10,
2, 3, 2, 0, 1, 4, 0, 7, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 0, 8, 0, 8, 2, 2,
2, 4, 1, 0, 1, 1, 1, 0, 0, 0,
9, 0, 1, 6, 1, 2, 3, 3, 1, 2,
2, 1, 2, 1, 2, 3, 2, 1, 5, 1,
1, 1, 2, 1, 1, 1, 1, 1, 2, 2,
4, 8, 5, 9, 3, 1, 1, 1, 1, 1,
1, 1, 1, 2, 3, 4, 7, 5, 6, 4,
6, 7, 6, 4, 6, 4, 6, 4, 6, 4,
3, 0, 1, 2, 1, 3, 4, 6, 8, 6,
4, 3, 3, 2, 0, 2, 3, 3, 4, 4,
1, 3, 2, 3, 2, 2, 2, 3, 2, 2,
2, 3, 2, 2, 2, 2, 2, 2, 2, 2,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
4, 3, 4, 1, 2, 3, 3, 3, 3, 0,
1, 5, 4, 1, 3, 3, 1, 5, 4, 1,
1, 3, 3, 2, 2, 2, 3, 3, 5, 3,
2, 2, 3, 5, 3, 3, 3, 4, 2, 2,
0, 3, 3, 3, 1, 1, 1, 1, 1, 1,
1, 1, 0, 0, 0, 2, 2, 2, 2, 0,
2, 2, 2
};
/* YYDEFACT[STATE-NAME] -- Default reduction number in state STATE-NUM.
Performed when YYTABLE doesn't specify something else to do. Zero
means the default is an error. */
static const yytype_uint16 yydefact[] =
{
34, 0, 21, 21, 21, 21, 21, 21, 21, 21,
0, 4, 8, 9, 3, 6, 7, 5, 10, 23,
362, 19, 22, 0, 36, 350, 176, 0, 363, 177,
0, 0, 173, 173, 0, 1, 37, 369, 20, 21,
350, 362, 0, 0, 242, 0, 0, 0, 21, 21,
0, 0, 45, 44, 0, 0, 40, 46, 0, 0,
0, 43, 0, 41, 0, 42, 0, 47, 0, 39,
199, 204, 203, 362, 0, 0, 200, 188, 179, 182,
0, 184, 191, 193, 201, 205, 206, 207, 21, 21,
21, 300, 301, 298, 297, 299, 283, 284, 285, 286,
287, 288, 289, 290, 291, 292, 293, 294, 295, 296,
21, 282, 281, 280, 302, 303, 304, 305, 306, 307,
308, 309, 21, 21, 21, 21, 21, 175, 174, 21,
21, 0, 21, 0, 260, 21, 21, 21, 136, 21,
0, 21, 0, 172, 0, 21, 0, 0, 108, 109,
110, 107, 117, 25, 24, 48, 0, 0, 331, 0,
364, 14, 243, 21, 362, 21, 21, 362, 21, 21,
0, 79, 21, 0, 0, 93, 0, 92, 0, 71,
0, 21, 73, 74, 21, 21, 178, 21, 21, 21,
126, 125, 21, 21, 21, 21, 179, 190, 362, 0,
0, 0, 0, 0, 0, 208, 362, 0, 0, 189,
17, 0, 185, 21, 21, 21, 0, 0, 199, 200,
194, 196, 192, 202, 268, 269, 274, 270, 272, 0,
0, 273, 0, 275, 278, 21, 21, 279, 15, 21,
21, 0, 262, 266, 276, 277, 0, 21, 21, 133,
135, 13, 0, 362, 0, 18, 21, 21, 21, 21,
0, 23, 370, 364, 355, 357, 359, 358, 360, 356,
361, 354, 371, 372, 364, 33, 32, 35, 364, 333,
334, 0, 21, 245, 364, 362, 252, 369, 84, 85,
364, 0, 86, 103, 21, 362, 21, 16, 94, 21,
0, 11, 67, 363, 101, 0, 0, 122, 123, 100,
0, 143, 0, 0, 178, 0, 0, 173, 0, 0,
0, 0, 0, 0, 0, 0, 0, 224, 364, 21,
0, 0, 0, 31, 30, 214, 21, 186, 168, 169,
170, 0, 187, 195, 29, 362, 28, 311, 0, 0,
21, 0, 0, 313, 323, 326, 319, 21, 257, 0,
0, 271, 267, 265, 264, 261, 12, 173, 0, 111,
364, 21, 0, 0, 0, 0, 0, 362, 0, 49,
0, 0, 0, 0, 0, 0, 0, 350, 50, 0,
38, 0, 0, 0, 365, 366, 367, 368, 246, 0,
0, 0, 0, 21, 21, 81, 87, 369, 363, 21,
72, 21, 0, 98, 106, 98, 21, 0, 178, 21,
98, 98, 0, 0, 0, 225, 21, 21, 0, 233,
197, 21, 229, 21, 235, 21, 237, 21, 239, 0,
209, 21, 0, 216, 217, 218, 219, 220, 215, 210,
21, 181, 21, 364, 310, 312, 0, 314, 328, 320,
0, 0, 0, 255, 21, 258, 259, 21, 0, 0,
0, 21, 113, 115, 112, 114, 369, 341, 340, 178,
0, 335, 0, 0, 0, 0, 148, 149, 150, 151,
152, 153, 154, 155, 156, 157, 158, 159, 160, 161,
162, 163, 329, 330, 0, 352, 353, 27, 26, 351,
364, 254, 78, 75, 0, 21, 0, 96, 363, 0,
0, 21, 0, 21, 140, 21, 223, 0, 142, 21,
21, 98, 21, 227, 0, 0, 21, 0, 0, 0,
0, 212, 21, 0, 0, 171, 0, 0, 319, 0,
0, 324, 325, 21, 21, 327, 256, 134, 132, 21,
21, 116, 0, 346, 362, 336, 337, 339, 344, 345,
342, 0, 21, 0, 21, 0, 80, 0, 97, 70,
68, 69, 53, 98, 363, 141, 98, 0, 0, 21,
0, 232, 230, 0, 21, 228, 234, 236, 238, 0,
222, 221, 21, 183, 322, 0, 315, 316, 317, 318,
118, 0, 0, 369, 253, 364, 0, 77, 21, 0,
48, 21, 129, 21, 0, 0, 0, 226, 231, 0,
21, 0, 321, 364, 254, 343, 0, 0, 76, 82,
102, 0, 52, 23, 53, 0, 0, 0, 165, 167,
0, 198, 0, 211, 0, 0, 362, 64, 0, 63,
0, 59, 61, 60, 57, 58, 62, 56, 350, 65,
55, 54, 0, 124, 369, 21, 128, 0, 144, 180,
213, 21, 21, 369, 349, 348, 104, 0, 363, 21,
139, 21, 146, 120, 119, 0, 130, 363, 0, 21,
347, 131, 145, 0, 21, 0, 0, 147
};
/* YYDEFGOTO[NTERM-NUM]. */
static const yytype_int16 yydefgoto[] =
{
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18,
22, 26, 36, 509, 347, 335, 277, 19, 155, 49,
260, 261, 619, 620, 642, 657, 643, 50, 51, 52,
53, 300, 184, 575, 171, 172, 406, 173, 174, 175,
176, 177, 178, 521, 54, 312, 55, 56, 294, 57,
382, 522, 147, 148, 149, 150, 151, 152, 59, 383,
61, 192, 645, 646, 139, 140, 141, 676, 384, 63,
418, 677, 691, 699, 503, 385, 65, 386, 67, 217,
142, 131, 27, 68, 305, 211, 69, 544, 78, 79,
80, 430, 431, 82, 83, 84, 85, 332, 86, 450,
602, 419, 87, 208, 42, 43, 44, 45, 573, 359,
132, 133, 349, 241, 134, 135, 136, 354, 461, 462,
355, 356, 137, 504, 24, 478, 158, 387, 388, 670,
40, 395, 396, 397, 274, 46, 47, 281, 156
};
/* YYPACT[STATE-NUM] -- Index in YYTABLE of the portion describing
STATE-NUM. */
#define YYPACT_NINF -366
static const yytype_int16 yypact[] =
{
795, 368, 45, 45, 45, 45, 45, 45, 45, 45,
76, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, -366, 87, 100, -366, -366, -366, 303, -366, 820,
859, 1739, 183, 183, -4, -366, 277, -366, -366, 45,
-366, -366, 127, 1838, 20, 62, 124, 271, 45, 45,
120, 229, -366, -366, 149, 252, -366, -366, 178, 283,
321, -366, 213, -366, 226, -366, 235, -366, 859, -366,
248, -366, -366, 444, 279, 505, 268, -366, 300, 228,
953, -366, 469, 469, -366, -366, -366, -366, 45, 45,
45, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, -366, -366, -366, -366, -366, -366, -366, -366, -366,
45, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, -366, 45, 45, 45, 45, 45, -366, -366, 45,
45, 1847, 45, 821, -366, 45, 45, 45, -366, 45,
266, 45, 219, -366, 21, 45, 38, 309, -366, 256,
251, 324, -366, -366, -366, 325, 633, 16, -366, 33,
-366, -366, 221, 45, -366, 45, 45, -366, 45, 45,
80, -366, 45, 338, 44, 225, 364, -366, 361, 358,
376, 45, -366, -366, 45, 45, -366, 45, 45, 45,
-366, -366, 45, 45, 45, 45, -366, -366, 289, 64,
638, 638, 638, 638, 379, -366, -366, 334, 30, -366,
-366, 292, 859, 45, 45, 45, 393, 859, -366, -366,
469, 469, 469, -366, -366, -366, -366, -366, -366, 936,
1193, -366, 224, -366, -366, 45, 45, -366, -366, 45,
45, 1739, -366, -366, -366, -366, 409, 45, 45, -366,
-366, -366, 311, -366, 237, -366, 45, 45, 45, 45,
1931, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, 1277, 45, -366, -366, -366, -366, -366, -366, -366,
-366, 403, 367, -366, 45, -366, 45, -366, 323, 45,
229, -366, -366, -366, -366, 308, -4, -366, -366, -366,
326, 97, 329, 330, 292, 638, 425, 310, 82, 859,
82, 859, 82, 859, 82, 859, 82, -366, -366, 49,
268, 434, 448, -366, -366, -366, 45, -366, -366, -366,
-366, 333, -366, 469, -366, -366, -366, -366, 682, 82,
45, 2033, 82, -366, -366, -366, 447, 45, -366, 230,
82, -366, -366, -366, -366, -366, -366, 183, 104, -366,
-366, 45, 82, 311, 311, 311, 311, -366, 432, -366,
79, 728, 428, 305, 431, 436, 435, -366, -366, 1734,
277, 976, 1065, 1350, -366, -366, -366, -366, -366, 1293,
1036, 476, 1065, 45, 45, 405, -366, -366, -366, 45,
-366, 45, 591, -366, -366, -366, 85, 454, -366, 45,
-366, -366, 347, 859, 82, -366, 45, 45, 381, -366,
-366, 45, -366, 45, -366, 45, -366, 45, -366, 854,
-366, 45, 448, -366, -366, -366, -366, -366, -366, -366,
45, -366, 45, -366, -366, -366, 1193, -366, -366, 103,
108, 1979, 53, -366, 45, -366, -366, 45, 46, 1065,
458, 45, -366, -366, -366, -366, -366, -366, -366, 370,
70, -366, 262, 110, 110, -27, -366, -366, -366, -366,
-366, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, -366, -366, -366, 477, -366, -366, -366, -366, -366,
-366, 1565, -366, 472, 382, 45, 607, -366, -366, 16,
33, 45, 391, 45, -366, 45, -366, 394, -366, 45,
45, -366, 45, -366, 82, 82, 45, 166, 82, 166,
166, -366, 45, 400, 859, -366, 1424, 82, 447, 45,
45, -366, -366, 45, 45, -366, -366, -366, -366, 45,
45, -366, 398, -366, -366, -366, -366, -366, -366, -366,
-366, 1367, 45, 1519, 45, 82, -366, 382, -366, -366,
-366, -366, -366, -366, -366, -366, -366, 104, 104, 45,
166, -366, -366, 82, 45, -366, -366, -366, -366, 400,
-366, -366, 45, 228, -366, 53, 87, 87, -366, -366,
-366, 1136, 402, -366, -366, -366, 1739, -366, 45, 46,
72, 45, -366, 45, 46, 46, 104, -366, -366, 859,
45, 30, -366, -366, 1565, -366, 960, 1441, 1652, 367,
-366, 1987, -366, -366, -366, 46, 159, 1854, -366, -366,
46, -366, 30, -366, 1065, 82, -366, -366, 477, -366,
614, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-366, 277, 46, -366, -366, 45, 402, 1650, -366, -366,
-366, 45, 45, -366, 6, -27, -366, 1497, -366, 45,
-366, 45, -366, -366, -366, 1514, -366, -366, 1854, 45,
402, -366, -366, 406, 45, 104, 46, -366
};
/* YYPGOTO[NTERM-NUM]. */
static const yytype_int16 yypgoto[] =
{
-366, -366, -366, -366, -366, -366, -366, -366, -366, -366,
-330, -1, -246, -365, 276, -292, -125, -366, -366, 234,
-104, -366, -123, -366, -366, -366, -366, -366, -241, -366,
-118, -366, 227, -366, 14, -44, -366, -366, -366, 352,
-54, -366, -366, -354, -366, -164, -236, -107, -366, -103,
510, -366, -205, -366, -366, -366, -168, -366, -366, 511,
-97, -366, -366, -366, -99, 517, 184, -366, 531, -78,
-366, -366, -366, -366, -112, 537, -73, 540, -71, -366,
255, -15, -239, -366, -255, 385, -59, -366, 516, 41,
383, -8, -83, 515, -25, -47, -366, 272, -366, 155,
0, 189, -366, -105, -339, -366, 566, -366, -24, -366,
-366, -215, -195, -366, -121, -89, -366, 150, -366, 65,
151, 160, -366, -366, -366, 8, -366, -23, -22, -366,
-30, -139, -133, -131, -366, -9, -290, -222, -260
};
/* YYTABLE[YYPACT[STATE-NUM]]. What to do in state STATE-NUM. If
positive, shift that token. If negative, reduce the rule which
number is the opposite. If YYTABLE_NINF, syntax error. */
#define YYTABLE_NINF -363
static const yytype_int16 yytable[] =
{
23, 186, 28, 29, 30, 31, 32, 33, 34, 25,
159, 37, 242, 412, 348, 390, 275, 143, 143, 380,
280, 251, 81, 272, 381, 273, 460, 401, 310, 468,
333, 313, 160, 275, 279, 352, 223, 360, 157, 253,
449, 391, 236, 21, -88, 295, 507, 179, 180, 372,
21, -21, 392, 344, 21, 221, 393, 222, 145, 422,
81, 523, 399, 164, 204, 206, 529, 530, 402, 21,
197, 564, -51, 553, 207, 21, 35, -21, -21, 165,
20, 290, 344, 568, 369, 21, 278, 224, 225, 226,
21, 182, 38, -21, 318, 320, 322, 324, 326, 505,
-21, 414, 417, 558, -241, 41, 439, 146, -19, 227,
416, 20, 39, 38, 417, 21, 563, -362, 517, -178,
365, 228, 229, 230, 231, 232, 276, 161, 233, 234,
163, 237, -21, 247, 243, 244, 245, 166, 246, 334,
249, 353, 181, 276, 252, 254, 278, 516, 469, -21,
541, -88, -21, 508, -88, 284, -88, -88, 287, -127,
674, 346, 283, 527, 285, 286, 344, 288, 289, 291,
554, 292, 138, 185, 223, 223, 183, 589, -21, -51,
302, -21, -21, 303, 304, 511, 306, 307, 308, 316,
346, 309, 311, 309, 309, 343, 138, 328, 317, 319,
321, 323, 325, 187, 337, 472, 473, 474, 475, 342,
424, -241, 338, 339, 340, 351, 562, -19, 460, 606,
607, -19, 549, -21, 344, 345, 550, 242, 578, 621,
344, 546, 623, 212, 361, 362, 193, 357, 363, 364,
435, 182, 437, 464, 370, -173, 367, 368, 624, 625,
371, 389, 194, 167, 640, 373, 374, 375, 376, 648,
649, 547, 457, 20, 195, -83, -127, 21, 272, 197,
273, -91, 167, 127, 346, -21, 400, 128, 594, -21,
673, 398, 153, 154, -83, 679, 407, 650, 571, 209,
587, 588, 205, 405, 622, 408, 223, 127, 410, 145,
210, 128, 143, -241, 41, 250, 20, 686, 678, 255,
168, 169, 690, 433, 423, 257, -362, 190, 191, 256,
313, 188, 189, 426, 427, -2, 183, 479, 440, 168,
169, 282, 346, 190, 191, 451, 453, 296, 346, 653,
532, 707, 213, 214, 215, 216, 569, 329, 146, 456,
626, 293, 143, 636, 330, 77, 463, 485, 520, 702,
680, -95, 167, 170, 297, -91, 706, 353, 476, 20,
470, 299, 353, 21, -83, -21, 301, 179, 247, 248,
-21, 581, 170, 272, 647, 273, 477, 258, 259, 315,
242, 481, 327, 637, 579, 580, 634, 671, 696, 262,
658, 638, 513, 514, 336, 660, 341, 701, 518, 366,
519, 654, 600, 601, 687, 524, 403, 263, 528, 168,
169, 413, 146, 695, 127, 534, 535, 404, 128, 272,
537, 273, 538, 20, 539, 409, 540, 21, 425, 415,
440, 351, 420, 421, -21, -21, 351, 441, 333, 543,
452, 545, 459, 480, 482, 443, 444, 445, 446, 447,
531, 198, 483, 556, 484, 515, 557, 526, -95, 536,
561, -95, 170, 635, -95, 560, -90, 262, 20, 306,
563, 311, 309, 309, 71, 72, 73, 74, 75, 574,
565, 566, 567, 170, 379, 263, 264, 265, 266, 267,
268, 269, 270, 272, 583, 273, 206, 586, 358, 271,
21, -350, 570, 242, 577, 278, 641, 242, -21, 704,
582, 672, 584, 659, 585, -21, -21, 411, 576, -21,
298, 590, 612, 618, 661, 593, 81, 689, 662, 58,
60, 599, 199, 200, 663, 201, 569, 675, 202, 203,
144, 467, 608, 609, 272, 613, 273, 334, 610, 611,
62, 635, 272, 664, 273, 692, 64, 448, 665, 66,
666, 614, 428, 616, 264, 265, 266, 267, 268, 269,
270, 314, 667, -90, 196, 603, -90, 271, -90, -90,
331, -91, 167, 629, 429, 220, 432, 542, 434, 630,
436, 631, 438, 442, -83, 525, 684, -89, 262, 162,
655, 551, 552, 605, -91, 167, 548, 639, 668, 669,
644, 651, 0, 0, 454, 455, 263, -83, 458, 652,
0, 143, 389, -332, 262, 465, 466, 0, 685, 206,
0, 0, 0, 21, 0, 0, 0, 683, 471, 168,
169, -21, 263, -21, -21, -21, -21, -21, -21, -21,
0, 0, 0, 0, 0, 700, 0, 0, 506, 0,
0, 0, 168, 169, 688, 0, 0, 0, 512, 0,
693, 694, 344, 0, 0, 0, 0, 0, 697, 0,
698, 0, 0, 0, 88, 89, 0, 90, 703, 0,
533, -91, 170, 705, -91, 264, 265, 266, 267, 268,
269, 270, 0, 0, -89, 0, 0, -89, 271, -89,
-89, -91, 0, 0, -91, 170, 0, -91, 0, 167,
0, 264, 265, 266, 267, 268, 269, 270, 555, 0,
-332, -83, 0, -332, 271, 559, -332, 91, 92, 93,
94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 0, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 0, 0, 0, 0, 124, 168, 169, 125, 0,
346, 0, 0, 126, 239, 0, 127, 0, 0, 240,
128, 0, 129, 130, 0, 0, 0, 0, 0, 0,
591, 592, 0, 595, 596, 597, 598, 0, 0, 0,
0, 238, 1, 604, 0, 2, 3, 4, 5, 6,
7, 8, 9, 88, 89, 0, 90, 0, -91, 170,
0, -91, -66, -138, -99, -105, -164, 0, 48, -166,
0, 617, 0, 0, -240, 394, 0, 0, -121, -121,
0, 0, 0, 0, 0, 0, 627, 0, 0, 628,
0, 0, 70, 263, 71, 72, 73, 74, 75, 76,
77, 632, 0, 0, 0, 0, 91, 92, 93, 94,
95, 96, 97, 98, 99, 100, 101, 102, 103, 104,
105, 106, 107, 108, 109, 110, 0, 111, 112, 113,
114, 115, 116, 117, 118, 119, 120, 121, 122, 123,
0, 0, 0, 0, 124, 0, 0, 125, 0, 0,
681, 682, 126, 239, 0, 127, 344, 345, 240, 128,
0, 129, 130, 0, 0, 0, 0, 0, 88, 89,
0, 90, 264, 265, 266, 267, 268, 269, 270, 0,
-338, 262, -240, -240, 0, 271, 218, 278, 71, 72,
73, 74, 75, 219, 0, 0, 333, 394, 0, 263,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 263, 0, 0, 0, 0,
0, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 0, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 0, 0, 510, 0, 124,
0, 0, 125, 0, 346, 0, 0, 126, 88, 89,
127, 90, 0, 0, 128, 0, 129, 130, 264, 265,
266, 267, 268, 269, 270, 344, 394, -338, 0, 0,
-338, 271, 0, -338, 264, 265, 266, 267, 268, 269,
270, 0, 0, 0, 263, 334, 0, 271, 0, 278,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 0, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 0, 0, 633, 0, 124,
0, 0, 125, 0, 0, 0, 0, 126, 88, 89,
127, 90, 0, 0, 128, 0, 129, 130, 0, 0,
0, 0, 0, 264, 265, 266, 267, 268, 269, 270,
0, 0, 0, 346, 0, 0, 271, 0, 278, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 345, 0, 0, 0, 0, 0,
0, 91, 92, 93, 94, 95, 96, 97, 98, 99,
100, 101, 102, 103, 104, 105, 106, 107, 108, 109,
110, 0, 111, 112, 113, 114, 115, 116, 117, 118,
119, 120, 121, 122, 123, 0, 0, 0, 0, 124,
0, 0, 125, 0, 0, 0, 0, 126, 0, 0,
127, 0, 0, 0, 128, 0, 129, 130, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, -251, 394, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121,
0, 0, 0, -250, 394, 0, 263, 0, 0, 0,
0, 0, 0, 0, 350, 0, 0, 127, 0, 0,
0, 128, 263, 0, 0, 0, 0, -251, -251, -251,
-251, -251, -251, -251, -251, -251, -251, -251, -251, -251,
-251, -251, -251, -250, -250, -250, -250, -250, -250, -250,
-250, -250, -250, -250, -250, -250, -250, -250, -250, 0,
507, 394, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, -249, 394, 263,
0, 0, 0, 0, 0, 264, 265, 266, 267, 268,
269, 270, 0, 0, -251, 0, 263, -251, 271, 0,
278, 264, 265, 266, 267, 268, 269, 270, 0, 0,
-250, 0, 0, -250, 271, 0, 278, -249, -249, -249,
-249, -249, -249, -249, -249, -249, -249, -249, -249, -249,
-249, -249, -249, 0, -263, 394, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, -248, 394, 263, 0, 0, 0, 0, 264, 265,
266, 267, 268, 269, 270, 0, 0, 508, 0, 0,
263, 271, 0, 278, 0, 264, 265, 266, 267, 268,
269, 270, 0, 0, -249, 0, 0, -249, 271, 0,
278, -248, -248, -248, -248, -248, -248, -248, -248, -248,
-248, -248, -248, -248, -248, -248, -248, -137, 262, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, -350, 262, 263, 0, 0, -247,
615, 0, 264, 265, 266, 267, 268, 269, 270, 0,
0, 0, -263, 263, 0, 271, 0, 278, 0, 264,
265, 266, 267, 268, 269, 270, 0, 0, -248, 0,
0, -248, 271, 0, 278, 0, 0, 0, 0, -247,
-247, -247, -247, -247, -247, -247, -247, -247, -247, -247,
-247, -247, -247, -247, -247, 0, 0, 88, 89, 0,
90, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 264, 265, 266, 267, 268,
269, 270, 0, 0, -137, 0, 0, 0, 271, 0,
-137, 0, 264, 265, 266, 267, 268, 269, 270, 0,
0, -350, 572, 0, 0, 271, -247, -350, 0, -247,
91, 92, 93, 94, 95, 96, 97, 98, 99, 100,
101, 102, 103, 104, 105, 106, 107, 108, 109, 110,
507, 111, 112, 113, 114, 115, 116, 117, 118, 119,
120, 121, 122, 123, 88, 89, 0, 90, 124, 0,
0, 125, 0, 0, 0, 0, 126, 239, 0, 127,
0, 0, 240, 128, 0, 129, 130, 0, 0, 0,
486, 487, 488, 489, 490, 491, 492, 493, 494, 495,
496, 497, 498, 499, 500, 501, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 91, 92, 93,
94, 95, 96, 97, 98, 99, 100, 101, 102, 103,
104, 105, 106, 107, 108, 109, 110, 0, 111, 112,
113, 114, 115, 116, 117, 118, 119, 120, 121, 122,
123, 88, 89, 0, 90, 124, 0, 508, 125, 0,
0, 0, 0, 126, 239, 0, 127, 0, 0, 240,
128, 0, 129, 130, 486, 487, 488, 489, 490, 491,
492, 493, 494, 495, 496, 497, 498, 499, 500, 501,
502, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 110, 0, 111, 112, 113, 114, 115,
116, 117, 118, 119, 120, 121, 122, 123, -244, 41,
0, 0, 124, 0, 0, 125, 0, 0, 0, 0,
126, -362, 0, 127, -241, 41, 0, 128, 0, 129,
130, 0, 0, 0, 0, 0, 0, -362, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, -244, -244,
-244, -244, -244, -244, -244, -244, -244, -244, -244, -244,
-244, -244, -244, -244, -241, -241, -241, -241, -241, -241,
-241, -241, -241, -241, -241, -241, -241, -241, -241, -241,
0, 0, 91, 92, 93, 94, 95, 96, 97, 98,
99, 100, 101, 102, 103, 104, 105, 106, 107, 108,
109, 235, 377, 111, 112, 113, 114, 115, 116, 117,
118, 119, 120, 121, -177, -244, -177, -177, -177, -177,
-177, -177, -177, -66, -138, -99, -105, -164, 0, 378,
-166, -241, 0, 0, 0, 0, 0, 0, 0, -121,
-121, -362, -362, -362, -362, -362, -362, -362, -362, -362,
-362, -362, -362, -362, -362, -362, -362, -362, 656, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
-177, 0, -177, -177, -177, -177, -177, -177, -177, -66,
-138, -99, -105, -164, 0, 378, -166, 0, 0, 0,
0, 0, 0, 0, 0, -121, -121, -362, -362, -362,
-362, -362, -362, -362, -362, -362, -362, -362, -362, -362,
-362, -362, -362, -362, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100, 101, 102, 103, 104, 105, 106,
107, 108, 109, 0, 0, 111, 112, 113, 114, 115,
116, 117, 118, 119, 120, 121, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
350, 0, 0, 127, 0, 0, 0, 128, 91, 92,
93, 94, 95, 96, 97, 98, 99, 100, 101, 102,
103, 104, 105, 106, 107, 108, 109, 0, 0, 111,
112, 113, 114, 115, 116, 117, 118, 119, 120, 121
};
#define yypact_value_is_default(yystate) \
((yystate) == (-366))
#define yytable_value_is_error(yytable_value) \
YYID (0)
static const yytype_int16 yycheck[] =
{
1, 55, 3, 4, 5, 6, 7, 8, 9, 1,
40, 20, 133, 303, 229, 261, 0, 32, 33, 260,
159, 0, 30, 156, 260, 156, 356, 287, 192, 368,
0, 195, 41, 0, 159, 230, 83, 232, 39, 1,
332, 263, 131, 5, 0, 1, 0, 48, 49, 254,
5, 13, 274, 0, 5, 80, 278, 82, 62, 314,
68, 415, 284, 1, 73, 1, 420, 421, 290, 5,
21, 1, 0, 20, 75, 5, 0, 13, 14, 17,
1, 1, 0, 110, 252, 5, 113, 88, 89, 90,
5, 12, 5, 13, 199, 200, 201, 202, 203, 391,
62, 306, 17, 468, 0, 1, 328, 111, 5, 110,
13, 1, 12, 5, 17, 5, 110, 13, 408, 113,
241, 122, 123, 124, 125, 126, 110, 0, 129, 130,
110, 132, 62, 112, 135, 136, 137, 13, 139, 109,
141, 230, 22, 110, 145, 146, 113, 407, 370, 111,
442, 107, 88, 107, 110, 164, 112, 113, 167, 0,
1, 108, 163, 418, 165, 166, 0, 168, 169, 170,
117, 172, 13, 24, 221, 222, 97, 531, 114, 107,
181, 111, 118, 184, 185, 400, 187, 188, 189, 198,
108, 192, 193, 194, 195, 220, 13, 206, 199, 200,
201, 202, 203, 25, 212, 373, 374, 375, 376, 217,
315, 107, 213, 214, 215, 230, 476, 114, 548, 549,
550, 118, 114, 113, 0, 1, 118, 348, 518, 583,
0, 453, 586, 5, 235, 236, 23, 13, 239, 240,
323, 12, 325, 13, 253, 86, 247, 248, 587, 588,
13, 260, 26, 1, 619, 256, 257, 258, 259, 624,
625, 456, 351, 1, 29, 13, 107, 5, 401, 21,
401, 0, 1, 114, 108, 13, 285, 118, 112, 17,
645, 282, 5, 6, 13, 650, 295, 626, 510, 21,
529, 530, 13, 294, 584, 296, 343, 114, 299, 62,
0, 118, 317, 0, 1, 86, 1, 672, 647, 0,
58, 59, 677, 321, 315, 64, 13, 12, 13, 63,
484, 38, 39, 13, 14, 0, 97, 381, 329, 58,
59, 110, 108, 12, 13, 336, 345, 112, 108, 631,
423, 706, 114, 115, 116, 117, 485, 13, 111, 350,
589, 13, 367, 613, 20, 21, 357, 387, 412, 698,
652, 0, 1, 111, 0, 113, 705, 456, 377, 1,
371, 13, 461, 5, 13, 113, 0, 378, 112, 113,
12, 520, 111, 516, 623, 516, 378, 63, 64, 100,
511, 383, 13, 615, 519, 520, 611, 643, 688, 1,
641, 616, 403, 404, 112, 641, 13, 697, 409, 0,
411, 633, 12, 13, 674, 416, 13, 19, 419, 58,
59, 113, 111, 683, 114, 426, 427, 60, 118, 562,
431, 562, 433, 1, 435, 112, 437, 5, 13, 113,
441, 456, 113, 113, 12, 13, 461, 13, 0, 450,
117, 452, 5, 25, 23, 7, 8, 9, 10, 11,
113, 17, 26, 464, 29, 60, 467, 13, 107, 88,
471, 110, 111, 612, 113, 17, 0, 1, 1, 480,
110, 482, 483, 484, 15, 16, 17, 18, 19, 17,
482, 483, 484, 111, 260, 19, 98, 99, 100, 101,
102, 103, 104, 636, 113, 636, 1, 113, 232, 111,
5, 113, 504, 634, 515, 113, 620, 638, 13, 113,
521, 644, 523, 641, 525, 20, 21, 300, 514, 97,
178, 532, 562, 577, 641, 536, 544, 676, 641, 29,
29, 542, 98, 99, 641, 101, 685, 646, 104, 105,
33, 367, 553, 554, 687, 564, 687, 109, 559, 560,
29, 700, 695, 641, 695, 677, 29, 119, 641, 29,
641, 572, 317, 574, 98, 99, 100, 101, 102, 103,
104, 196, 641, 107, 68, 544, 110, 111, 112, 113,
207, 0, 1, 594, 318, 80, 320, 442, 322, 599,
324, 602, 326, 331, 13, 416, 660, 0, 1, 43,
634, 461, 461, 548, 0, 1, 456, 618, 641, 641,
621, 629, -1, -1, 348, 349, 19, 13, 352, 630,
-1, 646, 641, 0, 1, 359, 360, -1, 668, 1,
-1, -1, -1, 5, -1, -1, -1, 656, 372, 58,
59, 13, 19, 15, 16, 17, 18, 19, 20, 21,
-1, -1, -1, -1, -1, 695, -1, -1, 392, -1,
-1, -1, 58, 59, 675, -1, -1, -1, 402, -1,
681, 682, 0, -1, -1, -1, -1, -1, 689, -1,
691, -1, -1, -1, 12, 13, -1, 15, 699, -1,
424, 110, 111, 704, 113, 98, 99, 100, 101, 102,
103, 104, -1, -1, 107, -1, -1, 110, 111, 112,
113, 107, -1, -1, 110, 111, -1, 113, -1, 1,
-1, 98, 99, 100, 101, 102, 103, 104, 462, -1,
107, 13, -1, 110, 111, 469, 113, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, -1, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, -1, -1, -1, -1, 103, 58, 59, 106, -1,
108, -1, -1, 111, 112, -1, 114, -1, -1, 117,
118, -1, 120, 121, -1, -1, -1, -1, -1, -1,
534, 535, -1, 537, 538, 539, 540, -1, -1, -1,
-1, 0, 27, 547, -1, 30, 31, 32, 33, 34,
35, 36, 37, 12, 13, -1, 15, -1, 110, 111,
-1, 113, 22, 23, 24, 25, 26, -1, 28, 29,
-1, 575, -1, -1, 0, 1, -1, -1, 38, 39,
-1, -1, -1, -1, -1, -1, 590, -1, -1, 593,
-1, -1, 13, 19, 15, 16, 17, 18, 19, 20,
21, 605, -1, -1, -1, -1, 65, 66, 67, 68,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78,
79, 80, 81, 82, 83, 84, -1, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98,
-1, -1, -1, -1, 103, -1, -1, 106, -1, -1,
654, 655, 111, 112, -1, 114, 0, 1, 117, 118,
-1, 120, 121, -1, -1, -1, -1, -1, 12, 13,
-1, 15, 98, 99, 100, 101, 102, 103, 104, -1,
0, 1, 108, 109, -1, 111, 13, 113, 15, 16,
17, 18, 19, 20, -1, -1, 0, 1, -1, 19,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 19, -1, -1, -1, -1,
-1, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, -1, 86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, -1, -1, 1, -1, 103,
-1, -1, 106, -1, 108, -1, -1, 111, 12, 13,
114, 15, -1, -1, 118, -1, 120, 121, 98, 99,
100, 101, 102, 103, 104, 0, 1, 107, -1, -1,
110, 111, -1, 113, 98, 99, 100, 101, 102, 103,
104, -1, -1, -1, 19, 109, -1, 111, -1, 113,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, -1, 86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, -1, -1, 1, -1, 103,
-1, -1, 106, -1, -1, -1, -1, 111, 12, 13,
114, 15, -1, -1, 118, -1, 120, 121, -1, -1,
-1, -1, -1, 98, 99, 100, 101, 102, 103, 104,
-1, -1, -1, 108, -1, -1, 111, -1, 113, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 1, -1, -1, -1, -1, -1,
-1, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, -1, 86, 87, 88, 89, 90, 91, 92, 93,
94, 95, 96, 97, 98, -1, -1, -1, -1, 103,
-1, -1, 106, -1, -1, -1, -1, 111, -1, -1,
114, -1, -1, -1, 118, -1, 120, 121, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, 0, 1, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
-1, -1, -1, 0, 1, -1, 19, -1, -1, -1,
-1, -1, -1, -1, 111, -1, -1, 114, -1, -1,
-1, 118, 19, -1, -1, -1, -1, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 40, 41, 42, 43, 44, 45, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, -1,
0, 1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 0, 1, 19,
-1, -1, -1, -1, -1, 98, 99, 100, 101, 102,
103, 104, -1, -1, 107, -1, 19, 110, 111, -1,
113, 98, 99, 100, 101, 102, 103, 104, -1, -1,
107, -1, -1, 110, 111, -1, 113, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, -1, 0, 1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, 0, 1, 19, -1, -1, -1, -1, 98, 99,
100, 101, 102, 103, 104, -1, -1, 107, -1, -1,
19, 111, -1, 113, -1, 98, 99, 100, 101, 102,
103, 104, -1, -1, 107, -1, -1, 110, 111, -1,
113, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 0, 1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 0, 1, 19, -1, -1, 0,
1, -1, 98, 99, 100, 101, 102, 103, 104, -1,
-1, -1, 108, 19, -1, 111, -1, 113, -1, 98,
99, 100, 101, 102, 103, 104, -1, -1, 107, -1,
-1, 110, 111, -1, 113, -1, -1, -1, -1, 40,
41, 42, 43, 44, 45, 46, 47, 48, 49, 50,
51, 52, 53, 54, 55, -1, -1, 12, 13, -1,
15, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1, 98, 99, 100, 101, 102,
103, 104, -1, -1, 107, -1, -1, -1, 111, -1,
113, -1, 98, 99, 100, 101, 102, 103, 104, -1,
-1, 107, 57, -1, -1, 111, 107, 113, -1, 110,
65, 66, 67, 68, 69, 70, 71, 72, 73, 74,
75, 76, 77, 78, 79, 80, 81, 82, 83, 84,
0, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 12, 13, -1, 15, 103, -1,
-1, 106, -1, -1, -1, -1, 111, 112, -1, 114,
-1, -1, 117, 118, -1, 120, 121, -1, -1, -1,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49,
50, 51, 52, 53, 54, 55, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, 65, 66, 67,
68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, -1, 86, 87,
88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 12, 13, -1, 15, 103, -1, 107, 106, -1,
-1, -1, -1, 111, 112, -1, 114, -1, -1, 117,
118, -1, 120, 121, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
56, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, 84, -1, 86, 87, 88, 89, 90,
91, 92, 93, 94, 95, 96, 97, 98, 0, 1,
-1, -1, 103, -1, -1, 106, -1, -1, -1, -1,
111, 13, -1, 114, 0, 1, -1, 118, -1, 120,
121, -1, -1, -1, -1, -1, -1, 13, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, 40, 41,
42, 43, 44, 45, 46, 47, 48, 49, 50, 51,
52, 53, 54, 55, 40, 41, 42, 43, 44, 45,
46, 47, 48, 49, 50, 51, 52, 53, 54, 55,
-1, -1, 65, 66, 67, 68, 69, 70, 71, 72,
73, 74, 75, 76, 77, 78, 79, 80, 81, 82,
83, 84, 1, 86, 87, 88, 89, 90, 91, 92,
93, 94, 95, 96, 13, 107, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, -1, 28,
29, 107, -1, -1, -1, -1, -1, -1, -1, 38,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
49, 50, 51, 52, 53, 54, 55, 56, 1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
13, -1, 15, 16, 17, 18, 19, 20, 21, 22,
23, 24, 25, 26, -1, 28, 29, -1, -1, -1,
-1, -1, -1, -1, -1, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52,
53, 54, 55, 56, 65, 66, 67, 68, 69, 70,
71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
81, 82, 83, -1, -1, 86, 87, 88, 89, 90,
91, 92, 93, 94, 95, 96, -1, -1, -1, -1,
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
111, -1, -1, 114, -1, -1, -1, 118, 65, 66,
67, 68, 69, 70, 71, 72, 73, 74, 75, 76,
77, 78, 79, 80, 81, 82, 83, -1, -1, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96
};
/* YYSTOS[STATE-NUM] -- The (internal number of the) accessing
symbol of state STATE-NUM. */
static const yytype_uint16 yystos[] =
{
0, 27, 30, 31, 32, 33, 34, 35, 36, 37,
123, 124, 125, 126, 127, 128, 129, 130, 131, 139,
1, 5, 132, 133, 246, 247, 133, 204, 133, 133,
133, 133, 133, 133, 133, 0, 134, 257, 5, 12,
252, 1, 226, 227, 228, 229, 257, 258, 28, 141,
149, 150, 151, 152, 166, 168, 169, 171, 172, 180,
181, 182, 190, 191, 197, 198, 199, 200, 205, 208,
13, 15, 16, 17, 18, 19, 20, 21, 210, 211,
212, 213, 215, 216, 217, 218, 220, 224, 12, 13,
15, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 77, 78, 79, 80, 81, 82, 83,
84, 86, 87, 88, 89, 90, 91, 92, 93, 94,
95, 96, 97, 98, 103, 106, 111, 114, 118, 120,
121, 203, 232, 233, 236, 237, 238, 244, 13, 186,
187, 188, 202, 203, 187, 62, 111, 174, 175, 176,
177, 178, 179, 5, 6, 140, 260, 133, 248, 252,
257, 0, 228, 110, 1, 17, 13, 1, 58, 59,
111, 156, 157, 159, 160, 161, 162, 163, 164, 133,
133, 22, 12, 97, 154, 24, 162, 25, 38, 39,
12, 13, 183, 23, 26, 29, 210, 21, 17, 98,
99, 101, 104, 105, 257, 13, 1, 133, 225, 21,
0, 207, 5, 114, 115, 116, 117, 201, 13, 20,
215, 216, 216, 217, 133, 133, 133, 133, 133, 133,
133, 133, 133, 133, 133, 84, 237, 133, 0, 112,
117, 235, 236, 133, 133, 133, 133, 112, 113, 133,
86, 0, 133, 1, 133, 0, 63, 64, 63, 64,
142, 143, 1, 19, 98, 99, 100, 101, 102, 103,
104, 111, 254, 255, 256, 0, 110, 138, 113, 138,
253, 259, 110, 133, 257, 133, 133, 257, 133, 133,
1, 133, 133, 13, 170, 1, 112, 0, 161, 13,
153, 0, 133, 133, 133, 206, 133, 133, 133, 133,
167, 133, 167, 167, 207, 100, 257, 133, 225, 133,
225, 133, 225, 133, 225, 133, 225, 13, 257, 13,
20, 212, 219, 0, 109, 137, 112, 213, 133, 133,
133, 13, 213, 216, 0, 1, 108, 136, 233, 234,
111, 203, 234, 237, 239, 242, 243, 13, 136, 231,
234, 133, 133, 133, 133, 236, 0, 133, 133, 178,
257, 13, 174, 133, 133, 133, 133, 1, 28, 141,
150, 168, 172, 181, 190, 197, 199, 249, 250, 257,
134, 259, 259, 259, 1, 253, 254, 255, 133, 259,
257, 260, 259, 13, 60, 133, 158, 257, 133, 112,
133, 154, 258, 113, 174, 113, 13, 17, 192, 223,
113, 113, 206, 133, 225, 13, 13, 14, 202, 136,
213, 214, 136, 213, 136, 214, 136, 214, 136, 259,
133, 13, 219, 7, 8, 9, 10, 11, 119, 137,
221, 133, 117, 257, 136, 136, 133, 237, 136, 5,
132, 240, 241, 133, 13, 136, 136, 188, 226, 259,
133, 136, 178, 178, 178, 178, 257, 247, 247, 162,
25, 247, 23, 26, 29, 252, 40, 41, 42, 43,
44, 45, 46, 47, 48, 49, 50, 51, 52, 53,
54, 55, 56, 196, 245, 137, 136, 0, 107, 135,
1, 233, 136, 133, 133, 60, 260, 258, 133, 133,
162, 165, 173, 165, 133, 223, 13, 206, 133, 165,
165, 113, 214, 136, 133, 133, 88, 133, 133, 133,
133, 137, 221, 133, 209, 133, 259, 234, 243, 114,
118, 239, 242, 20, 117, 136, 133, 133, 135, 136,
17, 133, 260, 110, 1, 247, 247, 247, 110, 253,
247, 259, 57, 230, 17, 155, 156, 133, 258, 138,
138, 253, 133, 113, 133, 133, 113, 204, 204, 165,
133, 136, 136, 133, 112, 136, 136, 136, 136, 133,
12, 13, 222, 211, 136, 241, 132, 132, 133, 133,
133, 133, 252, 257, 133, 1, 133, 136, 157, 144,
145, 165, 258, 165, 226, 226, 204, 136, 136, 133,
222, 133, 136, 1, 233, 253, 260, 259, 233, 133,
135, 142, 146, 148, 133, 184, 185, 204, 135, 135,
226, 213, 133, 137, 259, 230, 1, 147, 150, 152,
168, 169, 171, 182, 191, 198, 200, 208, 249, 250,
251, 134, 144, 135, 1, 186, 189, 193, 226, 135,
137, 136, 136, 257, 162, 252, 135, 260, 133, 253,
135, 194, 196, 133, 133, 260, 258, 133, 133, 195,
252, 258, 226, 133, 113, 133, 226, 135
};
#define yyerrok (yyerrstatus = 0)
#define yyclearin (yychar = YYEMPTY)
#define YYEMPTY (-2)
#define YYEOF 0
#define YYACCEPT goto yyacceptlab
#define YYABORT goto yyabortlab
#define YYERROR goto yyerrorlab
/* Like YYERROR except do call yyerror. This remains here temporarily
to ease the transition to the new meaning of YYERROR, for GCC.
Once GCC version 2 has supplanted version 1, this can go. However,
YYFAIL appears to be in use. Nevertheless, it is formally deprecated
in Bison 2.4.2's NEWS entry, where a plan to phase it out is
discussed. */
#define YYFAIL goto yyerrlab
#if defined YYFAIL
/* This is here to suppress warnings from the GCC cpp's
-Wunused-macros. Normally we don't worry about that warning, but
some users do, and we want to make it easy for users to remove
YYFAIL uses, which will produce warnings from Bison 2.5. */
#endif
#define YYRECOVERING() (!!yyerrstatus)
#define YYBACKUP(Token, Value) \
do \
if (yychar == YYEMPTY && yylen == 1) \
{ \
yychar = (Token); \
yylval = (Value); \
YYPOPSTACK (1); \
goto yybackup; \
} \
else \
{ \
yyerror (parser, YY_("syntax error: cannot back up")); \
YYERROR; \
} \
while (YYID (0))
#define YYTERROR 1
#define YYERRCODE 256
/* YYLLOC_DEFAULT -- Set CURRENT to span from RHS[1] to RHS[N].
If N is 0, then set CURRENT to the empty location which ends
the previous symbol: RHS[0] (always defined). */
#define YYRHSLOC(Rhs, K) ((Rhs)[K])
#ifndef YYLLOC_DEFAULT
# define YYLLOC_DEFAULT(Current, Rhs, N) \
do \
if (YYID (N)) \
{ \
(Current).first_line = YYRHSLOC (Rhs, 1).first_line; \
(Current).first_column = YYRHSLOC (Rhs, 1).first_column; \
(Current).last_line = YYRHSLOC (Rhs, N).last_line; \
(Current).last_column = YYRHSLOC (Rhs, N).last_column; \
} \
else \
{ \
(Current).first_line = (Current).last_line = \
YYRHSLOC (Rhs, 0).last_line; \
(Current).first_column = (Current).last_column = \
YYRHSLOC (Rhs, 0).last_column; \
} \
while (YYID (0))
#endif
/* This macro is provided for backward compatibility. */
#ifndef YY_LOCATION_PRINT
# define YY_LOCATION_PRINT(File, Loc) ((void) 0)
#endif
/* YYLEX -- calling `yylex' with the right arguments. */
#ifdef YYLEX_PARAM
# define YYLEX yylex (&yylval, YYLEX_PARAM)
#else
# define YYLEX yylex (&yylval, parser)
#endif
/* Enable debugging if requested. */
#if YYDEBUG
# ifndef YYFPRINTF
# include <stdio.h> /* INFRINGES ON USER NAME SPACE */
# define YYFPRINTF fprintf
# endif
# define YYDPRINTF(Args) \
do { \
if (yydebug) \
YYFPRINTF Args; \
} while (YYID (0))
# define YY_SYMBOL_PRINT(Title, Type, Value, Location) \
do { \
if (yydebug) \
{ \
YYFPRINTF (stderr, "%s ", Title); \
yy_symbol_print (stderr, \
Type, Value, parser); \
YYFPRINTF (stderr, "\n"); \
} \
} while (YYID (0))
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_value_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, BisonCSSParser* parser)
#else
static void
yy_symbol_value_print (yyoutput, yytype, yyvaluep, parser)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
BisonCSSParser* parser;
#endif
{
if (!yyvaluep)
return;
YYUSE (parser);
# ifdef YYPRINT
if (yytype < YYNTOKENS)
YYPRINT (yyoutput, yytoknum[yytype], *yyvaluep);
# else
YYUSE (yyoutput);
# endif
switch (yytype)
{
default:
break;
}
}
/*--------------------------------.
| Print this symbol on YYOUTPUT. |
`--------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_symbol_print (FILE *yyoutput, int yytype, YYSTYPE const * const yyvaluep, BisonCSSParser* parser)
#else
static void
yy_symbol_print (yyoutput, yytype, yyvaluep, parser)
FILE *yyoutput;
int yytype;
YYSTYPE const * const yyvaluep;
BisonCSSParser* parser;
#endif
{
if (yytype < YYNTOKENS)
YYFPRINTF (yyoutput, "token %s (", yytname[yytype]);
else
YYFPRINTF (yyoutput, "nterm %s (", yytname[yytype]);
yy_symbol_value_print (yyoutput, yytype, yyvaluep, parser);
YYFPRINTF (yyoutput, ")");
}
/*------------------------------------------------------------------.
| yy_stack_print -- Print the state stack from its BOTTOM up to its |
| TOP (included). |
`------------------------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_stack_print (yytype_int16 *yybottom, yytype_int16 *yytop)
#else
static void
yy_stack_print (yybottom, yytop)
yytype_int16 *yybottom;
yytype_int16 *yytop;
#endif
{
YYFPRINTF (stderr, "Stack now");
for (; yybottom <= yytop; yybottom++)
{
int yybot = *yybottom;
YYFPRINTF (stderr, " %d", yybot);
}
YYFPRINTF (stderr, "\n");
}
# define YY_STACK_PRINT(Bottom, Top) \
do { \
if (yydebug) \
yy_stack_print ((Bottom), (Top)); \
} while (YYID (0))
/*------------------------------------------------.
| Report that the YYRULE is going to be reduced. |
`------------------------------------------------*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yy_reduce_print (YYSTYPE *yyvsp, int yyrule, BisonCSSParser* parser)
#else
static void
yy_reduce_print (yyvsp, yyrule, parser)
YYSTYPE *yyvsp;
int yyrule;
BisonCSSParser* parser;
#endif
{
int yynrhs = yyr2[yyrule];
int yyi;
unsigned long int yylno = yyrline[yyrule];
YYFPRINTF (stderr, "Reducing stack by rule %d (line %lu):\n",
yyrule - 1, yylno);
/* The symbols being reduced. */
for (yyi = 0; yyi < yynrhs; yyi++)
{
YYFPRINTF (stderr, " $%d = ", yyi + 1);
yy_symbol_print (stderr, yyrhs[yyprhs[yyrule] + yyi],
&(yyvsp[(yyi + 1) - (yynrhs)])
, parser);
YYFPRINTF (stderr, "\n");
}
}
# define YY_REDUCE_PRINT(Rule) \
do { \
if (yydebug) \
yy_reduce_print (yyvsp, Rule, parser); \
} while (YYID (0))
/* Nonzero means print parse trace. It is left uninitialized so that
multiple parsers can coexist. */
int yydebug;
#else /* !YYDEBUG */
# define YYDPRINTF(Args)
# define YY_SYMBOL_PRINT(Title, Type, Value, Location)
# define YY_STACK_PRINT(Bottom, Top)
# define YY_REDUCE_PRINT(Rule)
#endif /* !YYDEBUG */
/* YYINITDEPTH -- initial size of the parser's stacks. */
#ifndef YYINITDEPTH
# define YYINITDEPTH 200
#endif
/* YYMAXDEPTH -- maximum size the stacks can grow to (effective only
if the built-in stack extension method is used).
Do not make this value too large; the results are undefined if
YYSTACK_ALLOC_MAXIMUM < YYSTACK_BYTES (YYMAXDEPTH)
evaluated with infinite-precision integer arithmetic. */
#ifndef YYMAXDEPTH
# define YYMAXDEPTH 10000
#endif
#if YYERROR_VERBOSE
# ifndef yystrlen
# if defined __GLIBC__ && defined _STRING_H
# define yystrlen strlen
# else
/* Return the length of YYSTR. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static YYSIZE_T
yystrlen (const char *yystr)
#else
static YYSIZE_T
yystrlen (yystr)
const char *yystr;
#endif
{
YYSIZE_T yylen;
for (yylen = 0; yystr[yylen]; yylen++)
continue;
return yylen;
}
# endif
# endif
# ifndef yystpcpy
# if defined __GLIBC__ && defined _STRING_H && defined _GNU_SOURCE
# define yystpcpy stpcpy
# else
/* Copy YYSRC to YYDEST, returning the address of the terminating '\0' in
YYDEST. */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static char *
yystpcpy (char *yydest, const char *yysrc)
#else
static char *
yystpcpy (yydest, yysrc)
char *yydest;
const char *yysrc;
#endif
{
char *yyd = yydest;
const char *yys = yysrc;
while ((*yyd++ = *yys++) != '\0')
continue;
return yyd - 1;
}
# endif
# endif
# ifndef yytnamerr
/* Copy to YYRES the contents of YYSTR after stripping away unnecessary
quotes and backslashes, so that it's suitable for yyerror. The
heuristic is that double-quoting is unnecessary unless the string
contains an apostrophe, a comma, or backslash (other than
backslash-backslash). YYSTR is taken from yytname. If YYRES is
null, do not copy; instead, return the length of what the result
would have been. */
static YYSIZE_T
yytnamerr (char *yyres, const char *yystr)
{
if (*yystr == '"')
{
YYSIZE_T yyn = 0;
char const *yyp = yystr;
for (;;)
switch (*++yyp)
{
case '\'':
case ',':
goto do_not_strip_quotes;
case '\\':
if (*++yyp != '\\')
goto do_not_strip_quotes;
/* Fall through. */
default:
if (yyres)
yyres[yyn] = *yyp;
yyn++;
break;
case '"':
if (yyres)
yyres[yyn] = '\0';
return yyn;
}
do_not_strip_quotes: ;
}
if (! yyres)
return yystrlen (yystr);
return yystpcpy (yyres, yystr) - yyres;
}
# endif
/* Copy into *YYMSG, which is of size *YYMSG_ALLOC, an error message
about the unexpected token YYTOKEN for the state stack whose top is
YYSSP.
Return 0 if *YYMSG was successfully written. Return 1 if *YYMSG is
not large enough to hold the message. In that case, also set
*YYMSG_ALLOC to the required number of bytes. Return 2 if the
required number of bytes is too large to store. */
static int
yysyntax_error (YYSIZE_T *yymsg_alloc, char **yymsg,
yytype_int16 *yyssp, int yytoken)
{
YYSIZE_T yysize0 = yytnamerr (0, yytname[yytoken]);
YYSIZE_T yysize = yysize0;
YYSIZE_T yysize1;
enum { YYERROR_VERBOSE_ARGS_MAXIMUM = 5 };
/* Internationalized format string. */
const char *yyformat = 0;
/* Arguments of yyformat. */
char const *yyarg[YYERROR_VERBOSE_ARGS_MAXIMUM];
/* Number of reported tokens (one for the "unexpected", one per
"expected"). */
int yycount = 0;
/* There are many possibilities here to consider:
- Assume YYFAIL is not used. It's too flawed to consider. See
<http://lists.gnu.org/archive/html/bison-patches/2009-12/msg00024.html>
for details. YYERROR is fine as it does not invoke this
function.
- If this state is a consistent state with a default action, then
the only way this function was invoked is if the default action
is an error action. In that case, don't check for expected
tokens because there are none.
- The only way there can be no lookahead present (in yychar) is if
this state is a consistent state with a default action. Thus,
detecting the absence of a lookahead is sufficient to determine
that there is no unexpected or expected token to report. In that
case, just report a simple "syntax error".
- Don't assume there isn't a lookahead just because this state is a
consistent state with a default action. There might have been a
previous inconsistent state, consistent state with a non-default
action, or user semantic action that manipulated yychar.
- Of course, the expected token list depends on states to have
correct lookahead information, and it depends on the parser not
to perform extra reductions after fetching a lookahead from the
scanner and before detecting a syntax error. Thus, state merging
(from LALR or IELR) and default reductions corrupt the expected
token list. However, the list is correct for canonical LR with
one exception: it will still contain any token that will not be
accepted due to an error action in a later state.
*/
if (yytoken != YYEMPTY)
{
int yyn = yypact[*yyssp];
yyarg[yycount++] = yytname[yytoken];
if (!yypact_value_is_default (yyn))
{
/* Start YYX at -YYN if negative to avoid negative indexes in
YYCHECK. In other words, skip the first -YYN actions for
this state because they are default actions. */
int yyxbegin = yyn < 0 ? -yyn : 0;
/* Stay within bounds of both yycheck and yytname. */
int yychecklim = YYLAST - yyn + 1;
int yyxend = yychecklim < YYNTOKENS ? yychecklim : YYNTOKENS;
int yyx;
for (yyx = yyxbegin; yyx < yyxend; ++yyx)
if (yycheck[yyx + yyn] == yyx && yyx != YYTERROR
&& !yytable_value_is_error (yytable[yyx + yyn]))
{
if (yycount == YYERROR_VERBOSE_ARGS_MAXIMUM)
{
yycount = 1;
yysize = yysize0;
break;
}
yyarg[yycount++] = yytname[yyx];
yysize1 = yysize + yytnamerr (0, yytname[yyx]);
if (! (yysize <= yysize1
&& yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
}
}
}
switch (yycount)
{
# define YYCASE_(N, S) \
case N: \
yyformat = S; \
break
YYCASE_(0, YY_("syntax error"));
YYCASE_(1, YY_("syntax error, unexpected %s"));
YYCASE_(2, YY_("syntax error, unexpected %s, expecting %s"));
YYCASE_(3, YY_("syntax error, unexpected %s, expecting %s or %s"));
YYCASE_(4, YY_("syntax error, unexpected %s, expecting %s or %s or %s"));
YYCASE_(5, YY_("syntax error, unexpected %s, expecting %s or %s or %s or %s"));
# undef YYCASE_
}
yysize1 = yysize + yystrlen (yyformat);
if (! (yysize <= yysize1 && yysize1 <= YYSTACK_ALLOC_MAXIMUM))
return 2;
yysize = yysize1;
if (*yymsg_alloc < yysize)
{
*yymsg_alloc = 2 * yysize;
if (! (yysize <= *yymsg_alloc
&& *yymsg_alloc <= YYSTACK_ALLOC_MAXIMUM))
*yymsg_alloc = YYSTACK_ALLOC_MAXIMUM;
return 1;
}
/* Avoid sprintf, as that infringes on the user's name space.
Don't have undefined behavior even if the translation
produced a string with the wrong number of "%s"s. */
{
char *yyp = *yymsg;
int yyi = 0;
while ((*yyp = *yyformat) != '\0')
if (*yyp == '%' && yyformat[1] == 's' && yyi < yycount)
{
yyp += yytnamerr (yyp, yyarg[yyi++]);
yyformat += 2;
}
else
{
yyp++;
yyformat++;
}
}
return 0;
}
#endif /* YYERROR_VERBOSE */
/*-----------------------------------------------.
| Release the memory associated to this symbol. |
`-----------------------------------------------*/
/*ARGSUSED*/
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
static void
yydestruct (const char *yymsg, int yytype, YYSTYPE *yyvaluep, BisonCSSParser* parser)
#else
static void
yydestruct (yymsg, yytype, yyvaluep, parser)
const char *yymsg;
int yytype;
YYSTYPE *yyvaluep;
BisonCSSParser* parser;
#endif
{
YYUSE (yyvaluep);
YYUSE (parser);
if (!yymsg)
yymsg = "Deleting";
YY_SYMBOL_PRINT (yymsg, yytype, yyvaluep, yylocationp);
switch (yytype)
{
default:
break;
}
}
/* Prevent warnings from -Wmissing-prototypes. */
#ifdef YYPARSE_PARAM
#if defined __STDC__ || defined __cplusplus
int yyparse (void *YYPARSE_PARAM);
#else
int yyparse ();
#endif
#else /* ! YYPARSE_PARAM */
#if defined __STDC__ || defined __cplusplus
int yyparse (BisonCSSParser* parser);
#else
int yyparse ();
#endif
#endif /* ! YYPARSE_PARAM */
/*----------.
| yyparse. |
`----------*/
#ifdef YYPARSE_PARAM
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (void *YYPARSE_PARAM)
#else
int
yyparse (YYPARSE_PARAM)
void *YYPARSE_PARAM;
#endif
#else /* ! YYPARSE_PARAM */
#if (defined __STDC__ || defined __C99__FUNC__ \
|| defined __cplusplus || defined _MSC_VER)
int
yyparse (BisonCSSParser* parser)
#else
int
yyparse (parser)
BisonCSSParser* parser;
#endif
#endif
{
/* The lookahead symbol. */
int yychar;
/* The semantic value of the lookahead symbol. */
YYSTYPE yylval;
/* Number of syntax errors so far. */
int yynerrs;
int yystate;
/* Number of tokens to shift before error messages enabled. */
int yyerrstatus;
/* The stacks and their tools:
`yyss': related to states.
`yyvs': related to semantic values.
Refer to the stacks thru separate pointers, to allow yyoverflow
to reallocate them elsewhere. */
/* The state stack. */
yytype_int16 yyssa[YYINITDEPTH];
yytype_int16 *yyss;
yytype_int16 *yyssp;
/* The semantic value stack. */
YYSTYPE yyvsa[YYINITDEPTH];
YYSTYPE *yyvs;
YYSTYPE *yyvsp;
YYSIZE_T yystacksize;
int yyn;
int yyresult;
/* Lookahead token as an internal (translated) token number. */
int yytoken;
/* The variables used to return semantic value and location from the
action routines. */
YYSTYPE yyval;
#if YYERROR_VERBOSE
/* Buffer for error messages, and its allocated size. */
char yymsgbuf[128];
char *yymsg = yymsgbuf;
YYSIZE_T yymsg_alloc = sizeof yymsgbuf;
#endif
#define YYPOPSTACK(N) (yyvsp -= (N), yyssp -= (N))
/* The number of symbols on the RHS of the reduced rule.
Keep to zero when no symbol should be popped. */
int yylen = 0;
yytoken = 0;
yyss = yyssa;
yyvs = yyvsa;
yystacksize = YYINITDEPTH;
YYDPRINTF ((stderr, "Starting parse\n"));
yystate = 0;
yyerrstatus = 0;
yynerrs = 0;
yychar = YYEMPTY; /* Cause a token to be read. */
/* Initialize stack pointers.
Waste one element of value and location stack
so that they stay on the same level as the state stack.
The wasted elements are never initialized. */
yyssp = yyss;
yyvsp = yyvs;
goto yysetstate;
/*------------------------------------------------------------.
| yynewstate -- Push a new state, which is found in yystate. |
`------------------------------------------------------------*/
yynewstate:
/* In all cases, when you get here, the value and location stacks
have just been pushed. So pushing a state here evens the stacks. */
yyssp++;
yysetstate:
*yyssp = yystate;
if (yyss + yystacksize - 1 <= yyssp)
{
/* Get the current used size of the three stacks, in elements. */
YYSIZE_T yysize = yyssp - yyss + 1;
#ifdef yyoverflow
{
/* Give user a chance to reallocate the stack. Use copies of
these so that the &'s don't force the real ones into
memory. */
YYSTYPE *yyvs1 = yyvs;
yytype_int16 *yyss1 = yyss;
/* Each stack pointer address is followed by the size of the
data in use in that stack, in bytes. This used to be a
conditional around just the two extra args, but that might
be undefined if yyoverflow is a macro. */
yyoverflow (YY_("memory exhausted"),
&yyss1, yysize * sizeof (*yyssp),
&yyvs1, yysize * sizeof (*yyvsp),
&yystacksize);
yyss = yyss1;
yyvs = yyvs1;
}
#else /* no yyoverflow */
# ifndef YYSTACK_RELOCATE
goto yyexhaustedlab;
# else
/* Extend the stack our own way. */
if (YYMAXDEPTH <= yystacksize)
goto yyexhaustedlab;
yystacksize *= 2;
if (YYMAXDEPTH < yystacksize)
yystacksize = YYMAXDEPTH;
{
yytype_int16 *yyss1 = yyss;
union yyalloc *yyptr =
(union yyalloc *) YYSTACK_ALLOC (YYSTACK_BYTES (yystacksize));
if (! yyptr)
goto yyexhaustedlab;
YYSTACK_RELOCATE (yyss_alloc, yyss);
YYSTACK_RELOCATE (yyvs_alloc, yyvs);
# undef YYSTACK_RELOCATE
if (yyss1 != yyssa)
YYSTACK_FREE (yyss1);
}
# endif
#endif /* no yyoverflow */
yyssp = yyss + yysize - 1;
yyvsp = yyvs + yysize - 1;
YYDPRINTF ((stderr, "Stack size increased to %lu\n",
(unsigned long int) yystacksize));
if (yyss + yystacksize - 1 <= yyssp)
YYABORT;
}
YYDPRINTF ((stderr, "Entering state %d\n", yystate));
if (yystate == YYFINAL)
YYACCEPT;
goto yybackup;
/*-----------.
| yybackup. |
`-----------*/
yybackup:
/* Do appropriate processing given the current state. Read a
lookahead token if we need one and don't already have one. */
/* First try to decide what to do without reference to lookahead token. */
yyn = yypact[yystate];
if (yypact_value_is_default (yyn))
goto yydefault;
/* Not known => get a lookahead token if don't already have one. */
/* YYCHAR is either YYEMPTY or YYEOF or a valid lookahead symbol. */
if (yychar == YYEMPTY)
{
YYDPRINTF ((stderr, "Reading a token: "));
yychar = YYLEX;
}
if (yychar <= YYEOF)
{
yychar = yytoken = YYEOF;
YYDPRINTF ((stderr, "Now at end of input.\n"));
}
else
{
yytoken = YYTRANSLATE (yychar);
YY_SYMBOL_PRINT ("Next token is", yytoken, &yylval, &yylloc);
}
/* If the proper action on seeing token YYTOKEN is to reduce or to
detect an error, take that action. */
yyn += yytoken;
if (yyn < 0 || YYLAST < yyn || yycheck[yyn] != yytoken)
goto yydefault;
yyn = yytable[yyn];
if (yyn <= 0)
{
if (yytable_value_is_error (yyn))
goto yyerrlab;
yyn = -yyn;
goto yyreduce;
}
/* Count tokens shifted since error; after three, turn off error
status. */
if (yyerrstatus)
yyerrstatus--;
/* Shift the lookahead token. */
YY_SYMBOL_PRINT ("Shifting", yytoken, &yylval, &yylloc);
/* Discard the shifted token. */
yychar = YYEMPTY;
yystate = yyn;
*++yyvsp = yylval;
goto yynewstate;
/*-----------------------------------------------------------.
| yydefault -- do the default action for the current state. |
`-----------------------------------------------------------*/
yydefault:
yyn = yydefact[yystate];
if (yyn == 0)
goto yyerrlab;
goto yyreduce;
/*-----------------------------.
| yyreduce -- Do a reduction. |
`-----------------------------*/
yyreduce:
/* yyn is the number of a rule to reduce with. */
yylen = yyr2[yyn];
/* If YYLEN is nonzero, implement the default value of the action:
`$$ = $1'.
Otherwise, the following line sets YYVAL to garbage.
This behavior is undocumented and Bison
users should not rely upon it. Assigning to YYVAL
unconditionally makes the parser a bit smaller, and it avoids a
GCC warning that YYVAL may be used uninitialized. */
yyval = yyvsp[1-yylen];
YY_REDUCE_PRINT (yyn);
switch (yyn)
{
case 11:
/* Line 1806 of yacc.c */
#line 386 "css/CSSGrammar.y"
{
parser->m_rule = (yyvsp[(3) - (5)].rule);
}
break;
case 12:
/* Line 1806 of yacc.c */
#line 392 "css/CSSGrammar.y"
{
parser->m_keyframe = (yyvsp[(3) - (5)].keyframe);
}
break;
case 13:
/* Line 1806 of yacc.c */
#line 398 "css/CSSGrammar.y"
{
parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList));
}
break;
case 14:
/* Line 1806 of yacc.c */
#line 404 "css/CSSGrammar.y"
{
/* can be empty */
}
break;
case 15:
/* Line 1806 of yacc.c */
#line 410 "css/CSSGrammar.y"
{
parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList));
int oldParsedProperties = parser->m_parsedProperties.size();
if (!parser->parseValue(parser->m_id, parser->m_important))
parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
parser->m_valueList = nullptr;
}
break;
case 16:
/* Line 1806 of yacc.c */
#line 420 "css/CSSGrammar.y"
{
parser->m_mediaList = (yyvsp[(4) - (5)].mediaList);
}
break;
case 17:
/* Line 1806 of yacc.c */
#line 426 "css/CSSGrammar.y"
{
if (parser->m_selectorListForParseSelector)
parser->m_selectorListForParseSelector->adoptSelectorVector(*(yyvsp[(3) - (4)].selectorList));
}
break;
case 18:
/* Line 1806 of yacc.c */
#line 433 "css/CSSGrammar.y"
{
parser->m_supportsCondition = (yyvsp[(3) - (4)].boolean);
}
break;
case 35:
/* Line 1806 of yacc.c */
#line 476 "css/CSSGrammar.y"
{
if (parser->m_styleSheet)
parser->m_styleSheet->parserSetEncodingFromCharsetRule((yyvsp[(3) - (5)].string));
parser->startEndUnknownRule();
}
break;
case 38:
/* Line 1806 of yacc.c */
#line 486 "css/CSSGrammar.y"
{
if ((yyvsp[(2) - (3)].rule) && parser->m_styleSheet)
parser->m_styleSheet->parserAppendRule((yyvsp[(2) - (3)].rule));
}
break;
case 48:
/* Line 1806 of yacc.c */
#line 505 "css/CSSGrammar.y"
{
parser->startRule();
}
break;
case 49:
/* Line 1806 of yacc.c */
#line 511 "css/CSSGrammar.y"
{
(yyval.rule) = (yyvsp[(2) - (2)].rule);
parser->m_hadSyntacticallyValidCSSRule = true;
parser->endRule(!!(yyval.rule));
}
break;
case 50:
/* Line 1806 of yacc.c */
#line 516 "css/CSSGrammar.y"
{
(yyval.rule) = 0;
parser->endRule(false);
}
break;
case 53:
/* Line 1806 of yacc.c */
#line 528 "css/CSSGrammar.y"
{ (yyval.ruleList) = 0; }
break;
case 54:
/* Line 1806 of yacc.c */
#line 529 "css/CSSGrammar.y"
{
(yyval.ruleList) = parser->appendRule((yyvsp[(1) - (3)].ruleList), (yyvsp[(2) - (3)].rule));
}
break;
case 55:
/* Line 1806 of yacc.c */
#line 535 "css/CSSGrammar.y"
{
parser->endRule(false);
}
break;
case 64:
/* Line 1806 of yacc.c */
#line 552 "css/CSSGrammar.y"
{
(yyval.rule) = (yyvsp[(2) - (2)].rule);
parser->endRule(!!(yyval.rule));
}
break;
case 65:
/* Line 1806 of yacc.c */
#line 556 "css/CSSGrammar.y"
{
(yyval.rule) = 0;
parser->endRule(false);
}
break;
case 66:
/* Line 1806 of yacc.c */
#line 563 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::IMPORT_RULE);
}
break;
case 67:
/* Line 1806 of yacc.c */
#line 569 "css/CSSGrammar.y"
{
parser->endRuleHeader();
parser->startRuleBody();
}
break;
case 68:
/* Line 1806 of yacc.c */
#line 576 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createImportRule((yyvsp[(2) - (6)].string), (yyvsp[(5) - (6)].mediaList));
}
break;
case 69:
/* Line 1806 of yacc.c */
#line 579 "css/CSSGrammar.y"
{
(yyval.rule) = 0;
}
break;
case 70:
/* Line 1806 of yacc.c */
#line 585 "css/CSSGrammar.y"
{
parser->addNamespace((yyvsp[(3) - (6)].string), (yyvsp[(4) - (6)].string));
(yyval.rule) = 0;
}
break;
case 71:
/* Line 1806 of yacc.c */
#line 592 "css/CSSGrammar.y"
{ (yyval.string).clear(); }
break;
case 75:
/* Line 1806 of yacc.c */
#line 602 "css/CSSGrammar.y"
{
(yyval.valueList) = 0;
}
break;
case 76:
/* Line 1806 of yacc.c */
#line 605 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(3) - (3)].valueList);
}
break;
case 77:
/* Line 1806 of yacc.c */
#line 611 "css/CSSGrammar.y"
{
parser->tokenToLowerCase((yyvsp[(3) - (6)].string));
(yyval.mediaQueryExp) = parser->createFloatingMediaQueryExp((yyvsp[(3) - (6)].string), (yyvsp[(5) - (6)].valueList));
if (!(yyval.mediaQueryExp))
YYERROR;
}
break;
case 78:
/* Line 1806 of yacc.c */
#line 617 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 79:
/* Line 1806 of yacc.c */
#line 623 "css/CSSGrammar.y"
{
(yyval.mediaQueryExpList) = parser->createFloatingMediaQueryExpList();
(yyval.mediaQueryExpList)->append(parser->sinkFloatingMediaQueryExp((yyvsp[(1) - (1)].mediaQueryExp)));
}
break;
case 80:
/* Line 1806 of yacc.c */
#line 627 "css/CSSGrammar.y"
{
(yyval.mediaQueryExpList) = (yyvsp[(1) - (5)].mediaQueryExpList);
(yyval.mediaQueryExpList)->append(parser->sinkFloatingMediaQueryExp((yyvsp[(5) - (5)].mediaQueryExp)));
}
break;
case 81:
/* Line 1806 of yacc.c */
#line 634 "css/CSSGrammar.y"
{
(yyval.mediaQueryExpList) = parser->createFloatingMediaQueryExpList();
}
break;
case 82:
/* Line 1806 of yacc.c */
#line 637 "css/CSSGrammar.y"
{
(yyval.mediaQueryExpList) = (yyvsp[(4) - (5)].mediaQueryExpList);
}
break;
case 83:
/* Line 1806 of yacc.c */
#line 643 "css/CSSGrammar.y"
{
(yyval.mediaQueryRestrictor) = MediaQuery::None;
}
break;
case 84:
/* Line 1806 of yacc.c */
#line 646 "css/CSSGrammar.y"
{
(yyval.mediaQueryRestrictor) = MediaQuery::Only;
}
break;
case 85:
/* Line 1806 of yacc.c */
#line 649 "css/CSSGrammar.y"
{
(yyval.mediaQueryRestrictor) = MediaQuery::Not;
}
break;
case 86:
/* Line 1806 of yacc.c */
#line 655 "css/CSSGrammar.y"
{
(yyval.mediaQuery) = parser->createFloatingMediaQuery(parser->sinkFloatingMediaQueryExpList((yyvsp[(1) - (2)].mediaQueryExpList)));
}
break;
case 87:
/* Line 1806 of yacc.c */
#line 658 "css/CSSGrammar.y"
{
parser->tokenToLowerCase((yyvsp[(2) - (3)].string));
(yyval.mediaQuery) = parser->createFloatingMediaQuery((yyvsp[(1) - (3)].mediaQueryRestrictor), (yyvsp[(2) - (3)].string), parser->sinkFloatingMediaQueryExpList((yyvsp[(3) - (3)].mediaQueryExpList)));
}
break;
case 89:
/* Line 1806 of yacc.c */
#line 666 "css/CSSGrammar.y"
{
parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError);
(yyval.mediaQuery) = parser->createFloatingNotAllQuery();
}
break;
case 90:
/* Line 1806 of yacc.c */
#line 670 "css/CSSGrammar.y"
{
parser->reportError(parser->lastLocationLabel(), InvalidMediaQueryCSSError);
(yyval.mediaQuery) = parser->createFloatingNotAllQuery();
}
break;
case 91:
/* Line 1806 of yacc.c */
#line 677 "css/CSSGrammar.y"
{
(yyval.mediaList) = parser->createMediaQuerySet();
}
break;
case 93:
/* Line 1806 of yacc.c */
#line 684 "css/CSSGrammar.y"
{
(yyval.mediaList) = parser->createMediaQuerySet();
(yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(1) - (1)].mediaQuery)));
}
break;
case 94:
/* Line 1806 of yacc.c */
#line 688 "css/CSSGrammar.y"
{
(yyval.mediaList) = (yyvsp[(1) - (2)].mediaList);
(yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(2) - (2)].mediaQuery)));
}
break;
case 95:
/* Line 1806 of yacc.c */
#line 692 "css/CSSGrammar.y"
{
(yyval.mediaList) = (yyvsp[(1) - (1)].mediaList);
(yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery(parser->createFloatingNotAllQuery()));
}
break;
case 96:
/* Line 1806 of yacc.c */
#line 699 "css/CSSGrammar.y"
{
(yyval.mediaList) = parser->createMediaQuerySet();
(yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(1) - (4)].mediaQuery)));
}
break;
case 97:
/* Line 1806 of yacc.c */
#line 703 "css/CSSGrammar.y"
{
(yyval.mediaList) = (yyvsp[(1) - (5)].mediaList);
(yyval.mediaList)->addMediaQuery(parser->sinkFloatingMediaQuery((yyvsp[(2) - (5)].mediaQuery)));
}
break;
case 98:
/* Line 1806 of yacc.c */
#line 710 "css/CSSGrammar.y"
{
parser->startRuleBody();
}
break;
case 99:
/* Line 1806 of yacc.c */
#line 716 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::MEDIA_RULE);
}
break;
case 100:
/* Line 1806 of yacc.c */
#line 722 "css/CSSGrammar.y"
{
parser->endRuleHeader();
}
break;
case 102:
/* Line 1806 of yacc.c */
#line 731 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createMediaRule((yyvsp[(2) - (8)].mediaList), (yyvsp[(7) - (8)].ruleList));
}
break;
case 104:
/* Line 1806 of yacc.c */
#line 741 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createSupportsRule((yyvsp[(4) - (10)].boolean), (yyvsp[(9) - (10)].ruleList));
}
break;
case 105:
/* Line 1806 of yacc.c */
#line 747 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::SUPPORTS_RULE);
parser->markSupportsRuleHeaderStart();
}
break;
case 106:
/* Line 1806 of yacc.c */
#line 754 "css/CSSGrammar.y"
{
parser->endRuleHeader();
parser->markSupportsRuleHeaderEnd();
}
break;
case 111:
/* Line 1806 of yacc.c */
#line 768 "css/CSSGrammar.y"
{
(yyval.boolean) = !(yyvsp[(3) - (3)].boolean);
}
break;
case 112:
/* Line 1806 of yacc.c */
#line 774 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(1) - (4)].boolean) && (yyvsp[(4) - (4)].boolean);
}
break;
case 113:
/* Line 1806 of yacc.c */
#line 777 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(1) - (4)].boolean) && (yyvsp[(4) - (4)].boolean);
}
break;
case 114:
/* Line 1806 of yacc.c */
#line 783 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(4) - (4)].boolean);
}
break;
case 115:
/* Line 1806 of yacc.c */
#line 786 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(4) - (4)].boolean);
}
break;
case 116:
/* Line 1806 of yacc.c */
#line 792 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(3) - (5)].boolean);
}
break;
case 118:
/* Line 1806 of yacc.c */
#line 796 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(3) - (6)].location), InvalidSupportsConditionCSSError);
(yyval.boolean) = false;
}
break;
case 119:
/* Line 1806 of yacc.c */
#line 803 "css/CSSGrammar.y"
{
(yyval.boolean) = false;
CSSPropertyID id = cssPropertyID((yyvsp[(3) - (10)].string));
if (id != CSSPropertyInvalid) {
parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(7) - (10)].valueList));
int oldParsedProperties = parser->m_parsedProperties.size();
(yyval.boolean) = parser->parseValue(id, (yyvsp[(8) - (10)].boolean));
// We just need to know if the declaration is supported as it is written. Rollback any additions.
if ((yyval.boolean))
parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
}
parser->m_valueList = nullptr;
parser->endProperty((yyvsp[(8) - (10)].boolean), false);
}
break;
case 120:
/* Line 1806 of yacc.c */
#line 817 "css/CSSGrammar.y"
{
(yyval.boolean) = false;
parser->endProperty(false, false, GeneralCSSError);
}
break;
case 121:
/* Line 1806 of yacc.c */
#line 824 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::KEYFRAMES_RULE);
}
break;
case 122:
/* Line 1806 of yacc.c */
#line 830 "css/CSSGrammar.y"
{
(yyval.boolean) = false;
}
break;
case 123:
/* Line 1806 of yacc.c */
#line 833 "css/CSSGrammar.y"
{
(yyval.boolean) = true;
}
break;
case 124:
/* Line 1806 of yacc.c */
#line 839 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createKeyframesRule((yyvsp[(2) - (9)].string), parser->sinkFloatingKeyframeVector((yyvsp[(8) - (9)].keyframeRuleList)), (yyvsp[(1) - (9)].boolean) /* isPrefixed */);
}
break;
case 128:
/* Line 1806 of yacc.c */
#line 851 "css/CSSGrammar.y"
{
parser->clearProperties();
}
break;
case 129:
/* Line 1806 of yacc.c */
#line 856 "css/CSSGrammar.y"
{
(yyval.keyframeRuleList) = parser->createFloatingKeyframeVector();
parser->resumeErrorLogging();
}
break;
case 130:
/* Line 1806 of yacc.c */
#line 860 "css/CSSGrammar.y"
{
(yyval.keyframeRuleList) = (yyvsp[(1) - (4)].keyframeRuleList);
(yyval.keyframeRuleList)->append((yyvsp[(2) - (4)].keyframe));
}
break;
case 131:
/* Line 1806 of yacc.c */
#line 864 "css/CSSGrammar.y"
{
parser->clearProperties();
parser->resumeErrorLogging();
}
break;
case 132:
/* Line 1806 of yacc.c */
#line 871 "css/CSSGrammar.y"
{
(yyval.keyframe) = parser->createKeyframe((yyvsp[(1) - (5)].valueList));
}
break;
case 133:
/* Line 1806 of yacc.c */
#line 877 "css/CSSGrammar.y"
{
(yyval.valueList) = parser->createFloatingValueList();
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (2)].value)));
}
break;
case 134:
/* Line 1806 of yacc.c */
#line 881 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (5)].valueList);
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(4) - (5)].value)));
}
break;
case 135:
/* Line 1806 of yacc.c */
#line 888 "css/CSSGrammar.y"
{
(yyval.value).setFromNumber((yyvsp[(1) - (2)].integer) * (yyvsp[(2) - (2)].number));
}
break;
case 136:
/* Line 1806 of yacc.c */
#line 891 "css/CSSGrammar.y"
{
if ((yyvsp[(1) - (1)].string).equalIgnoringCase("from"))
(yyval.value).setFromNumber(0);
else if ((yyvsp[(1) - (1)].string).equalIgnoringCase("to"))
(yyval.value).setFromNumber(100);
else {
YYERROR;
}
}
break;
case 137:
/* Line 1806 of yacc.c */
#line 903 "css/CSSGrammar.y"
{
parser->reportError(parser->lastLocationLabel(), InvalidKeyframeSelectorCSSError);
}
break;
case 138:
/* Line 1806 of yacc.c */
#line 909 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::PAGE_RULE);
}
break;
case 139:
/* Line 1806 of yacc.c */
#line 916 "css/CSSGrammar.y"
{
if ((yyvsp[(4) - (10)].selector))
(yyval.rule) = parser->createPageRule(parser->sinkFloatingSelector((yyvsp[(4) - (10)].selector)));
else {
// Clear properties in the invalid @page rule.
parser->clearProperties();
// Also clear margin at-rules here once we fully implement margin at-rules parsing.
(yyval.rule) = 0;
}
}
break;
case 140:
/* Line 1806 of yacc.c */
#line 929 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, (yyvsp[(1) - (2)].string), parser->m_defaultNamespace));
(yyval.selector)->setForPage();
}
break;
case 141:
/* Line 1806 of yacc.c */
#line 933 "css/CSSGrammar.y"
{
(yyval.selector) = (yyvsp[(2) - (3)].selector);
(yyval.selector)->prependTagSelector(QualifiedName(nullAtom, (yyvsp[(1) - (3)].string), parser->m_defaultNamespace));
(yyval.selector)->setForPage();
}
break;
case 142:
/* Line 1806 of yacc.c */
#line 938 "css/CSSGrammar.y"
{
(yyval.selector) = (yyvsp[(1) - (2)].selector);
(yyval.selector)->setForPage();
}
break;
case 143:
/* Line 1806 of yacc.c */
#line 942 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setForPage();
}
break;
case 146:
/* Line 1806 of yacc.c */
#line 954 "css/CSSGrammar.y"
{
parser->startDeclarationsForMarginBox();
}
break;
case 147:
/* Line 1806 of yacc.c */
#line 956 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createMarginAtRule((yyvsp[(1) - (7)].marginBox));
}
break;
case 148:
/* Line 1806 of yacc.c */
#line 962 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::TopLeftCornerMarginBox;
}
break;
case 149:
/* Line 1806 of yacc.c */
#line 965 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::TopLeftMarginBox;
}
break;
case 150:
/* Line 1806 of yacc.c */
#line 968 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::TopCenterMarginBox;
}
break;
case 151:
/* Line 1806 of yacc.c */
#line 971 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::TopRightMarginBox;
}
break;
case 152:
/* Line 1806 of yacc.c */
#line 974 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::TopRightCornerMarginBox;
}
break;
case 153:
/* Line 1806 of yacc.c */
#line 977 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::BottomLeftCornerMarginBox;
}
break;
case 154:
/* Line 1806 of yacc.c */
#line 980 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::BottomLeftMarginBox;
}
break;
case 155:
/* Line 1806 of yacc.c */
#line 983 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::BottomCenterMarginBox;
}
break;
case 156:
/* Line 1806 of yacc.c */
#line 986 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::BottomRightMarginBox;
}
break;
case 157:
/* Line 1806 of yacc.c */
#line 989 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::BottomRightCornerMarginBox;
}
break;
case 158:
/* Line 1806 of yacc.c */
#line 992 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::LeftTopMarginBox;
}
break;
case 159:
/* Line 1806 of yacc.c */
#line 995 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::LeftMiddleMarginBox;
}
break;
case 160:
/* Line 1806 of yacc.c */
#line 998 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::LeftBottomMarginBox;
}
break;
case 161:
/* Line 1806 of yacc.c */
#line 1001 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::RightTopMarginBox;
}
break;
case 162:
/* Line 1806 of yacc.c */
#line 1004 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::RightMiddleMarginBox;
}
break;
case 163:
/* Line 1806 of yacc.c */
#line 1007 "css/CSSGrammar.y"
{
(yyval.marginBox) = CSSSelector::RightBottomMarginBox;
}
break;
case 164:
/* Line 1806 of yacc.c */
#line 1013 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::FONT_FACE_RULE);
}
break;
case 165:
/* Line 1806 of yacc.c */
#line 1020 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createFontFaceRule();
}
break;
case 166:
/* Line 1806 of yacc.c */
#line 1026 "css/CSSGrammar.y"
{
parser->markViewportRuleBodyStart();
parser->startRuleHeader(CSSRuleSourceData::VIEWPORT_RULE);
}
break;
case 167:
/* Line 1806 of yacc.c */
#line 1034 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createViewportRule();
parser->markViewportRuleBodyEnd();
}
break;
case 168:
/* Line 1806 of yacc.c */
#line 1041 "css/CSSGrammar.y"
{ (yyval.relation) = CSSSelector::DirectAdjacent; }
break;
case 169:
/* Line 1806 of yacc.c */
#line 1042 "css/CSSGrammar.y"
{ (yyval.relation) = CSSSelector::IndirectAdjacent; }
break;
case 170:
/* Line 1806 of yacc.c */
#line 1043 "css/CSSGrammar.y"
{ (yyval.relation) = CSSSelector::Child; }
break;
case 171:
/* Line 1806 of yacc.c */
#line 1044 "css/CSSGrammar.y"
{
if ((yyvsp[(2) - (4)].string).equalIgnoringCase("deep"))
(yyval.relation) = CSSSelector::ShadowDeep;
else
YYERROR;
}
break;
case 173:
/* Line 1806 of yacc.c */
#line 1054 "css/CSSGrammar.y"
{ (yyval.integer) = 1; }
break;
case 174:
/* Line 1806 of yacc.c */
#line 1058 "css/CSSGrammar.y"
{ (yyval.integer) = -1; }
break;
case 175:
/* Line 1806 of yacc.c */
#line 1059 "css/CSSGrammar.y"
{ (yyval.integer) = 1; }
break;
case 176:
/* Line 1806 of yacc.c */
#line 1063 "css/CSSGrammar.y"
{
parser->startProperty();
}
break;
case 177:
/* Line 1806 of yacc.c */
#line 1069 "css/CSSGrammar.y"
{
parser->startRuleHeader(CSSRuleSourceData::STYLE_RULE);
parser->startSelector();
}
break;
case 178:
/* Line 1806 of yacc.c */
#line 1076 "css/CSSGrammar.y"
{
parser->endRuleHeader();
}
break;
case 179:
/* Line 1806 of yacc.c */
#line 1082 "css/CSSGrammar.y"
{
parser->endSelector();
}
break;
case 180:
/* Line 1806 of yacc.c */
#line 1088 "css/CSSGrammar.y"
{
(yyval.rule) = parser->createStyleRule((yyvsp[(2) - (9)].selectorList));
}
break;
case 181:
/* Line 1806 of yacc.c */
#line 1094 "css/CSSGrammar.y"
{
parser->startSelector();
}
break;
case 182:
/* Line 1806 of yacc.c */
#line 1099 "css/CSSGrammar.y"
{
(yyval.selectorList) = parser->reusableSelectorVector();
(yyval.selectorList)->shrink(0);
(yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(1) - (1)].selector)));
}
break;
case 183:
/* Line 1806 of yacc.c */
#line 1104 "css/CSSGrammar.y"
{
(yyval.selectorList) = (yyvsp[(1) - (6)].selectorList);
(yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(6) - (6)].selector)));
}
break;
case 186:
/* Line 1806 of yacc.c */
#line 1114 "css/CSSGrammar.y"
{
(yyval.selector) = (yyvsp[(3) - (3)].selector);
CSSParserSelector* end = (yyval.selector);
while (end->tagHistory())
end = end->tagHistory();
end->setRelation(CSSSelector::Descendant);
if ((yyvsp[(1) - (3)].selector)->isContentPseudoElement())
end->setRelationIsAffectedByPseudoContent();
end->setTagHistory(parser->sinkFloatingSelector((yyvsp[(1) - (3)].selector)));
}
break;
case 187:
/* Line 1806 of yacc.c */
#line 1124 "css/CSSGrammar.y"
{
(yyval.selector) = (yyvsp[(3) - (3)].selector);
CSSParserSelector* end = (yyval.selector);
while (end->tagHistory())
end = end->tagHistory();
end->setRelation((yyvsp[(2) - (3)].relation));
if ((yyvsp[(1) - (3)].selector)->isContentPseudoElement())
end->setRelationIsAffectedByPseudoContent();
end->setTagHistory(parser->sinkFloatingSelector((yyvsp[(1) - (3)].selector)));
}
break;
case 188:
/* Line 1806 of yacc.c */
#line 1137 "css/CSSGrammar.y"
{ (yyval.string).clear(); }
break;
case 189:
/* Line 1806 of yacc.c */
#line 1138 "css/CSSGrammar.y"
{ static const LChar star = '*'; (yyval.string).init(&star, 1); }
break;
case 191:
/* Line 1806 of yacc.c */
#line 1143 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelectorWithTagName(QualifiedName(nullAtom, (yyvsp[(1) - (1)].string), parser->m_defaultNamespace));
}
break;
case 192:
/* Line 1806 of yacc.c */
#line 1146 "css/CSSGrammar.y"
{
(yyval.selector) = parser->rewriteSpecifiersWithElementName(nullAtom, (yyvsp[(1) - (2)].string), (yyvsp[(2) - (2)].selector));
if (!(yyval.selector))
YYERROR;
}
break;
case 193:
/* Line 1806 of yacc.c */
#line 1151 "css/CSSGrammar.y"
{
(yyval.selector) = parser->rewriteSpecifiersWithNamespaceIfNeeded((yyvsp[(1) - (1)].selector));
if (!(yyval.selector))
YYERROR;
}
break;
case 194:
/* Line 1806 of yacc.c */
#line 1156 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelectorWithTagName(parser->determineNameInNamespace((yyvsp[(1) - (2)].string), (yyvsp[(2) - (2)].string)));
if (!(yyval.selector))
YYERROR;
}
break;
case 195:
/* Line 1806 of yacc.c */
#line 1161 "css/CSSGrammar.y"
{
(yyval.selector) = parser->rewriteSpecifiersWithElementName((yyvsp[(1) - (3)].string), (yyvsp[(2) - (3)].string), (yyvsp[(3) - (3)].selector));
if (!(yyval.selector))
YYERROR;
}
break;
case 196:
/* Line 1806 of yacc.c */
#line 1166 "css/CSSGrammar.y"
{
(yyval.selector) = parser->rewriteSpecifiersWithElementName((yyvsp[(1) - (2)].string), starAtom, (yyvsp[(2) - (2)].selector));
if (!(yyval.selector))
YYERROR;
}
break;
case 197:
/* Line 1806 of yacc.c */
#line 1174 "css/CSSGrammar.y"
{
(yyval.selectorList) = parser->createFloatingSelectorVector();
(yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(1) - (1)].selector)));
}
break;
case 198:
/* Line 1806 of yacc.c */
#line 1178 "css/CSSGrammar.y"
{
(yyval.selectorList) = (yyvsp[(1) - (5)].selectorList);
(yyval.selectorList)->append(parser->sinkFloatingSelector((yyvsp[(5) - (5)].selector)));
}
break;
case 199:
/* Line 1806 of yacc.c */
#line 1185 "css/CSSGrammar.y"
{
if (parser->m_context.isHTMLDocument())
parser->tokenToLowerCase((yyvsp[(1) - (1)].string));
(yyval.string) = (yyvsp[(1) - (1)].string);
}
break;
case 200:
/* Line 1806 of yacc.c */
#line 1190 "css/CSSGrammar.y"
{
static const LChar star = '*';
(yyval.string).init(&star, 1);
}
break;
case 202:
/* Line 1806 of yacc.c */
#line 1198 "css/CSSGrammar.y"
{
(yyval.selector) = parser->rewriteSpecifiers((yyvsp[(1) - (2)].selector), (yyvsp[(2) - (2)].selector));
}
break;
case 203:
/* Line 1806 of yacc.c */
#line 1204 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::Id);
if (isQuirksModeBehavior(parser->m_context.mode()))
parser->tokenToLowerCase((yyvsp[(1) - (1)].string));
(yyval.selector)->setValue((yyvsp[(1) - (1)].string));
}
break;
case 204:
/* Line 1806 of yacc.c */
#line 1211 "css/CSSGrammar.y"
{
if ((yyvsp[(1) - (1)].string)[0] >= '0' && (yyvsp[(1) - (1)].string)[0] <= '9') {
YYERROR;
} else {
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::Id);
if (isQuirksModeBehavior(parser->m_context.mode()))
parser->tokenToLowerCase((yyvsp[(1) - (1)].string));
(yyval.selector)->setValue((yyvsp[(1) - (1)].string));
}
}
break;
case 208:
/* Line 1806 of yacc.c */
#line 1228 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::Class);
if (isQuirksModeBehavior(parser->m_context.mode()))
parser->tokenToLowerCase((yyvsp[(2) - (2)].string));
(yyval.selector)->setValue((yyvsp[(2) - (2)].string));
}
break;
case 209:
/* Line 1806 of yacc.c */
#line 1238 "css/CSSGrammar.y"
{
if (parser->m_context.isHTMLDocument())
parser->tokenToLowerCase((yyvsp[(1) - (2)].string));
(yyval.string) = (yyvsp[(1) - (2)].string);
}
break;
case 210:
/* Line 1806 of yacc.c */
#line 1246 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setAttribute(QualifiedName(nullAtom, (yyvsp[(3) - (4)].string), nullAtom));
(yyval.selector)->setMatch(CSSSelector::Set);
}
break;
case 211:
/* Line 1806 of yacc.c */
#line 1251 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setAttribute(QualifiedName(nullAtom, (yyvsp[(3) - (8)].string), nullAtom));
(yyval.selector)->setMatch((CSSSelector::Match)(yyvsp[(4) - (8)].integer));
(yyval.selector)->setValue((yyvsp[(6) - (8)].string));
}
break;
case 212:
/* Line 1806 of yacc.c */
#line 1257 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setAttribute(parser->determineNameInNamespace((yyvsp[(3) - (5)].string), (yyvsp[(4) - (5)].string)));
(yyval.selector)->setMatch(CSSSelector::Set);
}
break;
case 213:
/* Line 1806 of yacc.c */
#line 1262 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setAttribute(parser->determineNameInNamespace((yyvsp[(3) - (9)].string), (yyvsp[(4) - (9)].string)));
(yyval.selector)->setMatch((CSSSelector::Match)(yyvsp[(5) - (9)].integer));
(yyval.selector)->setValue((yyvsp[(7) - (9)].string));
}
break;
case 214:
/* Line 1806 of yacc.c */
#line 1268 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 215:
/* Line 1806 of yacc.c */
#line 1274 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::Exact;
}
break;
case 216:
/* Line 1806 of yacc.c */
#line 1277 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::List;
}
break;
case 217:
/* Line 1806 of yacc.c */
#line 1280 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::Hyphen;
}
break;
case 218:
/* Line 1806 of yacc.c */
#line 1283 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::Begin;
}
break;
case 219:
/* Line 1806 of yacc.c */
#line 1286 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::End;
}
break;
case 220:
/* Line 1806 of yacc.c */
#line 1289 "css/CSSGrammar.y"
{
(yyval.integer) = CSSSelector::Contain;
}
break;
case 223:
/* Line 1806 of yacc.c */
#line 1300 "css/CSSGrammar.y"
{
if ((yyvsp[(2) - (2)].string).isFunction())
YYERROR;
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PagePseudoClass);
parser->tokenToLowerCase((yyvsp[(2) - (2)].string));
(yyval.selector)->setValue((yyvsp[(2) - (2)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown)
YYERROR;
}
break;
case 224:
/* Line 1806 of yacc.c */
#line 1313 "css/CSSGrammar.y"
{
if ((yyvsp[(3) - (3)].string).isFunction())
YYERROR;
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
parser->tokenToLowerCase((yyvsp[(3) - (3)].string));
(yyval.selector)->setValue((yyvsp[(3) - (3)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown) {
parser->reportError((yyvsp[(2) - (3)].location), InvalidSelectorPseudoCSSError);
YYERROR;
}
}
break;
case 225:
/* Line 1806 of yacc.c */
#line 1326 "css/CSSGrammar.y"
{
if ((yyvsp[(4) - (4)].string).isFunction())
YYERROR;
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoElement);
parser->tokenToLowerCase((yyvsp[(4) - (4)].string));
(yyval.selector)->setValue((yyvsp[(4) - (4)].string));
// FIXME: This call is needed to force selector to compute the pseudoType early enough.
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown) {
parser->reportError((yyvsp[(3) - (4)].location), InvalidSelectorPseudoCSSError);
YYERROR;
}
}
break;
case 226:
/* Line 1806 of yacc.c */
#line 1341 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoElement);
(yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(5) - (7)].selectorList)));
(yyval.selector)->setValue((yyvsp[(3) - (7)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type != CSSSelector::PseudoCue)
YYERROR;
}
break;
case 227:
/* Line 1806 of yacc.c */
#line 1350 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 228:
/* Line 1806 of yacc.c */
#line 1358 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList)));
parser->tokenToLowerCase((yyvsp[(2) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type != CSSSelector::PseudoAny)
YYERROR;
}
break;
case 229:
/* Line 1806 of yacc.c */
#line 1368 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 230:
/* Line 1806 of yacc.c */
#line 1372 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->setArgument((yyvsp[(4) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown)
YYERROR;
}
break;
case 231:
/* Line 1806 of yacc.c */
#line 1382 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->setArgument(AtomicString::number((yyvsp[(4) - (7)].integer) * (yyvsp[(5) - (7)].number)));
(yyval.selector)->setValue((yyvsp[(2) - (7)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown)
YYERROR;
}
break;
case 232:
/* Line 1806 of yacc.c */
#line 1392 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->setArgument((yyvsp[(4) - (6)].string));
parser->tokenToLowerCase((yyvsp[(2) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type == CSSSelector::PseudoUnknown)
YYERROR;
else if (type == CSSSelector::PseudoNthChild ||
type == CSSSelector::PseudoNthOfType ||
type == CSSSelector::PseudoNthLastChild ||
type == CSSSelector::PseudoNthLastOfType) {
if (!isValidNthToken((yyvsp[(4) - (6)].string)))
YYERROR;
}
}
break;
case 233:
/* Line 1806 of yacc.c */
#line 1409 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 234:
/* Line 1806 of yacc.c */
#line 1413 "css/CSSGrammar.y"
{
if (!(yyvsp[(4) - (6)].selector)->isSimple())
YYERROR;
else {
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
Vector<OwnPtr<CSSParserSelector> > selectorVector;
selectorVector.append(parser->sinkFloatingSelector((yyvsp[(4) - (6)].selector)));
(yyval.selector)->adoptSelectorVector(selectorVector);
parser->tokenToLowerCase((yyvsp[(2) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
}
}
break;
case 235:
/* Line 1806 of yacc.c */
#line 1428 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 236:
/* Line 1806 of yacc.c */
#line 1431 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList)));
parser->tokenToLowerCase((yyvsp[(2) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type != CSSSelector::PseudoHost)
YYERROR;
}
break;
case 237:
/* Line 1806 of yacc.c */
#line 1441 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 238:
/* Line 1806 of yacc.c */
#line 1445 "css/CSSGrammar.y"
{
(yyval.selector) = parser->createFloatingSelector();
(yyval.selector)->setMatch(CSSSelector::PseudoClass);
(yyval.selector)->adoptSelectorVector(*parser->sinkFloatingSelectorVector((yyvsp[(4) - (6)].selectorList)));
parser->tokenToLowerCase((yyvsp[(2) - (6)].string));
(yyval.selector)->setValue((yyvsp[(2) - (6)].string));
CSSSelector::PseudoType type = (yyval.selector)->pseudoType();
if (type != CSSSelector::PseudoHostContext)
YYERROR;
}
break;
case 239:
/* Line 1806 of yacc.c */
#line 1455 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 241:
/* Line 1806 of yacc.c */
#line 1464 "css/CSSGrammar.y"
{ (yyval.boolean) = false; }
break;
case 243:
/* Line 1806 of yacc.c */
#line 1466 "css/CSSGrammar.y"
{
(yyval.boolean) = (yyvsp[(1) - (2)].boolean) || (yyvsp[(2) - (2)].boolean);
}
break;
case 245:
/* Line 1806 of yacc.c */
#line 1473 "css/CSSGrammar.y"
{
parser->startProperty();
(yyval.boolean) = (yyvsp[(1) - (3)].boolean);
}
break;
case 246:
/* Line 1806 of yacc.c */
#line 1477 "css/CSSGrammar.y"
{
parser->startProperty();
(yyval.boolean) = (yyvsp[(1) - (4)].boolean) || (yyvsp[(2) - (4)].boolean);
}
break;
case 247:
/* Line 1806 of yacc.c */
#line 1484 "css/CSSGrammar.y"
{
(yyval.boolean) = false;
bool isPropertyParsed = false;
if ((yyvsp[(1) - (6)].id) != CSSPropertyInvalid) {
parser->m_valueList = parser->sinkFloatingValueList((yyvsp[(5) - (6)].valueList));
int oldParsedProperties = parser->m_parsedProperties.size();
(yyval.boolean) = parser->parseValue((yyvsp[(1) - (6)].id), (yyvsp[(6) - (6)].boolean));
if (!(yyval.boolean)) {
parser->rollbackLastProperties(parser->m_parsedProperties.size() - oldParsedProperties);
parser->reportError((yyvsp[(4) - (6)].location), InvalidPropertyValueCSSError);
} else
isPropertyParsed = true;
parser->m_valueList = nullptr;
}
parser->endProperty((yyvsp[(6) - (6)].boolean), isPropertyParsed);
}
break;
case 248:
/* Line 1806 of yacc.c */
#line 1501 "css/CSSGrammar.y"
{
/* When we encounter something like p {color: red !important fail;} we should drop the declaration */
parser->reportError((yyvsp[(4) - (8)].location), InvalidPropertyValueCSSError);
parser->endProperty(false, false);
(yyval.boolean) = false;
}
break;
case 249:
/* Line 1806 of yacc.c */
#line 1508 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(4) - (6)].location), InvalidPropertyValueCSSError);
parser->endProperty(false, false);
(yyval.boolean) = false;
}
break;
case 250:
/* Line 1806 of yacc.c */
#line 1514 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(3) - (4)].location), PropertyDeclarationCSSError);
parser->endProperty(false, false, GeneralCSSError);
(yyval.boolean) = false;
}
break;
case 251:
/* Line 1806 of yacc.c */
#line 1520 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(2) - (3)].location), PropertyDeclarationCSSError);
(yyval.boolean) = false;
}
break;
case 252:
/* Line 1806 of yacc.c */
#line 1527 "css/CSSGrammar.y"
{
(yyval.id) = cssPropertyID((yyvsp[(2) - (3)].string));
parser->setCurrentProperty((yyval.id));
if ((yyval.id) == CSSPropertyInvalid)
parser->reportError((yyvsp[(1) - (3)].location), InvalidPropertyCSSError);
}
break;
case 253:
/* Line 1806 of yacc.c */
#line 1536 "css/CSSGrammar.y"
{ (yyval.boolean) = true; }
break;
case 254:
/* Line 1806 of yacc.c */
#line 1537 "css/CSSGrammar.y"
{ (yyval.boolean) = false; }
break;
case 255:
/* Line 1806 of yacc.c */
#line 1541 "css/CSSGrammar.y"
{
(yyval.valueList) = parser->createFloatingValueList();
(yyval.valueList)->addValue(makeIdentValue((yyvsp[(1) - (2)].string)));
}
break;
case 256:
/* Line 1806 of yacc.c */
#line 1545 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (3)].valueList);
(yyval.valueList)->addValue(makeIdentValue((yyvsp[(2) - (3)].string)));
}
break;
case 257:
/* Line 1806 of yacc.c */
#line 1552 "css/CSSGrammar.y"
{
(yyval.value).setFromValueList(parser->sinkFloatingValueList(parser->createFloatingValueList()));
}
break;
case 258:
/* Line 1806 of yacc.c */
#line 1555 "css/CSSGrammar.y"
{
(yyval.value).setFromValueList(parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList)));
}
break;
case 259:
/* Line 1806 of yacc.c */
#line 1558 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 260:
/* Line 1806 of yacc.c */
#line 1564 "css/CSSGrammar.y"
{
(yyval.valueList) = parser->createFloatingValueList();
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (1)].value)));
}
break;
case 261:
/* Line 1806 of yacc.c */
#line 1568 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (3)].valueList);
(yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character)));
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(3) - (3)].value)));
}
break;
case 262:
/* Line 1806 of yacc.c */
#line 1573 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (2)].valueList);
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(2) - (2)].value)));
}
break;
case 263:
/* Line 1806 of yacc.c */
#line 1580 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(2) - (3)].location), PropertyDeclarationCSSError);
}
break;
case 264:
/* Line 1806 of yacc.c */
#line 1586 "css/CSSGrammar.y"
{
(yyval.character) = '/';
}
break;
case 265:
/* Line 1806 of yacc.c */
#line 1589 "css/CSSGrammar.y"
{
(yyval.character) = ',';
}
break;
case 267:
/* Line 1806 of yacc.c */
#line 1596 "css/CSSGrammar.y"
{ (yyval.value) = (yyvsp[(2) - (3)].value); (yyval.value).fValue *= (yyvsp[(1) - (3)].integer); }
break;
case 268:
/* Line 1806 of yacc.c */
#line 1597 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).isInt = false; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).unit = CSSPrimitiveValue::CSS_STRING; }
break;
case 269:
/* Line 1806 of yacc.c */
#line 1598 "css/CSSGrammar.y"
{ (yyval.value) = makeIdentValue((yyvsp[(1) - (2)].string)); }
break;
case 270:
/* Line 1806 of yacc.c */
#line 1600 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_DIMENSION; }
break;
case 271:
/* Line 1806 of yacc.c */
#line 1601 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(2) - (3)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_DIMENSION; }
break;
case 272:
/* Line 1806 of yacc.c */
#line 1602 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_URI; }
break;
case 273:
/* Line 1806 of yacc.c */
#line 1603 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_UNICODE_RANGE; }
break;
case 274:
/* Line 1806 of yacc.c */
#line 1604 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = (yyvsp[(1) - (2)].string); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; }
break;
case 275:
/* Line 1806 of yacc.c */
#line 1605 "css/CSSGrammar.y"
{ (yyval.value).id = CSSValueInvalid; (yyval.value).string = CSSParserString(); (yyval.value).isInt = false; (yyval.value).unit = CSSPrimitiveValue::CSS_PARSER_HEXCOLOR; }
break;
case 278:
/* Line 1806 of yacc.c */
#line 1609 "css/CSSGrammar.y"
{ /* Handle width: %; */
(yyval.value).id = CSSValueInvalid; (yyval.value).isInt = false; (yyval.value).unit = 0;
}
break;
case 280:
/* Line 1806 of yacc.c */
#line 1616 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number)); (yyval.value).isInt = true; }
break;
case 281:
/* Line 1806 of yacc.c */
#line 1617 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number)); }
break;
case 282:
/* Line 1806 of yacc.c */
#line 1618 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PERCENTAGE); }
break;
case 283:
/* Line 1806 of yacc.c */
#line 1619 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PX); }
break;
case 284:
/* Line 1806 of yacc.c */
#line 1620 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_CM); }
break;
case 285:
/* Line 1806 of yacc.c */
#line 1621 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_MM); }
break;
case 286:
/* Line 1806 of yacc.c */
#line 1622 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_IN); }
break;
case 287:
/* Line 1806 of yacc.c */
#line 1623 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PT); }
break;
case 288:
/* Line 1806 of yacc.c */
#line 1624 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_PC); }
break;
case 289:
/* Line 1806 of yacc.c */
#line 1625 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DEG); }
break;
case 290:
/* Line 1806 of yacc.c */
#line 1626 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_RAD); }
break;
case 291:
/* Line 1806 of yacc.c */
#line 1627 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_GRAD); }
break;
case 292:
/* Line 1806 of yacc.c */
#line 1628 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_TURN); }
break;
case 293:
/* Line 1806 of yacc.c */
#line 1629 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_MS); }
break;
case 294:
/* Line 1806 of yacc.c */
#line 1630 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_S); }
break;
case 295:
/* Line 1806 of yacc.c */
#line 1631 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_HZ); }
break;
case 296:
/* Line 1806 of yacc.c */
#line 1632 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_KHZ); }
break;
case 297:
/* Line 1806 of yacc.c */
#line 1633 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_EMS); }
break;
case 298:
/* Line 1806 of yacc.c */
#line 1634 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSParserValue::Q_EMS); }
break;
case 299:
/* Line 1806 of yacc.c */
#line 1635 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_EXS); }
break;
case 300:
/* Line 1806 of yacc.c */
#line 1636 "css/CSSGrammar.y"
{
(yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_REMS);
if (parser->m_styleSheet)
parser->m_styleSheet->parserSetUsesRemUnits(true);
}
break;
case 301:
/* Line 1806 of yacc.c */
#line 1641 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_CHS); }
break;
case 302:
/* Line 1806 of yacc.c */
#line 1642 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VW); }
break;
case 303:
/* Line 1806 of yacc.c */
#line 1643 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VH); }
break;
case 304:
/* Line 1806 of yacc.c */
#line 1644 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VMIN); }
break;
case 305:
/* Line 1806 of yacc.c */
#line 1645 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_VMAX); }
break;
case 306:
/* Line 1806 of yacc.c */
#line 1646 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPPX); }
break;
case 307:
/* Line 1806 of yacc.c */
#line 1647 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPI); }
break;
case 308:
/* Line 1806 of yacc.c */
#line 1648 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_DPCM); }
break;
case 309:
/* Line 1806 of yacc.c */
#line 1649 "css/CSSGrammar.y"
{ (yyval.value).setFromNumber((yyvsp[(1) - (1)].number), CSSPrimitiveValue::CSS_FR); }
break;
case 310:
/* Line 1806 of yacc.c */
#line 1653 "css/CSSGrammar.y"
{
(yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (4)].string), parser->sinkFloatingValueList((yyvsp[(3) - (4)].valueList))));
}
break;
case 311:
/* Line 1806 of yacc.c */
#line 1656 "css/CSSGrammar.y"
{
(yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (3)].string), parser->sinkFloatingValueList(parser->createFloatingValueList())));
}
break;
case 312:
/* Line 1806 of yacc.c */
#line 1659 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 314:
/* Line 1806 of yacc.c */
#line 1666 "css/CSSGrammar.y"
{ (yyval.value) = (yyvsp[(2) - (2)].value); (yyval.value).fValue *= (yyvsp[(1) - (2)].integer); }
break;
case 315:
/* Line 1806 of yacc.c */
#line 1670 "css/CSSGrammar.y"
{
(yyval.character) = '+';
}
break;
case 316:
/* Line 1806 of yacc.c */
#line 1673 "css/CSSGrammar.y"
{
(yyval.character) = '-';
}
break;
case 317:
/* Line 1806 of yacc.c */
#line 1676 "css/CSSGrammar.y"
{
(yyval.character) = '*';
}
break;
case 318:
/* Line 1806 of yacc.c */
#line 1679 "css/CSSGrammar.y"
{
(yyval.character) = '/';
}
break;
case 321:
/* Line 1806 of yacc.c */
#line 1690 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(3) - (5)].valueList);
(yyval.valueList)->insertValueAt(0, makeOperatorValue('('));
(yyval.valueList)->addValue(makeOperatorValue(')'));
}
break;
case 322:
/* Line 1806 of yacc.c */
#line 1695 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 323:
/* Line 1806 of yacc.c */
#line 1701 "css/CSSGrammar.y"
{
(yyval.valueList) = parser->createFloatingValueList();
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(1) - (1)].value)));
}
break;
case 324:
/* Line 1806 of yacc.c */
#line 1705 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (3)].valueList);
(yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character)));
(yyval.valueList)->addValue(parser->sinkFloatingValue((yyvsp[(3) - (3)].value)));
}
break;
case 325:
/* Line 1806 of yacc.c */
#line 1710 "css/CSSGrammar.y"
{
(yyval.valueList) = (yyvsp[(1) - (3)].valueList);
(yyval.valueList)->addValue(makeOperatorValue((yyvsp[(2) - (3)].character)));
(yyval.valueList)->stealValues(*((yyvsp[(3) - (3)].valueList)));
}
break;
case 327:
/* Line 1806 of yacc.c */
#line 1719 "css/CSSGrammar.y"
{
(yyval.value).setFromFunction(parser->createFloatingFunction((yyvsp[(1) - (5)].string), parser->sinkFloatingValueList((yyvsp[(3) - (5)].valueList))));
}
break;
case 328:
/* Line 1806 of yacc.c */
#line 1722 "css/CSSGrammar.y"
{
YYERROR;
}
break;
case 332:
/* Line 1806 of yacc.c */
#line 1738 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(2) - (3)].location), InvalidRuleCSSError);
}
break;
case 338:
/* Line 1806 of yacc.c */
#line 1752 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(4) - (5)].location), InvalidSupportsConditionCSSError);
parser->popSupportsRuleData();
}
break;
case 339:
/* Line 1806 of yacc.c */
#line 1756 "css/CSSGrammar.y"
{
parser->markViewportRuleBodyEnd();
}
break;
case 342:
/* Line 1806 of yacc.c */
#line 1761 "css/CSSGrammar.y"
{
parser->resumeErrorLogging();
parser->reportError((yyvsp[(1) - (3)].location), InvalidRuleCSSError);
}
break;
case 343:
/* Line 1806 of yacc.c */
#line 1768 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(2) - (5)].location), InvalidRuleCSSError);
}
break;
case 347:
/* Line 1806 of yacc.c */
#line 1777 "css/CSSGrammar.y"
{
parser->reportError((yyvsp[(2) - (4)].location), InvalidRuleCSSError);
}
break;
case 350:
/* Line 1806 of yacc.c */
#line 1785 "css/CSSGrammar.y"
{
parser->endInvalidRuleHeader();
}
break;
case 351:
/* Line 1806 of yacc.c */
#line 1791 "css/CSSGrammar.y"
{
parser->invalidBlockHit();
}
break;
case 362:
/* Line 1806 of yacc.c */
#line 1807 "css/CSSGrammar.y"
{
(yyval.location) = parser->currentLocation();
}
break;
case 363:
/* Line 1806 of yacc.c */
#line 1812 "css/CSSGrammar.y"
{
parser->setLocationLabel(parser->currentLocation());
}
break;
/* Line 1806 of yacc.c */
#line 5051 "/home/whm/kt_work/Android/CM12_0-Android501/out/target/product/victara/obj/GYP/shared_intermediates/blink/core/CSSGrammar.cpp"
default: break;
}
/* User semantic actions sometimes alter yychar, and that requires
that yytoken be updated with the new translation. We take the
approach of translating immediately before every use of yytoken.
One alternative is translating here after every semantic action,
but that translation would be missed if the semantic action invokes
YYABORT, YYACCEPT, or YYERROR immediately after altering yychar or
if it invokes YYBACKUP. In the case of YYABORT or YYACCEPT, an
incorrect destructor might then be invoked immediately. In the
case of YYERROR or YYBACKUP, subsequent parser actions might lead
to an incorrect destructor call or verbose syntax error message
before the lookahead is translated. */
YY_SYMBOL_PRINT ("-> $$ =", yyr1[yyn], &yyval, &yyloc);
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
*++yyvsp = yyval;
/* Now `shift' the result of the reduction. Determine what state
that goes to, based on the state we popped back to and the rule
number reduced by. */
yyn = yyr1[yyn];
yystate = yypgoto[yyn - YYNTOKENS] + *yyssp;
if (0 <= yystate && yystate <= YYLAST && yycheck[yystate] == *yyssp)
yystate = yytable[yystate];
else
yystate = yydefgoto[yyn - YYNTOKENS];
goto yynewstate;
/*------------------------------------.
| yyerrlab -- here on detecting error |
`------------------------------------*/
yyerrlab:
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = yychar == YYEMPTY ? YYEMPTY : YYTRANSLATE (yychar);
/* If not already recovering from an error, report this error. */
if (!yyerrstatus)
{
++yynerrs;
#if ! YYERROR_VERBOSE
yyerror (parser, YY_("syntax error"));
#else
# define YYSYNTAX_ERROR yysyntax_error (&yymsg_alloc, &yymsg, \
yyssp, yytoken)
{
char const *yymsgp = YY_("syntax error");
int yysyntax_error_status;
yysyntax_error_status = YYSYNTAX_ERROR;
if (yysyntax_error_status == 0)
yymsgp = yymsg;
else if (yysyntax_error_status == 1)
{
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
yymsg = (char *) YYSTACK_ALLOC (yymsg_alloc);
if (!yymsg)
{
yymsg = yymsgbuf;
yymsg_alloc = sizeof yymsgbuf;
yysyntax_error_status = 2;
}
else
{
yysyntax_error_status = YYSYNTAX_ERROR;
yymsgp = yymsg;
}
}
yyerror (parser, yymsgp);
if (yysyntax_error_status == 2)
goto yyexhaustedlab;
}
# undef YYSYNTAX_ERROR
#endif
}
if (yyerrstatus == 3)
{
/* If just tried and failed to reuse lookahead token after an
error, discard it. */
if (yychar <= YYEOF)
{
/* Return failure if at end of input. */
if (yychar == YYEOF)
YYABORT;
}
else
{
yydestruct ("Error: discarding",
yytoken, &yylval, parser);
yychar = YYEMPTY;
}
}
/* Else will try to reuse lookahead token after shifting the error
token. */
goto yyerrlab1;
/*---------------------------------------------------.
| yyerrorlab -- error raised explicitly by YYERROR. |
`---------------------------------------------------*/
yyerrorlab:
/* Pacify compilers like GCC when the user code never invokes
YYERROR and the label yyerrorlab therefore never appears in user
code. */
if (/*CONSTCOND*/ 0)
goto yyerrorlab;
/* Do not reclaim the symbols of the rule which action triggered
this YYERROR. */
YYPOPSTACK (yylen);
yylen = 0;
YY_STACK_PRINT (yyss, yyssp);
yystate = *yyssp;
goto yyerrlab1;
/*-------------------------------------------------------------.
| yyerrlab1 -- common code for both syntax error and YYERROR. |
`-------------------------------------------------------------*/
yyerrlab1:
yyerrstatus = 3; /* Each real token shifted decrements this. */
for (;;)
{
yyn = yypact[yystate];
if (!yypact_value_is_default (yyn))
{
yyn += YYTERROR;
if (0 <= yyn && yyn <= YYLAST && yycheck[yyn] == YYTERROR)
{
yyn = yytable[yyn];
if (0 < yyn)
break;
}
}
/* Pop the current state because it cannot handle the error token. */
if (yyssp == yyss)
YYABORT;
yydestruct ("Error: popping",
yystos[yystate], yyvsp, parser);
YYPOPSTACK (1);
yystate = *yyssp;
YY_STACK_PRINT (yyss, yyssp);
}
*++yyvsp = yylval;
/* Shift the error token. */
YY_SYMBOL_PRINT ("Shifting", yystos[yyn], yyvsp, yylsp);
yystate = yyn;
goto yynewstate;
/*-------------------------------------.
| yyacceptlab -- YYACCEPT comes here. |
`-------------------------------------*/
yyacceptlab:
yyresult = 0;
goto yyreturn;
/*-----------------------------------.
| yyabortlab -- YYABORT comes here. |
`-----------------------------------*/
yyabortlab:
yyresult = 1;
goto yyreturn;
#if !defined(yyoverflow) || YYERROR_VERBOSE
/*-------------------------------------------------.
| yyexhaustedlab -- memory exhaustion comes here. |
`-------------------------------------------------*/
yyexhaustedlab:
yyerror (parser, YY_("memory exhausted"));
yyresult = 2;
/* Fall through. */
#endif
yyreturn:
if (yychar != YYEMPTY)
{
/* Make sure we have latest lookahead translation. See comments at
user semantic actions for why this is necessary. */
yytoken = YYTRANSLATE (yychar);
yydestruct ("Cleanup: discarding lookahead",
yytoken, &yylval, parser);
}
/* Do not reclaim the symbols of the rule which action triggered
this YYABORT or YYACCEPT. */
YYPOPSTACK (yylen);
YY_STACK_PRINT (yyss, yyssp);
while (yyssp != yyss)
{
yydestruct ("Cleanup: popping",
yystos[*yyssp], yyvsp, parser);
YYPOPSTACK (1);
}
#ifndef yyoverflow
if (yyss != yyssa)
YYSTACK_FREE (yyss);
#endif
#if YYERROR_VERBOSE
if (yymsg != yymsgbuf)
YYSTACK_FREE (yymsg);
#endif
/* Make sure YYID is used. */
return YYID (yyresult);
}
/* Line 2067 of yacc.c */
#line 1832 "css/CSSGrammar.y"
| 181,258 | 90,375 |
#include "game.h"
bool isQuit = false;
WindowRef window;
AGLContext context;
#define SND_SIZE 8192
static AudioQueueRef audioQueue;
void soundFill(void* inUserData, AudioQueueRef inAQ, AudioQueueBufferRef inBuffer) {
void* frames = inBuffer->mAudioData;
UInt32 count = inBuffer->mAudioDataBytesCapacity / 4;
Sound::fill((Sound::Frame*)frames, count);
inBuffer->mAudioDataByteSize = count * 4;
AudioQueueEnqueueBuffer(audioQueue, inBuffer, 0, NULL);
// TODO: mutex
}
void soundInit() {
AudioStreamBasicDescription deviceFormat;
deviceFormat.mSampleRate = 44100;
deviceFormat.mFormatID = kAudioFormatLinearPCM;
deviceFormat.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger;
deviceFormat.mBytesPerPacket = 4;
deviceFormat.mFramesPerPacket = 1;
deviceFormat.mBytesPerFrame = 4;
deviceFormat.mChannelsPerFrame = 2;
deviceFormat.mBitsPerChannel = 16;
deviceFormat.mReserved = 0;
AudioQueueNewOutput(&deviceFormat, soundFill, NULL, NULL, NULL, 0, &audioQueue);
for (int i = 0; i < 2; i++) {
AudioQueueBufferRef mBuffer;
AudioQueueAllocateBuffer(audioQueue, SND_SIZE, &mBuffer);
soundFill(NULL, audioQueue, mBuffer);
}
AudioQueueStart(audioQueue, NULL);
}
// common input functions
InputKey keyToInputKey(int code) {
static const int codes[] = {
0x7B, 0x7C, 0x7E, 0x7D, 0x31, 0x24, 0x35, 0x38, 0x3B, 0x3A,
0x1D, 0x12, 0x13, 0x14, 0x15, 0x17, 0x16, 0x1A, 0x1C, 0x19, // 0..9
0x00, 0x0B, 0x08, 0x02, 0x0E, 0x03, 0x05, 0x04, 0x22, 0x26, 0x28, 0x25, 0x2E, // A..M
0x2D, 0x1F, 0x23, 0x0C, 0x0F, 0x01, 0x11, 0x20, 0x09, 0x0D, 0x07, 0x10, 0x06, // N..Z
};
for (int i = 0; i < sizeof(codes) / sizeof(codes[0]); i++)
if (codes[i] == code)
return (InputKey)(ikLeft + i);
return ikNone;
}
InputKey mouseToInputKey(int btn) {
switch (btn) {
case 1 : return ikMouseL;
case 2 : return ikMouseR;
case 3 : return ikMouseM;
}
return ikNone;
}
OSStatus eventHandler(EventHandlerCallRef handler, EventRef event, void* userData) {
OSType eventClass = GetEventClass(event);
UInt32 eventKind = GetEventKind(event);
switch (eventClass) {
case kEventClassWindow :
switch (eventKind) {
case kEventWindowClosed :
isQuit = true;
break;
case kEventWindowBoundsChanged : {
aglUpdateContext(context);
Rect rect;
GetWindowPortBounds(window, &rect);
Core::width = rect.right - rect.left;
Core::height = rect.bottom - rect.top;
break;
}
}
break;
case kEventClassMouse : {
EventMouseButton mouseButton;
CGPoint mousePos;
Rect wndRect;
GetEventParameter(event, kEventParamMouseLocation, typeHIPoint, NULL, sizeof(mousePos), NULL, &mousePos);
GetEventParameter(event, kEventParamMouseButton, typeMouseButton, NULL, sizeof(mouseButton), nil, &mouseButton);
GetWindowBounds(window, kWindowContentRgn, &wndRect);
mousePos.x -= wndRect.left;
mousePos.y -= wndRect.top;
vec2 pos(mousePos.x, mousePos.y);
switch (eventKind) {
case kEventMouseDown :
case kEventMouseUp : {
InputKey key = mouseToInputKey(mouseButton);
Input::setPos(key, pos);
Input::setDown(key, eventKind == kEventMouseDown);
break;
}
case kEventMouseDragged :
Input::setPos(ikMouseL, pos);
break;
}
break;
}
case kEventClassKeyboard : {
switch (eventKind) {
case kEventRawKeyDown :
case kEventRawKeyUp : {
uint32 keyCode;
if (GetEventParameter(event, kEventParamKeyCode, typeUInt32, NULL, sizeof(keyCode), NULL, &keyCode) == noErr)
Input::setDown(keyToInputKey(keyCode), eventKind != kEventRawKeyUp);
break;
}
case kEventRawKeyModifiersChanged : {
uint32 modifiers;
if (GetEventParameter(event, kEventParamKeyModifiers, typeUInt32, NULL, sizeof(modifiers), NULL, &modifiers) == noErr) {
Input::setDown(ikShift, modifiers & shiftKey);
Input::setDown(ikCtrl, modifiers & controlKey);
Input::setDown(ikAlt, modifiers & optionKey);
}
break;
}
}
break;
}
}
return CallNextEventHandler(handler, event);
}
int getTime() {
UInt64 t;
Microseconds((UnsignedWide*)&t);
return int(t / 1000);
}
char *contentPath;
int main() {
// init window
Rect rect = {0, 0, 720, 1280};
CreateNewWindow(kDocumentWindowClass, kWindowCloseBoxAttribute | kWindowCollapseBoxAttribute | kWindowFullZoomAttribute | kWindowResizableAttribute | kWindowStandardHandlerAttribute, &rect, &window);
SetWTitle(window, "\pOpenLara");
// init OpenGL context
GLint attribs[] = {
AGL_RGBA,
AGL_DOUBLEBUFFER,
AGL_BUFFER_SIZE, 32,
AGL_DEPTH_SIZE, 24,
AGL_STENCIL_SIZE, 8,
AGL_NONE
};
AGLPixelFormat format = aglChoosePixelFormat(NULL, 0, (GLint*)&attribs);
context = aglCreateContext(format, NULL);
aglDestroyPixelFormat(format);
aglSetDrawable(context, GetWindowPort(window));
aglSetCurrentContext(context);
// get path to game content
CFBundleRef bundle = CFBundleGetMainBundle();
CFURLRef bundleURL = CFBundleCopyBundleURL(bundle);
CFStringRef pathStr = CFURLCopyFileSystemPath(bundleURL, kCFURLPOSIXPathStyle);
contentPath = new char[1024];
CFStringGetFileSystemRepresentation(pathStr, contentPath, 1024);
strcat(contentPath, "/Contents/Resources/");
soundInit();
Game::init();
// show window
const int events[][2] = {
{ kEventClassWindow, kEventWindowClosed },
{ kEventClassWindow, kEventWindowBoundsChanged },
{ kEventClassKeyboard, kEventRawKeyDown },
{ kEventClassKeyboard, kEventRawKeyUp },
{ kEventClassKeyboard, kEventRawKeyModifiersChanged },
{ kEventClassMouse, kEventMouseDown },
{ kEventClassMouse, kEventMouseUp },
{ kEventClassMouse, kEventMouseDragged },
};
InstallEventHandler(GetApplicationEventTarget(), (EventHandlerUPP)eventHandler, sizeof(events) / sizeof(events[0]), (EventTypeSpec*)&events, NULL, NULL);
SelectWindow(window);
ShowWindow(window);
int lastTime = getTime(), fpsTime = lastTime + 1000, fps = 0;
EventRecord event;
while (!isQuit)
if (!GetNextEvent(0xffff, &event)) {
int time = getTime();
if (time <= lastTime)
continue;
float delta = (time - lastTime) * 0.001f;
while (delta > EPS) {
Core::deltaTime = min(delta, 1.0f / 30.0f);
Game::update();
delta -= Core::deltaTime;
}
lastTime = time;
Core::stats.dips = 0;
Core::stats.tris = 0;
Game::render();
aglSwapBuffers(context);
if (fpsTime < getTime()) {
LOG("FPS: %d DIP: %d TRI: %d\n", fps, Core::stats.dips, Core::stats.tris);
fps = 0;
fpsTime = getTime() + 1000;
} else
fps++;
}
Game::free();
delete[] contentPath;
// TODO: sndFree
aglSetCurrentContext(NULL);
ReleaseWindow(window);
return 0;
}
| 8,122 | 2,612 |
/*
Edit by Christina
*/
#include "LogisticRegression.hpp"
namespace husky{
namespace mllib{
/*
train a logistic regression model with even weighted instances.
*/
void LogisticRegression::fit(const Instances& instances){
if(this->mode == MODE::GLOBAL){
global_fit(instances);
}
else if(this->mode == MODE::LOCAL){
local_fit(instances);
}
else{
throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided.");
}
}
/*
train a logistic regression model using instance weight, which is specified as a attribute list of original_instances, name of which is 'instance_weight_name'.
*/
void LogisticRegression::fit(const Instances& instances, std::string instance_weight_name){
if(this->mode == MODE::GLOBAL){
global_fit(instances, instance_weight_name);
}
else if(this->mode == MODE::LOCAL){
local_fit(instances, instance_weight_name);
}
else{
throw std::invalid_argument("MODE " + std::to_string((int)mode) + " dosen't exit! Only 0(GLOBAL) and 1(LOCAL) mode are provided.");
}
}
/*
train model in global mode.
*/
void LogisticRegression::global_fit(const Instances& instances){
const int num_attri = instances.numAttributes;
matrix_double init_mat;
for(int i = 1; i < this->class_num; i++){
init_mat.push_back(vec_double(num_attri + 1, 0.0));
}
husky::lib::Aggregator<matrix_double> para_mat(init_mat,
[](matrix_double& a, const matrix_double& b){ a += b;},
[num_attri, this](matrix_double& m){
m.clear();
for(int i = 1; i < this->class_num; i++){
m.push_back(vec_double(num_attri + 1, 0.0));
}
});
husky::lib::Aggregator<double> global_squared_error(0.0,
[](double& a, const double& b){ a += b;},
[](double& v){ v = 0; }
);
global_squared_error.to_reset_each_iter();
auto& ac = husky::lib::AggregatorFactory::get_channel();
double old_weighted_squared_error = std::numeric_limits<double>::max();
double eta = eta0;
int eta_update_counter = 1;
int trival_improve_iter = 0;
//max_iter
for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta));
}
matrix_double para_update;
for(int i = 1; i < this->class_num; i++){
para_update.push_back(vec_double(num_attri + 1, 0.0));
}
matrix_double para_old = para_mat.get_value();
vec_double class_prob_tmp(this->class_num, 0.0);
list_execute(instances.enumerator(), {}, {&ac},
[&](Instance& instance){
vec_double x_with_const_term = instance.X;
x_with_const_term.push_back(1);
//calculate probability
double sum_tmp = 0;
for(int x = 0; x < class_num - 1; x++){
class_prob_tmp[x] = exp(para_old[x] * x_with_const_term);
sum_tmp += class_prob_tmp[x];
}
sum_tmp += 1;
class_prob_tmp.back() = 1;
class_prob_tmp /= sum_tmp;
//calculate error and udpate with regularization
auto label_tmp = instances.get_class(instance);
class_prob_tmp[label_tmp] -= 1;
global_squared_error.update(class_prob_tmp * class_prob_tmp);
for(int x = 0; x < class_num - 1; x++){
para_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term);
}
});
//to do the division only once.
para_update /= instances.numInstances;
//add regularization
double tmp;
for(int x = 0; x < class_num - 1; x++){
tmp = para_old[x].back();
para_old[x].back() = 0;
para_update[x] -= (eta * alpha * para_old[x]);
para_old[x].back() = tmp;
}
para_mat.update(para_update);
double weighted_squared_error = global_squared_error.get_value() / instances.numInstances;
//output the training infor.
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error));
}
if(old_weighted_squared_error < weighted_squared_error){
eta = eta0/pow(++eta_update_counter, 0.5);
trival_improve_iter = 0;
}
else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){
trival_improve_iter ++;
}
else{
trival_improve_iter = 0;
}
old_weighted_squared_error = weighted_squared_error;
husky::lib::AggregatorFactory::sync();
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value()));
}
}
this->param_matrix = para_mat.get_value();
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Training completed!");
}
return;
}
void LogisticRegression::global_fit(const Instances& instances, std::string instance_weight_name){
const int num_attri = instances.numAttributes;
matrix_double init_mat;
for(int i = 1; i < this->class_num; i++){
init_mat.push_back(vec_double(num_attri + 1, 0.0));
}
husky::lib::Aggregator<matrix_double> para_mat(init_mat,
[](matrix_double& a, const matrix_double& b){ a += b;},
[num_attri, this](matrix_double& m){
m.clear();
for(int i = 1; i < this->class_num; i++){
m.push_back(vec_double(num_attri + 1, 0.0));
}
});
husky::lib::Aggregator<double> global_squared_error(0.0,
[](double& a, const double& b){ a += b;},
[](double& v){ v = 0; }
);
global_squared_error.to_reset_each_iter();
auto& ac = husky::lib::AggregatorFactory::get_channel();
auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name);
double old_weighted_squared_error = std::numeric_limits<double>::max();
double eta = eta0;
int eta_update_counter = 1;
int trival_improve_iter = 0;
//max_iter
for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta));
}
matrix_double para_update;
for(int i = 1; i < this->class_num; i++){
para_update.push_back(vec_double(num_attri + 1, 0.0));
}
matrix_double para_old = para_mat.get_value();
vec_double class_prob_tmp(this->class_num, 0.0);
list_execute(instances.enumerator(), {}, {&ac},
[&](Instance& instance){
vec_double x_with_const_term = instance.X;
x_with_const_term.push_back(1);
//calculate probability
double sum_tmp = 0;
for(int x = 0; x < class_num - 1; x++){
class_prob_tmp[x] = exp(x_with_const_term * para_old[x]);
sum_tmp += class_prob_tmp[x];
}
sum_tmp += 1;
class_prob_tmp.back() = 1;
class_prob_tmp /= sum_tmp;
//calculate error and udpate with regularization
double weight = weight_attrList.get(instance);
auto label_tmp = instances.get_class(instance);
class_prob_tmp[label_tmp] -= 1;
global_squared_error.update(weight * class_prob_tmp * class_prob_tmp);
for(int x = 0; x < class_num - 1; x++){
para_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term);
}
});
double tmp;
for(int x = 0; x < class_num - 1; x++){
tmp = para_old[x].back();
para_old[x].back() = 0;
para_update[x] -= (eta * alpha * para_old[x]);
para_old[x].back() = tmp;
}
para_mat.update(para_update);
double weighted_squared_error = global_squared_error.get_value();
//output the training infor.
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("\tGlobal averaged squared error: " + std::to_string(weighted_squared_error));
}
if(old_weighted_squared_error < weighted_squared_error){
eta = eta0/pow(++eta_update_counter, 0.5);
trival_improve_iter = 0;
}
else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){
trival_improve_iter ++;
}
else{
trival_improve_iter = 0;
}
old_weighted_squared_error = weighted_squared_error;
husky::lib::AggregatorFactory::sync();
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("\tParameters: " + matrix_to_str(para_mat.get_value()));
}
}
this->param_matrix = para_mat.get_value();
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Training completed!");
}
return;
}
/*
train model in local mode.
*/
void LogisticRegression::local_fit(const Instances& instances){
int num_attri = instances.numAttributes;
matrix_double param_update;
for(int i = 1; i < this->class_num; i++){
param_matrix.push_back(vec_double(num_attri + 1, 0.0));
param_update.push_back(vec_double(num_attri + 1, 0.0));
}
double weighted_squared_error = 0;
double old_weighted_squared_error = std::numeric_limits<double>::max();
double eta = eta0;
int eta_update_counter = 1;
int trival_improve_iter = 0;
//count how many instances in local machine
int num_instances_local = 0;
list_execute(instances.enumerator(),{},{},
[&num_instances_local](Instance& instance){
num_instances_local++;
}
);
//max_iter
for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){
/*
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta));
}
*/
//reset variables
weighted_squared_error = 0;
for(int i = 0; i < this->class_num-1; i++){
param_update[i].assign(num_attri + 1, 0.0);
}
vec_double class_prob_tmp(this->class_num, 0.0);
list_execute(instances.enumerator(), {}, {},
[&](Instance& instance){
vec_double x_with_const_term = instance.X;
x_with_const_term.push_back(1);
//calculate probability
double sum_tmp = 0;
for(int x = 0; x < class_num-1; x++ ){
class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]);
sum_tmp += class_prob_tmp[x];
}
sum_tmp += 1;
class_prob_tmp.back() = 1;
class_prob_tmp /= sum_tmp;
//calculate error and update
auto label_tmp = instances.get_class(instance);
class_prob_tmp[label_tmp] -= 1;
weighted_squared_error += (class_prob_tmp * class_prob_tmp);
for(int x = 0; x < class_num - 1; x++){
param_update[x] -= (eta * class_prob_tmp[x] * x_with_const_term);
}
}
);
//update parameters.
param_update /= num_instances_local;
//regularization term
double tmp;
for(int x = 0; x < class_num - 1; x++){
tmp = param_matrix[x].back();
param_matrix[x].back() = 0;
param_update[x] -= (eta * alpha * param_matrix[x]);
param_matrix[x].back() = tmp;
}
param_matrix += param_update;
weighted_squared_error /= num_instances_local;
//output local error.
if(husky::Context::get_global_tid() == 0){
husky::base::log_msg("Iter#" + std::to_string(iter) + "\n"
+ "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n"
+ "Parameters: " + matrix_to_str(param_matrix));
//std::cout<<"Parameters: " + matrix_to_str(param_matrix)<<std::endl;
}
if(old_weighted_squared_error < weighted_squared_error){
eta = eta0/pow(++eta_update_counter, 0.5);
trival_improve_iter = 0;
}
else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){
trival_improve_iter ++;
}
else{
trival_improve_iter = 0;
}
old_weighted_squared_error = weighted_squared_error;
}
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Training completed!");
}
return;
}
void LogisticRegression::local_fit(const Instances& instances, std::string instance_weight_name){
int num_attri = instances.numAttributes;
matrix_double param_update;
for(int i = 1; i < this->class_num; i++){
param_matrix.push_back(vec_double(num_attri + 1, 0.0));
param_update.push_back(vec_double(num_attri + 1, 0.0));
}
auto& weight_attrList = instances.getAttrlist<double>(instance_weight_name);
double weighted_squared_error = 0;
double old_weighted_squared_error = std::numeric_limits<double>::max();
double eta = eta0;
int eta_update_counter = 1;
int trival_improve_iter = 0;
//count how many instances in local machine
int num_instances_local = 0;
list_execute(instances.enumerator(),{},{},
[&num_instances_local](Instance& instance){
num_instances_local++;
}
);
//max_iter
for(int iter = 1; iter <= max_iter && trival_improve_iter < max_trival_improve_iter; iter++){
/*
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Iter#" + std::to_string(iter) + "\teta: " + std::to_string(eta));
}
*/
//reset variables
weighted_squared_error = 0;
for(int i = 0; i < this->class_num-1; i++){
param_update[i].assign(num_attri + 1, 0.0);
}
vec_double class_prob_tmp(this->class_num, 0.0);
list_execute(instances.enumerator(), {}, {},
[&](Instance& instance){
vec_double x_with_const_term = instance.X;
x_with_const_term.push_back(1);
//calculate probability
double sum_tmp = 0;
for(int x = 0; x < class_num-1; x++ ){
class_prob_tmp[x] = exp(x_with_const_term * param_matrix[x]);
sum_tmp += class_prob_tmp[x];
}
sum_tmp += 1;
class_prob_tmp.back() = 1;
class_prob_tmp /= sum_tmp;
//calculate error and update
double weight = weight_attrList.get(instance);
auto label_tmp = instances.get_class(instance);
class_prob_tmp[label_tmp] -= 1;
weighted_squared_error += (weight * class_prob_tmp * class_prob_tmp);
for(int x = 0; x < class_num - 1; x++){
param_update[x] -= (weight * eta * class_prob_tmp[x] * x_with_const_term);
}
}
);
//regularization term
double tmp;
for(int x = 0; x < class_num - 1; x++){
tmp = param_matrix[x].back();
param_matrix[x].back() = 0;
param_update[x] -= (eta * alpha * param_matrix[x]);
param_matrix[x].back() = tmp;
}
param_matrix += param_update;
weighted_squared_error /= num_instances_local;
//output local error.
if(husky::Context::get_global_tid() == 0){
husky::base::log_msg("Iter#" + std::to_string(iter) + "\n"
+ "Local averaged squared error: " + std::to_string(weighted_squared_error) + "\n"
+ "Parameters: " + matrix_to_str(param_matrix));
}
if(old_weighted_squared_error < weighted_squared_error){
eta = eta0/pow(++eta_update_counter, 0.5);
trival_improve_iter = 0;
}
else if (fabs(old_weighted_squared_error - weighted_squared_error) < trival_improve_th ){
trival_improve_iter ++;
}
else{
trival_improve_iter = 0;
}
old_weighted_squared_error = weighted_squared_error;
}
if (husky::Context::get_global_tid() == 0) {
husky::base::log_msg("Training completed!");
}
return;
}
/*
* predict #prediciton contains label and class_proba in it.
*/
AttrList<Instance, Prediction>& LogisticRegression::predict(const Instances& instances,std::string prediction_name){
if(this->mode == MODE::LOCAL){
throw std::invalid_argument("Prediciton is not provided after training in LOCAL mode!");
}
AttrList<Instance, Prediction>& prediction = instances.enumerator().has_attrlist(prediction_name)? instances.getAttrlist<Prediction>(prediction_name) : instances.createAttrlist<Prediction>(prediction_name);
list_execute(instances.enumerator(), [&prediction, this](Instance& instance) {
vec_double feature_vector=instance.X;
feature_vector.push_back(1);
//calculate probability
vec_double class_prob_tmp(class_num, 0.0);
double sum_tmp = 0;
for(int x = 0; x < class_num-1; x++ ){
class_prob_tmp[x] = exp(feature_vector * param_matrix[x]);
sum_tmp += class_prob_tmp[x];
}
sum_tmp += 1;
class_prob_tmp.back() = 1;
class_prob_tmp /= sum_tmp;
//choose label with highest probability
double max_p = 0;
int label;
for(int x = 0; x < class_num; x++){
if(class_prob_tmp[x] > max_p){
max_p = class_prob_tmp[x];
label = x;
}
}
prediction.set(instance, Prediction(label, class_prob_tmp));
});
return prediction;
}
}
}
| 22,796 | 6,425 |
/*
Pattern to Word Bijection
https://binarysearch.com/problems/Pattern-to-Word-Bijection
Given two strings s and p, return whether s follows the pattern in p. That is, return whether each character in p can map to a non-empty word such that it maps to s.
Constraints
n ≤ 100,000 where n is the length of s
Example 1
Input
s = "hello world world world hello"
p = "abbba"
Output
true
Explanation
We can map "a" = "hello" and "b" = "world".
*/
#include "solution.hpp"
using namespace std;
class Solution {
public:
bool solve(string s, string p) {
unordered_map<string, int> m;
istringstream iss(s);
string ss;
int i = 0;
while(iss>>ss){
if(m.count(ss)) {
if(m[ss]!=p[i]) return false;
} else {
for(auto& k: m) {
if(k.second == p[i]) return false;
}
m[ss]=p[i];
}
i++;
}
return true;
}
}; | 993 | 323 |
/*
By: facug91
From: http://coj.uci.cu/contest/cproblem.xhtml?pid=3285&cid=1453
Name: Toby and Strange Function
Date: 05/06/2015
*/
#include <bits/stdc++.h>
#define time alkjdhasjldh3289rhau9dty
#define EPS 1e-9
#define DEBUG(x) cerr << "#" << (#x) << ": " << (x) << endl
const double PI = 2.0*acos(0.0);
#define INF 1000000000
//#define MOD 1000000007ll
//#define MAXN 10000100
using namespace std;
typedef long long ll;
typedef pair<int, int> ii; typedef pair<int, ii> iii;
typedef vector<int> vi; typedef vector<ii> vii; typedef vector<iii> viii;
ll n;
string s;
int main () {
ios_base::sync_with_stdio(0); cin.tie(0);
//cout<<fixed<<setprecision(7); cerr<<fixed<<setprecision(7); //cin.ignore(INT_MAX, ' '); //cout << setfill('0') << setw(5) << 25
int tc, i, j;
cin>>tc;
while (tc--) {
cin>>n>>s;
n %= s.length();
for (i=(int)s.length()-n; i<s.length(); i++) cout<<s[i];
n = (int)s.length()-n;
for (i=0; i<n; i++) cout<<s[i];
cout<<"\n";
}
return 0;
}
| 1,023 | 501 |
/*
* Copyright (c) 2009, Benjamin Peter <BenjaminPeter@arcor.de>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY Benjamin Peter ''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 Benjamin Peter 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 <string>
#include <iostream>
#include <map>
#include <vector>
#include <cstring>
using namespace std;
#include "exceptions.h"
#include "config/Configuration.h"
#include "config/BasicConfiguration.h"
#include "config/AnnoymeConfiguration.h"
// Input
#include "Event.h"
#include "InputEventReader.h"
#include "InputEventReaderFactory.h"
// Sound
#include "Sample.h"
#include "SoundOutput.h"
#include "SoundOutputFactory.h"
#include "SoundLoader.h"
#include "SoundLoaderFactory.h"
// Flow
#include "SoundOutputAdapter.h"
#include "InputEventHandler.h"
#include "HandlerSoundOutput.h"
#include "Dispatcher.h"
#include "Annoyme.h"
Annoyme::Annoyme()
: m_input(0)
, m_soundLoader(0)
, m_soundOutput(0)
, m_soundOutputAdapter(0)
, m_inputEventHandler(0)
, m_dispatcher(0)
{
}
Annoyme::~Annoyme()
{
if (m_dispatcher != 0) delete m_dispatcher;
if (m_inputEventHandler != 0) delete m_inputEventHandler;
if (m_soundOutputAdapter != 0) delete m_soundOutputAdapter;
if (m_soundOutput != 0) delete m_soundOutput;
if (m_soundLoader != 0) delete m_soundLoader;
if (m_input != 0) delete m_input;
}
void Annoyme::init() throw(AnnoymeException)
{
AnnoymeConfiguration::getInstance();
cout << "Creating key input reader.\n";
m_input = InputEventReaderFactory::getInstance()->getInputEventReader(
AnnoymeConfiguration::value("input.reader"));
cout << "Creating sound file loader.\n";
m_soundLoader = SoundLoaderFactory::getInstance()->getSoundLoader(
AnnoymeConfiguration::value("sound.loader"));
cout << "Creating sound output.\n";
m_soundOutput = SoundOutputFactory::getInstance()->getSoundOutput(
AnnoymeConfiguration::value("sound.output"),
AnnoymeConfiguration::value("sound.alsa.device"));
cout << "Loading sound files.\n";
m_soundLoader->loadFiles(AnnoymeConfiguration::value("sample_theme"));
cout << "Opening sound output.\n";
m_soundOutput->open();
cout << "Opening event input.\n";
m_input->open();
m_soundOutputAdapter = new SoundOutputAdapter(m_soundLoader, m_soundOutput);
m_inputEventHandler = new HandlerSoundOutput(m_soundOutputAdapter);
m_dispatcher = new Dispatcher(m_input, m_inputEventHandler);
cout << "Initializing dispatcher.\n";
m_dispatcher->init();
}
void Annoyme::run()
{
cout << "Starting dispatcher.\n";
m_dispatcher->run();
}
void Annoyme::close()
{
if (m_dispatcher != 0) m_dispatcher->close();
if (m_input != 0) m_input->close();
if (m_soundOutput != 0) m_soundOutput->close();
}
| 4,221 | 1,383 |
/*
* String.cpp
*
* Created on: Feb 19, 2015
* Author: mailmindlin
*/
#include "String.h"
#include "../algorithm.h"
#include "../limits.h"
#include "../memory.h"
#include "../Math.h"
#include "../strlen.h"
#include "Double.h"
#include "Integer.h"
#include "Long.h"
String::String(const String& str) :
size(str.length) {
expand();
for (size_t i = 0; i < str.length(); i++)
this->data[i] = str.data[i];
}
String::String(const String& str, size_t pos, size_t len) :
size(len) {
expand();
for (size_t i = 0; i < len; i++)
if ((this->data[i] = str.data[i + pos]) == 0)
break;
}
String::String(const char* s) :
size(strlen(s)) {
expand();
for (size_t i = 0; i < length; i++)
data[i] = s[i];
}
String::String(const char* s, size_t n) :
size(n) {
expand();
for (size_t i = 0; i < n; i++)
data[i] = s[i];
}
String::String(size_t n, char c) :
size(n) {
expand();
for (size_t i = 0; i < length; i++)
data[i] = c;
}
String::String(size_t length) :
size(length) {
expand();
}
String& String::operator =(const String& str) {
if (str == this)
return this;
String * result = new String(str);
delete this;
return result;
}
String& String::operator =(const char* s) {
String * result = new String(s);
delete this;
return result;
}
String& String::operator =(char c) {
String * result = new String(1, c);
delete this;
return result;
}
String& String::operator +(const char* c) {
return new String(c);
}
String& String::operator +(const String& str) {
return concat(str);
}
bool String::isEmpty() const {
return length() == 0;
}
char String::charAt(unsigned int index) {
return data[index];
}
String::~String() {
delete data;
}
String& String::concat(const char* c) {
size_t len = strlen(c);
String* result = new String(length() + len);
for (size_t i = 0; i < length(); i++)
result->data[i] = this->data[i];
for (size_t i = 0; i < len; i++)
result->data[i + length()] = c[i];
return result;
}
String& String::concat(const String& str) {
String* result = new String(length() + str.length());
for (size_t i = 0; i < length(); i++)
result->data[i] = this->data[i];
for (size_t i = 0; i < str.length(); i++)
result->data[i + length()] = str.data[i];
return result;
}
bool String::contains(const char* c) const {
return indexOf(c) != SIZE_T_MAX;
}
bool String::contains(String& str) const {
return indexOf(str) != SIZE_T_MAX;
}
bool String::endsWith(String& suffix) const {
return indexOf(suffix) == length() - suffix.length();
}
bool String::equals(Object o) const {
if (o == this)
return true;
if (!o.instanceof<String>())
return false;
String s = dynamic_cast<String>(o);
if (s.length() != length())
return false;
for (size_t i = 0; i < length(); i++)
if (s.data[i] != data[i])
return false;
return true;
}
bool String::equalsIgnoreCase(String& str) const {
if (str == this)
return true;
if (str.length() != length())
return false;
return str.toLowerCase().equals(toLowerCase());
}
void String::getChars(size_t srcBegin, size_t srcEnd, char* dst, size_t dstBegin) const {
const size_t delta = dstBegin - srcBegin;
for (size_t i = srcBegin; i < srcEnd; i++)
dst[i] = data[i + delta];
}
size_t String::indexOf(char c) const {
return indexOf(c, 0);
}
size_t String::indexOf(char c, size_t start) const {
for (size_t i = 0; i < length(); i++)
if (data[i] == c)
return i;
return SIZE_T_MAX;
}
size_t String::indexOf(String& str) const {
return indexOf(str, 0);
}
size_t String::indexOf(String& str, size_t start) const {
const size_t len = str.length();
for (size_t i = start; i < length() - len; i++) {
bool match = true;
for (size_t j = 0; match && j < len; j++)
match = (data[i + j] == str.data[j]) && match;
if (match)
return i;
}
return SIZE_T_MAX;
}
size_t String::indexOf(const char* c) const {
return indexOf(c, 0);
}
size_t String::indexOf(const char* c, size_t start) const {
const size_t len = strlen(c);
for (size_t i = start; i < length() - len; i++) {
bool match = true;
for (size_t j = 0; match && j < len; j++)
match = (data[i + j] == c[j]) && match;
if (match)
return i;
}
return SIZE_T_MAX;
}
size_t String::lastIndexOf(char c) {
return lastIndexOf(c, length());
}
size_t String::lastIndexOf(char c, size_t fromIndex) {
for (size_t i = fromIndex - 1; i > 0; i--)
if (data[i] == c)
return i;
return SIZE_T_MAX;
}
size_t String::lastIndexOf(String& str) {
return this->lastIndexOf(str, length());
}
size_t String::lastIndexOf(String& str, size_t fromIndex) {
for (size_t i = Math::min(fromIndex, length() - str.length()); i > 0; i--) {
bool match = true;
for (size_t j = 0; match && j < str.length(); j++)
match = (data[i + j] == str.data[j]) && match;
if (match)
return i;
}
return SIZE_T_MAX;
}
size_t String::length() const {
return size;
}
bool String::regionMatches(bool ignoreCase, size_t toffset, String& other, size_t oofset, size_t len) {
if (ignoreCase)
return substring(toffset, toffset + len).equalsIgnoreCase(other.substring(oofset, oofset + len));
else
return substring(toffset, toffset + len).equals(other.substring(oofset, oofset + len));
}
String& String::replace(char oldChar, char newChar) {
String * result = new String(length());
for (size_t i = 0; i < length(); i++)
result->data[i] = (data[i] == oldChar ? newChar : data[i]);
return result;
}
String& String::replace(const char* target, const char* replacement) {
String * result = this;
const size_t targlen = strlen(target);
const size_t repllen = strlen(replacement);
int index;
while ((index = result->indexOf(target)) > -1) {
String*tmp = result;
result = tmp->substring(0, index) + target + tmp->substring(index + repllen, tmp->length());
delete tmp;
}
if (result == this)
result = new String(this);
return result;
}
String& String::replace(String& target, String& replacement) {
String * result = this;
const size_t targlen = target.length();
const size_t repllen = replacement.length();
int index;
while ((index = result->indexOf(target)) > -1) {
String*tmp = result;
result = tmp->substring(0, index) + target + tmp->substring(index + repllen, tmp->length());
delete tmp;
}
if (result == this)
result = new String(this);
return result;
}
bool String::startsWith(String& prefix) {
return indexOf(prefix) == 0;
}
bool String::startsWith(String& prefix, size_t toffset) {
return this->regionMatches(false, toffset, prefix, 0, prefix.length());
}
char* String::subSequence(size_t beginIndex, size_t endIndex) {
return substring(beginIndex, endIndex).toCharArray();
}
String& String::substring(size_t beginIndex) {
return substring(beginIndex, length());
}
String& String::substring(size_t beginIndex, size_t endIndex) {
String* result = new String(endIndex - beginIndex);
for (size_t i = beginIndex; i < endIndex; i++)
result->data[i - beginIndex] = data[i];
return result;
}
char* String::toCharArray() const {
char* result = new char[length()];
Array::copy(this->data, result, 0, 0, length());
return result;
}
String& String::toLowerCase() const {
String* result = new String(length());
for (size_t i = 0; i < length(); i++)
result->data[i] = std::toLower(data[i]);
return result;
}
String& String::toString() const {
return &*this;
}
String& String::toUpperCase() const {
String* result = new String(length());
for (size_t i = 0; i < length(); i++)
result->data[i] = std::toUpper(data[i]);
return result;
}
String& String::trim() const {
size_t b = 0, e = 0;
for (b = 0; b < length() && (data[b] == ' ' || data[b] == '\t' || data[b] == '\n'); b++) {
}
for (e = length() - 1; e > b && (data[e] == ' ' || data[e] == '\t' || data[e] == '\n'); e--) {
}
String* result = new String(e - b);
Array::copy(data, result->data, b, 0, e - b);
return result;
}
String& String::valueOf(bool b) {
return new String(b ? "true" : "false");
}
String& String::valueOf(char c) {
return new String(c, 1);
}
String& String::valueOf(const char* c) {
return new String(c);
}
String& String::valueOf(char* data, size_t offset, size_t count) {
return new String(data, offset, count);
}
String& String::valueOf(double d, size_t radix) {
return Double::stringFor(d, radix);
}
String& String::valueOf(double d) {
return Double::stringFor(d);
}
String& String::valueOf(float f) {
return &nullptr; //TODO finish
}
String& String::valueOf(int i, size_t radix) {
return Integer::stringFor(i, radix);
}
String& String::valueOf(long l, size_t radix) {
return Long::stringFor(l, radix);
}
String& String::valueOfPtr(const void* ptr) {
return valueOf((int) ptr, 16);
}
String& String::valueOf(Object& obj) {
return obj.toString();
}
void String::expand() {
data = new char[size];
}
| 8,738 | 3,411 |
//
// Created by lishunan on 4/19/16.
//
#ifndef HOSTSVC_RPCCHANNEL_H
#define HOSTSVC_RPCCHANNEL_H
#include "HostSvcCommon.hpp"
#include <unordered_map>
using namespace google::protobuf;
namespace GkcHostSvc {
using messageHandler = function<void(RPCResponse)>;
class Connection : public protobuf::RpcChannel {
private:
std::condition_variable cv;
std::mutex m;
std::atomic<bool> connected{ false };
std::unordered_map<string, messageHandler> handlerMap;
RPCResponse response1;
int _clientID = -1;
WebsocketClient _WSclient;
shared_ptr < WebsocketConnecton> con;
shared_ptr<thread> pthread;
char pSend[1000];
public:
static shared_ptr<Connection> create(const string &server) {
return make_shared<Connection>(server);
}
void registerHandler(const string& s,messageHandler h)
{
handlerMap.insert({ s,h });
}
Connection(const string &server) {
_WSclient.init_asio();
_WSclient.start_perpetual();
_WSclient.set_access_channels(websocketpp::log::alevel::none);
_WSclient.set_open_handler([this](websocketpp::connection_hdl hdl) {
this->connected = true;
cout << "connected" << endl;
});
_WSclient.set_message_handler([this](websocketpp::connection_hdl hdl,WebsocketClient::message_ptr msg)
{
auto _respondString = msg->get_payload();
//cout << msg->get_opcode() << "opcode" << "received:" << _respondString.size() << endl;
RPCResponse r;
r.ParseFromString(_respondString);
if(r.ispushmessage())
{
cout << "received:"<<_respondString.size() << endl;
auto tt = handlerMap.at(r.pushtype());
tt(r);
}
else
{
response1 = r;
_clientID = r.clientid();
print(_clientID);
println(" receive response");
cv.notify_one();
}
});
#ifdef GKC_SSL
_WSclient.set_tls_init_handler([this](websocketpp::connection_hdl hdl)->shared_ptr<asio::ssl::context>
{
auto ctx = make_shared<asio::ssl::context>(asio::ssl::context::sslv23_client);
try {
ctx->set_options(asio::ssl::context::default_workarounds |
asio::ssl::context::no_sslv2 |
asio::ssl::context::no_sslv3 |
asio::ssl::context::single_dh_use);
ctx->set_verify_mode(0);
}
catch (std::exception& e) {
std::cout << e.what() << std::endl;
}
return ctx;
});
string protocal = "wss://";
#else
string protocal = "ws://";
#endif
pthread=make_shared<thread>([this]()
{
cout << "running" << endl;
_WSclient.run();
});
error_code ec;
con = _WSclient.get_connection(protocal+server,ec);
if(ec)
{
cout << "connection fail "+ec.message()<< endl;
exit(1);
}
if (_WSclient.connect(con) != nullptr) {
}
else
{
cout << "error connection" << endl;
}
}
Connection(const Connection &) = delete;
Connection(Connection &&) = default;
Connection &operator=(const Connection &) = delete;
Connection &operator=(Connection &&) = default;
int getClientID() {
return _clientID;
}
~Connection()
{
}
void close()
{
con->close(websocketpp::close::status::normal,"quit");
_WSclient.stop_perpetual();
pthread->join();
pthread.reset();
}
void CallMethod(const MethodDescriptor *method, RpcController *controller, const Message *request,
Message *response, Closure *done) override{
std::unique_lock<std::mutex> lk(m);
auto p = dynamic_cast<const RPCRequest *> (request);
while (!connected)
;
//cout << p->DebugString() << endl << p->ByteSize() << endl;
p->SerializeToArray(pSend, sizeof pSend);
auto messageSize = static_cast<size_t > (p->ByteSize());
auto ec = con->send(pSend, messageSize);
if (ec) {
cerr << "?" << ec.message() << endl;
return;
}
cv.wait(lk);
if(controller->Failed())
{
cerr << controller->ErrorText();
}
auto pLocalResponse = static_cast<RPCResponse *>(response);
*pLocalResponse = response1;
if (done != nullptr)
done->Run();
lk.unlock();
}
};
using pConnection=shared_ptr<Connection>;
}
#endif //HOSTSVC_RPCCHANNEL_H
| 4,254 | 1,720 |
// Copyright (c) 2005-2014 Code Synthesis Tools CC
//
// This program was generated by CodeSynthesis XSD, an XML Schema to
// C++ data binding compiler.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
// In addition, as a special exception, Code Synthesis Tools CC gives
// permission to link this program with the Xerces-C++ library (or with
// modified versions of Xerces-C++ that use the same license as Xerces-C++),
// and distribute linked combinations including the two. You must obey
// the GNU General Public License version 2 in all respects for all of
// the code used other than Xerces-C++. If you modify this copy of the
// program, you may extend this exception to your version of the program,
// but you are not obligated to do so. If you do not wish to do so, delete
// this exception statement from your version.
//
// Furthermore, Code Synthesis Tools CC makes a special exception for
// the Free/Libre and Open Source Software (FLOSS) which is described
// in the accompanying FLOSSE file.
//
// Begin prologue.
//
//
// End prologue.
#include <xsd/cxx/pre.hxx>
#include "SimController_ZoneControlTemperature_ThermostatThermalComfort.hxx"
#include "simcntrl_thermalcomfortcontrol_1_4_objecttype.hxx"
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimController_ZoneControlTemperature_ThermostatThermalComfort
//
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_AveragingMethod () const
{
return this->SimCntrl_AveragingMethod_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_AveragingMethod_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_AveragingMethod ()
{
return this->SimCntrl_AveragingMethod_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_type& x)
{
this->SimCntrl_AveragingMethod_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_AveragingMethod (const SimCntrl_AveragingMethod_optional& x)
{
this->SimCntrl_AveragingMethod_ = x;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_AveragingMethod (::std::auto_ptr< SimCntrl_AveragingMethod_type > x)
{
this->SimCntrl_AveragingMethod_.set (x);
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_SpecificPeopleName () const
{
return this->SimCntrl_SpecificPeopleName_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_SpecificPeopleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_SpecificPeopleName ()
{
return this->SimCntrl_SpecificPeopleName_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_type& x)
{
this->SimCntrl_SpecificPeopleName_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_SpecificPeopleName (const SimCntrl_SpecificPeopleName_optional& x)
{
this->SimCntrl_SpecificPeopleName_ = x;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_SpecificPeopleName (::std::auto_ptr< SimCntrl_SpecificPeopleName_type > x)
{
this->SimCntrl_SpecificPeopleName_.set (x);
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MinDry_BulbTempSetpoint () const
{
return this->SimCntrl_MinDry_BulbTempSetpoint_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MinDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MinDry_BulbTempSetpoint ()
{
return this->SimCntrl_MinDry_BulbTempSetpoint_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_type& x)
{
this->SimCntrl_MinDry_BulbTempSetpoint_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MinDry_BulbTempSetpoint (const SimCntrl_MinDry_BulbTempSetpoint_optional& x)
{
this->SimCntrl_MinDry_BulbTempSetpoint_ = x;
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MaxDry_BulbTempSetpoint () const
{
return this->SimCntrl_MaxDry_BulbTempSetpoint_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_MaxDry_BulbTempSetpoint_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MaxDry_BulbTempSetpoint ()
{
return this->SimCntrl_MaxDry_BulbTempSetpoint_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_type& x)
{
this->SimCntrl_MaxDry_BulbTempSetpoint_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_MaxDry_BulbTempSetpoint (const SimCntrl_MaxDry_BulbTempSetpoint_optional& x)
{
this->SimCntrl_MaxDry_BulbTempSetpoint_ = x;
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControlTypeScheduleName () const
{
return this->SimCntrl_ThermalComfortControlTypeScheduleName_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControlTypeScheduleName_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControlTypeScheduleName ()
{
return this->SimCntrl_ThermalComfortControlTypeScheduleName_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_type& x)
{
this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControlTypeScheduleName (const SimCntrl_ThermalComfortControlTypeScheduleName_optional& x)
{
this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControlTypeScheduleName (::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > x)
{
this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (x);
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_ObjectType () const
{
return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_ObjectType ()
{
return this->SimCntrl_ThermalComfortControl_1_4_ObjectType_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_type& x)
{
this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_ObjectType (const SimCntrl_ThermalComfortControl_1_4_ObjectType_optional& x)
{
this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_ObjectType (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > x)
{
this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (x);
}
const SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_Name () const
{
return this->SimCntrl_ThermalComfortControl_1_4_Name_;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::SimCntrl_ThermalComfortControl_1_4_Name_optional& SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_Name ()
{
return this->SimCntrl_ThermalComfortControl_1_4_Name_;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_type& x)
{
this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x);
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_Name (const SimCntrl_ThermalComfortControl_1_4_Name_optional& x)
{
this->SimCntrl_ThermalComfortControl_1_4_Name_ = x;
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimCntrl_ThermalComfortControl_1_4_Name (::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > x)
{
this->SimCntrl_ThermalComfortControl_1_4_Name_.set (x);
}
}
}
}
#include <xsd/cxx/xml/dom/parsing-source.hxx>
#include <xsd/cxx/tree/type-factory-map.hxx>
namespace _xsd
{
static
const ::xsd::cxx::tree::type_factory_plate< 0, char >
type_factory_plate_init;
}
namespace schema
{
namespace simxml
{
namespace MepModel
{
// SimController_ZoneControlTemperature_ThermostatThermalComfort
//
SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimController_ZoneControlTemperature_ThermostatThermalComfort ()
: ::schema::simxml::MepModel::SimController_ZoneControlTemperature (),
SimCntrl_AveragingMethod_ (this),
SimCntrl_SpecificPeopleName_ (this),
SimCntrl_MinDry_BulbTempSetpoint_ (this),
SimCntrl_MaxDry_BulbTempSetpoint_ (this),
SimCntrl_ThermalComfortControlTypeScheduleName_ (this),
SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this),
SimCntrl_ThermalComfortControl_1_4_Name_ (this)
{
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimController_ZoneControlTemperature_ThermostatThermalComfort (const RefId_type& RefId)
: ::schema::simxml::MepModel::SimController_ZoneControlTemperature (RefId),
SimCntrl_AveragingMethod_ (this),
SimCntrl_SpecificPeopleName_ (this),
SimCntrl_MinDry_BulbTempSetpoint_ (this),
SimCntrl_MaxDry_BulbTempSetpoint_ (this),
SimCntrl_ThermalComfortControlTypeScheduleName_ (this),
SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this),
SimCntrl_ThermalComfortControl_1_4_Name_ (this)
{
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimController_ZoneControlTemperature_ThermostatThermalComfort (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimController_ZoneControlTemperature (x, f, c),
SimCntrl_AveragingMethod_ (x.SimCntrl_AveragingMethod_, f, this),
SimCntrl_SpecificPeopleName_ (x.SimCntrl_SpecificPeopleName_, f, this),
SimCntrl_MinDry_BulbTempSetpoint_ (x.SimCntrl_MinDry_BulbTempSetpoint_, f, this),
SimCntrl_MaxDry_BulbTempSetpoint_ (x.SimCntrl_MaxDry_BulbTempSetpoint_, f, this),
SimCntrl_ThermalComfortControlTypeScheduleName_ (x.SimCntrl_ThermalComfortControlTypeScheduleName_, f, this),
SimCntrl_ThermalComfortControl_1_4_ObjectType_ (x.SimCntrl_ThermalComfortControl_1_4_ObjectType_, f, this),
SimCntrl_ThermalComfortControl_1_4_Name_ (x.SimCntrl_ThermalComfortControl_1_4_Name_, f, this)
{
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::
SimController_ZoneControlTemperature_ThermostatThermalComfort (const ::xercesc::DOMElement& e,
::xml_schema::flags f,
::xml_schema::container* c)
: ::schema::simxml::MepModel::SimController_ZoneControlTemperature (e, f | ::xml_schema::flags::base, c),
SimCntrl_AveragingMethod_ (this),
SimCntrl_SpecificPeopleName_ (this),
SimCntrl_MinDry_BulbTempSetpoint_ (this),
SimCntrl_MaxDry_BulbTempSetpoint_ (this),
SimCntrl_ThermalComfortControlTypeScheduleName_ (this),
SimCntrl_ThermalComfortControl_1_4_ObjectType_ (this),
SimCntrl_ThermalComfortControl_1_4_Name_ (this)
{
if ((f & ::xml_schema::flags::base) == 0)
{
::xsd::cxx::xml::dom::parser< char > p (e, true, false, true);
this->parse (p, f);
}
}
void SimController_ZoneControlTemperature_ThermostatThermalComfort::
parse (::xsd::cxx::xml::dom::parser< char >& p,
::xml_schema::flags f)
{
this->::schema::simxml::MepModel::SimController_ZoneControlTemperature::parse (p, f);
for (; p.more_content (); p.next_content (false))
{
const ::xercesc::DOMElement& i (p.cur_element ());
const ::xsd::cxx::xml::qualified_name< char > n (
::xsd::cxx::xml::dom::name< char > (i));
// SimCntrl_AveragingMethod
//
if (n.name () == "SimCntrl_AveragingMethod" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimCntrl_AveragingMethod_type > r (
SimCntrl_AveragingMethod_traits::create (i, f, this));
if (!this->SimCntrl_AveragingMethod_)
{
this->SimCntrl_AveragingMethod_.set (r);
continue;
}
}
// SimCntrl_SpecificPeopleName
//
if (n.name () == "SimCntrl_SpecificPeopleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimCntrl_SpecificPeopleName_type > r (
SimCntrl_SpecificPeopleName_traits::create (i, f, this));
if (!this->SimCntrl_SpecificPeopleName_)
{
this->SimCntrl_SpecificPeopleName_.set (r);
continue;
}
}
// SimCntrl_MinDry_BulbTempSetpoint
//
if (n.name () == "SimCntrl_MinDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimCntrl_MinDry_BulbTempSetpoint_)
{
this->SimCntrl_MinDry_BulbTempSetpoint_.set (SimCntrl_MinDry_BulbTempSetpoint_traits::create (i, f, this));
continue;
}
}
// SimCntrl_MaxDry_BulbTempSetpoint
//
if (n.name () == "SimCntrl_MaxDry_BulbTempSetpoint" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
if (!this->SimCntrl_MaxDry_BulbTempSetpoint_)
{
this->SimCntrl_MaxDry_BulbTempSetpoint_.set (SimCntrl_MaxDry_BulbTempSetpoint_traits::create (i, f, this));
continue;
}
}
// SimCntrl_ThermalComfortControlTypeScheduleName
//
if (n.name () == "SimCntrl_ThermalComfortControlTypeScheduleName" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimCntrl_ThermalComfortControlTypeScheduleName_type > r (
SimCntrl_ThermalComfortControlTypeScheduleName_traits::create (i, f, this));
if (!this->SimCntrl_ThermalComfortControlTypeScheduleName_)
{
this->SimCntrl_ThermalComfortControlTypeScheduleName_.set (r);
continue;
}
}
// SimCntrl_ThermalComfortControl_1_4_ObjectType
//
if (n.name () == "SimCntrl_ThermalComfortControl_1_4_ObjectType" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_ObjectType_type > r (
SimCntrl_ThermalComfortControl_1_4_ObjectType_traits::create (i, f, this));
if (!this->SimCntrl_ThermalComfortControl_1_4_ObjectType_)
{
this->SimCntrl_ThermalComfortControl_1_4_ObjectType_.set (r);
continue;
}
}
// SimCntrl_ThermalComfortControl_1_4_Name
//
if (n.name () == "SimCntrl_ThermalComfortControl_1_4_Name" && n.namespace_ () == "http://d-alchemy.com/schema/simxml/MepModel")
{
::std::auto_ptr< SimCntrl_ThermalComfortControl_1_4_Name_type > r (
SimCntrl_ThermalComfortControl_1_4_Name_traits::create (i, f, this));
if (!this->SimCntrl_ThermalComfortControl_1_4_Name_)
{
this->SimCntrl_ThermalComfortControl_1_4_Name_.set (r);
continue;
}
}
break;
}
}
SimController_ZoneControlTemperature_ThermostatThermalComfort* SimController_ZoneControlTemperature_ThermostatThermalComfort::
_clone (::xml_schema::flags f,
::xml_schema::container* c) const
{
return new class SimController_ZoneControlTemperature_ThermostatThermalComfort (*this, f, c);
}
SimController_ZoneControlTemperature_ThermostatThermalComfort& SimController_ZoneControlTemperature_ThermostatThermalComfort::
operator= (const SimController_ZoneControlTemperature_ThermostatThermalComfort& x)
{
if (this != &x)
{
static_cast< ::schema::simxml::MepModel::SimController_ZoneControlTemperature& > (*this) = x;
this->SimCntrl_AveragingMethod_ = x.SimCntrl_AveragingMethod_;
this->SimCntrl_SpecificPeopleName_ = x.SimCntrl_SpecificPeopleName_;
this->SimCntrl_MinDry_BulbTempSetpoint_ = x.SimCntrl_MinDry_BulbTempSetpoint_;
this->SimCntrl_MaxDry_BulbTempSetpoint_ = x.SimCntrl_MaxDry_BulbTempSetpoint_;
this->SimCntrl_ThermalComfortControlTypeScheduleName_ = x.SimCntrl_ThermalComfortControlTypeScheduleName_;
this->SimCntrl_ThermalComfortControl_1_4_ObjectType_ = x.SimCntrl_ThermalComfortControl_1_4_ObjectType_;
this->SimCntrl_ThermalComfortControl_1_4_Name_ = x.SimCntrl_ThermalComfortControl_1_4_Name_;
}
return *this;
}
SimController_ZoneControlTemperature_ThermostatThermalComfort::
~SimController_ZoneControlTemperature_ThermostatThermalComfort ()
{
}
}
}
}
#include <istream>
#include <xsd/cxx/xml/sax/std-input-source.hxx>
#include <xsd/cxx/tree/error-handler.hxx>
namespace schema
{
namespace simxml
{
namespace MepModel
{
}
}
}
#include <xsd/cxx/post.hxx>
// Begin epilogue.
//
//
// End epilogue.
| 20,939 | 7,159 |
class Solution
{
public:
int l(struct node* h){
int c;
while(h){
h=h->next;
++c;
}
return c;
}
struct node *reverse (struct node *head, int k)
{
if(l(head)<k)
return head;
struct node *prev=0;
struct node *next=0;
struct node *curr=head;
for(int i=0;i<k;i++){
next=curr->next;
curr->next=prev;
prev=curr;
curr=next;
}
head->next=reverse(curr,k);
return prev;
}
};
| 565 | 185 |
#include "querier/BaseChunkSeriesSet.hpp"
#include "base/Logging.hpp"
#include "index/PostingSet.hpp"
#include <unordered_set>
namespace tsdb {
namespace querier {
// BaseChunkSeriesSet loads the label set and chunk references for a postings
// list from an index. It filters out series that have labels set that should be
// unset
//
// The chunk pointer in ChunkMeta is not set
// NOTE(Alec), BaseChunkSeriesSet fine-grained filters the chunks using
// tombstone.
BaseChunkSeriesSet::BaseChunkSeriesSet(
const std::shared_ptr<block::IndexReaderInterface>& ir,
const std::shared_ptr<tombstone::TombstoneReaderInterface>& tr,
const std::set<tagtree::TSID>& list)
: ir(ir), tr(tr), cm(new ChunkSeriesMeta()), err_(false)
{
p = std::make_unique<index::PostingSet>(list);
}
// next() always called before at().
const std::shared_ptr<ChunkSeriesMeta>& BaseChunkSeriesSet::at() const
{
return cm;
}
bool BaseChunkSeriesSet::next() const
{
if (err_) return false;
while (p->next()) {
auto tsid = p->at();
cm->clear();
cm->tsid = tsid;
// Get labels and deque of ChunkMeta of the corresponding series.
if (!ir->series(tsid, cm->chunks)) {
// TODO, ErrNotFound
// err_ = true;
// return false;
continue;
}
// Get Intervals from MemTombstones
try {
// LOG_INFO << ref;
cm->intervals = tr->get(tsid);
} catch (const std::out_of_range& e) {
}
if (!(cm->intervals).empty()) {
std::vector<std::shared_ptr<chunk::ChunkMeta>>::iterator it =
cm->chunks.begin();
while (it != cm->chunks.end()) {
if (tombstone::is_subrange((*it)->min_time, (*it)->max_time,
cm->intervals))
it = cm->chunks.erase(it);
else
++it;
}
}
return true;
}
return false;
}
bool BaseChunkSeriesSet::error() const { return err_; }
} // namespace querier
} // namespace tsdb
| 2,122 | 648 |
// Copyright 2019 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 "absl/base/internal/scoped_set_env.h"
#ifdef _WIN32
#include <windows.h>
#endif
#include <cstdlib>
#include "absl/base/internal/raw_logging.h"
namespace absl {
inline namespace lts_2019_08_08 {
namespace base_internal {
namespace {
#ifdef _WIN32
const int kMaxEnvVarValueSize = 1024;
#endif
void SetEnvVar(const char* name, const char* value) {
#ifdef _WIN32
SetEnvironmentVariableA(name, value);
#else
if (value == nullptr) {
::unsetenv(name);
} else {
::setenv(name, value, 1);
}
#endif
}
} // namespace
ScopedSetEnv::ScopedSetEnv(const char* var_name, const char* new_value)
: var_name_(var_name), was_unset_(false) {
#ifdef _WIN32
char buf[kMaxEnvVarValueSize];
auto get_res = GetEnvironmentVariableA(var_name_.c_str(), buf, sizeof(buf));
ABSL_INTERNAL_CHECK(get_res < sizeof(buf), "value exceeds buffer size");
if (get_res == 0) {
was_unset_ = (GetLastError() == ERROR_ENVVAR_NOT_FOUND);
} else {
old_value_.assign(buf, get_res);
}
SetEnvironmentVariableA(var_name_.c_str(), new_value);
#else
const char* val = ::getenv(var_name_.c_str());
if (val == nullptr) {
was_unset_ = true;
} else {
old_value_ = val;
}
#endif
SetEnvVar(var_name_.c_str(), new_value);
}
ScopedSetEnv::~ScopedSetEnv() {
SetEnvVar(var_name_.c_str(), was_unset_ ? nullptr : old_value_.c_str());
}
} // namespace base_internal
} // inline namespace lts_2019_08_08
} // namespace absl
| 2,046 | 755 |
// Copyright (c) 2012-2017 VideoStitch SAS
// Copyright (c) 2018 stitchEm
#pragma once
#include "liveaudioprocessfactory.hpp"
class LiveAudioProcessorDelay : public LiveAudioProcessFactory {
public:
explicit LiveAudioProcessorDelay(const VideoStitch::Ptv::Value* config);
~LiveAudioProcessorDelay() = default;
QPixmap getIcon() const override;
QString getDescription() const override;
int getDelay() const;
void setDelay(const int value);
VideoStitch::Ptv::Value* serialize() const override;
AudioProcessorConfigurationWidget* createConfigurationWidget(QWidget* parent) override;
void serializeParameters(VideoStitch::Ptv::Value* value) override;
private:
int delay = 0;
};
| 703 | 214 |
// All content Copyright (C) 2018 Genomics plc
#ifndef VCF_FILTERDESC_HPP
#define VCF_FILTERDESC_HPP
#include "common.hpp"
#include <iostream>
namespace wecall
{
namespace vcf
{
struct FilterDesc
{
/// Basic constructor from constituent data
///
/// @param id Filter ID.
/// @param description Filter description.
FilterDesc( const std::string & id, const std::string & description );
/// Writes the filter to the output stream in the form of a VCF FILTER header line.
///
/// @param out Output stream
/// @param filterDesc Filter to be output
/// @return Output stream
friend std::ostream & operator<<( std::ostream & out, const FilterDesc & filterDesc );
friend bool operator<( const FilterDesc & lhs, const FilterDesc & rhs );
std::string id;
std::string description;
};
}
}
#endif
| 915 | 259 |
#include "shellprv.h"
#include "ids.h"
#include "ftadv.h"
#include "ftcmmn.h"
#include "ftaction.h"
#include "ftassoc.h"
const static DWORD cs_rgdwHelpIDsArray[] =
{ // Context Help IDs
IDC_FT_CMD_ACTION, IDH_FCAB_FT_CMD_ACTION,
IDC_FT_CMD_EXETEXT, IDH_FCAB_FT_CMD_EXE,
IDC_FT_CMD_EXE, IDH_FCAB_FT_CMD_EXE,
IDC_FT_CMD_BROWSE, IDH_FCAB_FT_CMD_BROWSE,
IDC_FT_CMD_DDEGROUP, IDH_FCAB_FT_CMD_USEDDE,
IDC_FT_CMD_USEDDE, IDH_FCAB_FT_CMD_USEDDE,
IDC_FT_CMD_DDEMSG, IDH_FCAB_FT_CMD_DDEMSG,
IDC_FT_CMD_DDEAPP, IDH_FCAB_FT_CMD_DDEAPP,
IDC_FT_CMD_DDEAPPNOT, IDH_FCAB_FT_CMD_DDEAPPNOT,
IDC_FT_CMD_DDETOPIC, IDH_FCAB_FT_CMD_DDETOPIC,
0, 0
};
CFTActionDlg::CFTActionDlg(PROGIDACTION* pProgIDAction, LPTSTR pszProgIDDescr,
BOOL fEdit) :
CFTDlg((ULONG_PTR)cs_rgdwHelpIDsArray),
_pProgIDAction(pProgIDAction), _pszProgIDDescr(pszProgIDDescr),
_fEdit(fEdit)
{
}
CFTActionDlg::~CFTActionDlg()
{
}
///////////////////////////////////////////////////////////////////////////////
// Logic specific to our problem
LRESULT CFTActionDlg::OnInitDialog(WPARAM wParam, LPARAM lParam)
{
DECLAREWAITCURSOR;
SetWaitCursor();
if (_fEdit || _fShowAgain)
{
TCHAR szTitle[50 + MAX_PROGIDDESCR + 5];
TCHAR szTitleTemplate[50];
_fShowAgain = FALSE;
if (LoadString(g_hinst, IDS_FT_EDITTITLE, szTitleTemplate, ARRAYSIZE(szTitleTemplate)))
{
StringCchPrintf(szTitle, ARRAYSIZE(szTitle), szTitleTemplate, _pszProgIDDescr);
SetWindowText(_hwnd, szTitle);
}
SetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction);
SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine);
SetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg);
SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication);
SetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning);
SetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic);
CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, _pProgIDAction->fUseDDE);
_ResizeDlgForDDE(_pProgIDAction->fUseDDE);
}
else
{
CheckDlgButton(_hwnd, IDC_FT_CMD_USEDDE, FALSE);
_ResizeDlgForDDE(FALSE);
}
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_ACTION), MAX_ACTION - 1);
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_EXE), MAX_ACTIONCMDLINE - 1);
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), MAX_ACTIONDDEMSG - 1);
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), MAX_ACTIONAPPL - 1);
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), MAX_ACTIONDDEAPPNOTRUN - 1);
Edit_LimitText(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), MAX_ACTIONTOPIC - 1);
ResetWaitCursor();
// Return TRUE so that system set focus
return TRUE;
}
BOOL CFTActionDlg::_Validate()
{
BOOL bRet = TRUE;
// Check the Action
TCHAR szAction[MAX_ACTION];
if (!GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, szAction, ARRAYSIZE(szAction)) ||
!*szAction)
{
ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_NOACTION),
MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP);
PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0,
(LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_ACTION));
bRet = FALSE;
}
if (bRet)
{
TCHAR szPath[MAX_PATH];
LPTSTR pszFileName = NULL;
// Check for valid exe
GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath, ARRAYSIZE(szPath));
PathRemoveArgs(szPath);
PathUnquoteSpaces(szPath);
pszFileName = PathFindFileName(szPath);
if(!(*szPath) ||
!(PathIsExe(szPath)) ||
((!(PathFileExists(szPath))) && (!(PathFindOnPath(pszFileName, NULL)))))
{
// Tell user that this exe is invalid
ShellMessageBox(g_hinst, _hwnd, MAKEINTRESOURCE(IDS_FT_MB_EXETEXT),
MAKEINTRESOURCE(IDS_FT), MB_OK | MB_ICONSTOP);
PostMessage(_hwnd, WM_CTRL_SETFOCUS, (WPARAM)0,
(LPARAM)GetDlgItem(_hwnd, IDC_FT_CMD_EXE));
bRet = FALSE;
}
}
return bRet;
}
void CFTActionDlg::SetShowAgain()
{
_fShowAgain = TRUE;
}
BOOL _IsThereAnyPercentArgument(LPTSTR pszCommand)
{
BOOL fRet = FALSE;
LPTSTR pszArgs = PathGetArgs(pszCommand);
if (pszArgs && *pszArgs)
{
if (StrStr(pszArgs, TEXT("%")))
{
fRet = TRUE;
}
}
return fRet;
}
LRESULT CFTActionDlg::OnOK(WORD wNotif)
{
if (_Validate())
{
GetDlgItemText(_hwnd, IDC_FT_CMD_ACTION, _pProgIDAction->szAction, MAX_ACTION);
// Is this a new action?
if (!_fEdit)
{
// Yes, initialize the old action field
StringCchCopy(_pProgIDAction->szOldAction, ARRAYSIZE(_pProgIDAction->szOldAction), _pProgIDAction->szAction);
// Build the ActionReg
StringCchCopy(_pProgIDAction->szActionReg, ARRAYSIZE(_pProgIDAction->szActionReg), _pProgIDAction->szAction);
// Replace spaces with underscores
LPTSTR psz = _pProgIDAction->szActionReg;
while (*psz)
{
if (TEXT(' ') == *psz)
{
*psz = TEXT('_');
}
psz = CharNext(psz);
}
StringCchCopy(_pProgIDAction->szOldActionReg, ARRAYSIZE(_pProgIDAction->szOldActionReg),
_pProgIDAction->szActionReg);
}
GetDlgItemText(_hwnd, IDC_FT_CMD_EXE, _pProgIDAction->szCmdLine, MAX_ACTIONCMDLINE);
GetDlgItemText(_hwnd, IDC_FT_CMD_DDEMSG, _pProgIDAction->szDDEMsg, MAX_ACTIONDDEMSG);
GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPP, _pProgIDAction->szDDEApplication, MAX_ACTIONAPPL);
GetDlgItemText(_hwnd, IDC_FT_CMD_DDEAPPNOT, _pProgIDAction->szDDEAppNotRunning, MAX_ACTIONDDEAPPNOTRUN);
GetDlgItemText(_hwnd, IDC_FT_CMD_DDETOPIC, _pProgIDAction->szDDETopic, MAX_ACTIONTOPIC);
_pProgIDAction->fUseDDE = IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE);
// Append %1 to action field, if required
if (!_IsThereAnyPercentArgument(_pProgIDAction->szCmdLine))
{
TCHAR* pszPercentToAppend;
if (StrChr(_pProgIDAction->szCmdLine,TEXT('\\')))
{
if (App_IsLFNAware(_pProgIDAction->szCmdLine))
pszPercentToAppend = TEXT(" \"%1\"");
else
pszPercentToAppend = TEXT(" %1");
}
else
{
TCHAR szFullPathFileName[MAX_PATH];
//
StringCchCopy(szFullPathFileName, ARRAYSIZE(szFullPathFileName), _pProgIDAction->szCmdLine);
//PathFindOnPath: first param is the filename, if it is on the path
// then it returns fully qualified, if not return false.
//Second param is optional directory to look in first
if (PathFindOnPath(szFullPathFileName, NULL))
{
if (App_IsLFNAware(szFullPathFileName))
pszPercentToAppend = TEXT(" \"%1\"");
else
pszPercentToAppend = TEXT(" %1");
}
else
{//just in case, default to good old behavior. Should not come here because
// ActionExeIsValid was done earlier
pszPercentToAppend = TEXT(" %1");
}
}
//append...
StringCchCat(_pProgIDAction->szCmdLine, ARRAYSIZE(_pProgIDAction->szCmdLine), pszPercentToAppend);
}
EndDialog(_hwnd, IDOK);
}
return FALSE;
}
LRESULT CFTActionDlg::OnCancel(WORD wNotif)
{
EndDialog(_hwnd, IDCANCEL);
return FALSE;
}
LRESULT CFTActionDlg::OnUseDDE(WORD wNotif)
{
_ResizeDlgForDDE(IsDlgButtonChecked(_hwnd, IDC_FT_CMD_USEDDE));
return FALSE;
}
LRESULT CFTActionDlg::OnBrowse(WORD wNotif)
{
TCHAR szPath[MAX_PATH];
TCHAR szTitle[40];
TCHAR szEXE[MAX_PATH];
TCHAR szFilters[MAX_PATH];
LPTSTR psz;
szPath[0] = 0;
EVAL(LoadString(g_hinst, IDS_CAP_OPENAS, szTitle, ARRAYSIZE(szTitle)));
EVAL(LoadString(g_hinst, IDS_FT_EXE, szEXE, ARRAYSIZE(szEXE)));
// And we need to convert #'s to \0's...
EVAL(LoadString(g_hinst, IDS_PROGRAMSFILTER, szFilters, ARRAYSIZE(szFilters)));
psz = szFilters;
while (*psz)
{
if (*psz == TEXT('#'))
{
LPTSTR pszT = psz;
psz = CharNext(psz);
*pszT = TEXT('\0');
}
else
psz = CharNext(psz);
}
if (GetFileNameFromBrowse(_hwnd, szPath, ARRAYSIZE(szPath), NULL, szEXE, szFilters, szTitle))
{
PathQuoteSpaces(szPath);
SetDlgItemText(_hwnd, IDC_FT_CMD_EXE, szPath);
}
return FALSE;
}
void CFTActionDlg::_ResizeDlgForDDE(BOOL fShow)
{
RECT rcDialog;
RECT rcControl;
GetWindowRect(_hwnd, &rcDialog);
if(fShow)
GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), &rcControl);
else
GetWindowRect(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), &rcControl);
// Hide/Show the windows to take care of the Tabbing. If we don't hide them then
// we tab through the "visible" window outside of the dialog.
ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEMSG), fShow);
ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPP), fShow);
ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEAPPNOT), fShow);
ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDETOPIC), fShow);
ShowWindow(GetDlgItem(_hwnd, IDC_FT_CMD_DDEGROUP), fShow);
SetWindowPos(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE), HWND_TOPMOST,
0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE|SWP_SHOWWINDOW);
MoveWindow(_hwnd, rcDialog.left, rcDialog.top, rcDialog.right - rcDialog.left,
(rcControl.bottom - rcDialog.top) + 10, TRUE);
SetFocus(GetDlgItem(_hwnd, IDC_FT_CMD_USEDDE));
}
LRESULT CFTActionDlg::OnDestroy(WPARAM wParam, LPARAM lParam)
{
CFTDlg::OnDestroy(wParam, lParam);
return FALSE;
}
///////////////////////////////////////////////////////////////////////////////
// Windows boiler plate code
LRESULT CFTActionDlg::OnCommand(WPARAM wParam, LPARAM lParam)
{
LRESULT lRes = FALSE;
switch(GET_WM_COMMAND_ID(wParam, lParam))
{
case IDC_FT_CMD_USEDDE:
// Resize Dialog to see/hide DDE controls
lRes = OnUseDDE(GET_WM_COMMAND_CMD(wParam, lParam));
break;
case IDC_FT_CMD_BROWSE:
lRes = OnBrowse(GET_WM_COMMAND_CMD(wParam, lParam));
break;
default:
lRes = CFTDlg::OnCommand(wParam, lParam);
break;
}
return lRes;
}
| 11,378 | 4,349 |
/**************************************************************************
Contains implementation for Worker class and its JobQueue subclass, which
handle job queues and stealing.
Author:
Jake McLeman
**************************************************************************/
#include <algorithm>
#ifdef _DEBUG
#include <assert.h>
#endif
#include "Job.h"
#include "JobExceptions.h"
#include "Manager.h"
#include "Worker.h"
namespace JobBot
{
Worker::Worker(Manager* aManager, Mode aMode,
const Specialization& aSpecialization)
: manager_(aManager), workerMode_(aMode),
workerSpecialization_(aSpecialization),
threadID_(std::this_thread::get_id()), keepWorking_(false),
isWorking_(false)
{
}
Worker::Specialization Worker::Specialization::None = {
{JobType::Huge, JobType::Graphics, JobType::Misc, JobType::IO,
JobType::Tiny}};
Worker::Specialization Worker::Specialization::IO = {
{JobType::IO, JobType::Huge, JobType::Misc, JobType::Graphics,
JobType::Tiny}};
Worker::Specialization Worker::Specialization::Graphics = {
{JobType::Graphics, JobType::Tiny, JobType::Misc, JobType::Null,
JobType::Null}};
Worker::Specialization Worker::Specialization::RealTime = {
{JobType::Tiny, JobType::Misc, JobType::Graphics, JobType::Null,
JobType::Null}};
void Worker::WorkWhileWaitingFor(Job* aWaitJob)
{
bool wasWorking = isWorking_;
isWorking_ = true;
aWaitJob->SetAllowCompletion(false);
while (!aWaitJob->IsFinished())
{
DoSingleJob();
}
aWaitJob->SetAllowCompletion(true);
isWorking_ = wasWorking;
}
void Worker::WorkWhileWaitingFor(std::atomic_bool& condition)
{
bool wasWorking = isWorking_;
isWorking_ = true;
while (!condition)
{
DoSingleJob();
}
isWorking_ = wasWorking;
}
void Worker::Start()
{
keepWorking_ = true;
DoWork();
}
void Worker::Stop()
{
keepWorking_ = false;
while (isWorking_)
;
}
void Worker::StopAfterCurrentTask() { keepWorking_ = false; }
Worker::Mode Worker::GetMode() { return workerMode_; }
std::thread::id Worker::GetThreadID() const { return threadID_; }
bool Worker::IsWorking() const { return isWorking_; }
void Worker::DoWork()
{
isWorking_ = true;
while (keepWorking_)
{
DoSingleJob();
}
isWorking_ = false;
}
void Worker::DoSingleJob()
{
static std::mutex waitMutex;
Job* job = GetAJob();
#ifdef _DEBUG
if (job != nullptr && job->GetUnfinishedJobCount() > 0)
#else
if (job != nullptr)
#endif
{
job->Run();
}
else
{
// If no job was found by any method, be a good citizen and step aside
// so that other processes on CPU can happen
if (workerMode_ == Mode::Volunteer)
{
std::this_thread::yield();
}
else
{
std::unique_lock<std::mutex> uniqueWait(waitMutex);
manager_->JobNotifier.wait(uniqueWait);
}
}
}
Job* Worker::GetAJob() { return manager_->RequestJob(workerSpecialization_); }
}
| 2,975 | 1,001 |
/*
* Portions Copyright (c) 1993-2015 NVIDIA Corporation. All rights reserved.
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
* Portions Copyright (c) 2009 Mike Giles, Oxford University. All rights reserved.
* Portions Copyright (c) 2008 Frances Y. Kuo and Stephen Joe. All rights reserved.
*
* Sobol Quasi-random Number Generator example
*
* Based on CUDA code submitted by Mike Giles, Oxford University, United Kingdom
* http://people.maths.ox.ac.uk/~gilesm/
*
* and C code developed by Stephen Joe, University of Waikato, New Zealand
* and Frances Kuo, University of New South Wales, Australia
* http://web.maths.unsw.edu.au/~fkuo/sobol/
*
* For theoretical background see:
*
* P. Bratley and B.L. Fox.
* Implementing Sobol's quasirandom sequence generator
* http://portal.acm.org/citation.cfm?id=42288
* ACM Trans. on Math. Software, 14(1):88-100, 1988
*
* S. Joe and F. Kuo.
* Remark on algorithm 659: implementing Sobol's quasirandom sequence generator.
* http://portal.acm.org/citation.cfm?id=641879
* ACM Trans. on Math. Software, 29(1):49-57, 2003
*/
#include <CL/sycl.hpp>
#include <dpct/dpct.hpp>
#include <iostream>
#include <stdexcept>
#include <math.h>
#include "sobol.h"
#include "sobol_gold.h"
#include "sobol_gpu.h"
#define L1ERROR_TOLERANCE (1e-6)
void printHelp(int argc, char *argv[])
{
if (argc > 0)
{
std::cout << "\nUsage: " << argv[0] << " <options>\n\n";
}
else
{
std::cout << "\nUsage: <program name> <options>\n\n";
}
std::cout << "\t--vectors=M specify number of vectors (required)\n";
std::cout << "\t The generator will output M vectors\n\n";
std::cout << "\t--dimensions=N specify number of dimensions (required)\n";
std::cout << "\t Each vector will consist of N components\n\n";
std::cout << std::endl;
}
int main(int argc, char *argv[])
{
dpct::device_ext &dev_ct1 = dpct::get_current_device();
sycl::queue &q_ct1 = dev_ct1.default_queue();
// We will generate n_vectors vectors of n_dimensions numbers
int n_vectors = atoi(argv[1]); //100000;
int n_dimensions = atoi(argv[2]); //100;
// Allocate memory for the arrays
std::cout << "Allocating CPU memory..." << std::endl;
unsigned int *h_directions = 0;
float *h_outputCPU = 0;
float *h_outputGPU = 0;
try
{
h_directions = new unsigned int [n_dimensions * n_directions];
h_outputCPU = new float [n_vectors * n_dimensions];
h_outputGPU = new float [n_vectors * n_dimensions];
}
catch (std::exception e)
{
std::cerr << "Caught exception: " << e.what() << std::endl;
std::cerr << "Unable to allocate CPU memory (try running with fewer vectors/dimensions)" << std::endl;
exit(EXIT_FAILURE);
}
std::cout << "Allocating GPU memory..." << std::endl;
unsigned int *d_directions;
float *d_output;
d_directions =
sycl::malloc_device<unsigned int>(n_dimensions * n_directions, q_ct1);
d_output = sycl::malloc_device<float>(n_vectors * n_dimensions, q_ct1);
// Initialize the direction numbers (done on the host)
std::cout << "Initializing direction numbers..." << std::endl;
initSobolDirectionVectors(n_dimensions, h_directions);
std::cout << "Executing QRNG on GPU..." << std::endl;
q_ct1
.memcpy(d_directions, h_directions,
n_dimensions * n_directions * sizeof(unsigned int))
.wait();
dev_ct1.queues_wait_and_throw();
sobolGPU(n_vectors, n_dimensions, d_directions, d_output);
q_ct1
.memcpy(h_outputGPU, d_output, n_vectors * n_dimensions * sizeof(float))
.wait();
std::cout << std::endl;
// Execute the QRNG on the host
std::cout << "Executing QRNG on CPU..." << std::endl;
sobolCPU(n_vectors, n_dimensions, h_directions, h_outputCPU);
// Check the results
std::cout << "Checking results..." << std::endl;
float l1norm_diff = 0.0F;
float l1norm_ref = 0.0F;
float l1error;
// Special case if n_vectors is 1, when the vector should be exactly 0
if (n_vectors == 1)
{
for (int d = 0, v = 0 ; d < n_dimensions ; d++)
{
float ref = h_outputCPU[d * n_vectors + v];
l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref);
l1norm_ref += fabs(ref);
}
// Output the L1-Error
l1error = l1norm_diff;
if (l1norm_ref != 0)
{
std::cerr << "Error: L1-Norm of the reference is not zero (for single vector), golden generator appears broken\n";
}
else
{
std::cout << "L1-Error: " << l1error << std::endl;
}
}
else
{
for (int d = 0 ; d < n_dimensions ; d++)
{
for (int v = 0 ; v < n_vectors ; v++)
{
float ref = h_outputCPU[d * n_vectors + v];
l1norm_diff += fabs(h_outputGPU[d * n_vectors + v] - ref);
l1norm_ref += fabs(ref);
}
}
// Output the L1-Error
l1error = l1norm_diff / l1norm_ref;
if (l1norm_ref == 0)
{
std::cerr << "Error: L1-Norm of the reference is zero, golden generator appears broken\n";
}
else
{
std::cout << "L1-Error: " << l1error << std::endl;
}
}
// Cleanup and terminate
std::cout << "Shutting down..." << std::endl;
delete h_directions;
delete h_outputCPU;
delete h_outputGPU;
sycl::free(d_directions, q_ct1);
sycl::free(d_output, q_ct1);
// Check pass/fail using L1 error
if (l1error < L1ERROR_TOLERANCE)
std::cout << "PASS" << std::endl;
else
std::cout << "FAIL" << std::endl;
return 0;
}
| 6,080 | 2,150 |
// BEGINLICENSE
//
// This file is part of helPME, which is distributed under the BSD 3-clause license,
// as described in the LICENSE file in the top level directory of this project.
//
// Author: Andrew C. Simmonett
//
// ENDLICENSE
#include "catch.hpp"
#include "helpme.h"
TEST_CASE("check that updates of kappa and unit cell parameters give the correct behavior.") {
constexpr double TOL = 1e-7;
double ccelec = 332.0716;
// Setup parameters and reference values.
helpme::Matrix<double> coords(
{{2.0, 2.0, 2.0}, {2.5, 2.0, 3.0}, {1.5, 2.0, 3.0}, {0.0, 0.0, 0.0}, {0.5, 0.0, 1.0}, {-0.5, 0.0, 1.0}});
helpme::Matrix<double> charges({-0.834, 0.417, 0.417, -0.834, 0.417, 0.417});
short nfftx = 20;
short nffty = 21;
short nfftz = 22;
short splineOrder = 5;
double refEnergy1 = 5.8537004;
helpme::Matrix<double> refForces1({{-0.60004038, -0.74129836, 6.31176591},
{0.50238424, 0.44175023, -2.53478813},
{0.34430074, 0.54474056, -2.60670541},
{-1.14160970, -1.04857552, 5.07874657},
{0.40743265, 0.45709529, -3.21032689},
{0.48655356, 0.34618192, -3.03887422}
});
helpme::Matrix<double> refVirial1({{0.61893621, 0.49018413, 0.54959991, 2.29084071, 2.35776919, -9.96248284}});
double refEnergy2 = 5.855746495;
helpme::Matrix<double> refForces2({{-0.60245163, -0.73942661, 6.31413552},
{0.50396028, 0.44092114, -2.53631961},
{0.34571162, 0.54380710, -2.60819278},
{-1.14467175, -1.04727038, 5.08209801},
{0.40871507, 0.45630372, -3.21165662},
{0.48780357, 0.34545271, -3.04026873}});
helpme::Matrix<double> refVirial2({{0.61199705, 0.49055936, 0.54134312, 2.28222850, 2.36819958, -9.94504929}});
double refEnergy3 = 6.871736497;
helpme::Matrix<double> refForces3({{-0.76684907, -0.94791216, 7.41216206},
{0.61560181, 0.54001262, -2.95904725},
{0.42875798, 0.68237489, -3.02853111},
{-1.40351882, -1.29196455, 5.91724551},
{0.52358846, 0.58722357, -3.77349856},
{0.60098832, 0.43008731, -3.56873433}});
helpme::Matrix<double> refVirial3({{0.69619831, 0.55213933, 0.60823304, 2.78138346, 2.86610280, -11.39571070}});
double refEnergy4 = 6.8718135;
helpme::Matrix<double> refForces4({{-0.76682663, -0.79604124, 7.42058381},
{0.61559595, 0.45348406, -2.96384799},
{0.42875295, 0.57298883, -3.03458962},
{-1.40348529, -1.08508863, 5.92864929},
{0.52356758, 0.49320229, -3.77867550},
{0.60096417, 0.36124367, -3.57252549}});
helpme::Matrix<double> refVirial4({{0.69622261, 0.55220016, 0.60784358, 2.78135060, 2.86647846, -11.39584386}});
double refEnergy5 = 7.55899485;
helpme::Matrix<double> refForces5({{-0.84350929, -0.87564537, 8.16264219},
{0.67715554, 0.49883247, -3.26023278},
{0.47162825, 0.63028771, -3.33804858},
{-1.54383381, -1.19359749, 6.52151422},
{0.57592433, 0.54252252, -4.15654305},
{0.66106059, 0.39736803, -3.92977804}});
helpme::Matrix<double> refVirial5({{0.76584487, 0.60742018, 0.66862794, 3.05948566, 3.15312630, -12.53542824}});
double refEnergy6 = 7.558688228;
helpme::Matrix<double> refForces6({{-0.84303319, -0.87557676, 8.16169899},
{0.67691837, 0.49890558, -3.25971866},
{0.47193007, 0.63032536, -3.33749220},
{-1.54317624, -1.19339693, 6.52017613},
{0.57607320, 0.54246197, -4.15560408},
{0.66144590, 0.39732351, -3.92883941}});
helpme::Matrix<double> refVirial6({{0.76545755, 0.60761239, 0.66897556, 3.05912581, 3.15274330, -12.53308757}});
double refEnergy7 = 0.007626089169;
helpme::Matrix<double> refForces7({{-0.00111343, -0.00115672, 0.00829002},
{0.00081670, 0.00059903, -0.00320443},
{0.00059187, 0.00079872, -0.00324183},
{-0.00187292, -0.00145863, 0.00637289},
{0.00076641, 0.00072244, -0.00423731},
{0.00081164, 0.00049523, -0.00397890}});
helpme::Matrix<double> refVirial7({{0.00068085, 0.00059011, 0.00057443, 0.00357792, 0.00368895, -0.01097979}});
SECTION("EFV routines") {
double energy;
helpme::Matrix<double> forces(6, 3);
helpme::Matrix<double> virial(1, 6);
auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD);
pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
// Start with random setup
forces.setZero();
virial.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
REQUIRE(virial.almostEquals(refVirial1));
// Call update with same parameters, to make sure everything's the same
forces.setZero();
virial.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
REQUIRE(virial.almostEquals(refVirial1));
// Now change the parameters, and make sure it updates correctly
forces.setZero();
virial.setZero();
pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy2).margin(TOL));
REQUIRE(forces.almostEquals(refForces2));
REQUIRE(virial.almostEquals(refVirial2));
// Back to the original setup
forces.setZero();
virial.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
REQUIRE(virial.almostEquals(refVirial1));
// Same, but new kappa value
forces.setZero();
virial.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy3).margin(TOL));
REQUIRE(forces.almostEquals(refForces3));
REQUIRE(virial.almostEquals(refVirial3));
// Adjust the grid slightly
forces.setZero();
virial.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy4).margin(TOL));
REQUIRE(forces.almostEquals(refForces4));
REQUIRE(virial.almostEquals(refVirial4));
// Adjust the scale factor slightly
forces.setZero();
virial.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy5).margin(TOL));
REQUIRE(forces.almostEquals(refForces5));
REQUIRE(virial.almostEquals(refVirial5));
// Adjust the scale factor slightly
forces.setZero();
virial.setZero();
pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy6).margin(TOL));
REQUIRE(forces.almostEquals(refForces6));
REQUIRE(virial.almostEquals(refVirial6));
// Change the physics from coulomb to some weird disperion
forces.setZero();
virial.setZero();
pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFVRec(0, charges, coords, forces, virial);
REQUIRE(energy == Approx(refEnergy7).margin(TOL));
REQUIRE(forces.almostEquals(refForces7));
REQUIRE(virial.almostEquals(refVirial7));
}
SECTION("EF routines") {
double energy;
helpme::Matrix<double> forces(6, 3);
auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD);
pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
// Start with random setup
forces.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
// Call update with same parameters, to make sure everything's the same
forces.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
// Now change the parameters, and make sure it updates correctly
forces.setZero();
pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy2).margin(TOL));
REQUIRE(forces.almostEquals(refForces2));
// Back to the original setup
forces.setZero();
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
REQUIRE(forces.almostEquals(refForces1));
// Same, but new kappa value
forces.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy3).margin(TOL));
REQUIRE(forces.almostEquals(refForces3));
// Adjust the grid slightly
forces.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy4).margin(TOL));
REQUIRE(forces.almostEquals(refForces4));
// Adjust the scale factor slightly
forces.setZero();
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy5).margin(TOL));
REQUIRE(forces.almostEquals(refForces5));
// Adjust the scale factor slightly
forces.setZero();
pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy6).margin(TOL));
REQUIRE(forces.almostEquals(refForces6));
// Change the physics from coulomb to some weird disperion
forces.setZero();
pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeEFRec(0, charges, coords, forces);
REQUIRE(energy == Approx(refEnergy7).margin(TOL));
REQUIRE(forces.almostEquals(refForces7));
}
SECTION("E routines") {
double energy;
auto pme = std::unique_ptr<PMEInstanceD>(new PMEInstanceD);
pme->setup(1, 0.3, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
// Start with random setup
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
// Call update with same parameters, to make sure everything's the same
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
// Now change the parameters, and make sure it updates correctly
pme->setLatticeVectors(21.5, 22.2, 20.1, 94, 91, 91, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy2).margin(TOL));
// Back to the original setup
pme->setLatticeVectors(21, 22, 20, 93, 92, 90, PMEInstanceD::LatticeType::XAligned);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy1).margin(TOL));
// Same, but new kappa value
pme->setup(1, 0.32, splineOrder, nfftx, nffty, nfftz, ccelec, 1);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy3).margin(TOL));
// Adjust the grid slightly
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, ccelec, 1);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy4).margin(TOL));
// Adjust the scale factor slightly
pme->setup(1, 0.32, splineOrder, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy5).margin(TOL));
// Adjust the scale factor slightly
pme->setup(1, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy6).margin(TOL));
// Change the physics from coulomb to some weird disperion
pme->setup(6, 0.32, splineOrder + 1, nfftx, nffty + 4, nfftz, 1.1 * ccelec, 1);
energy = pme->computeERec(0, charges, coords);
REQUIRE(energy == Approx(refEnergy7).margin(TOL));
}
}
| 15,069 | 6,678 |
#include <bits/stdc++.h>
using namespace std;
#define ff first
#define ss second
typedef long long ll;
typedef long double ld;
typedef pair<int, int> pi;
typedef pair<long long, long long> pl;
const int MOD = 1e9 + 7;
const ll INF = 1e18;
const double EPS = 1e-6;
int N;
ll X, Y, Z;
priority_queue<ll, vector<ll>, greater<ll>> extra, need;
int main() {
freopen("landscape.in", "r", stdin); freopen("landscape.out", "w", stdout);
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> N >> X >> Y >> Z;
ll ans = 0;
for (int i = 0; i < N; ++i) {
int A, B; cin >> A >> B;
int delta = B - A;
if (delta > 0) {
for (int j = 0; j < delta; ++j) {
ll cost = X;
if (!extra.empty() && extra.top() + Z * i < X) {
cost = extra.top() + Z * i; extra.pop();
}
ans += cost;
need.push(-cost - Z * i);
}
}
else {
for (int j = 0; j < -delta; ++j) {
ll cost = Y;
if (!need.empty() && need.top() + Z * i < Y) {
cost = need.top() + Z * i; need.pop();
}
ans += cost;
extra.push(-cost - Z * i);
}
}
}
cout << ans << '\n';
return 0;
}
| 1,152 | 548 |
// Copyright (c) 2009-2013 University of Twente
// Copyright (c) 2009-2013 Michael Weber <michaelw@cs.utwente.nl>
// Copyright (c) 2009-2013 Maks Verver <maksverver@geocities.com>
// Copyright (c) 2009-2013 Eindhoven University of Technology
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include "mcrl2/pg/FocusListLiftingStrategy.h"
/*! Credit for a vertex when it is put on the focus list. */
static const unsigned initial_credit = 2;
/*! Credit increase when a vertex on the focus list is successfully lifted. */
static const unsigned credit_increase = 2;
FocusListLiftingStrategy::FocusListLiftingStrategy( const ParityGame &game,
bool alternate, verti max_size, std::size_t max_lifts )
: LiftingStrategy(), V_(game.graph().V()), max_lift_attempts_(max_lifts),
phase_(1), num_lift_attempts_(0), lls_(game, alternate)
{
focus_list_.reserve(max_size);
}
void FocusListLiftingStrategy::lifted(verti vertex)
{
if (phase_ == 1)
{
lls_.lifted(vertex);
if (focus_list_.size() < focus_list_.capacity())
{
focus_list_.push_back(std::make_pair(vertex, initial_credit));
}
}
else /* phase_ == 2 */
{
if (vertex == read_pos_->first) prev_lifted_ = true;
}
}
verti FocusListLiftingStrategy::next()
{
verti res = phase_ == 1 ? phase1() : phase2();
++num_lift_attempts_;
return res;
}
verti FocusListLiftingStrategy::phase1()
{
if (focus_list_.size() == focus_list_.capacity() ||
num_lift_attempts_ >= V_)
{
if (focus_list_.empty())
{
/* This can only happen if lls_.num_failed >= V too */
assert(lls_.next() == NO_VERTEX);
return NO_VERTEX;
}
/* Switch to phase 2: */
phase_ = 2;
num_lift_attempts_ = 0;
read_pos_ = write_pos_ = focus_list_.begin();
mCRL2log(mcrl2::log::verbose) << "Switching to focus list of size " << focus_list_.size() << std::endl;
return phase2();
}
return lls_.next();
}
verti FocusListLiftingStrategy::phase2()
{
if (num_lift_attempts_ > 0)
{
// Adjust previous vertex credit and move to next position
focus_list::value_type prev = *read_pos_++;
if (prev_lifted_)
{
prev.second += credit_increase;
*write_pos_++ = prev;
}
else
if (prev.second > 0)
{
prev.second /= 2;
*write_pos_++ = prev;
}
// else, drop from list.
}
// Check if we've reached the end of the focus list; if so, restart:
if (read_pos_ == focus_list_.end())
{
focus_list_.erase(write_pos_, focus_list_.end());
read_pos_ = write_pos_ = focus_list_.begin();
}
if (focus_list_.empty() || num_lift_attempts_ >= max_lift_attempts_)
{
if (focus_list_.empty())
{
mCRL2log(mcrl2::log::verbose) << "Focus list exhausted." << std::endl;
}
else
{
mCRL2log(mcrl2::log::verbose) << "Maximum lift attempts (" << max_lift_attempts_ << ") on focus list reached." << std::endl;
focus_list_.clear();
}
/* Switch to phase 1 */
phase_ = 1;
num_lift_attempts_ = 0;
return phase1();
}
// Return current item on the focus list
prev_lifted_ = false;
return read_pos_->first;
}
LiftingStrategy *FocusListLiftingStrategyFactory::create(
const ParityGame &game, const SmallProgressMeasures &spm )
{
(void)spm; // unused
/* Ratio is absolute value if >1, or a fraction of the size of the game's
vertex set if <= 1. */
verti V = game.graph().V();
verti max_size = (size_ratio_ > 1) ? static_cast<verti>(size_ratio_) : static_cast<verti>(size_ratio_*V); // XXX Ugly casting here
if (max_size == 0) max_size = 1;
if (max_size > V) max_size = V;
verti max_lifts = (verti)(lift_ratio_ * max_size);
return new FocusListLiftingStrategy(
game, alternate_, max_size, max_lifts );
}
| 4,163 | 1,471 |
#include "modio.h"
#include <iostream>
int main(void)
{
modio::Instance modio_instance(MODIO_ENVIRONMENT_TEST, 7, "e91c01b8882f4affeddd56c96111977b");
volatile static bool finished = false;
auto wait = [&]() {
while (!finished)
{
modio_instance.sleep(10);
modio_instance.process();
}
};
auto finish = [&]() {
finished = true;
};
u32 mod_id;
std::cout << "Enter the mod id: " << std::endl;
std::cin >> mod_id;
std::vector<std::string> tags;
tags.push_back("Hard");
// We add tags to a mod by providing the tag names. Remember, they must be valid tags allowed by the parrent game
modio_instance.addModTags(mod_id, tags, [&](const modio::Response &response) {
std::cout << "Add tags response: " << response.code << std::endl;
if (response.code == 201)
{
std::cout << "Tags added successfully" << std::endl;
}
finish();
});
wait();
std::cout << "Process finished" << std::endl;
return 0;
}
| 984 | 372 |
#include "todo.hpp"
#include "zero_copy_value.hpp"
#include "sample.h"
// dummy service routines that simulate background threads or threadpools that actually complete the async tasks
void dummy_service_routine(todo td)
{
this_thread::sleep_for(chrono::milliseconds(200));
td.resolve();
td.wake();
}
void dummy_service_routine_sometimes_reject(todo td)
{
this_thread::sleep_for(chrono::milliseconds(400));
if(u(e)<6){
td.resolve();
}else{
td.reject(); // 40%
}
td.wake();
}
void dummy_error_handling(todo td)
{
this_thread::sleep_for(chrono::milliseconds(100));
td.finish();
td.wake();
}
void ftp_conn_service(todo td)
{
dummy_service_routine(td);
}
void downloading_service(todo td)
{
dummy_service_routine(td);
}
void uncompressing_service(todo td)
{
dummy_service_routine(td);
}
void decoding_service(todo td)
{
dummy_service_routine_sometimes_reject(td);
}
void fwrite_service(todo td)
{
dummy_service_routine_sometimes_reject(td);
}
// style 1:
// todo{job0}(job1)(job2)(job3)(job4,job3_err)[job4_err]();
// 1. define jobs first
// 2. chain functions with parentheses! {..}(..)(..)(..)[..]
// 3. use an empty () to kick off the whole callback chain
// {} captures init function for todo constructor
// () captures both on_resolve & on_reject
// [] captures on_reject only
void test1()
{
auto job0=[](todo* self){
cout<<"job0 connect to ftp server \n";
ftp_conn_service(*self);
};
auto job1=[](todo* self){
cout<<"job1 download file todo.zip \n";
downloading_service(*self);
};
auto job2=[](todo* self){
cout<<"job2 unzip file todo.zip \n";
uncompressing_service(*self);
};
auto job3=[](todo* self){
cout<<"job3 decipher file todo.data \n";
decoding_service(*self);
};
auto job4=[](todo* self){
cout<<"job4 write file todo.new \n";
fwrite_service(*self);
};
auto job3_err=[](todo* self){
cout<<"triggered by job3 decoding_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
};
auto job4_err=[](todo* self){
cout<<"triggered by job4 fwrite_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
};
todo{job0}(job1)(job2)(job3)(job4,job3_err)[job4_err]();
}
// style 2:
// use methods rather than parenthese
void test2()
{
todo td([](todo* self){ //func === std::function<void(todo*)>
cout<<"job0 connect to ftp server \n";
ftp_conn_service(*self);
});
td.then([](todo* self){
cout<<"job1 download file todo.zip \n";
downloading_service(*self);
}).then([](todo* self){ //then(func,func) === operator(func,func); then(nullptr, func) === operator[func]
cout<<"job2 unzip file todo.zip \n";
uncompressing_service(*self);
}).then([](todo* self){
cout<<"job3 decipher file todo.data \n";
decoding_service(*self);
}).then([](todo* self){
cout<<"job4 write file todo.new \n";
fwrite_service(*self);
}, [](todo* self){
cout<<"triggered by job3 decoding_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
}).then(nullptr, [](todo* self){
cout<<"triggered by job4 fwrite_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
});
td.run(); // run() === operator()
}
// style 3:
// all in one closure
void test3()
{
todo
{
[](todo* self){
cout<<"job0 connect to ftp server \n";
ftp_conn_service(*self);
}
}
(
[](todo* self){
cout<<"job1 download file todo.zip \n";
downloading_service(*self);
}
)
(
[](todo* self){
cout<<"job2 unzip file todo.zip \n";
uncompressing_service(*self);
}
)
(
[](todo* self){
cout<<"job3 decipher file todo.data \n";
decoding_service(*self);
}
)
(
[](todo* self){
cout<<"job4 write file todo.new \n";
fwrite_service(*self);
},
[](todo* self){
cout<<"triggered by job3 decoding_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
}
)
( //c++ does not allow consequtive left square brackets here, so we have to use () with first arg set to nullptr
nullptr,
[](todo* self){
cout<<"triggered by job4 fwrite_service failure! \n";
cout<<"quit now\n";
dummy_error_handling(*self);
}
)();
}
void test_zero_copy_value()
{
zero_copy_value a;
cout<<"a empty: "<<a.empty()<<endl; //1
cout<<"a typename: "<<a.type()<<endl; //Dn
zero_copy_value b(123);
cout<<"b typename: "<<b.type()<<endl; //i
cout<<"b data as int: "<<b.data<int>()<<endl; //123
zero_copy_value c(123.456);
cout<<"c typename: "<<c.type()<<endl; //d
cout<<"c data as double "<<c.data<double>()<<endl;
zero_copy_value d = c; // ctor ref++
zero_copy_value e = c.copy(); // make a copy
cout<<"c==d: "<<(c==d) <<endl;
cout<<"e==c: "<<(c==e) <<endl;
cout<<"e typename: "<<e.type()<<endl; //d
cout<<"e data as double "<<e.data<double>()<<endl;
zero_copy_value f = 100; // construct from a specific type
cout<<"f typename: "<<f.type()<<endl; //i
// cout<<"f data as double "<<f.data<double>()<<endl; //throw exception (should be int)
f=e; //operator= lvalue ref
cout<<"f typename: "<<f.type()<<endl; //i
cout<<"f data as double "<<e.data<double>()<<endl;
f=e.copy(); // operator= rvalue!
cout<<"f typename: "<<f.type()<<endl; //i
cout<<"f data as double "<<e.data<double>()<<endl;
}
int main()
{
promise1();
cout<<"sample ends\n";
cin.get();
cout<<"program ends\n";
return 0;
} | 5,983 | 2,136 |
#include <cppunit/extensions/HelperMacros.h>
#include <Poco/File.h>
#include "cppunit/BetterAssert.h"
#include "cppunit/FileTestFixture.h"
#include "core/FilesystemDeviceCache.h"
#include "model/DevicePrefix.h"
using namespace Poco;
namespace BeeeOn {
class FilesystemDeviceCacheTest : public FileTestFixture {
CPPUNIT_TEST_SUITE(FilesystemDeviceCacheTest);
CPPUNIT_TEST(testPairUnpair);
CPPUNIT_TEST(testPrepaired);
CPPUNIT_TEST(testBatchPair);
CPPUNIT_TEST_SUITE_END();
public:
void setUp();
void tearDown();
void testPairUnpair();
void testNothingPrepaired();
void testPrepaired();
void testBatchPair();
private:
FilesystemDeviceCache m_cache;
};
CPPUNIT_TEST_SUITE_REGISTRATION(FilesystemDeviceCacheTest);
void FilesystemDeviceCacheTest::setUp()
{
setUpAsDirectory();
m_cache.setCacheDir(testingPath().toString());
}
void FilesystemDeviceCacheTest::tearDown()
{
// remove all created named mutexes
for (const auto &prefix : DevicePrefix::all()) {
File mutex("/tmp/" + prefix.toString() + ".mutex");
try {
mutex.remove();
}
catch (...) {}
}
}
/**
* @brief Test we can pair and unpair a device and such device can be
* detected as paired. Paired device would always have a corresponding
* file created in the filesystem.
*/
void FilesystemDeviceCacheTest::testPairUnpair()
{
const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE;
const Path vdev(testingPath(), "vdev");
CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev);
const Path a300000001020304(testingPath(), "vdev/0xa300000001020304");
CPPUNIT_ASSERT(m_cache.paired(VDEV).empty());
CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304}));
m_cache.markPaired({0xa300000001020304});
CPPUNIT_ASSERT_FILE_EXISTS(vdev);
CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304);
CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size());
CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304}));
m_cache.markUnpaired({0xa300000001020304});
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304);
CPPUNIT_ASSERT(m_cache.paired(VDEV).empty());
CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304}));
}
/**
* @brief Test we can pre-pair a set of devices by creating appropriate files
* in the filesystem. Only such pre-paired devices are marked as paired.
*/
void FilesystemDeviceCacheTest::testPrepaired()
{
const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE;
const Path vdev(testingPath(), "vdev");
CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev);
CPPUNIT_ASSERT_NO_THROW(File(vdev).createDirectories());
const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa");
const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb");
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa);
CPPUNIT_ASSERT_NO_THROW(File(a3000000aaaaaaaa).createFile());
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb);
CPPUNIT_ASSERT_NO_THROW(File(a3000000bbbbbbbb).createFile());
CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size());
CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa}));
CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb}));
CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304}));
}
/**
* @brief Test pairing as a batch process. All already paired devices
* should be removed and only the given set is to be paired. The pairing
* status is visible when watching the filesystem.
*/
void FilesystemDeviceCacheTest::testBatchPair()
{
const DevicePrefix &VDEV = DevicePrefix::PREFIX_VIRTUAL_DEVICE;
const Path vdev(testingPath(), "vdev");
CPPUNIT_ASSERT_FILE_NOT_EXISTS(vdev);
const Path a3000000aaaaaaaa(testingPath(), "vdev/0xa3000000aaaaaaaa");
const Path a3000000bbbbbbbb(testingPath(), "vdev/0xa3000000bbbbbbbb");
const Path a300000001020304(testingPath(), "vdev/0xa300000001020304");
CPPUNIT_ASSERT(m_cache.paired(VDEV).empty());
m_cache.markPaired(VDEV, {{0xa3000000aaaaaaaa}, {0xa3000000bbbbbbbb}});
CPPUNIT_ASSERT_FILE_EXISTS(a3000000aaaaaaaa);
CPPUNIT_ASSERT_FILE_EXISTS(a3000000bbbbbbbb);
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304);
CPPUNIT_ASSERT_EQUAL(2, m_cache.paired(VDEV).size());
CPPUNIT_ASSERT(m_cache.paired({0xa3000000aaaaaaaa}));
CPPUNIT_ASSERT(m_cache.paired({0xa3000000bbbbbbbb}));
CPPUNIT_ASSERT(!m_cache.paired({0xa300000001020304}));
m_cache.markPaired(VDEV, {{0xa300000001020304}});
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa);
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb);
CPPUNIT_ASSERT_FILE_EXISTS(a300000001020304);
CPPUNIT_ASSERT_EQUAL(1, m_cache.paired(VDEV).size());
CPPUNIT_ASSERT(!m_cache.paired({0xa3000000aaaaaaaa}));
CPPUNIT_ASSERT(!m_cache.paired({0xa3000000bbbbbbbb}));
CPPUNIT_ASSERT(m_cache.paired({0xa300000001020304}));
m_cache.markPaired(VDEV, {});
CPPUNIT_ASSERT(m_cache.paired(VDEV).empty());
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000aaaaaaaa);
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a3000000bbbbbbbb);
CPPUNIT_ASSERT_FILE_NOT_EXISTS(a300000001020304);
CPPUNIT_ASSERT_DIR_EMPTY(vdev);
}
}
| 4,904 | 2,313 |
#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN
#include <vector>
#include "doctest.h"
#include "util.h"
using namespace std;
class Solution {
public:
bool isOneBitCharacter(vector<int>& bits) {
if(bits.size() < 2) {
return !bits[0];
}
if(bits[bits.size() - 2] == 0)
return true;
else {
int i = 0;
while(i < bits.size() - 1) {
if(bits[i] == 0)
i++;
else {
i += 2;
}
}
if(i == bits.size() - 1)
return true;
}
return false;
}
};
TEST_CASE("tests") {
Solution s;
vector<int> input;
bool soln;
SUBCASE("1") {
input = {1, 0, 0};
soln = true;
}
SUBCASE("2") {
input = {1, 1, 1, 0};
soln = false;
}
SUBCASE("3") {
input = {0, 1, 0};
soln = false;
}
SUBCASE("4") {
input = {0, 1, 0, 0};
soln = true;
}
SUBCASE("5") {
input = {1, 1, 0};
soln = true;
}
SUBCASE("6") {
input = {1, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 1, 0};
soln = false;
}
print_vector(input);
CHECK(s.isOneBitCharacter(input) == soln);
}
| 1,094 | 504 |
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
* vim: set ts=8 sts=4 et sw=4 tw=99:
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#include "builtin/RegExp.h"
#include "mozilla/CheckedInt.h"
#include "mozilla/TypeTraits.h"
#include "frontend/TokenStream.h"
#include "irregexp/RegExpParser.h"
#include "jit/InlinableNatives.h"
#include "util/StringBuffer.h"
#include "util/Unicode.h"
#include "vm/JSContext.h"
#include "vm/RegExpStatics.h"
#include "vm/SelfHosting.h"
#include "vm/JSObject-inl.h"
#include "vm/NativeObject-inl.h"
#include "vm/ObjectOperations-inl.h"
#include "vm/UnboxedObject-inl.h"
using namespace js;
using mozilla::CheckedInt;
using mozilla::IsAsciiDigit;
using JS::CompileOptions;
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 16-25.
*/
bool
js::CreateRegExpMatchResult(JSContext* cx, HandleString input, const MatchPairs& matches,
MutableHandleValue rval)
{
MOZ_ASSERT(input);
/*
* Create the (slow) result array for a match.
*
* Array contents:
* 0: matched string
* 1..pairCount-1: paren matches
* input: input string
* index: start index for the match
*/
/* Get the templateObject that defines the shape and type of the output object */
JSObject* templateObject = cx->realm()->regExps.getOrCreateMatchResultTemplateObject(cx);
if (!templateObject) {
return false;
}
size_t numPairs = matches.length();
MOZ_ASSERT(numPairs > 0);
/* Step 17. */
RootedArrayObject arr(cx, NewDenseFullyAllocatedArrayWithTemplate(cx, numPairs, templateObject));
if (!arr) {
return false;
}
/* Steps 22-24.
* Store a Value for each pair. */
for (size_t i = 0; i < numPairs; i++) {
const MatchPair& pair = matches[i];
if (pair.isUndefined()) {
MOZ_ASSERT(i != 0); /* Since we had a match, first pair must be present. */
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, UndefinedValue());
} else {
JSLinearString* str = NewDependentString(cx, input, pair.start, pair.length());
if (!str) {
return false;
}
arr->setDenseInitializedLength(i + 1);
arr->initDenseElement(i, StringValue(str));
}
}
/* Step 20 (reordered).
* Set the |index| property. */
arr->setSlot(RegExpRealm::MatchResultObjectIndexSlot, Int32Value(matches[0].start));
/* Step 21 (reordered).
* Set the |input| property. */
arr->setSlot(RegExpRealm::MatchResultObjectInputSlot, StringValue(input));
#ifdef DEBUG
RootedValue test(cx);
RootedId id(cx, NameToId(cx->names().index));
if (!NativeGetProperty(cx, arr, id, &test)) {
return false;
}
MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectIndexSlot));
id = NameToId(cx->names().input);
if (!NativeGetProperty(cx, arr, id, &test)) {
return false;
}
MOZ_ASSERT(test == arr->getSlot(RegExpRealm::MatchResultObjectInputSlot));
#endif
/* Step 25. */
rval.setObject(*arr);
return true;
}
static int32_t
CreateRegExpSearchResult(const MatchPairs& matches)
{
/* Fit the start and limit of match into a int32_t. */
uint32_t position = matches[0].start;
uint32_t lastIndex = matches[0].limit;
MOZ_ASSERT(position < 0x8000);
MOZ_ASSERT(lastIndex < 0x8000);
return position | (lastIndex << 15);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
static RegExpRunStatus
ExecuteRegExpImpl(JSContext* cx, RegExpStatics* res, MutableHandleRegExpShared re,
HandleLinearString input, size_t searchIndex, VectorMatchPairs* matches,
size_t* endIndex)
{
RegExpRunStatus status = RegExpShared::execute(cx, re, input, searchIndex, matches, endIndex);
/* Out of spec: Update RegExpStatics. */
if (status == RegExpRunStatus_Success && res) {
if (matches) {
if (!res->updateFromMatchPairs(cx, input, *matches)) {
return RegExpRunStatus_Error;
}
} else {
res->updateLazily(cx, input, re, searchIndex);
}
}
return status;
}
/* Legacy ExecuteRegExp behavior is baked into the JSAPI. */
bool
js::ExecuteRegExpLegacy(JSContext* cx, RegExpStatics* res, Handle<RegExpObject*> reobj,
HandleLinearString input, size_t* lastIndex, bool test,
MutableHandleValue rval)
{
RootedRegExpShared shared(cx, RegExpObject::getShared(cx, reobj));
if (!shared) {
return false;
}
VectorMatchPairs matches;
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &shared, input, *lastIndex,
&matches, nullptr);
if (status == RegExpRunStatus_Error) {
return false;
}
if (status == RegExpRunStatus_Success_NotFound) {
/* ExecuteRegExp() previously returned an array or null. */
rval.setNull();
return true;
}
*lastIndex = matches[0].limit;
if (test) {
/* Forbid an array, as an optimization. */
rval.setBoolean(true);
return true;
}
return CreateRegExpMatchResult(cx, input, matches, rval);
}
static bool
CheckPatternSyntaxSlow(JSContext* cx, HandleAtom pattern, RegExpFlag flags)
{
CompileOptions options(cx);
frontend::TokenStream dummyTokenStream(cx, options, nullptr, 0, nullptr);
return irregexp::ParsePatternSyntax(dummyTokenStream, cx->tempLifoAlloc(), pattern,
flags & UnicodeFlag);
}
static RegExpShared*
CheckPatternSyntax(JSContext* cx, HandleAtom pattern, RegExpFlag flags)
{
// If we already have a RegExpShared for this pattern/flags, we can
// avoid the much slower CheckPatternSyntaxSlow call.
if (RegExpShared* shared = cx->zone()->regExps().maybeGet(pattern, flags)) {
#ifdef DEBUG
// Assert the pattern is valid.
if (!CheckPatternSyntaxSlow(cx, pattern, flags)) {
MOZ_ASSERT(cx->isThrowingOutOfMemory() || cx->isThrowingOverRecursed());
return nullptr;
}
#endif
return shared;
}
if (!CheckPatternSyntaxSlow(cx, pattern, flags)) {
return nullptr;
}
// Allocate and return a new RegExpShared so we will hit the fast path
// next time.
return cx->zone()->regExps().get(cx, pattern, flags);
}
/*
* ES 2016 draft Mar 25, 2016 21.2.3.2.2.
*
* Steps 14-15 set |obj|'s "lastIndex" property to zero. Some of
* RegExpInitialize's callers have a fresh RegExp not yet exposed to script:
* in these cases zeroing "lastIndex" is infallible. But others have a RegExp
* whose "lastIndex" property might have been made non-writable: here, zeroing
* "lastIndex" can fail. We efficiently solve this problem by completely
* removing "lastIndex" zeroing from the provided function.
*
* CALLERS MUST HANDLE "lastIndex" ZEROING THEMSELVES!
*
* Because this function only ever returns a user-provided |obj| in the spec,
* we omit it and just return the usual success/failure.
*/
static bool
RegExpInitializeIgnoringLastIndex(JSContext* cx, Handle<RegExpObject*> obj,
HandleValue patternValue, HandleValue flagsValue)
{
RootedAtom pattern(cx);
if (patternValue.isUndefined()) {
/* Step 1. */
pattern = cx->names().empty;
} else {
/* Step 2. */
pattern = ToAtom<CanGC>(cx, patternValue);
if (!pattern) {
return false;
}
}
/* Step 3. */
RegExpFlag flags = RegExpFlag(0);
if (!flagsValue.isUndefined()) {
/* Step 4. */
RootedString flagStr(cx, ToString<CanGC>(cx, flagsValue));
if (!flagStr) {
return false;
}
/* Step 5. */
if (!ParseRegExpFlags(cx, flagStr, &flags)) {
return false;
}
}
/* Steps 7-8. */
RegExpShared* shared = CheckPatternSyntax(cx, pattern, flags);
if (!shared) {
return false;
}
/* Steps 9-12. */
obj->initIgnoringLastIndex(pattern, flags);
obj->setShared(*shared);
return true;
}
/* ES 2016 draft Mar 25, 2016 21.2.3.2.3. */
bool
js::RegExpCreate(JSContext* cx, HandleValue patternValue, HandleValue flagsValue,
MutableHandleValue rval)
{
/* Step 1. */
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject));
if (!regexp) {
return false;
}
/* Step 2. */
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, patternValue, flagsValue)) {
return false;
}
regexp->zeroLastIndex(cx);
rval.setObject(*regexp);
return true;
}
MOZ_ALWAYS_INLINE bool
IsRegExpObject(HandleValue v)
{
return v.isObject() && v.toObject().is<RegExpObject>();
}
/* ES6 draft rc3 7.2.8. */
bool
js::IsRegExp(JSContext* cx, HandleValue value, bool* result)
{
/* Step 1. */
if (!value.isObject()) {
*result = false;
return true;
}
RootedObject obj(cx, &value.toObject());
/* Steps 2-3. */
RootedValue isRegExp(cx);
RootedId matchId(cx, SYMBOL_TO_JSID(cx->wellKnownSymbols().match));
if (!GetProperty(cx, obj, obj, matchId, &isRegExp)) {
return false;
}
/* Step 4. */
if (!isRegExp.isUndefined()) {
*result = ToBoolean(isRegExp);
return true;
}
/* Steps 5-6. */
ESClass cls;
if (!GetClassOfValue(cx, value, &cls)) {
return false;
}
*result = cls == ESClass::RegExp;
return true;
}
/* ES6 B.2.5.1. */
MOZ_ALWAYS_INLINE bool
regexp_compile_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
Rooted<RegExpObject*> regexp(cx, &args.thisv().toObject().as<RegExpObject>());
// Step 3.
RootedValue patternValue(cx, args.get(0));
ESClass cls;
if (!GetClassOfValue(cx, patternValue, &cls)) {
return false;
}
if (cls == ESClass::RegExp) {
// Step 3a.
if (args.hasDefined(1)) {
JS_ReportErrorNumberASCII(cx, GetErrorMessage, nullptr, JSMSG_NEWREGEXP_FLAGGED);
return false;
}
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|. For the same reason,
// don't reuse the RegExpShared below.
RootedObject patternObj(cx, &patternValue.toObject());
RootedAtom sourceAtom(cx);
RegExpFlag flags;
{
// Step 3b.
RegExpShared* shared = RegExpToShared(cx, patternObj);
if (!shared) {
return false;
}
sourceAtom = shared->getSource();
flags = shared->getFlags();
}
// Step 5, minus lastIndex zeroing.
regexp->initIgnoringLastIndex(sourceAtom, flags);
} else {
// Step 4.
RootedValue P(cx, patternValue);
RootedValue F(cx, args.get(1));
// Step 5, minus lastIndex zeroing.
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) {
return false;
}
}
// The final niggling bit of step 5.
//
// |regexp| is user-exposed, but if its "lastIndex" property hasn't been
// made non-writable, we can still use a fast path to zero it.
if (regexp->lookupPure(cx->names().lastIndex)->writable()) {
regexp->zeroLastIndex(cx);
} else {
RootedValue zero(cx, Int32Value(0));
if (!SetProperty(cx, regexp, cx->names().lastIndex, zero)) {
return false;
}
}
args.rval().setObject(*regexp);
return true;
}
static bool
regexp_compile(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
/* Steps 1-2. */
return CallNonGenericMethod<IsRegExpObject, regexp_compile_impl>(cx, args);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1.
*/
bool
js::regexp_construct(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Steps 1.
bool patternIsRegExp;
if (!IsRegExp(cx, args.get(0), &patternIsRegExp)) {
return false;
}
// We can delay step 3 and step 4a until later, during
// GetPrototypeFromBuiltinConstructor calls. Accessing the new.target
// and the callee from the stack is unobservable.
if (!args.isConstructing()) {
// Step 3.b.
if (patternIsRegExp && !args.hasDefined(1)) {
RootedObject patternObj(cx, &args[0].toObject());
// Step 3.b.i.
RootedValue patternConstructor(cx);
if (!GetProperty(cx, patternObj, patternObj, cx->names().constructor, &patternConstructor)) {
return false;
}
// Step 3.b.ii.
if (patternConstructor.isObject() && patternConstructor.toObject() == args.callee()) {
args.rval().set(args[0]);
return true;
}
}
}
RootedValue patternValue(cx, args.get(0));
// Step 4.
ESClass cls;
if (!GetClassOfValue(cx, patternValue, &cls)) {
return false;
}
if (cls == ESClass::RegExp) {
// Beware! |patternObj| might be a proxy into another compartment, so
// don't assume |patternObj.is<RegExpObject>()|.
RootedObject patternObj(cx, &patternValue.toObject());
RootedAtom sourceAtom(cx);
RegExpFlag flags;
RootedRegExpShared shared(cx);
{
// Step 4.a.
shared = RegExpToShared(cx, patternObj);
if (!shared) {
return false;
}
sourceAtom = shared->getSource();
// Step 4.b.
// Get original flags in all cases, to compare with passed flags.
flags = shared->getFlags();
// If the RegExpShared is in another Zone, don't reuse it.
if (cx->zone() != shared->zone()) {
shared = nullptr;
}
}
// Step 7.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) {
return false;
}
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
if (!regexp) {
return false;
}
// Step 8.
if (args.hasDefined(1)) {
// Step 4.c / 21.2.3.2.2 RegExpInitialize step 4.
RegExpFlag flagsArg = RegExpFlag(0);
RootedString flagStr(cx, ToString<CanGC>(cx, args[1]));
if (!flagStr) {
return false;
}
if (!ParseRegExpFlags(cx, flagStr, &flagsArg)) {
return false;
}
// Don't reuse the RegExpShared if we have different flags.
if (flags != flagsArg) {
shared = nullptr;
}
if (!(flags & UnicodeFlag) && flagsArg & UnicodeFlag) {
// Have to check syntax again when adding 'u' flag.
// ES 2017 draft rev 9b49a888e9dfe2667008a01b2754c3662059ae56
// 21.2.3.2.2 step 7.
shared = CheckPatternSyntax(cx, sourceAtom, flagsArg);
if (!shared) {
return false;
}
}
flags = flagsArg;
}
regexp->initAndZeroLastIndex(sourceAtom, flags, cx);
if (shared) {
regexp->setShared(*shared);
}
args.rval().setObject(*regexp);
return true;
}
RootedValue P(cx);
RootedValue F(cx);
// Step 5.
if (patternIsRegExp) {
RootedObject patternObj(cx, &patternValue.toObject());
// Step 5.a.
if (!GetProperty(cx, patternObj, patternObj, cx->names().source, &P)) {
return false;
}
// Step 5.b.
F = args.get(1);
if (F.isUndefined()) {
if (!GetProperty(cx, patternObj, patternObj, cx->names().flags, &F)) {
return false;
}
}
} else {
// Steps 6.a-b.
P = patternValue;
F = args.get(1);
}
// Step 7.
RootedObject proto(cx);
if (!GetPrototypeFromBuiltinConstructor(cx, args, &proto)) {
return false;
}
Rooted<RegExpObject*> regexp(cx, RegExpAlloc(cx, GenericObject, proto));
if (!regexp) {
return false;
}
// Step 8.
if (!RegExpInitializeIgnoringLastIndex(cx, regexp, P, F)) {
return false;
}
regexp->zeroLastIndex(cx);
args.rval().setObject(*regexp);
return true;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.3.1
* steps 4, 7-8.
*/
bool
js::regexp_construct_raw_flags(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
MOZ_ASSERT(!args.isConstructing());
// Step 4.a.
RootedAtom sourceAtom(cx, AtomizeString(cx, args[0].toString()));
if (!sourceAtom) {
return false;
}
// Step 4.c.
int32_t flags = int32_t(args[1].toNumber());
// Step 7.
RegExpObject* regexp = RegExpAlloc(cx, GenericObject);
if (!regexp) {
return false;
}
// Step 8.
regexp->initAndZeroLastIndex(sourceAtom, RegExpFlag(flags), cx);
args.rval().setObject(*regexp);
return true;
}
MOZ_ALWAYS_INLINE bool
IsRegExpPrototype(HandleValue v)
{
if (IsRegExpObject(v) || !v.isObject()) {
return false;
}
// Note: The prototype shares its JSClass with instances.
return StandardProtoKeyOrNull(&v.toObject()) == JSProto_RegExp;
}
// ES 2017 draft 21.2.5.4.
MOZ_ALWAYS_INLINE bool
regexp_global_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->global());
return true;
}
bool
js::regexp_global(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_global_impl>(cx, args);
}
// ES 2017 draft 21.2.5.5.
MOZ_ALWAYS_INLINE bool
regexp_ignoreCase_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->ignoreCase());
return true;
}
bool
js::regexp_ignoreCase(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_ignoreCase_impl>(cx, args);
}
// ES 2017 draft 21.2.5.7.
MOZ_ALWAYS_INLINE bool
regexp_multiline_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->multiline());
return true;
}
bool
js::regexp_multiline(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_multiline_impl>(cx, args);
}
// ES 2017 draft 21.2.5.10.
MOZ_ALWAYS_INLINE bool
regexp_source_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Step 5.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
RootedAtom src(cx, reObj->getSource());
if (!src) {
return false;
}
// Step 7.
JSString* str = EscapeRegExpPattern(cx, src);
if (!str) {
return false;
}
args.rval().setString(str);
return true;
}
static bool
regexp_source(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setString(cx->names().emptyRegExp);
return true;
}
// Steps 1-4.
return CallNonGenericMethod<IsRegExpObject, regexp_source_impl>(cx, args);
}
// ES 2017 draft 21.2.5.12.
MOZ_ALWAYS_INLINE bool
regexp_sticky_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->sticky());
return true;
}
bool
js::regexp_sticky(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_sticky_impl>(cx, args);
}
// ES 2017 draft 21.2.5.15.
MOZ_ALWAYS_INLINE bool
regexp_unicode_impl(JSContext* cx, const CallArgs& args)
{
MOZ_ASSERT(IsRegExpObject(args.thisv()));
// Steps 4-6.
RegExpObject* reObj = &args.thisv().toObject().as<RegExpObject>();
args.rval().setBoolean(reObj->unicode());
return true;
}
bool
js::regexp_unicode(JSContext* cx, unsigned argc, JS::Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
// Step 3.a.
if (IsRegExpPrototype(args.thisv())) {
args.rval().setUndefined();
return true;
}
// Steps 1-3.
return CallNonGenericMethod<IsRegExpObject, regexp_unicode_impl>(cx, args);
}
const JSPropertySpec js::regexp_properties[] = {
JS_SELF_HOSTED_GET("flags", "RegExpFlagsGetter", 0),
JS_PSG("global", regexp_global, 0),
JS_PSG("ignoreCase", regexp_ignoreCase, 0),
JS_PSG("multiline", regexp_multiline, 0),
JS_PSG("source", regexp_source, 0),
JS_PSG("sticky", regexp_sticky, 0),
JS_PSG("unicode", regexp_unicode, 0),
JS_PS_END
};
const JSFunctionSpec js::regexp_methods[] = {
JS_SELF_HOSTED_FN(js_toSource_str, "RegExpToString", 0, 0),
JS_SELF_HOSTED_FN(js_toString_str, "RegExpToString", 0, 0),
JS_FN("compile", regexp_compile, 2,0),
JS_SELF_HOSTED_FN("exec", "RegExp_prototype_Exec", 1,0),
JS_SELF_HOSTED_FN("test", "RegExpTest" , 1,0),
JS_SELF_HOSTED_SYM_FN(match, "RegExpMatch", 1,0),
JS_SELF_HOSTED_SYM_FN(replace, "RegExpReplace", 2,0),
JS_SELF_HOSTED_SYM_FN(search, "RegExpSearch", 1,0),
JS_SELF_HOSTED_SYM_FN(split, "RegExpSplit", 2,0),
JS_FS_END
};
#define STATIC_PAREN_GETTER_CODE(parenNum) \
if (!res->createParen(cx, parenNum, args.rval())) \
return false; \
if (args.rval().isUndefined()) \
args.rval().setString(cx->runtime()->emptyString); \
return true
/*
* RegExp static properties.
*
* RegExp class static properties and their Perl counterparts:
*
* RegExp.input $_
* RegExp.lastMatch $&
* RegExp.lastParen $+
* RegExp.leftContext $`
* RegExp.rightContext $'
*/
#define DEFINE_STATIC_GETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
CallArgs args = CallArgsFromVp(argc, vp); \
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
if (!res) \
return false; \
code; \
}
DEFINE_STATIC_GETTER(static_input_getter, return res->createPendingInput(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastMatch_getter, return res->createLastMatch(cx, args.rval()))
DEFINE_STATIC_GETTER(static_lastParen_getter, return res->createLastParen(cx, args.rval()))
DEFINE_STATIC_GETTER(static_leftContext_getter, return res->createLeftContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_rightContext_getter, return res->createRightContext(cx, args.rval()))
DEFINE_STATIC_GETTER(static_paren1_getter, STATIC_PAREN_GETTER_CODE(1))
DEFINE_STATIC_GETTER(static_paren2_getter, STATIC_PAREN_GETTER_CODE(2))
DEFINE_STATIC_GETTER(static_paren3_getter, STATIC_PAREN_GETTER_CODE(3))
DEFINE_STATIC_GETTER(static_paren4_getter, STATIC_PAREN_GETTER_CODE(4))
DEFINE_STATIC_GETTER(static_paren5_getter, STATIC_PAREN_GETTER_CODE(5))
DEFINE_STATIC_GETTER(static_paren6_getter, STATIC_PAREN_GETTER_CODE(6))
DEFINE_STATIC_GETTER(static_paren7_getter, STATIC_PAREN_GETTER_CODE(7))
DEFINE_STATIC_GETTER(static_paren8_getter, STATIC_PAREN_GETTER_CODE(8))
DEFINE_STATIC_GETTER(static_paren9_getter, STATIC_PAREN_GETTER_CODE(9))
#define DEFINE_STATIC_SETTER(name, code) \
static bool \
name(JSContext* cx, unsigned argc, Value* vp) \
{ \
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global()); \
if (!res) \
return false; \
code; \
return true; \
}
static bool
static_input_setter(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
if (!res) {
return false;
}
RootedString str(cx, ToString<CanGC>(cx, args.get(0)));
if (!str) {
return false;
}
res->setPendingInput(str);
args.rval().setString(str);
return true;
}
const JSPropertySpec js::regexp_static_props[] = {
JS_PSGS("input", static_input_getter, static_input_setter,
JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastMatch", static_lastMatch_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("lastParen", static_lastParen_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("leftContext", static_leftContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("rightContext", static_rightContext_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$1", static_paren1_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$2", static_paren2_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$3", static_paren3_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$4", static_paren4_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$5", static_paren5_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$6", static_paren6_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$7", static_paren7_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$8", static_paren8_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSG("$9", static_paren9_getter, JSPROP_PERMANENT | JSPROP_ENUMERATE),
JS_PSGS("$_", static_input_getter, static_input_setter, JSPROP_PERMANENT),
JS_PSG("$&", static_lastMatch_getter, JSPROP_PERMANENT),
JS_PSG("$+", static_lastParen_getter, JSPROP_PERMANENT),
JS_PSG("$`", static_leftContext_getter, JSPROP_PERMANENT),
JS_PSG("$'", static_rightContext_getter, JSPROP_PERMANENT),
JS_SELF_HOSTED_SYM_GET(species, "RegExpSpecies", 0),
JS_PS_END
};
template <typename CharT>
static bool
IsTrailSurrogateWithLeadSurrogateImpl(HandleLinearString input, size_t index)
{
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(index > 0 && index < input->length());
const CharT* inputChars = input->chars<CharT>(nogc);
return unicode::IsTrailSurrogate(inputChars[index]) &&
unicode::IsLeadSurrogate(inputChars[index - 1]);
}
static bool
IsTrailSurrogateWithLeadSurrogate(HandleLinearString input, int32_t index)
{
if (index <= 0 || size_t(index) >= input->length()) {
return false;
}
return input->hasLatin1Chars()
? IsTrailSurrogateWithLeadSurrogateImpl<Latin1Char>(input, index)
: IsTrailSurrogateWithLeadSurrogateImpl<char16_t>(input, index);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
static RegExpRunStatus
ExecuteRegExp(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
VectorMatchPairs* matches, size_t* endIndex)
{
/*
* WARNING: Despite the presence of spec step comment numbers, this
* algorithm isn't consistent with any ES6 version, draft or
* otherwise. YOU HAVE BEEN WARNED.
*/
/* Steps 1-2 performed by the caller. */
Handle<RegExpObject*> reobj = regexp.as<RegExpObject>();
RootedRegExpShared re(cx, RegExpObject::getShared(cx, reobj));
if (!re) {
return RegExpRunStatus_Error;
}
RegExpStatics* res = GlobalObject::getRegExpStatics(cx, cx->global());
if (!res) {
return RegExpRunStatus_Error;
}
RootedLinearString input(cx, string->ensureLinear(cx));
if (!input) {
return RegExpRunStatus_Error;
}
/* Handled by caller */
MOZ_ASSERT(lastIndex >= 0 && size_t(lastIndex) <= input->length());
/* Steps 4-8 performed by the caller. */
/* Step 10. */
if (reobj->unicode()) {
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad
* 21.2.2.2 step 2.
* Let listIndex be the index into Input of the character that was
* obtained from element index of str.
*
* In the spec, pattern match is performed with decoded Unicode code
* points, but our implementation performs it with UTF-16 encoded
* string. In step 2, we should decrement lastIndex (index) if it
* points the trail surrogate that has corresponding lead surrogate.
*
* var r = /\uD83D\uDC38/ug;
* r.lastIndex = 1;
* var str = "\uD83D\uDC38";
* var result = r.exec(str); // pattern match starts from index 0
* print(result.index); // prints 0
*
* Note: this doesn't match the current spec text and result in
* different values for `result.index` under certain conditions.
* However, the spec will change to match our implementation's
* behavior. See https://github.com/tc39/ecma262/issues/128.
*/
if (IsTrailSurrogateWithLeadSurrogate(input, lastIndex)) {
lastIndex--;
}
}
/* Steps 3, 11-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExpImpl(cx, res, &re, input, lastIndex, matches, endIndex);
if (status == RegExpRunStatus_Error) {
return RegExpRunStatus_Error;
}
/* Steps 12.a.i, 12.c.i.i, 15 are done by Self-hosted function. */
return status;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
static bool
RegExpMatcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
MutableHandleValue rval)
{
/* Execute regular expression and gather matches. */
VectorMatchPairs matches;
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr);
if (status == RegExpRunStatus_Error) {
return false;
}
/* Steps 12.a, 12.c. */
if (status == RegExpRunStatus_Success_NotFound) {
rval.setNull();
return true;
}
/* Steps 16-25 */
return CreateRegExpMatchResult(cx, string, matches, rval);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
bool
js::RegExpMatcher(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
return RegExpMatcherImpl(cx, regexp, string, lastIndex, args.rval());
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpMatcherRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t maybeLastIndex,
MatchPairs* maybeMatches, MutableHandleValue output)
{
// The MatchPairs will always be passed in, but RegExp execution was
// successful only if the pairs have actually been filled in.
if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) {
return CreateRegExpMatchResult(cx, input, *maybeMatches, output);
}
// |maybeLastIndex| only contains a valid value when the RegExp execution
// was not successful.
MOZ_ASSERT(maybeLastIndex >= 0);
return RegExpMatcherImpl(cx, regexp, input, maybeLastIndex, output);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
* This code is inlined in CodeGenerator.cpp generateRegExpSearcherStub,
* changes to this code need to get reflected in there too.
*/
static bool
RegExpSearcherImpl(JSContext* cx, HandleObject regexp, HandleString string, int32_t lastIndex,
int32_t* result)
{
/* Execute regular expression and gather matches. */
VectorMatchPairs matches;
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, &matches, nullptr);
if (status == RegExpRunStatus_Error) {
return false;
}
/* Steps 12.a, 12.c. */
if (status == RegExpRunStatus_Success_NotFound) {
*result = -1;
return true;
}
/* Steps 16-25 */
*result = CreateRegExpSearchResult(matches);
return true;
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-25, except 12.a.i, 12.c.i.1, 15.
*/
bool
js::RegExpSearcher(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-25, except 12.a.i, 12.c.i.1, 15. */
int32_t result = 0;
if (!RegExpSearcherImpl(cx, regexp, string, lastIndex, &result)) {
return false;
}
args.rval().setInt32(result);
return true;
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpSearcherRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t lastIndex, MatchPairs* maybeMatches, int32_t* result)
{
MOZ_ASSERT(lastIndex >= 0);
// The MatchPairs will always be passed in, but RegExp execution was
// successful only if the pairs have actually been filled in.
if (maybeMatches && maybeMatches->pairsRaw()[0] > MatchPair::NoMatch) {
*result = CreateRegExpSearchResult(*maybeMatches);
return true;
}
return RegExpSearcherImpl(cx, regexp, input, lastIndex, result);
}
/*
* ES 2017 draft rev 6a13789aa9e7c6de4e96b7d3e24d9e6eba6584ad 21.2.5.2.2
* steps 3, 9-14, except 12.a.i, 12.c.i.1.
*/
bool
js::RegExpTester(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 3);
MOZ_ASSERT(IsRegExpObject(args[0]));
MOZ_ASSERT(args[1].isString());
MOZ_ASSERT(args[2].isNumber());
RootedObject regexp(cx, &args[0].toObject());
RootedString string(cx, args[1].toString());
int32_t lastIndex;
MOZ_ALWAYS_TRUE(ToInt32(cx, args[2], &lastIndex));
/* Steps 3, 9-14, except 12.a.i, 12.c.i.1. */
size_t endIndex = 0;
RegExpRunStatus status = ExecuteRegExp(cx, regexp, string, lastIndex, nullptr, &endIndex);
if (status == RegExpRunStatus_Error) {
return false;
}
if (status == RegExpRunStatus_Success) {
MOZ_ASSERT(endIndex <= INT32_MAX);
args.rval().setInt32(int32_t(endIndex));
} else {
args.rval().setInt32(-1);
}
return true;
}
/*
* Separate interface for use by IonMonkey.
* This code cannot re-enter Ion code.
*/
bool
js::RegExpTesterRaw(JSContext* cx, HandleObject regexp, HandleString input,
int32_t lastIndex, int32_t* endIndex)
{
MOZ_ASSERT(lastIndex >= 0);
size_t endIndexTmp = 0;
RegExpRunStatus status = ExecuteRegExp(cx, regexp, input, lastIndex, nullptr, &endIndexTmp);
if (status == RegExpRunStatus_Success) {
MOZ_ASSERT(endIndexTmp <= INT32_MAX);
*endIndex = int32_t(endIndexTmp);
return true;
}
if (status == RegExpRunStatus_Success_NotFound) {
*endIndex = -1;
return true;
}
return false;
}
using CapturesVector = GCVector<Value, 4>;
struct JSSubString
{
JSLinearString* base = nullptr;
size_t offset = 0;
size_t length = 0;
JSSubString() = default;
void initEmpty(JSLinearString* base) {
this->base = base;
offset = length = 0;
}
void init(JSLinearString* base, size_t offset, size_t length) {
this->base = base;
this->offset = offset;
this->length = length;
}
};
static void
GetParen(JSLinearString* matched, const JS::Value& capture, JSSubString* out)
{
if (capture.isUndefined()) {
out->initEmpty(matched);
return;
}
JSLinearString& captureLinear = capture.toString()->asLinear();
out->init(&captureLinear, 0, captureLinear.length());
}
template <typename CharT>
static bool
InterpretDollar(JSLinearString* matched, JSLinearString* string, size_t position, size_t tailPos,
Handle<CapturesVector> captures, JSLinearString* replacement,
const CharT* replacementBegin, const CharT* currentDollar,
const CharT* replacementEnd,
JSSubString* out, size_t* skip)
{
MOZ_ASSERT(*currentDollar == '$');
/* If there is only a dollar, bail now. */
if (currentDollar + 1 >= replacementEnd) {
return false;
}
/* ES 2016 draft Mar 25, 2016 Table 46. */
char16_t c = currentDollar[1];
if (IsAsciiDigit(c)) {
/* $n, $nn */
unsigned num = JS7_UNDEC(c);
if (num > captures.length()) {
// The result is implementation-defined, do not substitute.
return false;
}
const CharT* currentChar = currentDollar + 2;
if (currentChar < replacementEnd) {
c = *currentChar;
if (IsAsciiDigit(c)) {
unsigned tmpNum = 10 * num + JS7_UNDEC(c);
// If num > captures.length(), the result is implementation-defined.
// Consume next character only if num <= captures.length().
if (tmpNum <= captures.length()) {
currentChar++;
num = tmpNum;
}
}
}
if (num == 0) {
// The result is implementation-defined.
// Do not substitute.
return false;
}
*skip = currentChar - currentDollar;
MOZ_ASSERT(num <= captures.length());
GetParen(matched, captures[num -1], out);
return true;
}
*skip = 2;
switch (c) {
default:
return false;
case '$':
out->init(replacement, currentDollar - replacementBegin, 1);
break;
case '&':
out->init(matched, 0, matched->length());
break;
case '+':
// SpiderMonkey extension
if (captures.length() == 0) {
out->initEmpty(matched);
} else {
GetParen(matched, captures[captures.length() - 1], out);
}
break;
case '`':
out->init(string, 0, position);
break;
case '\'':
out->init(string, tailPos, string->length() - tailPos);
break;
}
return true;
}
template <typename CharT>
static bool
FindReplaceLengthString(JSContext* cx, HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep)
{
CheckedInt<uint32_t> replen = replacement->length();
JS::AutoCheckCannotGC nogc;
MOZ_ASSERT(firstDollarIndex < replacement->length());
const CharT* replacementBegin = replacement->chars<CharT>(nogc);
const CharT* currentDollar = replacementBegin + firstDollarIndex;
const CharT* replacementEnd = replacementBegin + replacement->length();
do {
JSSubString sub;
size_t skip;
if (InterpretDollar(matched, string, position, tailPos, captures, replacement,
replacementBegin, currentDollar, replacementEnd, &sub, &skip))
{
if (sub.length > skip) {
replen += sub.length - skip;
} else {
replen -= skip - sub.length;
}
currentDollar += skip;
} else {
currentDollar++;
}
currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
} while (currentDollar);
if (!replen.isValid()) {
ReportAllocationOverflow(cx);
return false;
}
*sizep = replen.value();
return true;
}
static bool
FindReplaceLength(JSContext* cx, HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, size_t* sizep)
{
return replacement->hasLatin1Chars()
? FindReplaceLengthString<Latin1Char>(cx, matched, string, position, tailPos, captures,
replacement, firstDollarIndex, sizep)
: FindReplaceLengthString<char16_t>(cx, matched, string, position, tailPos, captures,
replacement, firstDollarIndex, sizep);
}
/*
* Precondition: |sb| already has necessary growth space reserved (as
* derived from FindReplaceLength), and has been inflated to TwoByte if
* necessary.
*/
template <typename CharT>
static void
DoReplace(HandleLinearString matched, HandleLinearString string,
size_t position, size_t tailPos, Handle<CapturesVector> captures,
HandleLinearString replacement, size_t firstDollarIndex, StringBuffer &sb)
{
JS::AutoCheckCannotGC nogc;
const CharT* replacementBegin = replacement->chars<CharT>(nogc);
const CharT* currentChar = replacementBegin;
MOZ_ASSERT(firstDollarIndex < replacement->length());
const CharT* currentDollar = replacementBegin + firstDollarIndex;
const CharT* replacementEnd = replacementBegin + replacement->length();
do {
/* Move one of the constant portions of the replacement value. */
size_t len = currentDollar - currentChar;
sb.infallibleAppend(currentChar, len);
currentChar = currentDollar;
JSSubString sub;
size_t skip;
if (InterpretDollar(matched, string, position, tailPos, captures, replacement,
replacementBegin, currentDollar, replacementEnd, &sub, &skip))
{
sb.infallibleAppendSubstring(sub.base, sub.offset, sub.length);
currentChar += skip;
currentDollar += skip;
} else {
currentDollar++;
}
currentDollar = js_strchr_limit(currentDollar, '$', replacementEnd);
} while (currentDollar);
sb.infallibleAppend(currentChar, replacement->length() - (currentChar - replacementBegin));
}
static bool
NeedTwoBytes(HandleLinearString string, HandleLinearString replacement,
HandleLinearString matched, Handle<CapturesVector> captures)
{
if (string->hasTwoByteChars()) {
return true;
}
if (replacement->hasTwoByteChars()) {
return true;
}
if (matched->hasTwoByteChars()) {
return true;
}
for (size_t i = 0, len = captures.length(); i < len; i++) {
const Value& capture = captures[i];
if (capture.isUndefined()) {
continue;
}
if (capture.toString()->hasTwoByteChars()) {
return true;
}
}
return false;
}
/* ES 2016 draft Mar 25, 2016 21.1.3.14.1. */
bool
js::RegExpGetSubstitution(JSContext* cx, HandleArrayObject matchResult, HandleLinearString string,
size_t position, HandleLinearString replacement,
size_t firstDollarIndex, MutableHandleValue rval)
{
MOZ_ASSERT(firstDollarIndex < replacement->length());
// Step 1 (skipped).
// Step 10 (reordered).
uint32_t matchResultLength = matchResult->length();
MOZ_ASSERT(matchResultLength > 0);
MOZ_ASSERT(matchResultLength == matchResult->getDenseInitializedLength());
const Value& matchedValue = matchResult->getDenseElement(0);
RootedLinearString matched(cx, matchedValue.toString()->ensureLinear(cx));
if (!matched) {
return false;
}
// Step 2.
size_t matchLength = matched->length();
// Steps 3-5 (skipped).
// Step 6.
MOZ_ASSERT(position <= string->length());
uint32_t nCaptures = matchResultLength - 1;
Rooted<CapturesVector> captures(cx, CapturesVector(cx));
if (!captures.reserve(nCaptures)) {
return false;
}
// Step 7.
for (uint32_t i = 1; i <= nCaptures; i++) {
const Value& capture = matchResult->getDenseElement(i);
if (capture.isUndefined()) {
captures.infallibleAppend(capture);
continue;
}
JSLinearString* captureLinear = capture.toString()->ensureLinear(cx);
if (!captureLinear) {
return false;
}
captures.infallibleAppend(StringValue(captureLinear));
}
// Step 8 (skipped).
// Step 9.
CheckedInt<uint32_t> checkedTailPos(0);
checkedTailPos += position;
checkedTailPos += matchLength;
if (!checkedTailPos.isValid()) {
ReportAllocationOverflow(cx);
return false;
}
uint32_t tailPos = checkedTailPos.value();
// Step 11.
size_t reserveLength;
if (!FindReplaceLength(cx, matched, string, position, tailPos, captures, replacement,
firstDollarIndex, &reserveLength))
{
return false;
}
StringBuffer result(cx);
if (NeedTwoBytes(string, replacement, matched, captures)) {
if (!result.ensureTwoByteChars()) {
return false;
}
}
if (!result.reserve(reserveLength)) {
return false;
}
if (replacement->hasLatin1Chars()) {
DoReplace<Latin1Char>(matched, string, position, tailPos, captures,
replacement, firstDollarIndex, result);
} else {
DoReplace<char16_t>(matched, string, position, tailPos, captures,
replacement, firstDollarIndex, result);
}
// Step 12.
JSString* resultString = result.finishString();
if (!resultString) {
return false;
}
rval.setString(resultString);
return true;
}
bool
js::GetFirstDollarIndex(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
JSString* str = args[0].toString();
// Should be handled in different path.
MOZ_ASSERT(str->length() != 0);
int32_t index = -1;
if (!GetFirstDollarIndexRaw(cx, str, &index)) {
return false;
}
args.rval().setInt32(index);
return true;
}
template <typename TextChar>
static MOZ_ALWAYS_INLINE int
GetFirstDollarIndexImpl(const TextChar* text, uint32_t textLen)
{
const TextChar* end = text + textLen;
for (const TextChar* c = text; c != end; ++c) {
if (*c == '$') {
return c - text;
}
}
return -1;
}
int32_t
js::GetFirstDollarIndexRawFlat(JSLinearString* text)
{
uint32_t len = text->length();
JS::AutoCheckCannotGC nogc;
if (text->hasLatin1Chars()) {
return GetFirstDollarIndexImpl(text->latin1Chars(nogc), len);
}
return GetFirstDollarIndexImpl(text->twoByteChars(nogc), len);
}
bool
js::GetFirstDollarIndexRaw(JSContext* cx, JSString* str, int32_t* index)
{
JSLinearString* text = str->ensureLinear(cx);
if (!text) {
return false;
}
*index = GetFirstDollarIndexRawFlat(text);
return true;
}
bool
js::RegExpPrototypeOptimizable(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
args.rval().setBoolean(RegExpPrototypeOptimizableRaw(cx, &args[0].toObject()));
return true;
}
bool
js::RegExpPrototypeOptimizableRaw(JSContext* cx, JSObject* proto)
{
AutoUnsafeCallWithABI unsafe;
AutoAssertNoPendingException aanpe(cx);
if (!proto->isNative()) {
return false;
}
NativeObject* nproto = static_cast<NativeObject*>(proto);
Shape* shape = cx->realm()->regExps.getOptimizableRegExpPrototypeShape();
if (shape == nproto->lastProperty()) {
return true;
}
JSFunction* flagsGetter;
if (!GetOwnGetterPure(cx, proto, NameToId(cx->names().flags), &flagsGetter)) {
return false;
}
if (!flagsGetter) {
return false;
}
if (!IsSelfHostedFunctionWithName(flagsGetter, cx->names().RegExpFlagsGetter)) {
return false;
}
JSNative globalGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().global), &globalGetter)) {
return false;
}
if (globalGetter != regexp_global) {
return false;
}
JSNative ignoreCaseGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().ignoreCase), &ignoreCaseGetter)) {
return false;
}
if (ignoreCaseGetter != regexp_ignoreCase) {
return false;
}
JSNative multilineGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().multiline), &multilineGetter)) {
return false;
}
if (multilineGetter != regexp_multiline) {
return false;
}
JSNative stickyGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().sticky), &stickyGetter)) {
return false;
}
if (stickyGetter != regexp_sticky) {
return false;
}
JSNative unicodeGetter;
if (!GetOwnNativeGetterPure(cx, proto, NameToId(cx->names().unicode), &unicodeGetter)) {
return false;
}
if (unicodeGetter != regexp_unicode) {
return false;
}
// Check if @@match, @@search, and exec are own data properties,
// those values should be tested in selfhosted JS.
bool has = false;
if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().match), &has)) {
return false;
}
if (!has) {
return false;
}
if (!HasOwnDataPropertyPure(cx, proto, SYMBOL_TO_JSID(cx->wellKnownSymbols().search), &has)) {
return false;
}
if (!has) {
return false;
}
if (!HasOwnDataPropertyPure(cx, proto, NameToId(cx->names().exec), &has)) {
return false;
}
if (!has) {
return false;
}
cx->realm()->regExps.setOptimizableRegExpPrototypeShape(nproto->lastProperty());
return true;
}
bool
js::RegExpInstanceOptimizable(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
args.rval().setBoolean(RegExpInstanceOptimizableRaw(cx, &args[0].toObject(),
&args[1].toObject()));
return true;
}
bool
js::RegExpInstanceOptimizableRaw(JSContext* cx, JSObject* obj, JSObject* proto)
{
AutoUnsafeCallWithABI unsafe;
AutoAssertNoPendingException aanpe(cx);
RegExpObject* rx = &obj->as<RegExpObject>();
Shape* shape = cx->realm()->regExps.getOptimizableRegExpInstanceShape();
if (shape == rx->lastProperty()) {
return true;
}
if (!rx->hasStaticPrototype()) {
return false;
}
if (rx->staticPrototype() != proto) {
return false;
}
if (!RegExpObject::isInitialShape(rx)) {
return false;
}
cx->realm()->regExps.setOptimizableRegExpInstanceShape(rx->lastProperty());
return true;
}
/*
* Pattern match the script to check if it is is indexing into a particular
* object, e.g. 'function(a) { return b[a]; }'. Avoid calling the script in
* such cases, which are used by javascript packers (particularly the popular
* Dean Edwards packer) to efficiently encode large scripts. We only handle the
* code patterns generated by such packers here.
*/
bool
js::intrinsic_GetElemBaseForLambda(JSContext* cx, unsigned argc, Value* vp)
{
// This can only be called from self-hosted code.
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 1);
JSObject& lambda = args[0].toObject();
args.rval().setUndefined();
if (!lambda.is<JSFunction>()) {
return true;
}
RootedFunction fun(cx, &lambda.as<JSFunction>());
if (!fun->isInterpreted() || fun->isClassConstructor()) {
return true;
}
JSScript* script = JSFunction::getOrCreateScript(cx, fun);
if (!script) {
return false;
}
jsbytecode* pc = script->code();
/*
* JSOP_GETALIASEDVAR tells us exactly where to find the base object 'b'.
* Rule out the (unlikely) possibility of a function with environment
* objects since it would make our environment walk off.
*/
if (JSOp(*pc) != JSOP_GETALIASEDVAR || fun->needsSomeEnvironmentObject()) {
return true;
}
EnvironmentCoordinate ec(pc);
EnvironmentObject* env = &fun->environment()->as<EnvironmentObject>();
for (unsigned i = 0; i < ec.hops(); ++i) {
env = &env->enclosingEnvironment().as<EnvironmentObject>();
}
Value b = env->aliasedBinding(ec);
pc += JSOP_GETALIASEDVAR_LENGTH;
/* Look for 'a' to be the lambda's first argument. */
if (JSOp(*pc) != JSOP_GETARG || GET_ARGNO(pc) != 0) {
return true;
}
pc += JSOP_GETARG_LENGTH;
/* 'b[a]' */
if (JSOp(*pc) != JSOP_GETELEM) {
return true;
}
pc += JSOP_GETELEM_LENGTH;
/* 'return b[a]' */
if (JSOp(*pc) != JSOP_RETURN) {
return true;
}
/* 'b' must behave like a normal object. */
if (!b.isObject()) {
return true;
}
JSObject& bobj = b.toObject();
const Class* clasp = bobj.getClass();
if (!clasp->isNative() || clasp->getOpsLookupProperty() || clasp->getOpsGetProperty()) {
return true;
}
args.rval().setObject(bobj);
return true;
}
/*
* Emulates `b[a]` property access, that is detected in GetElemBaseForLambda.
* It returns the property value only if the property is data property and the
* property value is a string. Otherwise it returns undefined.
*/
bool
js::intrinsic_GetStringDataProperty(JSContext* cx, unsigned argc, Value* vp)
{
CallArgs args = CallArgsFromVp(argc, vp);
MOZ_ASSERT(args.length() == 2);
RootedObject obj(cx, &args[0].toObject());
if (!obj->isNative()) {
// The object is already checked to be native in GetElemBaseForLambda,
// but it can be swapped to another class that is non-native.
// Return undefined to mark failure to get the property.
args.rval().setUndefined();
return true;
}
JSAtom* atom = AtomizeString(cx, args[1].toString());
if (!atom) {
return false;
}
Value v;
if (GetPropertyPure(cx, obj, AtomToId(atom), &v) && v.isString()) {
args.rval().set(v);
} else {
args.rval().setUndefined();
}
return true;
}
| 57,609 | 19,674 |
#include "common.h"
#include "LoadVehicle.h"
#include "PassengerVehicle.h"
#include "EmergencyEquipment.h"
#include "EmergecyVehicle.h"
#include "Decision.h"
#include <list>
using namespace std;
// temparorily commented.
/*
int main() {
// the vehicle list.
Decision::VehicleList vehicleList;
// create Vehicles.
LoadVehicle * lv1 = new LoadVehicle ( "load1" );
vehicleList.push_back ( lv1 );
PassengerVehicle * pv1 = new PassengerVehicle ( "passenger1" );
vehicleList.push_back ( pv1 );
EmergecyVehicle * ev1 = new EmergecyVehicle ( "emergency1", "super", "buaa", 101 );
vehicleList.push_back ( ev1 );
// create Decison object.
Decision decision ( vehicleList );
pc ("part 1");
decision.printVehiclesSpecifications();
cr;
pc ("part 2");
decision.printEmergencyVehicles();
cr;
pc ("part 3");
ps ( decision.numberLongDistanceEmergencyVehicles() );
cr;
pc ("part 4");
ps ( decision.numBeds() );
cr;
pc ("part 5");
ps ( decision.numPassengers() );
cr;
// clear...
delete lv1;
delete pv1;
delete ev1;
return 0;
}
*/
| 1,059 | 440 |
#include "FileView.h"
#include <wx/stc/stc.h>
#include <wx/textfile.h>
enum {
MARGIN_LINE_NUMBERS
};
static wxString keywordsList;
static bool keywordsLoaded=false;
// rgb_bkgrnd=RGB( 0x22,0x55,0x88 );
// rgb_string=RGB( 0x00,0xff,0x66 );
// rgb_ident=RGB( 0xff,0xff,0xff );
// rgb_keyword=RGB( 0xaa,0xff,0xff );
// rgb_comment=RGB( 0xff,0xee,0x00 );
// rgb_digit=RGB( 0x33,0xff,0xdd );
// rgb_default=RGB( 0xee,0xee,0xee );
extern wxString blitzpath;
void FileView::LoadKeywords(){
if (!keywordsLoaded) {
wxArrayString keywords;
wxExecute( blitzpath + "/bin/blitzcc -k",keywords );
keywordsList = "";
wxArrayString::iterator it;
for( it=keywords.begin();it<keywords.end();it++ ){
keywordsList << " " << (*it).Lower();
}
keywordsLoaded = true;
}
}
FileView::FileView( wxString &path,wxWindow *parent,wxWindowID id ):path(path),wxPanel( parent,id ){
LoadKeywords();
// Inconsolata, Monaco, Consolas, 'Courier New', Courier
wxFont font;
#ifdef __WXMSW__
font = wxFontInfo(12).FaceName("Consolas");
#else
font = wxFontInfo(12).FaceName("Monaco");
#endif
wxStyledTextCtrl* text = new wxStyledTextCtrl(this, wxID_ANY);
if ( path.length()>0 ){
wxTextFile file;
file.Open( path );
source.Clear();
while( !file.Eof() ) {
source.Append( file.GetNextLine() );
source.Append( "\n" );
}
file.Close();
text->SetText( source );
}
text->StyleSetBackground( wxSTC_STYLE_DEFAULT, wxColour( 0x22,0x55,0x88 ) );
text->StyleSetForeground( wxSTC_STYLE_DEFAULT, wxColour( 0xee,0xee,0xee ) );
// text->StyleClearAll();
text->SetMarginWidth (MARGIN_LINE_NUMBERS, 25);
text->SetCaretForeground( wxColour( 0xff,0xff,0xff ) );
text->SetCaretLineBackground( wxColour( 0x1e,0x4a,0x76 ) );
text->SetCaretLineVisible( true );
text->SetMarginType(MARGIN_LINE_NUMBERS, wxSTC_MARGIN_NUMBER);
text->SetLexer(wxSTC_LEX_BLITZBASIC);
text->StyleSetFont( wxSTC_STYLE_DEFAULT,font );
text->StyleSetForeground( wxSTC_STYLE_LINENUMBER, wxColour (0xee,0xee,0xee) );
text->StyleSetBackground( wxSTC_STYLE_LINENUMBER, wxColour (0x1e,0x4a,0x76) );
text->StyleSetBackground( wxSTC_B_DEFAULT, wxColour( 0x22,0x55,0x88 ) );
text->StyleSetForeground( wxSTC_B_DEFAULT, wxColour( 0xee,0xee,0xee ) );
text->StyleSetBackground( wxSTC_B_STRING, wxColour( 0x22,0x55,0x88 ) );
text->StyleSetForeground( wxSTC_B_STRING, wxColour( 0x00,0xff,0x66 ) );
text->StyleSetForeground( wxSTC_B_COMMENT, wxColour( 0xff,0xee,0x00 ) );
text->StyleSetForeground( wxSTC_B_KEYWORD, wxColour( 0xaa,0xff,0xff ) );
text->StyleSetForeground( wxSTC_B_NUMBER, wxColour( 0x33,0xff,0xdd ) );
text->SetKeyWords(0, keywordsList);
wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
sizer->Add( text,1,wxEXPAND,0 );
SetSizer( sizer );
}
bool FileView::Save(){
wxTextFile file( path );
file.Open();
file.AddLine( source );
file.Write();
file.Close();
return true;
}
| 2,965 | 1,318 |
/*
// Copyright (c) 2018 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#include "id_button.hpp"
#include "power_button.hpp"
#include "reset_button.hpp"
int main(int argc, char* argv[])
{
int ret = 0;
phosphor::logging::log<phosphor::logging::level::INFO>(
"Start power button service...");
sd_event* event = nullptr;
ret = sd_event_default(&event);
if (ret < 0)
{
phosphor::logging::log<phosphor::logging::level::ERR>(
"Error creating a default sd_event handler");
return ret;
}
EventPtr eventP{event};
event = nullptr;
sdbusplus::bus::bus bus = sdbusplus::bus::new_default();
sdbusplus::server::manager::manager objManager{
bus, "/xyz/openbmc_project/Chassis/Buttons"};
bus.request_name("xyz.openbmc_project.Chassis.Buttons");
std::unique_ptr<PowerButton> pb;
if (hasGpio<PowerButton>())
{
pb = std::make_unique<PowerButton>(bus, POWER_DBUS_OBJECT_NAME, eventP);
}
std::unique_ptr<ResetButton> rb;
if (hasGpio<ResetButton>())
{
rb = std::make_unique<ResetButton>(bus, RESET_DBUS_OBJECT_NAME, eventP);
}
std::unique_ptr<IDButton> ib;
if (hasGpio<IDButton>())
{
ib = std::make_unique<IDButton>(bus, ID_DBUS_OBJECT_NAME, eventP);
}
try
{
bus.attach_event(eventP.get(), SD_EVENT_PRIORITY_NORMAL);
ret = sd_event_loop(eventP.get());
if (ret < 0)
{
phosphor::logging::log<phosphor::logging::level::ERR>(
"Error occurred during the sd_event_loop",
phosphor::logging::entry("RET=%d", ret));
}
}
catch (std::exception& e)
{
phosphor::logging::log<phosphor::logging::level::ERR>(e.what());
ret = -1;
}
return ret;
}
| 2,343 | 795 |
#include "mex.h"
#include <string.h> // for memset
/*
* Choose variables for coarse grid
* Greedy algorithm
*
* After selection,
*
* \sum_{j\in coarse} c_ij > beta \sum_j c_ij for all i
*
* Starting with an empty coarse set, we sequentially add variables from fine
* That their \sum_{j\in coarse} c_ij (to current estimate of coarse)
* is smaller than: beta \sum_ij c_ij
*
* Usage
* c = ChooseCoarseGreedy_mex(nC, ord, beta)
*
* Inputs
* nC - sparse, n x n matrix, with nC_ij = c_ij / (sum_j c_ij)
* ord - n elements vector of indices,
* indicates the order at which the fine variables should be
* considered in the greedy algorithm.
* beta - scalar 0 < beta < 1 governing the coarsening rate (usually 0.2)
*
* Output
* c - n element indicator vector for the chosen coarse variables
*
* To compile:
* >> mex -largeArrayDims -O ChooseCoarseGreedy_mex.cpp
*
*/
#line __LINE__ "AdjustPdeg"
#define STR(s) #s
#define ERR_CODE(a,b) a ":" "line_" STR(b)
// INPUTS
enum {
iC = 0,
iO,
iB,
nI
};
// OUTPUTS
enum {
oC = 0,
nO
};
void
mexFunction(
int nout,
mxArray* pout[],
int nin,
const mxArray* pin[])
{
if ( nin != nI )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"must have %d inputs", nI);
if (nout==0)
return;
if (nout != nO )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"must have exactly %d output", nO);
if ( mxIsComplex(pin[iC]) || !mxIsSparse(pin[iC]) ||
! mxIsDouble(pin[iC]) || mxGetNumberOfDimensions(pin[iC]) != 2 )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"nC must be a sparse double matrix");
mwSize n = mxGetM(pin[iC]);
if ( mxGetN(pin[iC]) != n )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"nC must be a square matrix");
if ( mxIsComplex(pin[iO]) || mxIsSparse(pin[iO]) ||
! mxIsDouble(pin[iO]) || mxGetNumberOfElements(pin[iO]) != n )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"ord must be a double vector with %d elements", n);
if ( mxGetNumberOfElements(pin[iB]) != 1 )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"beta must be a scalar");
double beta = mxGetScalar(pin[iB]);
if ( beta <= 0 || beta >= 1 )
mexErrMsgIdAndTxt(ERR_CODE(__FILE__, __LINE__),"beta must be in the range (0,1)");
// allocate space for sum_jc
double* sum_jc = new double[n];
memset(sum_jc, 0, n*sizeof(double));
// allocate space for indicator vector c
pout[oC] = mxCreateLogicalMatrix(1, n);
mxLogical* c = mxGetLogicals(pout[oC]);
double* pr = mxGetPr(pin[iC]);
mwIndex* pir = mxGetIr(pin[iC]);
mwIndex* pjc = mxGetJc(pin[iC]);
double* ord = mxGetPr(pin[iO]);
for ( mwIndex ii(0); ii < n ; ii++ ) {
mwIndex current = static_cast<mwIndex>(ord[ii])-1; // convert from matlab's 1-based indexing to 0-based indexing
mxAssert( current >= 0 && current < n, "order contains out of range indices");
if ( sum_jc[current] <= beta ) {
// we need to add current to coarse
c[current] = true;
// update sum_jc accordingly
for ( mwIndex jj = pjc[current] ; jj < pjc[current+1] ; jj++ ) {
mwIndex row = pir[jj];
sum_jc[row] += pr[jj];
}
}
}
delete[] sum_jc;
}
| 3,568 | 1,340 |
#ifndef PYTHONIC_NUMPY_TRANSPOSE_HPP
#define PYTHONIC_NUMPY_TRANSPOSE_HPP
#include "pythonic/utils/proxy.hpp"
#include "pythonic/utils/numpy_conversion.hpp"
#include "pythonic/utils/nested_container.hpp"
#include "pythonic/types/ndarray.hpp"
#include "pythonic/types/numpy_type.hpp"
#include "pythonic/__builtin__/ValueError.hpp"
namespace pythonic {
namespace numpy {
template<class T>
types::numpy_texpr<types::ndarray<T, 2>>
transpose(types::ndarray<T, 2> const& arr) {
return types::numpy_texpr<types::ndarray<T, 2>>(arr);
}
template<class T, unsigned long N, class... C>
types::ndarray<T,N> _transpose(types::ndarray<T,N> const & a, long const l[N])
{
auto shape = a.shape;
types::array<long, N> shp;
for(unsigned long i=0; i<N; ++i)
shp[i] = shape[l[i]];
types::ndarray<T,N> new_array(shp, __builtin__::None);
types::array<long, N> new_strides;
new_strides[N-1] = 1;
std::transform(new_strides.rbegin(), new_strides.rend() -1, shp.rbegin(), new_strides.rbegin() + 1, std::multiplies<long>());
types::array<long, N> old_strides;
old_strides[N-1] = 1;
std::transform(old_strides.rbegin(), old_strides.rend() -1, shape.rbegin(), old_strides.rbegin() + 1, std::multiplies<long>());
auto iter = a.buffer,
iter_end = a.buffer + a.flat_size();
for(long i=0; iter!=iter_end; ++iter, ++i) {
long offset = 0;
for(unsigned long s=0; s<N; s++)
offset += ((i/old_strides[l[s]]) % shape[l[s]])*new_strides[s];
new_array.buffer[offset] = *iter;
}
return new_array;
}
template<class T, size_t N>
types::ndarray<T,N> transpose(types::ndarray<T,N> const & a)
{
long t[N];
for(unsigned long i = 0; i<N; ++i)
t[N-1-i] = i;
return _transpose(a, t);
}
template<class T, size_t N, size_t M>
types::ndarray<T,N> transpose(types::ndarray<T,N> const & a, types::array<long, M> const& t)
{
static_assert(N==M, "axes don't match array");
long val = t[M-1];
if(val>=long(N))
throw types::ValueError("invalid axis for this array");
return _transpose(a, &t[0]);
}
NUMPY_EXPR_TO_NDARRAY0(transpose);
PROXY(pythonic::numpy, transpose);
}
}
#endif
| 2,754 | 923 |
#include "DataFormats/EcalDetId/interface/ESDetId.h"
#include "DataFormats/EcalDigi/interface/ESDataFrame.h"
#include "SimDataFormats/CaloHit/interface/PCaloHit.h"
#include "SimCalorimetry/CaloSimAlgos/interface/CaloHitResponse.h"
#include "SimCalorimetry/CaloSimAlgos/interface/CaloTDigitizer.h"
#include "SimCalorimetry/EcalSimAlgos/interface/EcalSimParameterMap.h"
#include "SimCalorimetry/EcalSimAlgos/interface/ESShape.h"
#include "SimCalorimetry/EcalSimAlgos/interface/EcalDigitizerTraits.h"
#include "SimCalorimetry/EcalSimAlgos/interface/ESElectronicsSim.h"
#include "SimDataFormats/CrossingFrame/interface/CrossingFrame.h"
#include <vector>
#include <iostream>
#include <iterator>
int main() {
// make a silly little hit in each subdetector, which should
// correspond to a 300 keV particle
ESDetId ESDetId(1, 1, 1, 1, 1);
PCaloHit ESHit(ESDetId.rawId(), 0.0003, 0.);
vector<DetId> ESDetIds;
ESDetIds.push_back(ESDetId);
vector<PCaloHit> ESHits;
ESHits.push_back(ESHit);
string ESName = "EcalHitsES";
edm::EventID id;
CrossingFrame<PCaloHit> crossingFrame(-5, 5, 25, ESName, 1);
crossingFrame.addSignals(&ESHits,id);
EcalSimParameterMap parameterMap;
ESShape shape(1);
CaloHitResponse ESResponse(¶meterMap, &shape);
ESElectronicsSim electronicsSim(true, 3, 1, 1000, 9, 78.47);
bool addNoise = false;
CaloTDigitizer<ESDigitizerTraits> ESDigitizer(&ESResponse, &electronicsSim, addNoise);
ESDigitizer.setDetIds(ESDetIds);
unique_ptr<ESDigiCollection> ESResult(new ESDigiCollection);
MixCollection<PCaloHit> ESHitCollection(&crossingFrame);
ESDigitizer.run(ESHitCollection, *ESResult);
// print out all the digis
cout << "ES Frames" << endl;
copy(ESResult->begin(), ESResult->end(), std::ostream_iterator<ESDataFrame>(std::cout, "\n"));
return 0;
}
| 1,828 | 733 |
/* Copyright (C) 2016-2017 INRA
*
* 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.
*/
#ifndef ORG_VLEPROJECT_EFYJ_MATRIX_HPP
#define ORG_VLEPROJECT_EFYJ_MATRIX_HPP
#include <algorithm>
#include <initializer_list>
#include <vector>
#include <cassert>
namespace efyj {
/**
* An \e matrix defined a two-dimensional template array. Informations are
* stored into a \e std::vector<T> by default.
*
* \tparam T Type of element
* \tparam Containre Type of container to store two-dimensional array.
*/
template<typename T, class Container = std::vector<T>>
class matrix
{
public:
using container_type = Container;
using value_type = T;
using reference = typename container_type::reference;
using const_reference = typename container_type::const_reference;
using iterator = typename container_type::iterator;
using const_iterator = typename container_type::const_iterator;
using reverse_iterator = typename container_type::reverse_iterator;
using const_reverse_iterator =
typename container_type::const_reverse_iterator;
using size_type = typename container_type::size_type;
protected:
container_type m_c;
size_type m_rows, m_columns;
public:
matrix();
explicit matrix(size_type rows, size_type cols);
explicit matrix(size_type rows, size_type cols, const value_type& value);
~matrix() = default;
matrix(const matrix& q) = default;
matrix(matrix&& q) = default;
matrix& operator=(const matrix& q) = default;
matrix& operator=(matrix&& q) = default;
void assign(std::initializer_list<value_type> list);
void resize(size_type rows, size_type cols);
void resize(size_type rows, size_type cols, const value_type& value);
iterator begin() noexcept;
const_iterator begin() const noexcept;
iterator end() noexcept;
const_iterator end() const noexcept;
reverse_iterator rbegin() noexcept;
const_reverse_iterator rbegin() const noexcept;
reverse_iterator rend() noexcept;
const_reverse_iterator rend() const noexcept;
const_iterator cbegin() const noexcept;
const_iterator cend() const noexcept;
const_reverse_iterator crbegin() const noexcept;
const_reverse_iterator crend() const noexcept;
bool empty() const noexcept;
size_type size() const noexcept;
size_type rows() const noexcept;
size_type columns() const noexcept;
void set(size_type row, size_type col, const value_type& x);
void set(size_type row, size_type col, value_type&& x);
template<class... Args>
void emplace(size_type row, size_type col, Args&&... args);
const_reference operator()(size_type row, size_type col) const;
reference operator()(size_type row, size_type col);
void swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c)));
void clear() noexcept;
private:
void m_check_index(size_type row, size_type col) const;
};
template<typename T, class Container>
matrix<T, Container>::matrix()
: m_c()
, m_rows(0)
, m_columns(0)
{}
template<typename T, class Container>
matrix<T, Container>::matrix(size_type rows, size_type columns)
: m_c(rows * columns)
, m_rows(rows)
, m_columns(columns)
{}
template<typename T, class Container>
matrix<T, Container>::matrix(size_type rows,
size_type columns,
const value_type& value)
: m_c(rows * columns, value)
, m_rows(rows)
, m_columns(columns)
{}
template<typename T, class Container>
void
matrix<T, Container>::assign(std::initializer_list<value_type> list)
{
m_c.assign(list.begin(), list.end());
}
template<typename T, class Container>
void
matrix<T, Container>::resize(size_type rows, size_type cols)
{
container_type new_c(rows * cols);
size_type rmin = std::min(rows, m_rows);
size_type cmin = std::min(cols, m_columns);
for (size_type r = 0; r != rmin; ++r)
for (size_type c = 0; c != cmin; ++c)
new_c[r * cols + c] = m_c[r * m_columns + c];
m_columns = cols;
m_rows = rows;
std::swap(new_c, m_c);
}
template<typename T, class Container>
void
matrix<T, Container>::resize(size_type rows,
size_type cols,
const value_type& value)
{
m_c.resize(rows * cols);
m_rows = rows;
m_columns = cols;
std::fill(m_c.begin(), m_c.end(), value);
}
template<typename T, class Container>
typename matrix<T, Container>::iterator
matrix<T, Container>::begin() noexcept
{
return m_c.begin();
}
template<typename T, class Container>
typename matrix<T, Container>::const_iterator
matrix<T, Container>::begin() const noexcept
{
return m_c.begin();
}
template<typename T, class Container>
typename matrix<T, Container>::iterator
matrix<T, Container>::end() noexcept
{
return m_c.end();
}
template<typename T, class Container>
typename matrix<T, Container>::const_iterator
matrix<T, Container>::end() const noexcept
{
return m_c.end();
}
template<typename T, class Container>
typename matrix<T, Container>::reverse_iterator
matrix<T, Container>::rbegin() noexcept
{
return m_c.rbegin();
}
template<typename T, class Container>
typename matrix<T, Container>::const_reverse_iterator
matrix<T, Container>::rbegin() const noexcept
{
return m_c.rbegin();
}
template<typename T, class Container>
typename matrix<T, Container>::reverse_iterator
matrix<T, Container>::rend() noexcept
{
return m_c.rend();
}
template<typename T, class Container>
typename matrix<T, Container>::const_reverse_iterator
matrix<T, Container>::rend() const noexcept
{
return m_c.rend();
}
template<typename T, class Container>
typename matrix<T, Container>::const_iterator
matrix<T, Container>::cbegin() const noexcept
{
return m_c.cbegin();
}
template<typename T, class Container>
typename matrix<T, Container>::const_iterator
matrix<T, Container>::cend() const noexcept
{
return m_c.cend();
}
template<typename T, class Container>
typename matrix<T, Container>::const_reverse_iterator
matrix<T, Container>::crbegin() const noexcept
{
return m_c.crbegin();
}
template<typename T, class Container>
typename matrix<T, Container>::const_reverse_iterator
matrix<T, Container>::crend() const noexcept
{
return m_c.crend();
}
template<typename T, class Container>
bool
matrix<T, Container>::empty() const noexcept
{
return m_c.empty();
}
template<typename T, class Container>
typename matrix<T, Container>::size_type
matrix<T, Container>::size() const noexcept
{
return m_c.size();
}
template<typename T, class Container>
typename matrix<T, Container>::size_type
matrix<T, Container>::rows() const noexcept
{
return m_rows;
}
template<typename T, class Container>
typename matrix<T, Container>::size_type
matrix<T, Container>::columns() const noexcept
{
return m_columns;
}
template<typename T, class Container>
void
matrix<T, Container>::set(size_type row, size_type column, const value_type& x)
{
m_check_index(row, column);
m_c[row * m_columns + column] = x;
}
template<typename T, class Container>
void
matrix<T, Container>::set(size_type row, size_type column, value_type&& x)
{
m_check_index(row, column);
m_c.emplace(m_c.begin() + (row * m_columns + column), std::move(x));
}
template<typename T, class Container>
template<class... Args>
void
matrix<T, Container>::emplace(size_type row, size_type column, Args&&... args)
{
m_check_index(row, column);
m_c.emplace(m_c.begin() + (row * m_columns + column),
std::forward<Args>(args)...);
}
template<typename T, class Container>
typename matrix<T, Container>::const_reference
matrix<T, Container>::operator()(size_type row, size_type column) const
{
m_check_index(row, column);
return m_c[row * m_columns + column];
}
template<typename T, class Container>
typename matrix<T, Container>::reference
matrix<T, Container>::operator()(size_type row, size_type column)
{
m_check_index(row, column);
return m_c[row * m_columns + column];
}
template<typename T, class Container>
void
matrix<T, Container>::swap(matrix& c) noexcept(noexcept(m_c.swap(c.m_c)))
{
std::swap(m_c, c.m_c);
std::swap(m_columns, c.m_columns);
std::swap(m_rows, c.m_rows);
}
template<typename T, class Container>
void
matrix<T, Container>::clear() noexcept
{
m_c.clear();
m_rows = 0;
m_columns = 0;
}
template<typename T, class Container>
void
matrix<T, Container>::m_check_index([[maybe_unused]] size_type row,
[[maybe_unused]] size_type column) const
{
assert(column < m_columns || row < m_rows);
}
}
#endif
| 9,636 | 3,096 |
/*
* This file belongs to the Galois project, a C++ library for exploiting parallelism.
* The code is being released under the terms of the 3-Clause BSD License (a
* copy is located in LICENSE.txt at the top-level directory).
*
* Copyright (C) 2018, The University of Texas at Austin. All rights reserved.
* UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS
* SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF
* PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF
* DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH
* RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances
* shall University be liable for incidental, special, indirect, direct or
* consequential damages or loss of profits, interruption of business, or
* related expenses which may arise from use of Software or Documentation,
* including but not limited to those resulting from defects in Software and/or
* Documentation, or loss or inaccuracy of data of any kind.
*/
#include <vector>
#include <set>
#include <map>
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <numeric>
#include <algorithm>
#include <cmath>
#include <fstream>
#include "Metis.h"
#include "galois/graphs/ReadGraph.h"
#include "galois/Timer.h"
//#include "GraphReader.h"
#include "Lonestar/BoilerPlate.h"
#include "galois/graphs/FileGraph.h"
#include "galois/LargeArray.h"
namespace cll = llvm::cl;
static const char* name = "GMetis";
static const char* desc =
"Partitions a graph into K parts and minimizing the graph cut";
static const char* url = "gMetis";
static cll::opt<InitialPartMode> partMode(
cll::desc("Choose a inital part mode:"),
cll::values(clEnumVal(GGP, "GGP"), clEnumVal(GGGP, "GGGP (default)"),
clEnumVal(MGGGP, "MGGGP")),
cll::init(GGGP));
static cll::opt<refinementMode> refineMode(
cll::desc("Choose a refinement mode:"),
cll::values(clEnumVal(BKL, "BKL"), clEnumVal(BKL2, "BKL2 (default)"),
clEnumVal(ROBO, "ROBO"), clEnumVal(GRACLUS, "GRACLUS")
),
cll::init(BKL2));
static cll::opt<bool>
mtxInput("mtxinput",
cll::desc("Use text mtx files instead of binary galois gr files"),
cll::init(false));
static cll::opt<bool> weighted("weighted", cll::desc("weighted"),
cll::init(false));
static cll::opt<bool>
verbose("verbose",
cll::desc("verbose output (debugging mode, takes extra time)"),
cll::init(false));
static cll::opt<std::string> outfile("output",
cll::desc("output partition file name"));
static cll::opt<std::string>
orderedfile("ordered", cll::desc("output ordered graph file name"));
static cll::opt<std::string>
permutationfile("permutation", cll::desc("output permutation file name"));
static cll::opt<std::string> filename(cll::Positional,
cll::desc("<input file>"), cll::Required);
static cll::opt<int> numPartitions(cll::Positional,
cll::desc("<Number of partitions>"),
cll::Required);
static cll::opt<double> imbalance(
"balance",
cll::desc("Fraction deviated from mean partition size (default 0.01)"),
cll::init(0.01));
// const double COARSEN_FRACTION = 0.9;
/**
* KMetis Algorithm
*/
void Partition(MetisGraph* metisGraph, unsigned nparts) {
galois::StatTimer TM;
TM.start();
unsigned fineMetisGraphWeight = metisGraph->getTotalWeight();
unsigned meanWeight = ((double)fineMetisGraphWeight) / (double)nparts;
// unsigned coarsenTo = std::max(metisGraph->getNumNodes() / (40 *
// intlog2(nparts)), 20 * (nparts));
unsigned coarsenTo = 20 * nparts;
if (verbose)
std::cout << "Starting coarsening: \n";
galois::StatTimer T("Coarsen");
T.start();
MetisGraph* mcg = coarsen(metisGraph, coarsenTo, verbose);
T.stop();
if (verbose)
std::cout << "Time coarsen: " << T.get() << "\n";
galois::StatTimer T2("Partition");
T2.start();
std::vector<partInfo> parts;
parts = partition(mcg, fineMetisGraphWeight, nparts, partMode);
T2.stop();
if (verbose)
std::cout << "Init edge cut : " << computeCut(*mcg->getGraph()) << "\n\n";
std::vector<partInfo> initParts = parts;
if (verbose)
std::cout << "Time clustering: " << T2.get() << '\n';
if (verbose) {
switch (refineMode) {
case BKL2:
std::cout << "Sorting refinnement with BKL2\n";
break;
case BKL:
std::cout << "Sorting refinnement with BKL\n";
break;
case ROBO:
std::cout << "Sorting refinnement with ROBO\n";
break;
case GRACLUS:
std::cout << "Sorting refinnement with GRACLUS\n";
break;
default:
abort();
}
}
galois::StatTimer T3("Refine");
T3.start();
refine(mcg, parts, meanWeight - (unsigned)(meanWeight * imbalance),
meanWeight + (unsigned)(meanWeight * imbalance), refineMode, verbose);
T3.stop();
if (verbose)
std::cout << "Time refinement: " << T3.get() << "\n";
TM.stop();
std::cout << "Initial dist\n";
printPartStats(initParts);
std::cout << "\n";
std::cout << "Refined dist\n";
printPartStats(parts);
std::cout << "\n";
std::cout << "Time: " << TM.get() << '\n';
return;
}
// printGraphBeg(*graph)
typedef galois::graphs::FileGraph FG;
typedef FG::GraphNode FN;
template <typename GNode, typename Weights>
struct order_by_degree {
GGraph& graph;
Weights& weights;
order_by_degree(GGraph& g, Weights& w) : graph(g), weights(w) {}
bool operator()(const GNode& a, const GNode& b) {
uint64_t wa = weights[a];
uint64_t wb = weights[b];
int pa = graph.getData(a, galois::MethodFlag::UNPROTECTED).getPart();
int pb = graph.getData(b, galois::MethodFlag::UNPROTECTED).getPart();
if (pa != pb) {
return pa < pb;
}
return wa < wb;
}
};
typedef galois::substrate::PerThreadStorage<std::map<GNode, uint64_t>>
PerThreadDegInfo;
int main(int argc, char** argv) {
galois::SharedMemSys G;
LonestarStart(argc, argv, name, desc, url);
srand(-1);
MetisGraph metisGraph;
GGraph& graph = *metisGraph.getGraph();
galois::graphs::readGraph(graph, filename);
galois::do_all(galois::iterate(graph),
[&](GNode node) {
for (auto jj : graph.edges(node)) {
graph.getEdgeData(jj) = 1;
// weight+=1;
}
},
galois::loopname("initMorphGraph"));
graphStat(graph);
std::cout << "\n";
galois::preAlloc(galois::runtime::numPagePoolAllocTotal() * 5);
galois::reportPageAlloc("MeminfoPre");
Partition(&metisGraph, numPartitions);
galois::reportPageAlloc("MeminfoPost");
std::cout << "Total edge cut: " << computeCut(graph) << "\n";
if (outfile != "") {
MetisGraph* coarseGraph = &metisGraph;
while (coarseGraph->getCoarserGraph())
coarseGraph = coarseGraph->getCoarserGraph();
std::ofstream outFile(outfile.c_str());
for (auto it = graph.begin(), ie = graph.end(); it != ie; it++) {
unsigned gPart = graph.getData(*it).getPart();
outFile << gPart << '\n';
}
}
if (orderedfile != "" || permutationfile != "") {
galois::graphs::FileGraph g;
g.fromFile(filename);
typedef galois::LargeArray<GNode> Permutation;
Permutation perm;
perm.create(g.size());
std::copy(graph.begin(), graph.end(), perm.begin());
PerThreadDegInfo threadDegInfo;
std::vector<int> parts(numPartitions);
for (unsigned int i = 0; i < parts.size(); i++) {
parts[i] = i;
}
using WL = galois::worklists::PerSocketChunkFIFO<16>;
galois::for_each(
galois::iterate(parts),
[&](int part, auto& lwl) {
constexpr auto flag = galois::MethodFlag::UNPROTECTED;
typedef std::vector<
std::pair<unsigned, GNode>,
galois::PerIterAllocTy::rebind<std::pair<unsigned, GNode>>::other>
GD;
// copy and translate all edges
GD orderedNodes(GD::allocator_type(lwl.getPerIterAlloc()));
for (auto n : graph) {
auto& nd = graph.getData(n, flag);
if (static_cast<int>(nd.getPart()) == part) {
int edges = std::distance(graph.edge_begin(n, flag),
graph.edge_end(n, flag));
orderedNodes.push_back(std::make_pair(edges, n));
}
}
std::sort(orderedNodes.begin(), orderedNodes.end());
int index = 0;
std::map<GNode, uint64_t>& threadMap(*threadDegInfo.getLocal());
for (auto p : orderedNodes) {
GNode n = p.second;
threadMap[n] += index;
for (auto eb : graph.edges(n, flag)) {
GNode neigh = graph.getEdgeDst(eb);
auto& nd = graph.getData(neigh, flag);
if (static_cast<int>(nd.getPart()) == part) {
threadMap[neigh] += index;
}
}
index++;
}
},
galois::wl<WL>(), galois::per_iter_alloc(),
galois::loopname("Order Graph"));
std::map<GNode, uint64_t> globalMap;
for (unsigned int i = 0; i < threadDegInfo.size(); i++) {
std::map<GNode, uint64_t>& localMap(*threadDegInfo.getRemote(i));
for (auto mb = localMap.begin(), me = localMap.end(); mb != me; mb++) {
globalMap[mb->first] = mb->second;
}
}
order_by_degree<GNode, std::map<GNode, uint64_t>> fn(graph, globalMap);
std::map<GNode, int> nodeIdMap;
int id = 0;
for (auto nb = graph.begin(), ne = graph.end(); nb != ne; nb++) {
nodeIdMap[*nb] = id;
id++;
}
// compute inverse
std::stable_sort(perm.begin(), perm.end(), fn);
galois::LargeArray<uint64_t> perm2;
perm2.create(g.size());
// compute permutation
id = 0;
for (auto pb = perm.begin(), pe = perm.end(); pb != pe; pb++) {
int prevId = nodeIdMap[*pb];
perm2[prevId] = id;
// std::cout<<prevId <<" "<<id<<std::endl;
id++;
}
galois::graphs::FileGraph out;
galois::graphs::permute<int>(g, perm2, out);
if (orderedfile != "")
out.toFile(orderedfile);
if (permutationfile != "") {
std::ofstream file(permutationfile.c_str());
galois::LargeArray<uint64_t> transpose;
transpose.create(g.size());
uint64_t id = 0;
for (auto& ii : perm2) {
transpose[ii] = id++;
}
for (auto& ii : transpose) {
file << ii << "\n";
}
}
}
return 0;
}
| 10,787 | 3,771 |
#pragma once
#include "types.hpp"
struct Grid {
// Number of grid points
int Nx;
int Ny;
int Nz;
// Starting grid points
int Nx0;
int Ny0;
int Nz0;
// Length of domain in this grid
// Domain in this grid is [L0,L0+L]
FLOAT Lx;
FLOAT Ly;
FLOAT Lz;
FLOAT Lx0;
FLOAT Ly0;
FLOAT Lz0;
// MPI info
int rank;
int size;
int[3][3][3] neighbors;
};
| 388 | 184 |
/*
* Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/es/v20180416/EsClient.h>
#include <tencentcloud/core/Executor.h>
#include <tencentcloud/core/Runnable.h>
using namespace TencentCloud;
using namespace TencentCloud::Es::V20180416;
using namespace TencentCloud::Es::V20180416::Model;
using namespace std;
namespace
{
const string VERSION = "2018-04-16";
const string ENDPOINT = "es.tencentcloudapi.com";
}
EsClient::EsClient(const Credential &credential, const string ®ion) :
EsClient(credential, region, ClientProfile())
{
}
EsClient::EsClient(const Credential &credential, const string ®ion, const ClientProfile &profile) :
AbstractClient(ENDPOINT, VERSION, credential, region, profile)
{
}
EsClient::CreateInstanceOutcome EsClient::CreateInstance(const CreateInstanceRequest &request)
{
auto outcome = MakeRequest(request, "CreateInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
CreateInstanceResponse rsp = CreateInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return CreateInstanceOutcome(rsp);
else
return CreateInstanceOutcome(o.GetError());
}
else
{
return CreateInstanceOutcome(outcome.GetError());
}
}
void EsClient::CreateInstanceAsync(const CreateInstanceRequest& request, const CreateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->CreateInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::CreateInstanceOutcomeCallable EsClient::CreateInstanceCallable(const CreateInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<CreateInstanceOutcome()>>(
[this, request]()
{
return this->CreateInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DeleteInstanceOutcome EsClient::DeleteInstance(const DeleteInstanceRequest &request)
{
auto outcome = MakeRequest(request, "DeleteInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DeleteInstanceResponse rsp = DeleteInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DeleteInstanceOutcome(rsp);
else
return DeleteInstanceOutcome(o.GetError());
}
else
{
return DeleteInstanceOutcome(outcome.GetError());
}
}
void EsClient::DeleteInstanceAsync(const DeleteInstanceRequest& request, const DeleteInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DeleteInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DeleteInstanceOutcomeCallable EsClient::DeleteInstanceCallable(const DeleteInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<DeleteInstanceOutcome()>>(
[this, request]()
{
return this->DeleteInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DescribeInstanceLogsOutcome EsClient::DescribeInstanceLogs(const DescribeInstanceLogsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeInstanceLogs");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeInstanceLogsResponse rsp = DescribeInstanceLogsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeInstanceLogsOutcome(rsp);
else
return DescribeInstanceLogsOutcome(o.GetError());
}
else
{
return DescribeInstanceLogsOutcome(outcome.GetError());
}
}
void EsClient::DescribeInstanceLogsAsync(const DescribeInstanceLogsRequest& request, const DescribeInstanceLogsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeInstanceLogs(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DescribeInstanceLogsOutcomeCallable EsClient::DescribeInstanceLogsCallable(const DescribeInstanceLogsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeInstanceLogsOutcome()>>(
[this, request]()
{
return this->DescribeInstanceLogs(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DescribeInstanceOperationsOutcome EsClient::DescribeInstanceOperations(const DescribeInstanceOperationsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeInstanceOperations");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeInstanceOperationsResponse rsp = DescribeInstanceOperationsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeInstanceOperationsOutcome(rsp);
else
return DescribeInstanceOperationsOutcome(o.GetError());
}
else
{
return DescribeInstanceOperationsOutcome(outcome.GetError());
}
}
void EsClient::DescribeInstanceOperationsAsync(const DescribeInstanceOperationsRequest& request, const DescribeInstanceOperationsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeInstanceOperations(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DescribeInstanceOperationsOutcomeCallable EsClient::DescribeInstanceOperationsCallable(const DescribeInstanceOperationsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeInstanceOperationsOutcome()>>(
[this, request]()
{
return this->DescribeInstanceOperations(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DescribeInstancesOutcome EsClient::DescribeInstances(const DescribeInstancesRequest &request)
{
auto outcome = MakeRequest(request, "DescribeInstances");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeInstancesResponse rsp = DescribeInstancesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeInstancesOutcome(rsp);
else
return DescribeInstancesOutcome(o.GetError());
}
else
{
return DescribeInstancesOutcome(outcome.GetError());
}
}
void EsClient::DescribeInstancesAsync(const DescribeInstancesRequest& request, const DescribeInstancesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeInstances(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DescribeInstancesOutcomeCallable EsClient::DescribeInstancesCallable(const DescribeInstancesRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeInstancesOutcome()>>(
[this, request]()
{
return this->DescribeInstances(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DescribeViewsOutcome EsClient::DescribeViews(const DescribeViewsRequest &request)
{
auto outcome = MakeRequest(request, "DescribeViews");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DescribeViewsResponse rsp = DescribeViewsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DescribeViewsOutcome(rsp);
else
return DescribeViewsOutcome(o.GetError());
}
else
{
return DescribeViewsOutcome(outcome.GetError());
}
}
void EsClient::DescribeViewsAsync(const DescribeViewsRequest& request, const DescribeViewsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DescribeViews(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DescribeViewsOutcomeCallable EsClient::DescribeViewsCallable(const DescribeViewsRequest &request)
{
auto task = std::make_shared<std::packaged_task<DescribeViewsOutcome()>>(
[this, request]()
{
return this->DescribeViews(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::DiagnoseInstanceOutcome EsClient::DiagnoseInstance(const DiagnoseInstanceRequest &request)
{
auto outcome = MakeRequest(request, "DiagnoseInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
DiagnoseInstanceResponse rsp = DiagnoseInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return DiagnoseInstanceOutcome(rsp);
else
return DiagnoseInstanceOutcome(o.GetError());
}
else
{
return DiagnoseInstanceOutcome(outcome.GetError());
}
}
void EsClient::DiagnoseInstanceAsync(const DiagnoseInstanceRequest& request, const DiagnoseInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->DiagnoseInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::DiagnoseInstanceOutcomeCallable EsClient::DiagnoseInstanceCallable(const DiagnoseInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<DiagnoseInstanceOutcome()>>(
[this, request]()
{
return this->DiagnoseInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::GetRequestTargetNodeTypesOutcome EsClient::GetRequestTargetNodeTypes(const GetRequestTargetNodeTypesRequest &request)
{
auto outcome = MakeRequest(request, "GetRequestTargetNodeTypes");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
GetRequestTargetNodeTypesResponse rsp = GetRequestTargetNodeTypesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return GetRequestTargetNodeTypesOutcome(rsp);
else
return GetRequestTargetNodeTypesOutcome(o.GetError());
}
else
{
return GetRequestTargetNodeTypesOutcome(outcome.GetError());
}
}
void EsClient::GetRequestTargetNodeTypesAsync(const GetRequestTargetNodeTypesRequest& request, const GetRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->GetRequestTargetNodeTypes(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::GetRequestTargetNodeTypesOutcomeCallable EsClient::GetRequestTargetNodeTypesCallable(const GetRequestTargetNodeTypesRequest &request)
{
auto task = std::make_shared<std::packaged_task<GetRequestTargetNodeTypesOutcome()>>(
[this, request]()
{
return this->GetRequestTargetNodeTypes(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::RestartInstanceOutcome EsClient::RestartInstance(const RestartInstanceRequest &request)
{
auto outcome = MakeRequest(request, "RestartInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RestartInstanceResponse rsp = RestartInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RestartInstanceOutcome(rsp);
else
return RestartInstanceOutcome(o.GetError());
}
else
{
return RestartInstanceOutcome(outcome.GetError());
}
}
void EsClient::RestartInstanceAsync(const RestartInstanceRequest& request, const RestartInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RestartInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::RestartInstanceOutcomeCallable EsClient::RestartInstanceCallable(const RestartInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<RestartInstanceOutcome()>>(
[this, request]()
{
return this->RestartInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::RestartKibanaOutcome EsClient::RestartKibana(const RestartKibanaRequest &request)
{
auto outcome = MakeRequest(request, "RestartKibana");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RestartKibanaResponse rsp = RestartKibanaResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RestartKibanaOutcome(rsp);
else
return RestartKibanaOutcome(o.GetError());
}
else
{
return RestartKibanaOutcome(outcome.GetError());
}
}
void EsClient::RestartKibanaAsync(const RestartKibanaRequest& request, const RestartKibanaAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RestartKibana(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::RestartKibanaOutcomeCallable EsClient::RestartKibanaCallable(const RestartKibanaRequest &request)
{
auto task = std::make_shared<std::packaged_task<RestartKibanaOutcome()>>(
[this, request]()
{
return this->RestartKibana(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::RestartNodesOutcome EsClient::RestartNodes(const RestartNodesRequest &request)
{
auto outcome = MakeRequest(request, "RestartNodes");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
RestartNodesResponse rsp = RestartNodesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return RestartNodesOutcome(rsp);
else
return RestartNodesOutcome(o.GetError());
}
else
{
return RestartNodesOutcome(outcome.GetError());
}
}
void EsClient::RestartNodesAsync(const RestartNodesRequest& request, const RestartNodesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->RestartNodes(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::RestartNodesOutcomeCallable EsClient::RestartNodesCallable(const RestartNodesRequest &request)
{
auto task = std::make_shared<std::packaged_task<RestartNodesOutcome()>>(
[this, request]()
{
return this->RestartNodes(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdateDiagnoseSettingsOutcome EsClient::UpdateDiagnoseSettings(const UpdateDiagnoseSettingsRequest &request)
{
auto outcome = MakeRequest(request, "UpdateDiagnoseSettings");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateDiagnoseSettingsResponse rsp = UpdateDiagnoseSettingsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateDiagnoseSettingsOutcome(rsp);
else
return UpdateDiagnoseSettingsOutcome(o.GetError());
}
else
{
return UpdateDiagnoseSettingsOutcome(outcome.GetError());
}
}
void EsClient::UpdateDiagnoseSettingsAsync(const UpdateDiagnoseSettingsRequest& request, const UpdateDiagnoseSettingsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateDiagnoseSettings(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdateDiagnoseSettingsOutcomeCallable EsClient::UpdateDiagnoseSettingsCallable(const UpdateDiagnoseSettingsRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateDiagnoseSettingsOutcome()>>(
[this, request]()
{
return this->UpdateDiagnoseSettings(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdateDictionariesOutcome EsClient::UpdateDictionaries(const UpdateDictionariesRequest &request)
{
auto outcome = MakeRequest(request, "UpdateDictionaries");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateDictionariesResponse rsp = UpdateDictionariesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateDictionariesOutcome(rsp);
else
return UpdateDictionariesOutcome(o.GetError());
}
else
{
return UpdateDictionariesOutcome(outcome.GetError());
}
}
void EsClient::UpdateDictionariesAsync(const UpdateDictionariesRequest& request, const UpdateDictionariesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateDictionaries(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdateDictionariesOutcomeCallable EsClient::UpdateDictionariesCallable(const UpdateDictionariesRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateDictionariesOutcome()>>(
[this, request]()
{
return this->UpdateDictionaries(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdateInstanceOutcome EsClient::UpdateInstance(const UpdateInstanceRequest &request)
{
auto outcome = MakeRequest(request, "UpdateInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateInstanceResponse rsp = UpdateInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateInstanceOutcome(rsp);
else
return UpdateInstanceOutcome(o.GetError());
}
else
{
return UpdateInstanceOutcome(outcome.GetError());
}
}
void EsClient::UpdateInstanceAsync(const UpdateInstanceRequest& request, const UpdateInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdateInstanceOutcomeCallable EsClient::UpdateInstanceCallable(const UpdateInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateInstanceOutcome()>>(
[this, request]()
{
return this->UpdateInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdateJdkOutcome EsClient::UpdateJdk(const UpdateJdkRequest &request)
{
auto outcome = MakeRequest(request, "UpdateJdk");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateJdkResponse rsp = UpdateJdkResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateJdkOutcome(rsp);
else
return UpdateJdkOutcome(o.GetError());
}
else
{
return UpdateJdkOutcome(outcome.GetError());
}
}
void EsClient::UpdateJdkAsync(const UpdateJdkRequest& request, const UpdateJdkAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateJdk(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdateJdkOutcomeCallable EsClient::UpdateJdkCallable(const UpdateJdkRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateJdkOutcome()>>(
[this, request]()
{
return this->UpdateJdk(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdatePluginsOutcome EsClient::UpdatePlugins(const UpdatePluginsRequest &request)
{
auto outcome = MakeRequest(request, "UpdatePlugins");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdatePluginsResponse rsp = UpdatePluginsResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdatePluginsOutcome(rsp);
else
return UpdatePluginsOutcome(o.GetError());
}
else
{
return UpdatePluginsOutcome(outcome.GetError());
}
}
void EsClient::UpdatePluginsAsync(const UpdatePluginsRequest& request, const UpdatePluginsAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdatePlugins(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdatePluginsOutcomeCallable EsClient::UpdatePluginsCallable(const UpdatePluginsRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdatePluginsOutcome()>>(
[this, request]()
{
return this->UpdatePlugins(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpdateRequestTargetNodeTypesOutcome EsClient::UpdateRequestTargetNodeTypes(const UpdateRequestTargetNodeTypesRequest &request)
{
auto outcome = MakeRequest(request, "UpdateRequestTargetNodeTypes");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpdateRequestTargetNodeTypesResponse rsp = UpdateRequestTargetNodeTypesResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpdateRequestTargetNodeTypesOutcome(rsp);
else
return UpdateRequestTargetNodeTypesOutcome(o.GetError());
}
else
{
return UpdateRequestTargetNodeTypesOutcome(outcome.GetError());
}
}
void EsClient::UpdateRequestTargetNodeTypesAsync(const UpdateRequestTargetNodeTypesRequest& request, const UpdateRequestTargetNodeTypesAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpdateRequestTargetNodeTypes(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpdateRequestTargetNodeTypesOutcomeCallable EsClient::UpdateRequestTargetNodeTypesCallable(const UpdateRequestTargetNodeTypesRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpdateRequestTargetNodeTypesOutcome()>>(
[this, request]()
{
return this->UpdateRequestTargetNodeTypes(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpgradeInstanceOutcome EsClient::UpgradeInstance(const UpgradeInstanceRequest &request)
{
auto outcome = MakeRequest(request, "UpgradeInstance");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpgradeInstanceResponse rsp = UpgradeInstanceResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpgradeInstanceOutcome(rsp);
else
return UpgradeInstanceOutcome(o.GetError());
}
else
{
return UpgradeInstanceOutcome(outcome.GetError());
}
}
void EsClient::UpgradeInstanceAsync(const UpgradeInstanceRequest& request, const UpgradeInstanceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpgradeInstance(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpgradeInstanceOutcomeCallable EsClient::UpgradeInstanceCallable(const UpgradeInstanceRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpgradeInstanceOutcome()>>(
[this, request]()
{
return this->UpgradeInstance(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
EsClient::UpgradeLicenseOutcome EsClient::UpgradeLicense(const UpgradeLicenseRequest &request)
{
auto outcome = MakeRequest(request, "UpgradeLicense");
if (outcome.IsSuccess())
{
auto r = outcome.GetResult();
string payload = string(r.Body(), r.BodySize());
UpgradeLicenseResponse rsp = UpgradeLicenseResponse();
auto o = rsp.Deserialize(payload);
if (o.IsSuccess())
return UpgradeLicenseOutcome(rsp);
else
return UpgradeLicenseOutcome(o.GetError());
}
else
{
return UpgradeLicenseOutcome(outcome.GetError());
}
}
void EsClient::UpgradeLicenseAsync(const UpgradeLicenseRequest& request, const UpgradeLicenseAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context)
{
auto fn = [this, request, handler, context]()
{
handler(this, request, this->UpgradeLicense(request), context);
};
Executor::GetInstance()->Submit(new Runnable(fn));
}
EsClient::UpgradeLicenseOutcomeCallable EsClient::UpgradeLicenseCallable(const UpgradeLicenseRequest &request)
{
auto task = std::make_shared<std::packaged_task<UpgradeLicenseOutcome()>>(
[this, request]()
{
return this->UpgradeLicense(request);
}
);
Executor::GetInstance()->Submit(new Runnable([task]() { (*task)(); }));
return task->get_future();
}
| 28,858 | 8,311 |
/*
combines coil images using sensitivity maps to retain phase.
usage: o = combcoils(m, s)
input:
m : coil images. [x y z coils images]
s : sensitivity maps. [x y z coils]
output:
o : single combined image. [x y z]
*/
#include "mex.h"
#include <math.h>
#define X plhs[0]
#define M prhs[0]
#define S prhs[1]
// don't worry about dynamic memory allocation for now
#define MAXNC 64
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
// get sizes
const mwSize *msize = mxGetDimensions(M);
size_t ndims = mxGetNumberOfDimensions(M);
int nx = msize[0];
int ny = msize[1];
int nz = msize[2];
int nc = msize[3];
int ni = (ndims>4) ? msize[4] : 1;
int nv = nx*ny*nz;
// create output array
mwSize outsz[4];
outsz[0] = nx;
outsz[1] = ny;
outsz[2] = nz;
outsz[3] = ni;
X = mxCreateNumericArray(ndims-1, outsz, mxDOUBLE_CLASS, mxCOMPLEX);
double *xr = mxGetPr(X); double *xi = mxGetPi(X);
// get input data
double *mr = mxGetPr(M); double *mi = mxGetPi(M); /* image data from coils */
double *sr = mxGetPr(S); double *si = mxGetPi(S); /* senstivities */
double stmr; // s' * m
double stmi;
double stsr; // s' * s
double stsi;
int ix, iy, iz, ic, ip, ii; // indices
int io, co; // image and coil offsets
int nvpf = nx*ny*nz*nc;
for (ii=0; ii<ni; ii++){
io = ii*nvpf;
// voxel-wise recon ........................................................
for (ix=0; ix<nx; ix++)
for (iy=0; iy<ny; iy++)
for (iz=0; iz<nz; iz++){
ip = iz*nx*ny+iy*nx+ix;
// performs a pseudo-inverse, i.e. Ax = b -> x = inv(A'A)*A'b
// m = s x (x is a scalar)
// x = (s'm)/(s's)
stmr = 0.0;
stmi = 0.0;
stsr = 0.0;
stsi = 0.0;
for (ic=0; ic<nc; ic++){
co = ic*nv;
stmr += sr[ip+co]*mr[ip+co+io]+si[ip+co]*mi[ip+co+io];
stmi += sr[ip+co]*mi[ip+co+io]-si[ip+co]*mr[ip+co+io];
stsr += sr[ip+co]*sr[ip+co]+si[ip+co]*si[ip+co];
// stsi is always zero
}
xr[ip+ii*nv] = stmr/stsr;
xi[ip+ii*nv] = stmi/stsr;
}
// .........................................................................
}
}
| 2,279 | 980 |
/**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#ifndef IROHA_WSVRESTORER_HPP
#define IROHA_WSVRESTORER_HPP
#include "common/result.hpp"
namespace iroha {
namespace ametsuchi {
class Storage;
/**
* Interface for World State View restoring from the storage
*/
class WsvRestorer {
public:
virtual ~WsvRestorer() = default;
/**
* Recover WSV (World State View).
* @param storage storage of blocks in ledger
* @return ledger state after restoration on success, otherwise error
* string
*/
virtual iroha::expected::
Result<boost::optional<std::unique_ptr<LedgerState>>, std::string>
restoreWsv(Storage &storage) = 0;
};
} // namespace ametsuchi
} // namespace iroha
#endif // IROHA_WSVRESTORER_HPP
| 864 | 288 |
//===----------------------------------------------------------------------===//
//
// The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
// UNSUPPORTED: c++98, c++03, c++11
#include <functional>
#include <string>
template <class T>
struct is_transparent
{
private:
struct two {char lx; char lxx;};
template <class U> static two test(...);
template <class U> static char test(typename U::is_transparent* = 0);
public:
static const bool value = sizeof(test<T>(0)) == 1;
};
int main ()
{
static_assert ( !is_transparent<std::less<int>>::value, "" );
static_assert ( !is_transparent<std::less<std::string>>::value, "" );
static_assert ( is_transparent<std::less<void>>::value, "" );
static_assert ( is_transparent<std::less<>>::value, "" );
static_assert ( !is_transparent<std::less_equal<int>>::value, "" );
static_assert ( !is_transparent<std::less_equal<std::string>>::value, "" );
static_assert ( is_transparent<std::less_equal<void>>::value, "" );
static_assert ( is_transparent<std::less_equal<>>::value, "" );
static_assert ( !is_transparent<std::equal_to<int>>::value, "" );
static_assert ( !is_transparent<std::equal_to<std::string>>::value, "" );
static_assert ( is_transparent<std::equal_to<void>>::value, "" );
static_assert ( is_transparent<std::equal_to<>>::value, "" );
static_assert ( !is_transparent<std::not_equal_to<int>>::value, "" );
static_assert ( !is_transparent<std::not_equal_to<std::string>>::value, "" );
static_assert ( is_transparent<std::not_equal_to<void>>::value, "" );
static_assert ( is_transparent<std::not_equal_to<>>::value, "" );
static_assert ( !is_transparent<std::greater<int>>::value, "" );
static_assert ( !is_transparent<std::greater<std::string>>::value, "" );
static_assert ( is_transparent<std::greater<void>>::value, "" );
static_assert ( is_transparent<std::greater<>>::value, "" );
static_assert ( !is_transparent<std::greater_equal<int>>::value, "" );
static_assert ( !is_transparent<std::greater_equal<std::string>>::value, "" );
static_assert ( is_transparent<std::greater_equal<void>>::value, "" );
static_assert ( is_transparent<std::greater_equal<>>::value, "" );
return 0;
}
| 2,486 | 829 |
/// \author Tim Quelch
#include <algorithm>
#include <chrono>
#include <cmath>
#include <deque>
#include <iomanip>
#include <iostream>
#include <png++/png.hpp>
#include <random>
#include <tuple>
#include "maze.h"
namespace mazes {
namespace detail {
/// Holds the x y coordinates of a point in the maze
struct Point {
int x; ///< x coordinate
int y; ///< y coordinate
/// Construct with given values
/// \param x The x coordinate
/// \param y The y coordinate
Point(int x = 0, int y = 0)
: x{x}
, y{y} {}
/// Orders points lexicographically by x coordinate then y coordinate
/// \param rhs Another point
/// \returns true if the point is lexicographically less than the other by x then y
bool operator<(const Point& rhs) { return std::tie(x, y) < std::tie(rhs.x, rhs.y); }
/// Points are equal if both x and y are equal
/// \param rhs Another point
/// \returns true if both x and y are equal
bool operator==(const Point& rhs) { return x == rhs.x && y == rhs.y; }
};
/// Generates a random integer between a and b
int randInt(int a, int b) {
static auto seed = std::chrono::system_clock::now().time_since_epoch().count();
static auto randEngine = std::default_random_engine{seed};
auto dist = std::uniform_int_distribution{a, b};
return dist(randEngine);
}
/// Checks if a coordinate is within the boundaries of the maze. That is, if it x and y are
/// greater than 1 and less than size - 1
/// \param p A Point
/// \param gridSize the length of the side of the maze
/// \returns true if the point is within the walls of the maze
bool isLegal(Point p, int gridSize) {
return p.x > 0 && p.x < gridSize - 1 && p.y > 0 && p.y < gridSize - 1;
}
/// Checks if point is a wall that can be removed to form a loop. Wall must be a vertical or
/// horizontal wall, not a T wall, or X wall.
/// \param grid Grid of the maze
/// \param p A Point
/// \returns true if the point can be removed to form a loop
bool isWall(const std::vector<std::vector<bool>>& grid, Point p) {
int countWalls = 0;
countWalls += grid[p.x - 1][p.y] ? 0 : 1;
countWalls += grid[p.x + 1][p.y] ? 0 : 1;
countWalls += grid[p.x][p.y - 1] ? 0 : 1;
countWalls += grid[p.x][p.y + 1] ? 0 : 1;
bool wall = !grid[p.x][p.y];
bool nsWall = !grid[p.x][p.y + 1] && !grid[p.x][p.y - 1];
bool esWall = !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y];
return wall && (nsWall || esWall) && !(nsWall && esWall) && (countWalls < 3);
}
/// Returns a list the points of the neighbours of a point. Neighbours are in the four
/// cardinal directions and are a distance of two away. They are two away so that the wall
/// inbetween is jumped.
std::list<Point> getNeighbours(unsigned gridSize, Point p) {
auto newNodes = std::list<Point>{};
newNodes.push_back({p.x - 2, p.y});
newNodes.push_back({p.x, p.y - 2});
newNodes.push_back({p.x, p.y + 2});
newNodes.push_back({p.x + 2, p.y});
newNodes.remove_if([gridSize](Point p) { return !isLegal(p, gridSize); });
return newNodes;
}
/// Returns and removes a random point from a list
/// \param points Reference to a list of points. A random point is removed from this list
/// \returns The Point removed from the list
Point popPoint(std::list<Point>& points) {
unsigned index = randInt(0, points.size() - 1);
auto it = points.begin();
for (unsigned i = 0; i < index; i++) {
it++;
}
points.erase(it);
return *it;
}
/// Check if a point is a horizontal corridor. That is, it has corridors to the left and
/// right, and walls to the top and bottom
bool isHCorridor(Point p, const std::vector<std::vector<bool>>& grid) {
return grid[p.x - 1][p.y] && grid[p.x + 1][p.y] && !grid[p.x][p.y - 1] &&
!grid[p.x][p.y + 1];
}
/// Check if a point is a vertical corridor. That is, it has corridors to the top and
/// bottom, and walls to the left and right
bool isVCorridor(Point p, const std::vector<std::vector<bool>>& grid) {
return !grid[p.x - 1][p.y] && !grid[p.x + 1][p.y] && grid[p.x][p.y - 1] &&
grid[p.x][p.y + 1];
}
/// Calculate the manhatten distance between two points
int calcCost(Point one, Point two) {
return std::abs(one.x - two.x) + std::abs(one.y - two.y);
}
/// Initialise a grid to false
std::vector<std::vector<bool>> initGrid(unsigned size) {
auto grid = std::vector<std::vector<bool>>();
grid.resize(size);
for (unsigned i = 0; i < size; i++) {
grid[i].resize(size, false);
}
return grid;
}
/// Generate maze with Prims method
void generatePrims(std::vector<std::vector<bool>>& grid) {
const auto size = grid.size();
// Randomly generate initial point
auto init =
Point{randInt(0, (size - 2) / 2) * 2 + 1, randInt(0, (size - 2) / 2) * 2 + 1};
grid[init.x][init.y] = true;
// Generate frontier points from neighbours
auto frontierPoints = std::list<Point>{getNeighbours(size, init)};
// Expand maze until grid is full
while (!frontierPoints.empty()) {
// Pick random frontier point and set it to true
auto p1 = Point{popPoint(frontierPoints)};
grid[p1.x][p1.y] = true;
// Pick a random neighbours which is a pathway, and link the two points by setting
// the intermediate point to a pathway
auto neighbours = std::list<Point>{getNeighbours(size, p1)};
neighbours.remove_if([&grid](Point p) { return !grid[p.x][p.y]; });
auto p2 = Point{popPoint(neighbours)};
grid[p2.x - (p2.x - p1.x) / 2][p2.y - (p2.y - p1.y) / 2] = true;
// Find and add the new frontier points
auto newFrontierPoints = std::list<Point>{getNeighbours(size, p1)};
newFrontierPoints.remove_if([&grid](Point p) { return grid[p.x][p.y]; });
frontierPoints.merge(newFrontierPoints);
frontierPoints.unique();
}
}
std::list<std::pair<Point, Point>> divideChamber(std::vector<std::vector<bool>>& grid,
std::pair<Point, Point> chamber) {
const auto x1 = chamber.first.x;
const auto y1 = chamber.first.y;
const auto x2 = chamber.second.x;
const auto y2 = chamber.second.y;
const auto size = x2 - x1;
const auto mid = (size + 1) / 2;
if (size < 2) {
return {};
}
// Set chamber to pathways
for (auto i = x1; i <= x2; i++) {
for (auto j = y1; j <= y2; j++) {
grid[i][j] = true;
}
}
// Set inner walls to walls
for (auto i = x1; i <= x2; i++) {
grid[i][y1 + mid] = false;
}
for (auto j = y1; j <= y2; j++) {
grid[x1 + mid][j] = false;
}
// Create openings in walls
const auto rand = [mid]() { return randInt(0, mid / 2) * 2; };
auto openings = std::vector<Point>{{x1 + mid, y1 + rand()},
{x1 + mid, y1 + mid + 1 + rand()},
{x1 + rand(), y1 + mid},
{x1 + mid + 1 + rand(), y1 + mid}};
openings.erase(openings.cbegin() + randInt(0, 3));
for (auto p : openings) {
grid[p.x][p.y] = true;
}
// Return the subdivided chambers
return {{{x1, y1}, {x1 + mid - 1, y1 + mid - 1}},
{{x1 + mid + 1, y1 + mid + 1}, {x2, y2}},
{{x1 + mid + 1, y1}, {x2, y1 + mid - 1}},
{{x1, y1 + mid + 1}, {x1 + mid - 1, y2}}};
}
/// Generate maze with recursive division method
void generateDivision(std::vector<std::vector<bool>>& grid) {
const auto size = static_cast<int>(grid.size());
auto chambers = std::deque<std::pair<Point, Point>>{};
chambers.push_back({{1, 1}, {size - 2, size - 2}});
while (!chambers.empty()) {
auto newChambers = divideChamber(grid, chambers.front());
chambers.pop_front();
for (const auto& c : newChambers) {
chambers.push_back(c);
}
}
}
/// Remove walls to create multiple paths in the maze. Pick random points until a valid
/// wall is found, then set it to be a pathway
void addLoops(std::vector<std::vector<bool>>& grid, double loopFactor) {
const auto size = grid.size();
const unsigned loops = size * size * loopFactor * loopFactor;
for (unsigned i = 0; i < loops; i++) {
Point p;
do {
p = Point(randInt(1, size - 2), randInt(1, size - 2));
} while (!isWall(grid, p));
grid[p.x][p.y] = true;
}
}
/// Add the entrance and exit of the maze
void addEntranceAndExit(std::vector<std::vector<bool>>& grid) {
const auto size = grid.size();
grid[1][0] = true;
grid[size - 2][size - 1] = true;
}
/// Generate the grid of a maze. There is an entrance in the top left, and an exit in the
/// bottom right.
/// \param size the length of the side of the maze
/// \param loopFactor the factor of loopiness in the maze. 0 means there is a single
/// solution, increasing increases number of solutions
/// \returns the grid of the maze. can be indexed with v[x][y]
/// \callgraph
std::vector<std::vector<bool>>
generateGrid(unsigned size, double loopFactor, Maze::Method method) {
auto grid = initGrid(size);
switch (method) {
case Maze::Method::prims:
generatePrims(grid);
break;
case Maze::Method::division:
generateDivision(grid);
break;
}
addLoops(grid, loopFactor);
addEntranceAndExit(grid);
return grid;
}
/// Generate the graph of a maze from the grid. The maze is sorted left to right, then top
/// to bottom, therefore the entrance is the first node, and the exit is the last node
/// \param grid The Maze grid to generate the graph from
/// \returns A list of Nodes that make up the graph of the maze
std::list<std::shared_ptr<Maze::Node>>
generateGraph(const std::vector<std::vector<bool>>& grid) {
using Node = Maze::Node;
using Edge = Maze::Edge;
const int size = grid.size();
auto graph = std::list<std::shared_ptr<Node>>{}; // nodes in the graph
auto above = std::list<std::shared_ptr<Node>>{}; // nodes that are above current
// Add start node
auto first = std::make_shared<Node>(1, 0, std::list<Edge>{});
graph.push_back(first);
above.push_back(first);
// Iterate through whole grid
for (int j = 1; j < size; j++) {
auto left = std::shared_ptr<Node>{nullptr}; // The node that is left of present
auto nodeAbove = above.begin(); // Iterator to start of above nodes
for (int i = 1; i < size - 1; i++) {
if (grid[i][j]) {
// Ignore point if it is a corridor
if (!isHCorridor({i, j}, grid) && !isVCorridor({i, j}, grid)) {
auto edges = std::list<Edge>{};
// Add edge if there is a node to the left
if (left) {
int cost = calcCost({i, j}, {left->x, left->y});
edges.push_back({left, cost});
}
// Add edge if there is a node above
if (nodeAbove != above.end() && (*nodeAbove)->x == i) {
int cost = calcCost({i, j}, {(*nodeAbove)->x, (*nodeAbove)->y});
edges.push_back({*nodeAbove, cost});
nodeAbove = above.erase(nodeAbove);
}
// Create the node
auto node = std::make_shared<Node>(i, j, edges);
graph.push_back(node);
above.insert(nodeAbove, node);
left = node;
// Add edges to this node from all edges
for (const auto& edge : edges) {
edge.node->edges.push_back({node, edge.cost});
}
}
// Iterate above iterator if needed
if (isVCorridor({i, j}, grid) && nodeAbove != above.end() &&
(*nodeAbove)->x == i) {
nodeAbove++;
}
} else {
// If current is wall, reset left and iterate above
left = nullptr;
if (nodeAbove != above.end() && (*nodeAbove)->x == i) {
nodeAbove = above.erase(nodeAbove);
}
}
}
}
// Sort the list of nodes. Entrance will be first, exit will be last
graph.sort([](auto& one, auto& two) {
return std::tie(one->x, one->y) < std::tie(two->x, two->y);
});
return graph;
}
} // namespace detail
// Construct maze with given size. Generate grid and graph
Maze::Maze(unsigned size, double loopFactor, Maze::Method method)
: size_{size}
, grid_{detail::generateGrid(size, loopFactor, method)}
, graph_{detail::generateGraph(grid_)} {}
// Print the maze to stdout
void Maze::print() const {
std::cout << " ";
for (unsigned i = 0; i < size_; i++) {
std::cout << std::setw(2) << i << " ";
}
std::cout << "\n\n";
for (unsigned j = 0; j < size_; j++) {
std::cout << std::setw(2) << j << " ";
for (unsigned i = 0; i < size_; i++) {
if (grid_[i][j]) {
std::cout << " ";
} else {
std::cout << " # ";
}
}
std::cout << "\n";
}
std::cout << "\n";
}
// Print the graph nodes over the maze to stdout
void Maze::printGraph() const {
// Create grid where nodes are true
auto graphGrid = std::vector<std::vector<bool>>{};
graphGrid.resize(size_);
for (unsigned i = 0; i < size_; i++) {
graphGrid[i].resize(size_, false);
}
for (auto nodePtr : graph_) {
graphGrid[nodePtr->x][nodePtr->y] = true;
}
// Print to output
std::cout << " ";
for (unsigned i = 0; i < size_; i++) {
std::cout << std::setw(2) << i << " ";
}
std::cout << "\n\n";
for (unsigned j = 0; j < size_; j++) {
std::cout << std::setw(2) << j << " ";
for (unsigned i = 0; i < size_; i++) {
if (graphGrid[i][j]) {
std::cout << " o ";
} else if (grid_[i][j]) {
std::cout << " ";
} else {
std::cout << " # ";
}
}
std::cout << "\n";
}
std::cout << "\n";
}
// Write the maze to PNG
void Maze::writePng(std::string_view filename) const {
auto image = png::image<png::rgb_pixel>{size_, size_};
for (unsigned j = 0; j < size_; j++) {
for (unsigned i = 0; i < size_; i++) {
if (grid_[i][j]) {
image[j][i] = png::rgb_pixel(255, 255, 255);
} else {
image[j][i] = png::rgb_pixel(0, 0, 0);
}
}
}
image.write(filename.data());
}
// Write the graph nodes over the maze to PNG
void Maze::writePngGraph(std::string_view filename) const {
auto image = png::image<png::rgb_pixel>{size_, size_};
// Write maze
for (unsigned j = 0; j < size_; j++) {
for (unsigned i = 0; i < size_; i++) {
if (grid_[i][j]) {
image[j][i] = png::rgb_pixel(255, 255, 255);
} else {
image[j][i] = png::rgb_pixel(0, 0, 0);
}
}
}
// Write graph
for (auto nodePtr : graph_) {
image[nodePtr->y][nodePtr->x] = png::rgb_pixel(255, 0, 0);
}
image.write(filename.data());
}
// Write the maze with a given path to PNG
void Maze::writePngPath(std::list<std::shared_ptr<Node>> path,
std::string_view filename) const {
auto image = png::image<png::rgb_pixel>{size_, size_};
// Write maze
for (unsigned j = 0; j < size_; j++) {
for (unsigned i = 0; i < size_; i++) {
if (grid_[i][j]) {
image[j][i] = png::rgb_pixel(255, 255, 255);
} else {
image[j][i] = png::rgb_pixel(0, 0, 0);
}
}
}
// Write path
auto prev = detail::Point{path.front()->x, path.front()->y};
for (const auto& node : path) {
auto start = detail::Point{std::min(prev.x, node->x), std::min(prev.y, node->y)};
auto end =
detail::Point{std::max(prev.x + 1, node->x + 1), std::max(prev.y + 1, node->y + 1)};
for (int i = start.x; i != end.x; i++) {
for (int j = start.y; j != end.y; j++) {
image[j][i] = png::rgb_pixel(255, 0, 0);
}
}
prev = {node->x, node->y};
}
image.write(filename.data());
}
} // namespace mazes
| 19,369 | 5,789 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "hbase/test-util/test-util.h"
#include <string.h>
#include <folly/Format.h>
#include "hbase/client/zk-util.h"
using hbase::TestUtil;
using folly::Random;
std::string TestUtil::RandString(int len) {
// Create the whole string.
// Filling everything with z's
auto s = std::string(len, 'z');
// Now pick a bunch of random numbers
for (int i = 0; i < len; i++) {
// use Folly's random to get the numbers
// as I don't want to have to learn
// all the cpp rand invocation magic.
auto r = Random::rand32('a', 'z');
// Cast that to ascii.
s[i] = static_cast<char>(r);
}
return s;
}
TestUtil::TestUtil() : temp_dir_(TestUtil::RandString()) {}
TestUtil::~TestUtil() {
if (mini_) {
StopMiniCluster();
mini_ = nullptr;
}
}
void TestUtil::StartMiniCluster(int32_t num_region_servers) {
mini_ = std::make_unique<MiniCluster>();
mini_->StartCluster(num_region_servers);
conf()->Set(ZKUtil::kHBaseZookeeperQuorum_, mini_->GetConfValue(ZKUtil::kHBaseZookeeperQuorum_));
conf()->Set(ZKUtil::kHBaseZookeeperClientPort_,
mini_->GetConfValue(ZKUtil::kHBaseZookeeperClientPort_));
}
void TestUtil::StopMiniCluster() { mini_->StopCluster(); }
void TestUtil::CreateTable(const std::string &table, const std::string &family) {
mini_->CreateTable(table, family);
}
void TestUtil::CreateTable(const std::string &table, const std::vector<std::string> &families) {
mini_->CreateTable(table, families);
}
void TestUtil::CreateTable(const std::string &table, const std::string &family,
const std::vector<std::string> &keys) {
mini_->CreateTable(table, family, keys);
}
void TestUtil::CreateTable(const std::string &table, const std::vector<std::string> &families,
const std::vector<std::string> &keys) {
mini_->CreateTable(table, families, keys);
}
void TestUtil::MoveRegion(const std::string ®ion, const std::string &server) {
mini_->MoveRegion(region, server);
}
void TestUtil::StartStandAloneInstance() {
auto p = temp_dir_.path().string();
auto cmd = std::string{"bin/start-local-hbase.sh " + p};
auto res_code = std::system(cmd.c_str());
CHECK_EQ(res_code, 0);
}
void TestUtil::StopStandAloneInstance() {
auto res_code = std::system("bin/stop-local-hbase.sh");
CHECK_EQ(res_code, 0);
}
void TestUtil::RunShellCmd(const std::string &command) {
auto cmd_string = folly::sformat("echo \"{}\" | ../bin/hbase shell", command);
auto res_code = std::system(cmd_string.c_str());
CHECK_EQ(res_code, 0);
}
| 3,365 | 1,120 |
// Copyright 2021 D-Wave Systems Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
namespace busclique {
size_t binom(size_t);
/*
Coordinate arithmetic is absolutely fraught with challenges. In order to
reduce the possibility of bugs, we've introduced an extremely pedantic system
of coordinate types. The busclique algorithms use two kinds of coordinate
systems:
* matrix coordinates (y, x) which are featured in the chimera coordinate
system (y, x, u, k) -- where u indicates the 'orientation' of a qubit,
either vertical(u=0) or horizontal(u=1) and k indicates the 'shore index'
of a qubit (irrelevant here)
* relative coordinates (w, z) which are features in the pegasus and zephyr
coordinate systems (u, w, k[, j], z) -- where u is the orientation as
above and k and j are similarly irrelevant.
The relationship between matrix and relative coordinates is that
* (y, x, u=0) is equivalent to (z=y, w=x, u=0), and
* (y, x, u=1) is equivalent to (w=y, z=x, u=1)
We have encoded this equivalence in four types, size_y, size_x, size_w, and
size_z. Each type supports arithmetic with itself, but forbids confusion. For
example,
size_y y0, y1;
size_x x0, x0;
(y0 + y1*y0 + y1)/(y1-y0) // cool
y0 + x0; // compile error!
But, we need to convert between matrix and relative coordinates frequently!
We do that with the `vert` and `horz` functions:
bool u = 0;
size_y y;
size_x x;
size_w w0, w1;
size_z z0, z1;
w1 = w0 + vert(y);
z1 = z0 + vert(x);
u = 1;
w1 = w0 + horz(x);
z1 = z0 + horz(y);
Sometimes, we *really* need to mix things up. There are two ways to convert
a coordinate to a size_t: implicitly through `coordinate_base::operator size_t`,
or explicitly through `coordinate_index()`. The implicit conversion is
private, to prevent accidental implicit conversions. The `coordinate_converter`
class is a friend to the coordinate types, and that's the only place we need to
be very careful. We use the `coordinate_index()` method in very few one-off
instances. Ideally, it should only be used for indexing into arrays:
size_y y;
uint8_t mem[100];
mem[coordinate_index(y)];
This entire file, and the associated refactor, is a very heavy-handed approach
to fixing a bug (segfaulting non-square Chimera graphs). However, it reduces a
significant amount of anxiety in developing and extending this library. In
small tests, code involving coordinate classes is optimized down to identical
assembly to the same code using size_t in their place. We'll see if that's true
in a complex codebase...
Update: Curious. The performance was rather miserable on my system (gcc 9.3.0);
at around 3x slower than before the change that I hoped would be "zero cost." I
decided to roll back very carefully; not changing any more code than necessary
to ensure a clean test. I commented out the coordinate types, and replaced them
with `typedef size_t ...`. In the initial version, the coordinate types had
methods, specifically, `coordinate_base.index`, `coordinate_base.horz` and
`coordinate_base.vert`. I replaced these with global functions because we can't
attach methods to a size_t. Sure enough, the performance returned to normal.
For sake of a fuller understanding, I refactored `coordinate_base` to support
the same syntax, and lo and behold, the performance stayed the same.
Since I'm using a very up-to-date gcc, I am reluctant to put the coordinate
types into the release build. If I was a docker shepherd, I'd probably spool up
a few dozen instances and benchmark on all the gcc's and clang's and msvc's that
I could get my hands on. Alas, it is much easier to rely on the fact that CI
tests with debugging enabled, and retain the flag-dependent build since I've
already written it. A note, I'd be oh-so-slightly more comfortable if `vert`,
`horz`, and `coordinate_index` were macros. But I take a deep breath and remind
myself what century I'm programming in.
*/
class coordinate_converter;
#if defined CPPDEBUG || defined SAFE_COORDS
//! a tag-struct used to indicate y-coordinates
struct coord_y {};
//! a tag-struct used to indicate x-coordinates
struct coord_x {};
//! a tag-struct used to indicate w-coordinates -- given a qubit, the w
//! coordinate corresponds to an offset perpendicular to the qubit
struct coord_w {};
//! a tag-struct used to indicate z-coordinates -- given a qubit, the z
//! coordinate corresponds to an offset parallel to the qubit
struct coord_z {};
//! This struct defines the relationships between y, x, w, and z in vertical
//! context. That is, the y coordinate is a parallel offset (z coordinate)
//! from the perspective of a vertical qubit. Likewise, the x coordinate is a
//! perpendicular offset (w coordinate)
template<typename T> struct vert_lut;
template<> struct vert_lut<coord_y> { typedef coord_z type; };
template<> struct vert_lut<coord_x> { typedef coord_w type; };
template<> struct vert_lut<coord_w> { typedef coord_x type; };
template<> struct vert_lut<coord_z> { typedef coord_y type; };
//! This sruct defines the relationships between y, x, w, and z in horizontal
//! context. That is, the y coordinate is a perpendicular offset (w coordinate)
//! from the perspective of a vertical qubit. Likewise, the x coordinate is a
//! parallel offset (z coordinate)
template<typename T> struct horz_lut;
template<> struct horz_lut<coord_y> { typedef coord_w type; };
template<> struct horz_lut<coord_x> { typedef coord_z type; };
template<> struct horz_lut<coord_w> { typedef coord_y type; };
template<> struct horz_lut<coord_z> { typedef coord_x type; };
// Check that vert_lut is idempotent
static_assert(std::is_same<vert_lut<vert_lut<coord_y>::type>::type, coord_y>::value, "idempotence check failed");
static_assert(std::is_same<vert_lut<vert_lut<coord_x>::type>::type, coord_x>::value, "idempotence check failed");
static_assert(std::is_same<vert_lut<vert_lut<coord_w>::type>::type, coord_w>::value, "idempotence check failed");
static_assert(std::is_same<vert_lut<vert_lut<coord_z>::type>::type, coord_z>::value, "idempotence check failed");
// Check that horz_lut is idempotent
static_assert(std::is_same<horz_lut<horz_lut<coord_y>::type>::type, coord_y>::value, "idempotence check failed");
static_assert(std::is_same<horz_lut<horz_lut<coord_x>::type>::type, coord_x>::value, "idempotence check failed");
static_assert(std::is_same<horz_lut<horz_lut<coord_w>::type>::type, coord_w>::value, "idempotence check failed");
static_assert(std::is_same<horz_lut<horz_lut<coord_z>::type>::type, coord_z>::value, "idempotence check failed");
// Check that vert_lut and horz_lut are orthogonal
static_assert(std::is_same<vert_lut<horz_lut<coord_y>::type>::type, coord_x>::value, "orthogonality check failed");
static_assert(std::is_same<vert_lut<horz_lut<coord_x>::type>::type, coord_y>::value, "orthogonality check failed");
static_assert(std::is_same<vert_lut<horz_lut<coord_w>::type>::type, coord_z>::value, "orthogonality check failed");
static_assert(std::is_same<vert_lut<horz_lut<coord_z>::type>::type, coord_w>::value, "orthogonality check failed");
static_assert(std::is_same<horz_lut<vert_lut<coord_y>::type>::type, coord_x>::value, "orthogonality check failed");
static_assert(std::is_same<horz_lut<vert_lut<coord_x>::type>::type, coord_y>::value, "orthogonality check failed");
static_assert(std::is_same<horz_lut<vert_lut<coord_w>::type>::type, coord_z>::value, "orthogonality check failed");
static_assert(std::is_same<horz_lut<vert_lut<coord_z>::type>::type, coord_w>::value, "orthogonality check failed");
//! This template class represents a generic coordinate type. The intention is
//! that the template parameter T is one of coord_w, coord_z, coord_y, coord_x.
//! Class instances are meant to behave similar to a size_t; but similar to a
//! system of units, we disallow implicit conversions between coordinates of
//! different kinds.
template<typename T>
class coordinate_base;
//! This function is coodinate_base's only friend. It performs an explicit
//! conversion from a coordinate_base<T> to a size_t. Ideally, this will be
//! used very rarely outside of the coordinate_converter class.
template<typename T>
size_t coordinate_index(coordinate_base<T>);
template<typename T>
class coordinate_base {
typedef coordinate_base<T> cb;
friend size_t coordinate_index<T>(cb);
size_t v;
operator size_t() { return v; }
public:
constexpr coordinate_base() {}
coordinate_base(size_t v) : v(v) {}
coordinate_base(const coordinate_base<T> &c) : v(c.v) {}
cb operator++(int) { cb t = *this; v++; return t; }
cb operator--(int) { cb t = *this; v--; return t; }
cb &operator++() { v++; return *this; }
cb &operator--() { v--; return *this; }
cb operator+(cb a) const { return v+a; }
cb operator-(cb a) const { return v-a; }
cb operator/(cb a) const { return v/a; }
cb operator*(cb a) const { return v*a; }
cb operator+(unsigned int a) const { return v+a; }
cb operator-(unsigned int a) const { return v-a; }
cb operator/(unsigned int a) const { return v/a; }
cb operator*(unsigned int a) const { return v*a; }
bool operator<(cb a) const { return v<a.v; }
bool operator>(cb a) const { return v>a.v; }
bool operator<=(cb a) const { return v<=a.v; }
bool operator>=(cb a) const { return v>=a.v; }
bool operator==(cb a) const { return v==a.v; }
};
//!
//! a class to protect y-coordinates as a unit type
typedef coordinate_base<coord_y> size_y;
//! a class to protect x-coordinates as a unit type
typedef coordinate_base<coord_x> size_x;
//! a class to protect w-coordinates as a unit type -- given a qubit, the w
//! coordinate corresponds to an offset perpendicular to the qubit
typedef coordinate_base<coord_w> size_w;
//! a class to protect z-coordinates as a unit type -- given a qubit, the z
//! coordinate corresponds to an offset parallel to the qubit
typedef coordinate_base<coord_z> size_z;
template<typename T>
size_t coordinate_index(coordinate_base<T> c) {
return c;
}
//! This purely for convenience, to make implementations of coordinate_converter
//! methods cleaner.
size_t coordinate_index(size_t c) {
return c;
}
//! This function translates between relative coordinates (w, z) and matrix
//! coordinates (y, x) in the context of a vertical qubit address.
template<typename T>
coordinate_base<typename vert_lut<T>::type> vert(const coordinate_base<T> c) {
return coordinate_index(c);
}
template<typename T>
coordinate_base<typename horz_lut<T>::type> horz(const coordinate_base<T> c) {
return coordinate_index(c);
}
template<typename T>
size_t binom(coordinate_base<T> c) {
return binom(coordinate_index(c));
}
#else
// if neither CPPDEBUG nor COORDINATE_TYPES is set, we take the safeties off.
// All coordinates are just size_t's.
typedef size_t size_y;
typedef size_t size_x;
typedef size_t size_w;
typedef size_t size_z;
inline const size_t &coordinate_index(const size_t &c) { return c; }
inline const size_t &vert(const size_t &c) { return c; }
inline const size_t &horz(const size_t &c) { return c; }
#endif
//! An arena to perform arithmetic that does not respect the unit system defined
//! in coordinate_base<T>. This class is not a friend of coordinate_base<T> so
//! so that we can do all of our bounds-checking here, with full type-safety.
//! The generic pattern is that bounds-checking is done inside a public method,
//! respecting the unit systems, and then we explicitly convert coordinates and
//! dimensions to size_t, to be combined in a private method with the _impl
//! suffix.
class coordinate_converter {
private:
//! a convenience shortener to reduce line lengths
template<typename T>
static size_t coord(T c) { return coordinate_index(c); }
private:
//! private implementation of cell_index
static size_t cell_index_impl(size_t y, size_t x, size_t u, size_t dim_y, size_t dim_x) {
return u + 2*(x + dim_x*y);
}
public:
//! This computes compute the index of A[u][y][x] in an array A of dimension
//! [2][dim_y][dim_x]
static size_t cell_index(size_y y, size_x x, bool u, size_y dim_y, size_x dim_x) {
minorminer_assert(y < dim_y);
minorminer_assert(x < dim_x);
return cell_index_impl(coord(y), coord(x), u, coord(dim_y), coord(dim_x));
}
//! This computes compute the index of A[u][y][x] in an array A of dimension
//! [2][dim_y][dim_x]; where y and x are determined from w and z, depending
//! on the orientation u
static size_t cell_index(bool u, size_w w, size_z z, size_y dim_y, size_x dim_x) {
if (u) {
return cell_index(horz(w), horz(z), u, dim_y, dim_x);
} else {
return cell_index(vert(z), vert(w), u, dim_y, dim_x);
}
}
private:
//! private implementation of chimera_linear
static size_t chimera_linear_impl(size_t y, size_t x, size_t u, size_t k, size_t dim_y, size_t dim_x, size_t shore) {
return k + shore*(u + 2*(x + dim_x*y));
}
public:
//! given a chimera coordinate (y, x, u, k) with chimera dimensions
//! (m, n, t) = (dim_y, dim_x, shore), compute the linear index.
template <typename shore_t>
static size_t chimera_linear(size_y y, size_x x, bool u, shore_t k, size_y dim_y, size_x dim_x, shore_t shore) {
minorminer_assert(y < dim_y);
minorminer_assert(x < dim_x);
minorminer_assert(k < shore);
return chimera_linear_impl(coord(y), coord(x), u, k, coord(dim_y), coord(dim_x), shore);
}
//! given a linear index q0 in a chimera graph with dimensions
//! (m, n, t) = (dim_y, dim_x, shore), compute the coordinate (y, x, u, k)
template <typename shore_t>
static void linear_chimera(size_t q0, size_y &y, size_x &x, bool &u, shore_t &k, size_y dim_y, size_x dim_x, shore_t shore) {
size_t q = q0;
k = q%coord(shore);
q = q/coord(shore);
u = q%2;
q = q/2;
x = q%coord(dim_x);
q = q/coord(dim_x);
minorminer_assert(q < coord(dim_y));
y = q;
minorminer_assert(q0 == chimera_linear(y, x, u, k, dim_y, dim_x, shore));
}
private:
//! private implementation of linemajor_linear
static size_t linemajor_linear_impl(size_t u, size_t w, size_t k, size_t z, size_t dim_w, size_t shore, size_t dim_z) {
return z + dim_z*(k + shore*(w + dim_w*u));
}
public:
//! Pegasus and Zephyr coordinates exist in relative coordinate systems. We
//! note that our implementation of Zephyr coordinates differs from the one
//! used other places -- we've merged the k and j indices into one. The name
//! 'linemajor' indicates that the (u, w, k) parameters specify a line of
//! colinear qubits. This function is used to pack a Zephyr or Pegasus
//! coordinate address (u, w, k, z) into a linear index. The interpretation
//! of dim_w, shore, and dim_z is determined by the relevant topology, and
//! we expect callers to know what they're doing.
//! Specifically, for pegasus_graph(m), dim_w = 6*m, shore = 2, dim_z = m-1
//! and for zephyr_graph(m), dim_w = 2*m+1, shore=2*t, dim_z = m
template <typename shore_t>
static size_t linemajor_linear(bool u, size_w w, shore_t k, size_z z, size_w dim_w, shore_t shore, size_z dim_z) {
minorminer_assert(w < dim_w);
minorminer_assert(k < shore);
minorminer_assert(z < dim_z);
return linemajor_linear_impl(u, coord(w), k, coord(z), coord(dim_w), shore, coord(dim_z));
}
//! Pegasus and Zephyr coordinates exist in relative coordinate systems. We
//! note that our implementation of Zephyr coordinates differs from the one
//! used other places -- we've merged the k and j indices into one. The name
//! 'linemajor' indicates that the (u, w, k) parameters specify a line of
//! colinear qubits. This function is used to unpack a Zephyr or Pegasus
//! linear index to a coordinate address (u, w, k, z). The interpretation
//! of dim_w, shore, and dim_z is determined by the relevant topology, and
//! we expect callers to know what they're doing.
//! Specifically, for pegasus_graph(m), dim_w = 6*m, shore = 2, dim_z = m-1
//! and for zephyr_graph(m), dim_w = 2*m+1, shore=2*t, dim_z = m
template <typename shore_t>
static void linear_linemajor(size_t q0, bool &u, size_w &w, shore_t &k, size_z &z, size_w dim_w, shore_t shore, size_z dim_z) {
size_t q = q0;
z = q%coord(dim_z);
q = q/coord(dim_z);
k = q%shore;
q = q/shore;
w = q%coord(dim_w);
q = q/coord(dim_w);
minorminer_assert(q < 2);
u = q;
minorminer_assert(q0 == linemajor_linear(u, w, k, z, dim_w, shore, dim_z));
}
public:
template<typename T, typename ... Args>
static size_t product(T t) { return coord(t); }
//! explicitly convert all arguments into a size_t and return the product of
//! them all.
template<typename T, typename ... Args>
static size_t product(T t, Args ...args) {
return coord(t) * product(args...);
}
template<typename T, typename ... Args>
static size_t sum(T t) { return coord(t); }
//! explicitly convert all arguments into a size_t and return the product of
//! them all.
template<typename T, typename ... Args>
static size_t sum(T t, Args ...args) {
return coord(t) + sum(args...);
}
//! explicitly convert both arguments into a size_t and return the minimum
template<typename S, typename T>
static size_t min(S s, T t) { return std::min(coord(s), coord(t)); }
//! explicitly convert both arguments into a size_t and return the maximum
template<typename S, typename T>
static size_t max(S s, T t) { return std::max(coord(s), coord(t)); }
private:
//! private implementation of grid_index
static size_t grid_index_impl(size_t y, size_t x, size_t dim_y, size_t dim_x) {
return x + dim_x*y;
}
public:
//! Implements addressing into a 2-dimensional array T[dim_y][dim_x]
static size_t grid_index(size_y y, size_x x, size_y dim_y, size_x dim_x) {
minorminer_assert(y < dim_y);
minorminer_assert(x < dim_x);
return grid_index_impl(coord(y), coord(x), coord(dim_y), coord(dim_x));
}
private:
//! private implementation of bundle_cache_index
static size_t bundle_cache_index_impl(size_t u, size_t w, size_t z0, size_t z1, size_t stride_u, size_t stride_w) {
minorminer_assert(z0 <= z1);
minorminer_assert(binom(z1) + z0 < stride_w);
return u*stride_u + w*stride_w + binom(z1) + z0;
}
public:
//! This addressing scheme is wikkid complicated. The majority of the logic
//! is contained in bundle_cache.hpp. We store line masks (that is, sets of
//! k-indices) corresponding to the line segment (u, w, z0, z1). That is,
//! if the bit i is set in line_mask[bundle_cache_index(u, w, z0, z1)], then
//! line of qubits [(u, w, i, z) for z in range(z0, z1+1)] and the necessary
//! external couplers are present in the linemajor representation of the
//! topology. We assume that the caller knows what it's doing with stride_u
//! and stride_w. We do belts-and-suspenders assertion testing in
//! bundle_cache::compute_line_masks for added confidence that the caller
//! actually knows what it's doing.
static size_t bundle_cache_index(bool u, size_w w, size_z z0, size_z z1, size_t stride_u, size_t stride_w) {
return bundle_cache_index_impl(u, coord(w), coord(z0), coord(z1), stride_u, stride_w);
}
};
}
| 20,360 | 6,873 |
/*
Copyright 2017 Nervana Systems Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#pragma once
#include <vector>
#include <string>
#include <opencv2/core/core.hpp>
extern std::vector<std::string> label_list;
std::vector<uint8_t> make_image_from_metadata(const std::string& metadata);
nervana::boundingbox::box
crop_single_box(nervana::boundingbox::box expected, cv::Rect cropbox, float scale);
void plot(const std::vector<nervana::box>& list, const std::string& prefix);
void plot(const std::string& path);
| 1,009 | 309 |
// Copyright (C) 2015-2019 Internet Systems Consortium, Inc. ("ISC")
//
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include <config.h>
#include <eval/dependency.h>
#include <dhcpsrv/client_class_def.h>
#include <dhcpsrv/cfgmgr.h>
#include <boost/foreach.hpp>
using namespace isc::data;
namespace isc {
namespace dhcp {
//********** ClientClassDef ******************//
ClientClassDef::ClientClassDef(const std::string& name,
const ExpressionPtr& match_expr,
const CfgOptionPtr& cfg_option)
: name_(name), match_expr_(match_expr), required_(false),
depend_on_known_(false), cfg_option_(cfg_option),
next_server_(asiolink::IOAddress::IPV4_ZERO_ADDRESS()) {
// Name can't be blank
if (name_.empty()) {
isc_throw(BadValue, "Client Class name cannot be blank");
}
// We permit an empty expression for now. This will likely be useful
// for automatic classes such as vendor class.
// For classes without options, make sure we have an empty collection
if (!cfg_option_) {
cfg_option_.reset(new CfgOption());
}
}
ClientClassDef::ClientClassDef(const ClientClassDef& rhs)
: name_(rhs.name_), match_expr_(ExpressionPtr()), required_(false),
depend_on_known_(false), cfg_option_(new CfgOption()),
next_server_(asiolink::IOAddress::IPV4_ZERO_ADDRESS()) {
if (rhs.match_expr_) {
match_expr_.reset(new Expression());
*match_expr_ = *(rhs.match_expr_);
}
if (rhs.cfg_option_def_) {
rhs.cfg_option_def_->copyTo(*cfg_option_def_);
}
if (rhs.cfg_option_) {
rhs.cfg_option_->copyTo(*cfg_option_);
}
required_ = rhs.required_;
depend_on_known_ = rhs.depend_on_known_;
next_server_ = rhs.next_server_;
sname_ = rhs.sname_;
filename_ = rhs.filename_;
}
ClientClassDef::~ClientClassDef() {
}
std::string
ClientClassDef::getName() const {
return (name_);
}
void
ClientClassDef::setName(const std::string& name) {
name_ = name;
}
const ExpressionPtr&
ClientClassDef::getMatchExpr() const {
return (match_expr_);
}
void
ClientClassDef::setMatchExpr(const ExpressionPtr& match_expr) {
match_expr_ = match_expr;
}
std::string
ClientClassDef::getTest() const {
return (test_);
}
void
ClientClassDef::setTest(const std::string& test) {
test_ = test;
}
bool
ClientClassDef::getRequired() const {
return (required_);
}
void
ClientClassDef::setRequired(bool required) {
required_ = required;
}
bool
ClientClassDef::getDependOnKnown() const {
return (depend_on_known_);
}
void
ClientClassDef::setDependOnKnown(bool depend_on_known) {
depend_on_known_ = depend_on_known;
}
const CfgOptionDefPtr&
ClientClassDef::getCfgOptionDef() const {
return (cfg_option_def_);
}
void
ClientClassDef::setCfgOptionDef(const CfgOptionDefPtr& cfg_option_def) {
cfg_option_def_ = cfg_option_def;
}
const CfgOptionPtr&
ClientClassDef::getCfgOption() const {
return (cfg_option_);
}
void
ClientClassDef::setCfgOption(const CfgOptionPtr& cfg_option) {
cfg_option_ = cfg_option;
}
bool
ClientClassDef::dependOnClass(const std::string& name) const {
return (isc::dhcp::dependOnClass(match_expr_, name));
}
bool
ClientClassDef::equals(const ClientClassDef& other) const {
return ((name_ == other.name_) &&
((!match_expr_ && !other.match_expr_) ||
(match_expr_ && other.match_expr_ &&
(*match_expr_ == *(other.match_expr_)))) &&
((!cfg_option_ && !other.cfg_option_) ||
(cfg_option_ && other.cfg_option_ &&
(*cfg_option_ == *other.cfg_option_))) &&
((!cfg_option_def_ && !other.cfg_option_def_) ||
(cfg_option_def_ && other.cfg_option_def_ &&
(*cfg_option_def_ == *other.cfg_option_def_))) &&
(required_ == other.required_) &&
(depend_on_known_ == other.depend_on_known_) &&
(next_server_ == other.next_server_) &&
(sname_ == other.sname_) &&
(filename_ == other.filename_));
}
ElementPtr
ClientClassDef:: toElement() const {
uint16_t family = CfgMgr::instance().getFamily();
ElementPtr result = Element::createMap();
// Set user-context
contextToElement(result);
// Set name
result->set("name", Element::create(name_));
// Set original match expression (empty string won't parse)
if (!test_.empty()) {
result->set("test", Element::create(test_));
}
// Set only-if-required
if (required_) {
result->set("only-if-required", Element::create(required_));
}
// Set option-def (used only by DHCPv4)
if (cfg_option_def_ && (family == AF_INET)) {
result->set("option-def", cfg_option_def_->toElement());
}
// Set option-data
result->set("option-data", cfg_option_->toElement());
if (family != AF_INET) {
// Other parameters are DHCPv4 specific
return (result);
}
// Set next-server
result->set("next-server", Element::create(next_server_.toText()));
// Set server-hostname
result->set("server-hostname", Element::create(sname_));
// Set boot-file-name
result->set("boot-file-name", Element::create(filename_));
return (result);
}
std::ostream& operator<<(std::ostream& os, const ClientClassDef& x) {
os << "ClientClassDef:" << x.getName();
return (os);
}
//********** ClientClassDictionary ******************//
ClientClassDictionary::ClientClassDictionary()
: map_(new ClientClassDefMap()), list_(new ClientClassDefList()) {
}
ClientClassDictionary::ClientClassDictionary(const ClientClassDictionary& rhs)
: map_(new ClientClassDefMap()), list_(new ClientClassDefList()) {
BOOST_FOREACH(ClientClassDefPtr cclass, *(rhs.list_)) {
ClientClassDefPtr copy(new ClientClassDef(*cclass));
addClass(copy);
}
}
ClientClassDictionary::~ClientClassDictionary() {
}
void
ClientClassDictionary::addClass(const std::string& name,
const ExpressionPtr& match_expr,
const std::string& test,
bool required,
bool depend_on_known,
const CfgOptionPtr& cfg_option,
CfgOptionDefPtr cfg_option_def,
ConstElementPtr user_context,
asiolink::IOAddress next_server,
const std::string& sname,
const std::string& filename) {
ClientClassDefPtr cclass(new ClientClassDef(name, match_expr, cfg_option));
cclass->setTest(test);
cclass->setRequired(required);
cclass->setDependOnKnown(depend_on_known);
cclass->setCfgOptionDef(cfg_option_def);
cclass->setContext(user_context),
cclass->setNextServer(next_server);
cclass->setSname(sname);
cclass->setFilename(filename);
addClass(cclass);
}
void
ClientClassDictionary::addClass(ClientClassDefPtr& class_def) {
if (!class_def) {
isc_throw(BadValue, "ClientClassDictionary::addClass "
" - class definition cannot be null");
}
if (findClass(class_def->getName())) {
isc_throw(DuplicateClientClassDef, "Client Class: "
<< class_def->getName() << " has already been defined");
}
list_->push_back(class_def);
(*map_)[class_def->getName()] = class_def;
}
ClientClassDefPtr
ClientClassDictionary::findClass(const std::string& name) const {
ClientClassDefMap::iterator it = map_->find(name);
if (it != map_->end()) {
return (*it).second;
}
return(ClientClassDefPtr());
}
void
ClientClassDictionary::removeClass(const std::string& name) {
for (ClientClassDefList::iterator this_class = list_->begin();
this_class != list_->end(); ++this_class) {
if ((*this_class)->getName() == name) {
list_->erase(this_class);
break;
}
}
map_->erase(name);
}
const ClientClassDefListPtr&
ClientClassDictionary::getClasses() const {
return (list_);
}
bool
ClientClassDictionary::dependOnClass(const std::string& name,
std::string& dependent_class) const {
// Skip previous classes as they should not depend on name.
bool found = false;
for (ClientClassDefList::iterator this_class = list_->begin();
this_class != list_->end(); ++this_class) {
if (found) {
if ((*this_class)->dependOnClass(name)) {
dependent_class = (*this_class)->getName();
return (true);
}
} else {
if ((*this_class)->getName() == name) {
found = true;
}
}
}
return (false);
}
bool
ClientClassDictionary::equals(const ClientClassDictionary& other) const {
if (list_->size() != other.list_->size()) {
return (false);
}
ClientClassDefList::const_iterator this_class = list_->cbegin();
ClientClassDefList::const_iterator other_class = other.list_->cbegin();
while (this_class != list_->cend() &&
other_class != other.list_->cend()) {
if (!*this_class || !*other_class ||
**this_class != **other_class) {
return false;
}
++this_class;
++other_class;
}
return (true);
}
ElementPtr
ClientClassDictionary::toElement() const {
ElementPtr result = Element::createList();
// Iterate on the map
for (ClientClassDefList::const_iterator this_class = list_->begin();
this_class != list_->cend(); ++this_class) {
result->add((*this_class)->toElement());
}
return (result);
}
std::list<std::string>
builtinNames = {
// DROP is not in this list because it is special but not built-in.
// In fact DROP is set from an expression as callouts can drop
// directly the incoming packet. The expression must not depend on
// KNOWN/UNKNOWN which are set far after the drop point.
"ALL", "KNOWN", "UNKNOWN", "BOOTP"
};
std::list<std::string>
builtinPrefixes = {
"VENDOR_CLASS_", "HA_", "AFTER_", "EXTERNAL_"
};
bool
isClientClassBuiltIn(const ClientClass& client_class) {
for (std::list<std::string>::const_iterator bn = builtinNames.cbegin();
bn != builtinNames.cend(); ++bn) {
if (client_class == *bn) {
return true;
}
}
for (std::list<std::string>::const_iterator bt = builtinPrefixes.cbegin();
bt != builtinPrefixes.cend(); ++bt) {
if (client_class.size() <= bt->size()) {
continue;
}
auto mis = std::mismatch(bt->cbegin(), bt->cend(), client_class.cbegin());
if (mis.first == bt->cend()) {
return true;
}
}
return false;
}
bool
isClientClassDefined(ClientClassDictionaryPtr& class_dictionary,
bool& depend_on_known,
const ClientClass& client_class) {
// First check built-in classes
if (isClientClassBuiltIn(client_class)) {
// Check direct dependency on [UN]KNOWN
if ((client_class == "KNOWN") || (client_class == "UNKNOWN")) {
depend_on_known = true;
}
return (true);
}
// Second check already defined, i.e. in the dictionary
ClientClassDefPtr def = class_dictionary->findClass(client_class);
if (def) {
// Check indirect dependency on [UN]KNOWN
if (def->getDependOnKnown()) {
depend_on_known = true;
}
return (true);
}
// Not defined...
return (false);
}
} // namespace isc::dhcp
} // namespace isc
| 11,876 | 3,691 |
/*
Copyright (c) 2017, Arvid Norberg
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
* Neither the name of the author nor the names of its
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef TORRENT_DEFERRED_HANDLER_HPP
#define TORRENT_DEFERRED_HANDLER_HPP
#include "libtorrent/assert.hpp"
#include "libtorrent/io_service.hpp"
namespace libtorrent { namespace aux {
template <typename Handler>
struct handler_wrapper
{
handler_wrapper(bool& in_flight, Handler&& h)
: m_handler(std::move(h))
, m_in_flight(in_flight) {}
template <typename... Args>
void operator()(Args&&... a)
{
TORRENT_ASSERT(m_in_flight);
m_in_flight = false;
m_handler(std::forward<Args>(a)...);
}
// forward asio handler allocator to the underlying handler's
friend void* asio_handler_allocate(
std::size_t size, handler_wrapper<Handler>* h)
{
return asio_handler_allocate(size, &h->m_handler);
}
friend void asio_handler_deallocate(
void* ptr, std::size_t size, handler_wrapper<Handler>* h)
{
asio_handler_deallocate(ptr, size, &h->m_handler);
}
private:
Handler m_handler;
bool& m_in_flight;
};
struct deferred_handler
{
template <typename Handler>
void post(io_service& ios, Handler&& h)
{
if (m_in_flight) return;
m_in_flight = true;
ios.post(handler_wrapper<Handler>(m_in_flight, std::forward<Handler>(h)));
}
private:
bool m_in_flight = false;
};
}}
#endif
| 2,720 | 1,003 |
#include "Color.h"
#include "Colorf.h"
#include <assert.h>
#include "config.h"
//-----------------------------------------------------------------------------
namespace pix
{
inline static uint8_t convertColorFloatToByte( float src )
{
float f = src;
if ( f < 0.f )
f = 0.f;
else if ( f > 1.f )
f = 1.f;
int i = (int)( f*255.f + .5f );
if ( i < 0 )
i = 0;
else if ( i > 255 )
i = 255;
assert( i >= 0 && i < 256 );
return (uint8_t)i;
}
//-----------------------------------------------------------------------------
Color::Color( const Colorf& source )
{
setRed( convertColorFloatToByte(source.red()) );
setGreen( convertColorFloatToByte(source.green()) );
setBlue( convertColorFloatToByte(source.blue()) );
setAlpha( convertColorFloatToByte(source.alpha()) );
}
} // pix
| 842 | 330 |
class Solution {
public:
int max(int a, int b) {
if(a > b) return a;
else return b;
}
int lengthOfLongestSubstring(string s) {
if(s.length() == 0) return 0;
set<char> set;
int left = 0, right = 0, length = 0;
while(right < s.length()) {
if(set.find(s[right]) == set.end()){
set.insert(s[right]);
right++;
length = max(length, set.size());
} else {
set.erase(s[left]);
left++;
}
}
return length;
}
};s | 596 | 187 |
//==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
// Copyright 2012 - 2014 MetaScale SAS
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED
#define BOOST_SIMD_ARITHMETIC_FUNCTIONS_GENERIC_REMQUO_HPP_INCLUDED
#include <boost/simd/arithmetic/functions/remquo.hpp>
#include <boost/simd/include/functions/simd/round2even.hpp>
#include <boost/simd/include/functions/simd/toint.hpp>
#include <boost/simd/include/functions/simd/minus.hpp>
#include <boost/simd/include/functions/simd/is_eqz.hpp>
#include <boost/simd/include/functions/simd/divides.hpp>
#include <boost/simd/include/functions/simd/is_invalid.hpp>
#include <boost/simd/include/functions/simd/logical_or.hpp>
#include <boost/simd/include/functions/simd/multiplies.hpp>
#include <boost/simd/include/functions/simd/if_allbits_else.hpp>
#include <boost/simd/sdk/config.hpp>
#include <boost/dispatch/meta/as_integer.hpp>
#include <boost/fusion/include/std_pair.hpp>
#include <boost/type_traits/is_same.hpp>
#include <boost/dispatch/attributes.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_DISPATCH_IMPLEMENT_IF ( remquo_
, tag::cpu_
, (A0)(A1)
, ( boost::is_same
< typename dispatch::meta::
as_integer<A0,signed>::type
, A1
>
)
, (generic_< floating_<A0> >)
(generic_< floating_<A0> >)
(generic_< integer_<A1> > )
)
{
typedef A0 result_type;
BOOST_FORCEINLINE
result_type operator()(A0 const& a0,A0 const& a1,A1& a3) const
{
result_type a2;
boost::simd::remquo(a0, a1, a2, a3);
return a2;
}
};
BOOST_DISPATCH_IMPLEMENT ( remquo_, tag::cpu_
, (A0)
, (generic_< floating_<A0> >)
(generic_< floating_<A0> >)
)
{
typedef typename dispatch::meta::as_integer<A0, signed>::type quo_t;
typedef std::pair<A0,quo_t> result_type;
BOOST_FORCEINLINE result_type operator()(A0 const& a0,A0 const& a1) const
{
A0 first;
quo_t second;
boost::simd::remquo( a0, a1, first, second );
return result_type(first, second);
}
};
BOOST_DISPATCH_IMPLEMENT_IF ( remquo_, tag::cpu_
, (A0)(A1)
, ( boost::is_same
< typename dispatch::meta::
as_integer<A0,signed>::type
, A1
>
)
, (generic_<floating_<A0> >)
(generic_<floating_<A0> >)
(generic_<floating_<A0> >)
(generic_<integer_ <A1> >)
)
{
typedef void result_type;
BOOST_FORCEINLINE
result_type operator()(A0 const& a0, A0 const& a1,A0& a2, A1& a3) const
{
A0 const d = round2even(a0/a1);
#if defined(BOOST_SIMD_NO_INVALIDS)
a2 = if_allbits_else(is_eqz(a1), a0-d*a1);
#else
a2 = if_allbits_else(l_or(is_invalid(a0), is_eqz(a1)), a0-d*a1);
#endif
a3 = toint(d);
}
};
} } }
#endif
| 4,311 | 1,366 |
#include "ndnph/app/ping-client.hpp"
#include "ndnph/app/ping-server.hpp"
#include "ndnph/keychain/ec.hpp"
#include "ndnph/keychain/null.hpp"
#include "mock/bridge-fixture.hpp"
#include "mock/mock-key.hpp"
#include "mock/mock-transport.hpp"
#include "test-common.hpp"
namespace ndnph {
namespace {
TEST(Ping, Client)
{
g::NiceMock<MockTransport> transport;
Face face(transport);
StaticRegion<1024> region;
PingClient client(Name::parse(region, "/ping"), face, 10);
int nInterests = 0;
EXPECT_CALL(transport, doSend)
.Times(g::Between(5, 20))
.WillRepeatedly([&](std::vector<uint8_t> wire, uint64_t) {
StaticRegion<1024> region;
Interest interest = region.create<Interest>();
EXPECT_TRUE(Decoder(wire.data(), wire.size()).decode(interest));
EXPECT_EQ(interest.getName().size(), 2);
EXPECT_FALSE(interest.getCanBePrefix());
EXPECT_TRUE(interest.getMustBeFresh());
++nInterests;
if (nInterests == 2) {
Data data = region.create<Data>();
data.setName(interest.getName().getPrefix(-1));
data.setFreshnessPeriod(1);
transport.receive(data.sign(NullKey::get()));
} else if (nInterests == 4) {
// no response
} else {
Data data = region.create<Data>();
data.setName(interest.getName());
data.setFreshnessPeriod(1);
transport.receive(data.sign(NullKey::get()));
}
return true;
});
for (int i = 0; i < 120; ++i) {
face.loop();
port::Clock::sleep(1);
}
auto cnt = client.readCounters();
EXPECT_EQ(cnt.nTxInterests, nInterests);
EXPECT_EQ(cnt.nRxData, cnt.nTxInterests - 2);
}
TEST(Ping, Server)
{
g::NiceMock<MockTransport> transport;
Face face(transport);
StaticRegion<1024> sRegion;
EcPrivateKey pvt;
EcPublicKey pub;
ASSERT_TRUE(ec::generate(sRegion, Name::parse(sRegion, "/server"), pvt, pub));
PingServer server(Name::parse(sRegion, "/ping"), face, pvt);
std::set<std::string> interestNames;
std::set<std::string> dataNames;
EXPECT_CALL(transport, doSend).Times(20).WillRepeatedly([&](std::vector<uint8_t> wire, uint64_t) {
StaticRegion<1024> tRegion;
Data data = tRegion.create<Data>();
EXPECT_TRUE(Decoder(wire.data(), wire.size()).decode(data));
EXPECT_TRUE(data.verify(pub));
std::string uri;
boost::conversion::try_lexical_convert(data.getName(), uri);
dataNames.insert(uri);
EXPECT_THAT(dataNames, g::ElementsAreArray(interestNames));
return true;
});
for (int i = 0; i < 20; ++i) {
std::string uri = "/8=ping/8=" + std::to_string(i);
interestNames.insert(uri);
StaticRegion<1024> cRegion;
Interest interest = cRegion.create<Interest>();
interest.setName(Name::parse(cRegion, uri.data()));
interest.setMustBeFresh(true);
transport.receive(interest);
face.loop();
}
EXPECT_THAT(dataNames, g::ElementsAreArray(interestNames));
}
using PingEndToEndFixture = BridgeFixture;
TEST_F(PingEndToEndFixture, EndToEnd)
{
StaticRegion<1024> region;
PingServer serverA(Name::parse(region, "/ping"), faceA);
PingClient clientB(Name::parse(region, "/ping"), faceB, 10);
int i = 120;
runInThreads([] {}, [&] { return --i >= 0; });
auto cnt = clientB.readCounters();
EXPECT_GE(cnt.nTxInterests, 5);
EXPECT_LE(cnt.nTxInterests, 20);
EXPECT_GE(cnt.nRxData, cnt.nTxInterests - 2);
EXPECT_LE(cnt.nRxData, cnt.nTxInterests);
}
} // namespace
} // namespace ndnph
| 3,460 | 1,342 |
//
// OCCAM
//
// Copyright (c) 2011-2016, SRI International
//
// 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 SRI International nor the names of its contributors may
// be used to endorse or promote products derived from this software without
// specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#include "llvm/ADT/StringMap.h"
#include "llvm/IR/User.h"
#include "llvm/IR/InstVisitor.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Instructions.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#include "llvm/Pass.h"
//#include "llvm/IR/PassManager.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/raw_ostream.h"
#include "PrevirtualizeInterfaces.h"
#include <vector>
#include <string>
#include <fstream>
using namespace llvm;
static cl::opt<std::string>
KeepExternalFile("Pkeep-external",
cl::desc("<file> : list of function names to be whitelisted"),
cl::init(""));
namespace previrt
{
static inline GlobalValue::LinkageTypes
localizeLinkage(GlobalValue::LinkageTypes l)
{
switch (l) {
case GlobalValue::ExternalLinkage:
return GlobalValue::InternalLinkage;
case GlobalValue::ExternalWeakLinkage:
return GlobalValue::WeakODRLinkage;
case GlobalValue::AppendingLinkage:
return GlobalValue::AppendingLinkage;
case GlobalValue::CommonLinkage:
// CommonLinkage is most similar to weak linkage
// However, we mark it as internal linkage so that other
// optimizations are applicable.
//return GlobalValue::WeakODRLinkage;
return GlobalValue::InternalLinkage;
// TODO I'm not sure if all external definitions have an
// appropriate internal counterpart
default:
errs() << "Got other linkage! " << l << "\n";
return l;
}
}
/*
* Remove all code from the given module that is not necessary to
* implement the given interface.
*/
bool
MinimizeComponent(Module& M, const ComponentInterface& I)
{
bool modified = false;
int hidden = 0;
int internalized = 0;
/*
errs() << "<interface>\n";
I.dump();
errs() << "</interface>\n";
*/
std::set<std::string> keep_external;
if (KeepExternalFile != "") {
std::ifstream infile(KeepExternalFile);
if (infile.is_open()) {
std::string line;
while (std::getline(infile, line)) {
//errs() << "Adding " << line << " to the white list.\n";
keep_external.insert(line);
}
infile.close();
} else {
errs() << "Warning: ignored whitelist because something failed.\n";
}
}
// Set all functions that are not in the interface to internal linkage only
for (auto &f: M) {
if (keep_external.count(f.getName())) {
errs() << "Did not internalize " << f.getName() << " because it is whitelisted.\n";
continue;
}
if (!f.isDeclaration() && f.hasExternalLinkage() &&
I.calls.find(f.getName()) == I.calls.end() &&
I.references.find(f.getName()) == I.references.end()) {
errs() << "Hiding '" << f.getName() << "'\n";
f.setLinkage(GlobalValue::InternalLinkage);
hidden++;
modified = true;
}
}
// Set all initialized global variables that are not referenced in
// the interface to "localized linkage" only
for (auto &gv: M.globals()) {
if (gv.hasName() && keep_external.count(gv.getName())) {
errs() << "Did not internalize " << gv.getName() << " because it is whitelisted.\n";
continue;
}
if ((gv.hasExternalLinkage() || gv.hasCommonLinkage()) &&
gv.hasInitializer() &&
I.references.find(gv.getName()) == I.references.end()) {
errs() << "internalizing '" << gv.getName() << "'\n";
gv.setLinkage(localizeLinkage(gv.getLinkage()));
internalized++;
modified = true;
}
}
/* TODO: We want to do this, but libc has some problems...
for (Module::alias_iterator i = M.alias_begin(), e = M.alias_end(); i != e; ++i) {
if (i->hasExternalLinkage() &&
I.references.find(i->getName()) == I.references.end() &&
I.calls.find(i->getName()) == end) {
errs() << "internalizing '" << i->getName() << "'\n";
i->setLinkage(localizeLinkage(i->getLinkage()));
modified = true;
}
}
*/
// Perform global dead code elimination
// TODO: To what extent should we do this here, versus
// doing it elsewhere?
legacy::PassManager cdeMgr;
legacy::PassManager mcMgr;
ModulePass* modulePassDCE = createGlobalDCEPass();
cdeMgr.add(modulePassDCE);
//mfMgr.add(createMergeFunctionsPass());
ModulePass* constantMergePass = createConstantMergePass();
mcMgr.add(constantMergePass);
bool moreToDo = true;
unsigned int iters = 0;
while (moreToDo && iters < 10000) {
moreToDo = false;
if (cdeMgr.run(M)) moreToDo = true;
// (originally commented) if (mfMgr.run(M)) moreToDo = true;
if (mcMgr.run(M)) moreToDo = true;
modified = modified || moreToDo;
++iters;
}
if (moreToDo) {
if (cdeMgr.run(M))
errs() << "GlobalDCE still had more to do\n";
//if (mfMgr.run(M)) errs() << "MergeFunctions still had more to do\n";
if (mcMgr.run(M))
errs() << "MergeConstants still had more to do\n";
}
if (modified) {
errs() << "Progress: hidden = " << hidden << " internalized " << internalized << "\n";
}
return modified;
}
static cl::list<std::string> OccamComponentInput(
"Poccam-input", cl::NotHidden, cl::desc(
"specifies the interface to prune with respect to"));
class OccamPass : public ModulePass
{
public:
ComponentInterface interface;
static char ID;
public:
OccamPass() :
ModulePass(ID)
{
errs() << "OccamPass()\n";
for (cl::list<std::string>::const_iterator b =
OccamComponentInput.begin(), e = OccamComponentInput.end(); b
!= e; ++b) {
errs() << "Reading file '" << *b << "'...";
if (interface.readFromFile(*b)) {
errs() << "success\n";
} else {
errs() << "failed\n";
}
}
errs() << "Done reading.\n";
}
virtual
~OccamPass()
{
}
public:
virtual bool
runOnModule(Module& M)
{
errs() << "OccamPass::runOnModule: " << M.getModuleIdentifier() << "\n";
return MinimizeComponent(M, this->interface);
}
};
char OccamPass::ID;
static RegisterPass<OccamPass> X("Poccam",
"hide/eliminate all non-external dependencies", false, false);
}
| 7,879 | 2,666 |
#include <catch2/catch.hpp>
#include "../../share/json_helper.hpp"
#include "manipulator/types.hpp"
#include <pqrs/json.hpp>
TEST_CASE("simple_modifications.json") {
auto json = krbn::unit_testing::json_helper::load_jsonc("../../../src/apps/PreferencesWindow/Resources/simple_modifications.json");
for (const auto& entry : json) {
if (auto data = pqrs::json::find_object(entry, "data")) {
krbn::manipulator::to_event_definition e(data->value());
}
}
}
| 474 | 168 |
#include "openvslam/data/bow_vocabulary.h"
namespace openvslam {
namespace data {
namespace bow_vocabulary_util {
void compute_bow(data::bow_vocabulary* bow_vocab, const cv::Mat& descriptors, data::bow_vector& bow_vec, data::bow_feature_vector& bow_feat_vec) {
#ifdef USE_DBOW2
bow_vocab->transform(util::converter::to_desc_vec(descriptors), bow_vec, bow_feat_vec, 4);
#else
bow_vocab->transform(descriptors, 4, bow_vec, bow_feat_vec);
#endif
}
}; // namespace bow_vocabulary_util
}; // namespace data
}; // namespace openvslam
| 539 | 215 |
#include "MeshManager.h"
#include "BufferManager.h"
#include "MaterialManager.h"
#include "SkeletonManager.h"
#include "Resources/Mesh.h"
#include "Resources/Material.h"
#include "FileSystem/FileReader.h"
#include "FileSystem/DirectoryHelper.h"
#include "Renderer/IRenderer.h"
#include "Physics/Physics.h"
#include "ZEGameContext.h"
#define RETURN_SHAPE_IF(shapeType, s) \
if (StringFunc::Compare(s, #shapeType ) == 0) \
{ \
return shapeType; \
}
namespace ZE
{
IMPLEMENT_CLASS_1(MeshManager, ResourceManager)
struct MeshSkinData
{
Float32 Position[3];
Float32 Normal[3];
Float32 TexCoord[2];
Int32 BoneIDs[4];
Float32 BoneWeights[4];
};
struct MeshSkinDataWithTangent
{
Float32 Position[3];
Float32 Normal[3];
Float32 TexCoord[2];
Int32 BoneIDs[4];
Float32 BoneWeights[4];
Float32 Tangent[3];
};
MeshManager* MeshManager::s_instance = nullptr;
void MeshManager::Init()
{
Handle hMeshManager("Mesh Manager", sizeof(MeshManager));
s_instance = new(hMeshManager) MeshManager();
}
void MeshManager::Destroy()
{
if(s_instance)
s_instance->unloadResources();
delete s_instance;
s_instance = nullptr;
}
ZE::MeshManager* MeshManager::GetInstance()
{
return s_instance;
}
PhysicsShape GetShapeFromString(const char* shapeName)
{
RETURN_SHAPE_IF(BOX, shapeName)
RETURN_SHAPE_IF(SPHERE, shapeName)
RETURN_SHAPE_IF(CAPSULE, shapeName)
RETURN_SHAPE_IF(PLANE, shapeName)
RETURN_SHAPE_IF(CONVEX_MESHES, shapeName)
RETURN_SHAPE_IF(TRIANGLE_MESHES, shapeName)
RETURN_SHAPE_IF(HEIGHT_FIELDS, shapeName)
return PHYSICS_SHAPE_NONE;
}
void MeshManager::loadPhysicsBodySetup(FileReader* fileReader, Mesh* pMesh)
{
Handle hPhysicsBodySetup("Physics Body Setup", sizeof(PhysicsBodySetup));
PhysicsBodySetup* pPhysicsBodySetup = new(hPhysicsBodySetup) PhysicsBodySetup();
char tokenBuffer[64];
// Read physic data type : single/file/multi
fileReader->readNextString(tokenBuffer);
if (StringFunc::Compare(tokenBuffer, "single") == 0)
{
PhysicsBodyDesc bodyDesc;
fileReader->readNextString(tokenBuffer);
bodyDesc.ShapeType = GetShapeFromString(tokenBuffer);
switch (bodyDesc.ShapeType)
{
case BOX:
bodyDesc.HalfExtent.setX(fileReader->readNextFloat());
bodyDesc.HalfExtent.setY(fileReader->readNextFloat());
bodyDesc.HalfExtent.setZ(fileReader->readNextFloat());
break;
case SPHERE:
bodyDesc.Radius = fileReader->readNextFloat();
break;
case CAPSULE:
bodyDesc.Radius = fileReader->readNextFloat();
bodyDesc.HalfHeight = fileReader->readNextFloat();
break;
case PLANE:
break;
case CONVEX_MESHES:
// #TODO Read buffer
break;
case TRIANGLE_MESHES:
// #TODO Read buffer
break;
case HEIGHT_FIELDS:
// #TODO Read HeightField
break;
}
// Mass expected
fileReader->readNextString(tokenBuffer);
if (StringFunc::Compare(tokenBuffer, "Mass") == 0)
{
pPhysicsBodySetup->Mass = fileReader->readNextFloat();
}
pPhysicsBodySetup->m_bodies.push_back(bodyDesc);
}
else if (StringFunc::Compare(tokenBuffer, "multi") == 0)
{
// #TODO need to implement multi descriptor
}
else if (StringFunc::Compare(tokenBuffer, "file") == 0)
{
// #TODO need to implement file descriptor for this
}
pMesh->m_hPhysicsBodySetup = hPhysicsBodySetup;
}
ZE::ERenderTopologyEnum getTopologyByName(const char* stringType)
{
COMPARE_RETURN(stringType, TOPOLOGY_TRIANGLE_STRIP);
COMPARE_RETURN(stringType, TOPOLOGY_POINT);
COMPARE_RETURN(stringType, TOPOLOGY_LINE);
COMPARE_RETURN(stringType, TOPOLOGY_LINE_STRIP);
return TOPOLOGY_TRIANGLE;
}
void MeshManager::loadBuffers(FileReader* fileReader, Mesh* pMesh)
{
char buffer[256];
// READ VERTEX BUFFER
fileReader->readNextString(buffer);
int bufferLayoutType = getBufferLayoutByString(buffer);
if (bufferLayoutType == -1)
{
ZEINFO("BufferManager: Can't find buffer layout type for %s", buffer);
return;
}
Handle hVertexBufferData("Buffer Data", sizeof(BufferData));
BufferData* pVertexBuffer = new(hVertexBufferData) BufferData(VERTEX_BUFFER);
pVertexBuffer->setBufferLayout(bufferLayoutType);
int numVertex = fileReader->readNextInt();
Handle dataHandle;
if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_TC2_SKIN)
{
dataHandle = Handle("Data", sizeof(MeshSkinData) * numVertex);
MeshSkinData* pData = new(dataHandle) MeshSkinData[numVertex];
Vector3 minVertex(999999.9f);
Vector3 maxVertex(-999999.9f);
Vector3 centerVertex(0.0f);
for (int i = 0; i < numVertex; i++)
{
pData[i].Position[0] = fileReader->readNextFloat();
pData[i].Position[1] = fileReader->readNextFloat();
pData[i].Position[2] = fileReader->readNextFloat();
pData[i].Normal[0] = fileReader->readNextFloat();
pData[i].Normal[1] = fileReader->readNextFloat();
pData[i].Normal[2] = fileReader->readNextFloat();
pData[i].TexCoord[0] = fileReader->readNextFloat();
pData[i].TexCoord[1] = fileReader->readNextFloat();
pData[i].BoneIDs[0] = fileReader->readNextInt();
pData[i].BoneIDs[1] = fileReader->readNextInt();
pData[i].BoneIDs[2] = fileReader->readNextInt();
pData[i].BoneIDs[3] = fileReader->readNextInt();
pData[i].BoneWeights[0] = fileReader->readNextFloat();
pData[i].BoneWeights[1] = fileReader->readNextFloat();
pData[i].BoneWeights[2] = fileReader->readNextFloat();
pData[i].BoneWeights[3] = fileReader->readNextFloat();
if (minVertex.m_x > pData[i].Position[0])
{
minVertex.m_x = pData[i].Position[0];
}
if (minVertex.m_y > pData[i].Position[1])
{
minVertex.m_y = pData[i].Position[1];
}
if (minVertex.m_z > pData[i].Position[2])
{
minVertex.m_z = pData[i].Position[2];
}
if (maxVertex.m_x < pData[i].Position[0])
{
maxVertex.m_x = pData[i].Position[0];
}
if (maxVertex.m_y < pData[i].Position[1])
{
maxVertex.m_y = pData[i].Position[1];
}
if (maxVertex.m_z < pData[i].Position[2])
{
maxVertex.m_z = pData[i].Position[2];
}
centerVertex = centerVertex + Vector3(pData[i].Position);
}
centerVertex = (minVertex + maxVertex) * 0.5f;
pMesh->m_boxMin = minVertex;
pMesh->m_boxMax = maxVertex;
pMesh->m_centerOffset = centerVertex;
Vector3 centerToMax = maxVertex - centerVertex;
pMesh->m_radius = centerToMax.length();
pVertexBuffer->SetData(pData, sizeof(MeshSkinData), numVertex);
}
else if (bufferLayoutType == BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN)
{
dataHandle = Handle("Data", sizeof(MeshSkinDataWithTangent) * numVertex);
MeshSkinDataWithTangent* pData = new(dataHandle) MeshSkinDataWithTangent[numVertex];
Vector3 minVertex(9999.9f);
Vector3 maxVertex(-9999.9f);
Vector3 centerVertex(0.0f);
for (int i = 0; i < numVertex; i++)
{
pData[i].Position[0] = fileReader->readNextFloat();
pData[i].Position[1] = fileReader->readNextFloat();
pData[i].Position[2] = fileReader->readNextFloat();
pData[i].Normal[0] = fileReader->readNextFloat();
pData[i].Normal[1] = fileReader->readNextFloat();
pData[i].Normal[2] = fileReader->readNextFloat();
pData[i].TexCoord[0] = fileReader->readNextFloat();
pData[i].TexCoord[1] = fileReader->readNextFloat();
pData[i].Tangent[0] = fileReader->readNextFloat();
pData[i].Tangent[1] = fileReader->readNextFloat();
pData[i].Tangent[2] = fileReader->readNextFloat();
pData[i].BoneIDs[0] = fileReader->readNextInt();
pData[i].BoneIDs[1] = fileReader->readNextInt();
pData[i].BoneIDs[2] = fileReader->readNextInt();
pData[i].BoneIDs[3] = fileReader->readNextInt();
pData[i].BoneWeights[0] = fileReader->readNextFloat();
pData[i].BoneWeights[1] = fileReader->readNextFloat();
pData[i].BoneWeights[2] = fileReader->readNextFloat();
pData[i].BoneWeights[3] = fileReader->readNextFloat();
if (minVertex.m_x > pData[i].Position[0])
{
minVertex.m_x = pData[i].Position[0];
}
if (minVertex.m_y > pData[i].Position[1])
{
minVertex.m_y = pData[i].Position[1];
}
if (minVertex.m_z > pData[i].Position[2])
{
minVertex.m_z = pData[i].Position[2];
}
if (maxVertex.m_x < pData[i].Position[0])
{
maxVertex.m_x = pData[i].Position[0];
}
if (maxVertex.m_y < pData[i].Position[1])
{
maxVertex.m_y = pData[i].Position[1];
}
if (maxVertex.m_z < pData[i].Position[2])
{
maxVertex.m_z = pData[i].Position[2];
}
}
centerVertex = (minVertex + maxVertex) * 0.5f;
pMesh->m_boxMin = minVertex;
pMesh->m_boxMax = maxVertex;
pMesh->m_centerOffset = centerVertex;
Vector3 centerToMax = maxVertex - centerVertex;
pMesh->m_radius = centerToMax.length();
pVertexBuffer->SetData(pData, sizeof(MeshSkinDataWithTangent), numVertex);
}
else
{
int dataPerVertex = 6;
switch (bufferLayoutType)
{
case BUFFER_LAYOUT_V3_C3:
dataPerVertex = 6;
break;
case BUFFER_LAYOUT_V3_N3_TC2:
dataPerVertex = 8;
break;
case BUFFER_LAYOUT_V3_N3_T3_TC2:
dataPerVertex = 11;
break;
case BUFFER_LAYOUT_V3_N3_TC2_SKIN:
dataPerVertex = 16;
break;
default:
break;
}
int totalSize = dataPerVertex * numVertex;
dataHandle = Handle("Data", sizeof(Float32) * totalSize);
Float32* pData = new(dataHandle) Float32[totalSize];
Vector3 minVertex(999999.9f);
Vector3 maxVertex(-999999.9f);
Vector3 centerVertex(0.0f);
for (int i = 0; i < totalSize; ++i)
{
pData[i] = fileReader->readNextFloat();
if (i % dataPerVertex == 0)
{
if (minVertex.m_x > pData[i])
{
minVertex.m_x = pData[i];
}
if (maxVertex.m_x < pData[i])
{
maxVertex.m_x = pData[i];
}
}
else if (i % dataPerVertex == 1)
{
if (minVertex.m_y > pData[i])
{
minVertex.m_y = pData[i];
}
if (maxVertex.m_y < pData[i])
{
maxVertex.m_y = pData[i];
}
}
else if (i % dataPerVertex == 2)
{
if (minVertex.m_z > pData[i])
{
minVertex.m_z = pData[i];
}
if (maxVertex.m_z < pData[i])
{
maxVertex.m_z = pData[i];
}
}
}
centerVertex = (minVertex + maxVertex) * 0.5f;
pMesh->m_boxMin = minVertex;
pMesh->m_boxMax = maxVertex;
pMesh->m_centerOffset = centerVertex;
Vector3 centerToMax = maxVertex - centerVertex;
pMesh->m_radius = centerToMax.length();
pVertexBuffer->SetData(pData, sizeof(Float32) * dataPerVertex, numVertex);
}
// READ OPTIONAL INDEX BUFFER
Handle hIndexBufferData("Buffer Data", sizeof(BufferData));
BufferData* pIndexBuffer = nullptr;
Handle indexDataHandle;
fileReader->readNextString(buffer);
if (StringFunc::Compare(buffer, "INDICE_BUFFER_NONE") != 0)
{
int numIndex = fileReader->readNextInt();
indexDataHandle = Handle("Data", sizeof(Int32) * numIndex);
UInt32* indexData = new(indexDataHandle) UInt32[numIndex];
for (int i = 0; i < numIndex; ++i)
{
indexData[i] = fileReader->readNextInt();
}
pIndexBuffer = new(hIndexBufferData) BufferData(INDEX_BUFFER);
pIndexBuffer->SetData(indexData, sizeof(UInt32), numIndex);
}
ScopedRenderThreadOwnership renderLock(gGameContext->getRenderer());
Handle hResult = BufferManager::getInstance()->createBufferArray(pVertexBuffer, pIndexBuffer, nullptr);
if (hVertexBufferData.isValid())
{
hVertexBufferData.release();
dataHandle.release();
}
if (hIndexBufferData.isValid())
{
hIndexBufferData.release();
indexDataHandle.release();
}
pMesh->m_bufferArray = hResult.getObject<IGPUBufferArray>();
fileReader->readNextString(buffer);
if (StringFunc::Compare(buffer, "TOPOLOGY") == 0)
{
fileReader->readNextString(buffer);
if (pMesh->m_bufferArray)
{
pMesh->m_bufferArray->setRenderTopology(getTopologyByName(buffer));
}
}
fileReader->close();
}
int MeshManager::getBufferLayoutByString(const char* stringType)
{
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_C3);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_TC2_SKIN);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_TC2_SKIN);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2);
COMPARE_RETURN(stringType, BUFFER_LAYOUT_V3_N3_T3_B3_TC2_SKIN);
return -1;
}
ZE::Handle MeshManager::loadResource_Internal(const char* resourceFilePath, ResourceCreateSettings* settings)
{
Handle meshHandle("Mesh Handle", sizeof(Mesh));
Mesh* pMesh;
FileReader reader(resourceFilePath);
if (!reader.isValid())
{
ZEWARNING("Mesh file not found : %s", resourceFilePath);
return meshHandle;
}
char tokenBuffer[256];
pMesh = new(meshHandle) Mesh();
while (!reader.eof())
{
reader.readNextString(tokenBuffer);
if (StringFunc::Compare(tokenBuffer, "vbuff") == 0)
{
reader.readNextString(tokenBuffer);
String path = GetResourcePath(tokenBuffer);
FileReader bufferFileReader(path.c_str());
if (!bufferFileReader.isValid())
{
ZEINFO("BufferManager: File %s not find", path.c_str());
return Handle();
}
loadBuffers(&bufferFileReader, pMesh);
}
else if (StringFunc::Compare(tokenBuffer, "mat") == 0)
{
reader.readNextString(tokenBuffer);
Handle hMaterial = MaterialManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str());
if (hMaterial.isValid())
{
pMesh->m_material = hMaterial.getObject<Material>();
}
}
else if (StringFunc::Compare(tokenBuffer, "double_side") == 0)
{
pMesh->m_doubleSided = true;
}
else if (StringFunc::Compare(tokenBuffer, "physics") == 0)
{
loadPhysicsBodySetup(&reader, pMesh);
}
else if (StringFunc::Compare(tokenBuffer, "skeleton") == 0)
{
reader.readNextString(tokenBuffer);
Handle hSkeleton = SkeletonManager::GetInstance()->loadResource(GetResourcePath(tokenBuffer).c_str());
if (hSkeleton.isValid())
{
pMesh->m_hSkeleton = hSkeleton;
}
}
}
reader.close();
return meshHandle;
}
void MeshManager::preUnloadResource(Resource* _resource)
{
Mesh* pMesh = _resource->m_hActual.getObject<Mesh>();
if (pMesh)
{
if (pMesh->m_hPhysicsBodySetup.isValid())
{
pMesh->m_hPhysicsBodySetup.release();
}
if (pMesh->m_bufferArray)
{
pMesh->m_bufferArray->release();
}
}
}
} | 14,499 | 6,564 |
#ifndef SCREAM_STD_META_HPP
#define SCREAM_STD_META_HPP
/*
* Emulating c++1z features
*
* This file contains some features that belongs to the std namespace,
* and that are likely (if not already scheduled) to be in future standards.
* However, we have limited access to c++1z standard on target platforms,
* so we can only rely on c++11 features. Everything else that we may need,
* we try to emulate here.
*/
#include <memory>
#include "share/scream_assert.hpp"
namespace scream {
namespace util {
// =============== type_traits utils ============== //
// <type_traits> has remove_all_extents but lacks the analogous
// remove_all_pointers
template<typename T>
struct remove_all_pointers {
using type = T;
};
template<typename T>
struct remove_all_pointers<T*> {
using type = typename remove_all_pointers<T>::type;
};
// std::remove_const does not remove the leading const cv from
// the type <const T*>. Indeed, remove_const can only remove the
// const cv from the pointer, not the pointee.
template<typename T>
struct remove_all_consts : std::remove_const<T> {};
template<typename T>
struct remove_all_consts<T*> {
using type = typename remove_all_consts<T>::type*;
};
// ================ std::any ================= //
namespace impl {
class holder_base {
public:
virtual ~holder_base() = default;
virtual const std::type_info& type () const = 0;
};
template <typename HeldType>
class holder : public holder_base {
public:
template<typename... Args>
static holder<HeldType>* create(const Args&... args) {
holder* ptr = new holder<HeldType>();
ptr->m_value = std::make_shared<HeldType>(args...);
return ptr;
}
template<typename T>
static
typename std::enable_if<std::is_base_of<HeldType,T>::value,holder<HeldType>*>::type
create(std::shared_ptr<T> ptr_in)
{
holder* ptr = new holder<HeldType>();
ptr->m_value = ptr_in;
return ptr;
}
const std::type_info& type () const { return typeid(HeldType); }
HeldType& value () { return *m_value; }
std::shared_ptr<HeldType> ptr () const { return m_value; }
private:
holder () = default;
// Note: we store a shared_ptr rather than a HeldType directly,
// since we may store multiple copies of the concrete object.
// Since we don't know if the actual object is copiable, we need
// to store copiable pointers (hence, cannot use unique_ptr).
std::shared_ptr<HeldType> m_value;
};
} // namespace impl
class any {
public:
any () = default;
template<typename T, typename... Args>
void reset (Args... args) {
m_content.reset( impl::holder<T>::create(args...) );
}
impl::holder_base& content () const {
error::runtime_check(static_cast<bool>(m_content), "Error! Object not yet initialized.\n", -1);
return *m_content;
}
impl::holder_base* content_ptr () const {
return m_content.get();
}
private:
std::shared_ptr<impl::holder_base> m_content;
};
template<typename ConcreteType>
bool any_is_type (const any& src) {
const auto& src_type = src.content().type();
const auto& req_type = typeid(ConcreteType);
return src_type==req_type;
}
template<typename ConcreteType>
ConcreteType& any_cast (any& src) {
const auto& src_type = src.content().type();
const auto& req_type = typeid(ConcreteType);
error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1);
impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr());
error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1);
return ptr->value();
}
template<typename ConcreteType>
const ConcreteType& any_cast (const any& src) {
const auto& src_type = src.content().type();
const auto& req_type = typeid(ConcreteType);
error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1);
impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr());
error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1);
return ptr->value();
}
template<typename ConcreteType>
std::shared_ptr<ConcreteType> any_ptr_cast (any& src) {
const auto& src_type = src.content().type();
const auto& req_type = typeid(ConcreteType);
error::runtime_check(src_type==req_type, std::string("Error! Invalid cast requested, from '") + src_type.name() + "' to '" + req_type.name() + "'.\n", -1);
impl::holder<ConcreteType>* ptr = dynamic_cast<impl::holder<ConcreteType>*>(src.content_ptr());
error::runtime_check(ptr!=nullptr, "Error! Failed dynamic_cast during any_cast. This is an internal problem, please, contact developers.\n", -1);
return ptr->ptr();
}
} // namespace util
} // namespace scream
#endif // SCREAM_STD_META_HPP
| 5,036 | 1,685 |
// Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#include "IntroTutorialsPrivatePCH.h"
#include "LevelEditor.h"
#include "SDockTab.h"
#include "EditorTutorial.h"
#if WITH_EDITORONLY_DATA
namespace
{
void GatherEditorTutorialForLocalization(const UObject* const Object, FPropertyLocalizationDataGatherer& PropertyLocalizationDataGatherer, const EPropertyLocalizationGathererTextFlags GatherTextFlags)
{
const UEditorTutorial* const EditorTutorial = CastChecked<UEditorTutorial>(Object);
// Editor Tutorial assets never exist at runtime, so treat all of their properties and script data as editor-only (as they may be derived from by a blueprint)
PropertyLocalizationDataGatherer.GatherLocalizationDataFromObject(EditorTutorial, GatherTextFlags | EPropertyLocalizationGathererTextFlags::ForceEditorOnly);
}
}
#endif
UEditorTutorial::UEditorTutorial(const FObjectInitializer& ObjectInitializer)
: Super(ObjectInitializer)
{
#if WITH_EDITORONLY_DATA
static struct FAutomaticRegistrationOfLocalizationGatherer
{
FAutomaticRegistrationOfLocalizationGatherer()
{
FPropertyLocalizationDataGatherer::GetTypeSpecificLocalizationDataGatheringCallbacks().Add(UEditorTutorial::StaticClass(), &GatherEditorTutorialForLocalization);
}
} AutomaticRegistrationOfLocalizationGatherer;
#endif
}
UWorld* UEditorTutorial::GetWorld() const
{
#if WITH_EDITOR
if (GIsEditor)
{
return GWorld;
}
#endif // WITH_EDITOR
return GEngine->GetWorldContexts()[0].World();
}
void UEditorTutorial::GoToNextTutorialStage()
{
FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials"));
IntroTutorials.GoToNextStage(nullptr);
}
void UEditorTutorial::GoToPreviousTutorialStage()
{
FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials"));
IntroTutorials.GoToPreviousStage();
}
void UEditorTutorial::BeginTutorial(UEditorTutorial* TutorialToStart, bool bRestart)
{
FIntroTutorials& IntroTutorials = FModuleManager::GetModuleChecked<FIntroTutorials>(TEXT("IntroTutorials"));
IntroTutorials.LaunchTutorial(TutorialToStart, bRestart ? IIntroTutorials::ETutorialStartType::TST_RESTART : IIntroTutorials::ETutorialStartType::TST_CONTINUE);
}
void UEditorTutorial::HandleTutorialStageStarted(FName StageName)
{
FEditorScriptExecutionGuard ScriptGuard;
OnTutorialStageStarted(StageName);
}
void UEditorTutorial::HandleTutorialStageEnded(FName StageName)
{
FEditorScriptExecutionGuard ScriptGuard;
OnTutorialStageEnded(StageName);
}
void UEditorTutorial::HandleTutorialLaunched()
{
FEditorScriptExecutionGuard ScriptGuard;
FLevelEditorModule& LevelEditorModule = FModuleManager::GetModuleChecked<FLevelEditorModule>(TEXT("LevelEditor"));
LevelEditorModule.GetLevelEditorTabManager()->InvokeTab(FTabId("TutorialsBrowser"))->RequestCloseTab();
OnTutorialLaunched();
}
void UEditorTutorial::HandleTutorialClosed()
{
FEditorScriptExecutionGuard ScriptGuard;
OnTutorialClosed();
}
void UEditorTutorial::OpenAsset(UObject* Asset)
{
FAssetEditorManager::Get().OpenEditorForAsset(Asset);
}
AActor* UEditorTutorial::GetActorReference(FString PathToActor)
{
#if WITH_EDITOR
return Cast<AActor>(StaticFindObject(AActor::StaticClass(), GEditor->GetEditorWorldContext().World(), *PathToActor, false));
#else
return nullptr;
#endif //WITH_EDITOR
}
void UEditorTutorial::SetEngineFolderVisibilty(bool bNewVisibility)
{
bool bDisplayEngine = GetDefault<UContentBrowserSettings>()->GetDisplayEngineFolder();
// If we cannot change the vis state, or it matches the new request leave it
if (bDisplayEngine == bNewVisibility)
{
return;
}
if (bNewVisibility)
{
GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(true);
}
else
{
GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(false);
GetMutableDefault<UContentBrowserSettings>()->SetDisplayEngineFolder(false, true);
}
GetMutableDefault<UContentBrowserSettings>()->PostEditChange();
}
bool UEditorTutorial::GetEngineFolderVisibilty()
{
return GetDefault<UContentBrowserSettings>()->GetDisplayEngineFolder();
}
| 4,133 | 1,333 |
/**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <cstdlib>
#include <memory>
#include <random>
#include <unistd.h>
#include <folly/Memory.h>
#include <folly/Singleton.h>
#include <folly/io/async/EventBase.h>
#include <thrift/lib/cpp/async/TAsyncSocket.h>
#include <thrift/lib/cpp2/async/HeaderClientChannel.h>
#include "common/init/Init.h"
#include "logdevice/lib/test/copyloadtestapp/server/gen-cpp2/CopyLoaderTest.h"
#include "logdevice/common/Checksum.h"
#include "logdevice/common/commandline_util.h"
#include "logdevice/common/commandline_util_chrono.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/EpochMetaData.h"
#include "logdevice/common/Timer.h"
#include "logdevice/common/ReaderImpl.h"
#include "logdevice/common/Semaphore.h"
#include "logdevice/common/util.h"
#include "logdevice/include/Client.h"
#include "logdevice/include/Err.h"
#include "logdevice/include/Record.h"
#include "logdevice/include/types.h"
#include "logdevice/lib/ClientSettingsImpl.h"
using namespace facebook;
using namespace facebook::logdevice;
using apache::thrift::HeaderClientChannel;
using apache::thrift::async::TAsyncSocket;
using folly::EventBase;
using std::make_unique;
using std::chrono::steady_clock;
struct CommandLineSettings {
bool no_payload;
size_t total_buffer_size = 2000000;
std::chrono::milliseconds findtime_timeout{10000};
std::chrono::milliseconds confirmation_duration{60 * 1000};
boost::program_options::options_description desc;
std::string config_path;
std::string host_ip;
uint32_t num_threads;
uint32_t port;
uint32_t task_index;
};
void parse_command_line(int argc,
const char* argv[],
CommandLineSettings& command_line_settings,
ClientSettingsImpl& client_settings) {
using boost::program_options::bool_switch;
using boost::program_options::value;
// clang-format off
command_line_settings.desc.add_options()
("help,h",
"produce this help message and exit")
("verbose,v",
"also include a description of all LogDevice Client settings in the help "
"message")
("config-path",
value<std::string>(&command_line_settings.config_path)
->required(),
"path to config file")
("port",
value<uint32_t>(&command_line_settings.port)
->default_value(1739),
"Port for thrift service")
("task-index",
value<uint32_t>(&command_line_settings.task_index)
->default_value(0),
"tupperware task index used for process identication")
("server-address",
value<std::string>(&command_line_settings.host_ip)
->default_value("127.0.0.1"),
"host server ip address. Default is 127.0.0.1")
("threads-number",
value<uint32_t>(&command_line_settings.num_threads)
->default_value(10),
"number of threads that are going to execute tasks independently")
("no-payload",
bool_switch(&command_line_settings.no_payload)
->default_value(false),
"request storage servers send records without paylaod")
("buffer-size",
value<size_t>(&command_line_settings.total_buffer_size)
->default_value(command_line_settings.total_buffer_size),
"client read buffer size for all logs")
("loglevel",
value<std::string>()
->default_value("info")
->notifier(dbg::parseLoglevelOption),
"One of the following: critical, error, warning, info, debug")
("findtime-timeout",
chrono_value(&command_line_settings.findtime_timeout)
->notifier([](std::chrono::milliseconds val) -> void {
if (val.count() < 0) {
throw boost::program_options::error("findtime-timeout must be > 0");
}
}),
"Timeout for calls to findTime")
;
// clang-format on
try {
auto fallback_fn = [&](int ac, const char* av[]) {
boost::program_options::variables_map parsed =
program_options_parse_no_positional(
ac, av, command_line_settings.desc);
// Check for --help before calling notify(), so that required options
// aren't required.
if (parsed.count("help")) {
std::cout
<< "Test application that connects to LogDevice and reads logs.\n\n"
<< command_line_settings.desc;
if (parsed.count("verbose")) {
std::cout << std::endl;
std::cout << "LogDevice Client settings:" << std::endl << std::endl;
std::cout << client_settings.getSettingsUpdater()->help(
SettingFlag::CLIENT);
}
exit(0);
}
// Surface any errors
boost::program_options::notify(parsed);
};
client_settings.getSettingsUpdater()->parseFromCLI(
argc, argv, &SettingsUpdater::mustBeClientOption, fallback_fn);
} catch (const boost::program_options::error& ex) {
std::cerr << argv[0] << ": " << ex.what() << '\n';
exit(1);
}
}
void client_thread(CommandLineSettings command_line_settings,
const ClientSettingsImpl& client_settings,
int thread_id) {
EventBase eventBase;
uint64_t client_id =
(uint64_t(command_line_settings.task_index) << 32) | uint64_t(thread_id);
try {
// Create a client to the service
auto socket = TAsyncSocket::newSocket(
&eventBase, command_line_settings.host_ip, command_line_settings.port);
auto channel = HeaderClientChannel::newChannel(socket);
auto thrift_client =
make_unique<thrift::CopyLoaderTestAsyncClient>(std::move(channel));
auto local_client_settings =
std::make_unique<ClientSettingsImpl>(client_settings);
std::shared_ptr<Client> logdevice_client =
Client::create("Test cluster",
command_line_settings.config_path,
"none",
command_line_settings.findtime_timeout,
std::move(local_client_settings));
if (!logdevice_client) {
ld_error("Could not create client: %s", error_description(err));
return;
}
// Reader will read one log at one range at once.
// stopReading() will be invoced after end of each reading.
auto reader = logdevice_client->createReader(1);
reader->waitOnlyWhenNoData();
reader->setTimeout(std::chrono::seconds(1));
unsigned long wait_time = 100;
std::default_random_engine generator;
std::string process_info;
process_info.append("Tupperware task id: ")
.append(std::to_string(command_line_settings.task_index))
.append(". Thread id: ")
.append(std::to_string(thread_id));
while (1) {
// Get a tasks
std::vector<thrift::Task> tasks;
while (true) {
thrift_client->sync_getTask(tasks, client_id, process_info);
if (tasks.size() != 0) {
wait_time = 1000;
break;
} else {
// radnomize wait time
std::uniform_int_distribution<int> distribution(
wait_time / 2 * 3, wait_time * 3);
wait_time = std::min(distribution(generator), 60 * 1000);
LOG(INFO) << "Thread " << thread_id << " is about to sleep "
<< wait_time << "ms.";
std::this_thread::sleep_for(std::chrono::milliseconds(wait_time));
}
}
for (int i = 0; i < tasks.size(); ++i) {
lsn_t lsn_start = compose_lsn(epoch_t(tasks[i].start_lsn.lsn_hi),
esn_t(tasks[i].start_lsn.lsn_lo));
lsn_t lsn_end = compose_lsn(
epoch_t(tasks[i].end_lsn.lsn_hi), esn_t(tasks[i].end_lsn.lsn_lo));
LOG(INFO) << "Task id: " << tasks[i].id << " thread id: " << thread_id
<< " lsn: " << lsn_start << " - " << lsn_end
<< "start procesing.";
auto ret =
reader->startReading((logid_t)tasks[i].log_id, lsn_start, lsn_end);
ld_check(ret == 0);
auto time_begin = std::chrono::steady_clock::now();
auto last_time_confirmed = time_begin;
std::vector<std::unique_ptr<DataRecord>> records;
GapRecord gap;
size_t all_records_size = 0;
size_t all_records_count = 0;
bool is_confirmed = true;
while (reader->isReading((logid_t)tasks[i].log_id)) {
records.clear();
int nread = reader->read(100, &records, &gap);
all_records_size += std::accumulate(
std::begin(records),
std::end(records),
std::size_t(0),
[](size_t& sum, std::unique_ptr<DataRecord>& record) {
return sum + record->payload.size();
});
all_records_count += records.size();
auto cur_time = std::chrono::steady_clock::now();
auto time_elapsed =
std::chrono::duration_cast<std::chrono::milliseconds>(
cur_time - last_time_confirmed);
if (time_elapsed > command_line_settings.confirmation_duration) {
bool rv = thrift_client->sync_confirmOngoingTaskExecution(
tasks[i].id, client_id);
if (!rv) {
is_confirmed = false;
break;
}
last_time_confirmed = cur_time;
}
}
if (!is_confirmed) {
continue;
}
auto time_all = std::chrono::steady_clock::now() - time_begin;
double time_elapsed_sec =
double(
std::chrono::duration_cast<std::chrono::milliseconds>(time_all)
.count()) /
1000;
char buf[128];
snprintf(buf, sizeof buf, "%.3f", time_elapsed_sec);
std::string logging_info;
logging_info.append(process_info)
.append(". Records size read: ")
.append(std::to_string(all_records_count))
.append(". Data loaded: ")
.append(std::to_string(all_records_size))
.append(". Time spent to read in seconds: ")
.append(buf);
thrift_client->sync_informTaskFinished(
tasks[i].id, client_id, logging_info, all_records_size);
}
}
} catch (apache::thrift::transport::TTransportException& ex) {
LOG(ERROR) << "Request failed " << ex.what();
}
}
int main(int argc, const char* argv[]) {
logdeviceInit();
ClientSettingsImpl client_settings;
CommandLineSettings command_line_settings;
parse_command_line(argc, argv, command_line_settings, client_settings);
std::vector<std::thread> client_threads;
for (int i = 0; i < command_line_settings.num_threads; ++i) {
client_threads.emplace_back(
client_thread, command_line_settings, std::ref(client_settings), i);
}
for (auto& client_thread : client_threads) {
client_thread.join();
}
// Don't use custom command line parameters in in initFacebook()
// to prevent parsing errors
argc = 0;
initFacebook(&argc, const_cast<char***>(&argv));
return 0;
}
| 11,094 | 3,534 |
#pragma once
class IEncoder;
class EncodingRenderer
{
public:
EncodingRenderer( std::shared_ptr<IEncoder> encoder, ComPtr<ID3D11Device> pD3DDevice, ComPtr<ID3D11DeviceContext> pImmediateContext, boost::rational<int32_t> refreshRate );
void renderEncoding( ID3D11ShaderResourceView* srv );
private:
std::shared_ptr<IEncoder> mEncoder;
ComPtr<ID3D11Device> mD3DDevice;
ComPtr<ID3D11DeviceContext> mImmediateContext;
ComPtr<ID3D11Texture2D> mPreStagingY;
ComPtr<ID3D11Texture2D> mPreStagingU;
ComPtr<ID3D11Texture2D> mPreStagingV;
ComPtr<ID3D11Texture2D> mStagingY;
ComPtr<ID3D11Texture2D> mStagingU;
ComPtr<ID3D11Texture2D> mStagingV;
ComPtr<ID3D11UnorderedAccessView> mPreStagingYUAV;
ComPtr<ID3D11UnorderedAccessView> mPreStagingUUAV;
ComPtr<ID3D11UnorderedAccessView> mPreStagingVUAV;
ComPtr<ID3D11Buffer> mVSizeCB;
ComPtr<ID3D11ComputeShader> mRendererYUVCS;
struct CBVSize
{
uint32_t vscale;
uint32_t padding1;
uint32_t padding2;
uint32_t padding3;
} mCb;
boost::rational<int32_t> mRefreshRate;
};
| 1,200 | 493 |
// Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <algorithm>
#include <string>
#include <vector>
#include "chrome/browser/enterprise/connectors/connectors_prefs.h"
#include "chrome/browser/enterprise/connectors/connectors_service.h"
#include "chrome/browser/enterprise/connectors/file_system/account_info_utils.h"
#include "chrome/browser/enterprise/connectors/service_provider_config.h"
#include "components/prefs/pref_registry_simple.h"
namespace enterprise_connectors {
const char kSendDownloadToCloudPref[] =
"enterprise_connectors.send_download_to_cloud";
const char kOnFileAttachedPref[] = "enterprise_connectors.on_file_attached";
const char kOnFileDownloadedPref[] = "enterprise_connectors.on_file_downloaded";
const char kOnBulkDataEntryPref[] = "enterprise_connectors.on_bulk_data_entry";
const char kOnSecurityEventPref[] = "enterprise_connectors.on_security_event";
const char kContextAwareAccessSignalsAllowlistPref[] =
"enterprise_connectors.device_trust.origins";
const char kDeviceTrustPrivateKeyPref[] =
"enterprise_connectors.device_trust.private_key";
const char kDeviceTrustPublicKeyPref[] =
"enterprise_connectors.device_trust.public_key";
const char kOnFileAttachedScopePref[] =
"enterprise_connectors.scope.on_file_attached";
const char kOnFileDownloadedScopePref[] =
"enterprise_connectors.scope.on_file_downloaded";
const char kOnBulkDataEntryScopePref[] =
"enterprise_connectors.scope.on_bulk_data_entry";
const char kOnSecurityEventScopePref[] =
"enterprise_connectors.scope.on_security_event";
namespace {
void RegisterFileSystemPrefs(PrefRegistrySimple* registry) {
std::vector<std::string> all_service_providers =
GetServiceProviderConfig()->GetServiceProviderNames();
std::vector<std::string> fs_service_providers;
std::copy_if(all_service_providers.begin(), all_service_providers.end(),
std::back_inserter(fs_service_providers), [](const auto& name) {
const ServiceProviderConfig::ServiceProvider* provider =
GetServiceProviderConfig()->GetServiceProvider(name);
return !provider->fs_home_url().empty();
});
for (const auto& name : fs_service_providers) {
RegisterFileSystemPrefsForServiceProvider(registry, name);
}
}
} // namespace
void RegisterProfilePrefs(PrefRegistrySimple* registry) {
registry->RegisterListPref(kSendDownloadToCloudPref);
registry->RegisterListPref(kOnFileAttachedPref);
registry->RegisterListPref(kOnFileDownloadedPref);
registry->RegisterListPref(kOnBulkDataEntryPref);
registry->RegisterListPref(kOnSecurityEventPref);
registry->RegisterIntegerPref(kOnFileAttachedScopePref, 0);
registry->RegisterIntegerPref(kOnFileDownloadedScopePref, 0);
registry->RegisterIntegerPref(kOnBulkDataEntryScopePref, 0);
registry->RegisterIntegerPref(kOnSecurityEventScopePref, 0);
registry->RegisterListPref(kContextAwareAccessSignalsAllowlistPref);
RegisterFileSystemPrefs(registry);
}
void RegisterLocalPrefs(PrefRegistrySimple* registry) {
registry->RegisterStringPref(kDeviceTrustPrivateKeyPref, std::string());
registry->RegisterStringPref(kDeviceTrustPublicKeyPref, std::string());
}
} // namespace enterprise_connectors
| 3,377 | 1,052 |
#ifndef TIME_TASK_HPP
#define TIME_TASK_HPP
//////////////////////////////////////////////////////
// INCLUDES
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// FORWARD DECLARATIONS
//////////////////////////////////////////////////////
//////////////////////////////////////////////////////
// CLASS
//////////////////////////////////////////////////////
class TimeTask
{
public:
TimeTask( float startTime, float endTime, void (*OnTrigger)( void* ), void* context );
~TimeTask();
void Update( float elapsedTime );
float GetElapsedTimeSeconds();
float GetStartTimeSeconds();
float GetEndTimeSeconds();
void OnTrigger();
private:
float mStartTimeSeconds;
float mEndTimeSeconds;
float mElapsedTimeSeconds;
void (*OnTriggerCallback)( void* );
void* mContext;
};
#endif
| 850 | 226 |
/*
* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation.
*
* This code 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
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*
*/
#ifndef CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP
#define CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP
private:
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Sparc load/store emission
//
// The sparc ld/st instructions cannot accomodate displacements > 13 bits long.
// The following "pseudo" sparc instructions (load/store) make it easier to use the indexed addressing mode
// by allowing 32 bit displacements:
//
// When disp <= 13 bits long, a single load or store instruction is emitted with (disp + [d]).
// When disp > 13 bits long, code is emitted to set the displacement into the O7 register,
// and then a load or store is emitted with ([O7] + [d]).
//
int store(LIR_Opr from_reg, Register base, int offset, BasicType type, bool wide, bool unaligned);
int store(LIR_Opr from_reg, Register base, Register disp, BasicType type, bool wide);
int load(Register base, int offset, LIR_Opr to_reg, BasicType type, bool wide, bool unaligned);
int load(Register base, Register disp, LIR_Opr to_reg, BasicType type, bool wide);
void monitorexit(LIR_Opr obj_opr, LIR_Opr lock_opr, Register hdr, int monitor_no);
int shift_amount(BasicType t);
static bool is_single_instruction(LIR_Op* op);
// Record the type of the receiver in ReceiverTypeData
void type_profile_helper(Register mdo, int mdo_offset_bias,
ciMethodData *md, ciProfileData *data,
Register recv, Register tmp1, Label* update_done);
// Setup pointers to MDO, MDO slot, also compute offset bias to access the slot.
void setup_md_access(ciMethod* method, int bci,
ciMethodData*& md, ciProfileData*& data, int& mdo_offset_bias);
public:
void pack64(LIR_Opr src, LIR_Opr dst);
void unpack64(LIR_Opr src, LIR_Opr dst);
enum {
#ifdef _LP64
call_stub_size = 68,
#else
call_stub_size = 20,
#endif // _LP64
exception_handler_size = DEBUG_ONLY(1*K) NOT_DEBUG(128),
deopt_handler_size = DEBUG_ONLY(1*K) NOT_DEBUG(64) };
#endif // CPU_SPARC_VM_C1_LIRASSEMBLER_SPARC_HPP
| 3,243 | 1,073 |
/*
The structure of the class is as follows
class _stack{
stack<int> s;
int minEle;
public :
int getMin();
int pop();
void push(int);
};
*/
/*returns min element from stack*/
stack<int> st;
int _stack :: getMin()
{
if(s.empty()){
while(!st.empty()){
st.pop();
}
}
//Your code here
if(st.empty()){
return -1;
}
return st.top();
}
/*returns poped element from stack*/
int _stack ::pop()
{
if(s.empty()){
while(!st.empty()){
st.pop();
}
}
//Your code here
int ans = -1;
if(!s.empty()){
ans = s.top();
s.pop();
st.pop();
}
return ans;
}
/*push element x into the stack*/
void _stack::push(int x)
{
//Your code here
if(s.empty()){
while(!st.empty()){
st.pop();
}
s.push(x);
st.push(x);
return;
}
s.push(x);
if(st.top() > x){
st.push(x);
}
else{
st.push(st.top());
}
}
| 1,027 | 389 |
//
// ASTExpr.cpp
// Emojicode
//
// Created by Theo Weidmann on 03/08/2017.
// Copyright © 2017 Theo Weidmann. All rights reserved.
//
#include "ASTExpr.hpp"
#include "Analysis/FunctionAnalyser.hpp"
#include "Compiler.hpp"
#include "Functions/Initializer.hpp"
#include "MemoryFlowAnalysis/MFFunctionAnalyser.hpp"
#include "Scoping/SemanticScoper.hpp"
#include "Types/Class.hpp"
#include "Types/Enum.hpp"
#include "Types/TypeExpectation.hpp"
namespace EmojicodeCompiler {
void ASTUnaryMFForwarding::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) {
expr_->analyseMemoryFlow(analyser, type);
}
Type ASTTypeAsValue::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) {
auto &type = type_->analyseType(analyser->typeContext());
ASTTypeValueType::checkTypeValue(tokenType_, type, analyser->typeContext(), position());
return Type(MakeTypeAsValue, type);
}
Type ASTSizeOf::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) {
type_->analyseType(analyser->typeContext());
return analyser->integer();
}
Type ASTConditionalAssignment::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) {
Type t = analyser->expect(TypeExpectation(false, false), &expr_);
if (t.unboxedType() != TypeType::Optional) {
throw CompilerError(position(), "Condition assignment can only be used with optionals.");
}
t = t.optionalType();
auto &variable = analyser->scoper().currentScope().declareVariable(varName_, t, true, position());
variable.initialize();
varId_ = variable.id();
return analyser->boolean();
}
void ASTConditionalAssignment::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) {
analyser->recordVariableSet(varId_, expr_.get(), expr_->expressionType().optionalType());
analyser->take(expr_.get());
}
Type ASTSuper::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) {
if (isSuperconstructorRequired(analyser->functionType())) {
analyseSuperInit(analyser);
return Type::noReturn();
}
if (analyser->functionType() != FunctionType::ObjectMethod) {
throw CompilerError(position(), "Not within an object-context.");
}
Class *superclass = analyser->typeContext().calleeType().klass()->superclass();
if (superclass == nullptr) {
throw CompilerError(position(), "Class has no superclass.");
}
function_ = superclass->getMethod(name_, Type(superclass), analyser->typeContext(),
args_.mood(), position());
calleeType_ = Type(superclass);
return analyser->analyseFunctionCall(&args_, calleeType_, function_);
}
void ASTSuper::analyseSuperInit(ExpressionAnalyser *analyser) {
if (analyser->typeContext().calleeType().klass()->superclass() == nullptr) {
throw CompilerError(position(), "Class does not have a super class");
}
if (analyser->pathAnalyser().hasPotentially(PathAnalyserIncident::CalledSuperInitializer)) {
analyser->compiler()->error(CompilerError(position(), "Superinitializer might have already been called."));
}
analyser->scoper().instanceScope()->uninitializedVariablesCheck(position(), "Instance variable \"", "\" must be "
"initialized before calling the superinitializer.");
init_ = true;
auto eclass = analyser->typeContext().calleeType().klass();
auto initializer = eclass->superclass()->getInitializer(name_, Type(eclass),
analyser->typeContext(), position());
calleeType_ = Type(eclass->superclass());
analyser->analyseFunctionCall(&args_, calleeType_, initializer);
analyseSuperInitErrorProneness(analyser, initializer);
function_ = initializer;
analyser->pathAnalyser().recordIncident(PathAnalyserIncident::CalledSuperInitializer);
}
void ASTSuper::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) {
analyser->recordThis(function_->memoryFlowTypeForThis());
analyser->analyseFunctionCall(&args_, nullptr, function_);
}
void ASTSuper::analyseSuperInitErrorProneness(ExpressionAnalyser *eanalyser, const Initializer *initializer) {
auto analyser = dynamic_cast<FunctionAnalyser *>(eanalyser);
if (initializer->errorProne()) {
auto thisInitializer = dynamic_cast<const Initializer*>(analyser->function());
if (!thisInitializer->errorProne()) {
throw CompilerError(position(), "Cannot call an error-prone super initializer in a non ",
"error-prone initializer.");
}
if (!initializer->errorType()->type().identicalTo(thisInitializer->errorType()->type(), analyser->typeContext(),
nullptr)) {
throw CompilerError(position(), "Super initializer must have same error enum type.");
}
manageErrorProneness_ = true;
analyseInstanceVariables(analyser);
}
}
Type ASTCallableCall::analyse(ExpressionAnalyser *analyser, const TypeExpectation &expectation) {
Type type = analyser->expect(TypeExpectation(false, false), &callable_);
if (type.type() != TypeType::Callable) {
throw CompilerError(position(), "Given value is not callable.");
}
if (args_.args().size() != type.genericArguments().size() - 1) {
throw CompilerError(position(), "Callable expects ", type.genericArguments().size() - 1,
" arguments but ", args_.args().size(), " were supplied.");
}
for (size_t i = 1; i < type.genericArguments().size(); i++) {
analyser->expectType(type.genericArguments()[i], &args_.args()[i - 1]);
}
return type.genericArguments()[0];
}
void ASTCallableCall::analyseMemoryFlow(MFFunctionAnalyser *analyser, MFFlowCategory type) {
callable_->analyseMemoryFlow(analyser, MFFlowCategory::Borrowing);
for (auto &arg : args_.args()) {
analyser->take(arg.get());
arg->analyseMemoryFlow(analyser, MFFlowCategory::Escaping); // We cannot at all say what the callable will do.
}
}
} // namespace EmojicodeCompiler
| 6,191 | 1,808 |
// Copyright 2015 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 <stddef.h>
#include <stdint.h>
#include <utility>
#include "base/auto_reset.h"
#include "base/bind.h"
#include "base/callback.h"
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/run_loop.h"
#include "base/strings/stringprintf.h"
#include "base/test/test_timeouts.h"
#include "base/time/time.h"
#include "base/values.h"
#include "build/build_config.h"
#include "components/html_viewer/public/interfaces/test_html_viewer.mojom.h"
#include "components/mus/public/cpp/tests/window_server_test_base.h"
#include "components/mus/public/cpp/window.h"
#include "components/mus/public/cpp/window_tree_connection.h"
#include "components/web_view/frame.h"
#include "components/web_view/frame_connection.h"
#include "components/web_view/frame_tree.h"
#include "components/web_view/public/interfaces/frame.mojom.h"
#include "components/web_view/test_frame_tree_delegate.h"
#include "mojo/services/accessibility/public/interfaces/accessibility.mojom.h"
#include "mojo/shell/public/cpp/application_impl.h"
#include "net/test/embedded_test_server/embedded_test_server.h"
using mus::mojom::WindowTreeClientPtr;
using mus::WindowServerTestBase;
using web_view::Frame;
using web_view::FrameConnection;
using web_view::FrameTree;
using web_view::FrameTreeDelegate;
using web_view::mojom::FrameClient;
namespace mojo {
namespace {
const char kAddFrameWithEmptyPageScript[] =
"var iframe = document.createElement(\"iframe\");"
"iframe.src = \"http://127.0.0.1:%u/empty_page.html\";"
"document.body.appendChild(iframe);";
void OnGotContentHandlerForRoot(bool* got_callback) {
*got_callback = true;
ignore_result(WindowServerTestBase::QuitRunLoop());
}
mojo::ApplicationConnection* ApplicationConnectionForFrame(Frame* frame) {
return static_cast<FrameConnection*>(frame->user_data())
->application_connection();
}
std::string GetFrameText(ApplicationConnection* connection) {
html_viewer::TestHTMLViewerPtr test_html_viewer;
connection->ConnectToService(&test_html_viewer);
std::string result;
test_html_viewer->GetContentAsText([&result](const String& mojo_string) {
result = mojo_string;
ASSERT_TRUE(WindowServerTestBase::QuitRunLoop());
});
if (!WindowServerTestBase::DoRunLoopWithTimeout())
ADD_FAILURE() << "Timed out waiting for execute to complete";
// test_html_viewer.WaitForIncomingResponse();
return result;
}
scoped_ptr<base::Value> ExecuteScript(ApplicationConnection* connection,
const std::string& script) {
html_viewer::TestHTMLViewerPtr test_html_viewer;
connection->ConnectToService(&test_html_viewer);
scoped_ptr<base::Value> result;
test_html_viewer->ExecuteScript(script, [&result](const String& json_string) {
result = base::JSONReader::Read(json_string.To<std::string>());
ASSERT_TRUE(WindowServerTestBase::QuitRunLoop());
});
if (!WindowServerTestBase::DoRunLoopWithTimeout())
ADD_FAILURE() << "Timed out waiting for execute to complete";
return result;
}
// FrameTreeDelegate that can block waiting for navigation to start.
class TestFrameTreeDelegateImpl : public web_view::TestFrameTreeDelegate {
public:
explicit TestFrameTreeDelegateImpl(mojo::ApplicationImpl* app)
: TestFrameTreeDelegate(app), frame_tree_(nullptr) {}
~TestFrameTreeDelegateImpl() override {}
void set_frame_tree(FrameTree* frame_tree) { frame_tree_ = frame_tree; }
// Resets the navigation state for |frame|.
void ClearGotNavigate(Frame* frame) { frames_navigated_.erase(frame); }
// Waits until |frame| has |count| children and the last child has navigated.
bool WaitForChildFrameCount(Frame* frame, size_t count) {
if (DidChildNavigate(frame, count))
return true;
waiting_for_frame_child_count_.reset(new FrameAndChildCount);
waiting_for_frame_child_count_->frame = frame;
waiting_for_frame_child_count_->count = count;
return WindowServerTestBase::DoRunLoopWithTimeout();
}
// Returns true if |frame| has navigated. If |frame| hasn't navigated runs
// a nested message loop until |frame| navigates.
bool WaitForFrameNavigation(Frame* frame) {
if (frames_navigated_.count(frame))
return true;
frames_waiting_for_navigate_.insert(frame);
return WindowServerTestBase::DoRunLoopWithTimeout();
}
// TestFrameTreeDelegate:
void DidStartNavigation(Frame* frame) override {
frames_navigated_.insert(frame);
if (waiting_for_frame_child_count_ &&
DidChildNavigate(waiting_for_frame_child_count_->frame,
waiting_for_frame_child_count_->count)) {
waiting_for_frame_child_count_.reset();
ASSERT_TRUE(WindowServerTestBase::QuitRunLoop());
}
if (frames_waiting_for_navigate_.count(frame)) {
frames_waiting_for_navigate_.erase(frame);
ignore_result(WindowServerTestBase::QuitRunLoop());
}
}
private:
struct FrameAndChildCount {
Frame* frame;
size_t count;
};
// Returns true if |frame| has |count| children and the last child frame
// has navigated.
bool DidChildNavigate(Frame* frame, size_t count) {
return ((frame->children().size() == count) &&
(frames_navigated_.count(frame->children()[count - 1])));
}
FrameTree* frame_tree_;
// Any time DidStartNavigation() is invoked the frame is added here. Frames
// are inserted as void* as this does not track destruction of the frames.
std::set<void*> frames_navigated_;
// The set of frames waiting for a navigation to occur.
std::set<Frame*> frames_waiting_for_navigate_;
// Set of frames waiting for a certain number of children and navigation.
scoped_ptr<FrameAndChildCount> waiting_for_frame_child_count_;
DISALLOW_COPY_AND_ASSIGN(TestFrameTreeDelegateImpl);
};
} // namespace
class HTMLFrameTest : public WindowServerTestBase {
public:
HTMLFrameTest() {}
~HTMLFrameTest() override {}
protected:
// Creates the frame tree showing an empty page at the root and adds (via
// script) a frame showing the same empty page.
Frame* LoadEmptyPageAndCreateFrame() {
mus::Window* embed_window = window_manager()->NewWindow();
frame_tree_delegate_.reset(
new TestFrameTreeDelegateImpl(application_impl()));
FrameConnection* root_connection = InitFrameTree(
embed_window, "http://127.0.0.1:%u/empty_page2.html");
if (!root_connection) {
ADD_FAILURE() << "unable to establish root connection";
return nullptr;
}
const std::string frame_text =
GetFrameText(root_connection->application_connection());
if (frame_text != "child2") {
ADD_FAILURE() << "unexpected text " << frame_text;
return nullptr;
}
return CreateEmptyChildFrame(frame_tree_->root());
}
Frame* CreateEmptyChildFrame(Frame* parent) {
const size_t initial_frame_count = parent->children().size();
// Dynamically add a new frame.
ExecuteScript(ApplicationConnectionForFrame(parent),
AddPortToString(kAddFrameWithEmptyPageScript));
frame_tree_delegate_->WaitForChildFrameCount(parent,
initial_frame_count + 1);
if (HasFatalFailure())
return nullptr;
return parent->FindFrame(parent->window()->children().back()->id());
}
std::string AddPortToString(const std::string& string) {
const uint16_t assigned_port = http_server_->host_port_pair().port();
return base::StringPrintf(string.c_str(), assigned_port);
}
mojo::URLRequestPtr BuildRequestForURL(const std::string& url_string) {
mojo::URLRequestPtr request(mojo::URLRequest::New());
request->url = mojo::String::From(AddPortToString(url_string));
return request;
}
FrameConnection* InitFrameTree(mus::Window* view,
const std::string& url_string) {
frame_tree_delegate_.reset(
new TestFrameTreeDelegateImpl(application_impl()));
scoped_ptr<FrameConnection> frame_connection(new FrameConnection);
bool got_callback = false;
frame_connection->Init(
application_impl(), BuildRequestForURL(url_string),
base::Bind(&OnGotContentHandlerForRoot, &got_callback));
ignore_result(WindowServerTestBase::DoRunLoopWithTimeout());
if (!got_callback)
return nullptr;
FrameConnection* result = frame_connection.get();
FrameClient* frame_client = frame_connection->frame_client();
WindowTreeClientPtr tree_client = frame_connection->GetWindowTreeClient();
frame_tree_.reset(new FrameTree(
result->GetContentHandlerID(), view, std::move(tree_client),
frame_tree_delegate_.get(), frame_client, std::move(frame_connection),
Frame::ClientPropertyMap(), base::TimeTicks::Now()));
frame_tree_delegate_->set_frame_tree(frame_tree_.get());
return result;
}
// ViewManagerTest:
void SetUp() override {
WindowServerTestBase::SetUp();
// Start a test server.
http_server_.reset(new net::EmbeddedTestServer);
http_server_->ServeFilesFromSourceDirectory(
"components/test/data/html_viewer");
ASSERT_TRUE(http_server_->Start());
}
void TearDown() override {
frame_tree_.reset();
http_server_.reset();
WindowServerTestBase::TearDown();
}
scoped_ptr<net::EmbeddedTestServer> http_server_;
scoped_ptr<FrameTree> frame_tree_;
scoped_ptr<TestFrameTreeDelegateImpl> frame_tree_delegate_;
private:
DISALLOW_COPY_AND_ASSIGN(HTMLFrameTest);
};
// Crashes on linux_chromium_rel_ng only. http://crbug.com/567337
#if defined(OS_LINUX)
#define MAYBE_PageWithSingleFrame DISABLED_PageWithSingleFrame
#else
#define MAYBE_PageWithSingleFrame PageWithSingleFrame
#endif
TEST_F(HTMLFrameTest, MAYBE_PageWithSingleFrame) {
mus::Window* embed_window = window_manager()->NewWindow();
FrameConnection* root_connection = InitFrameTree(
embed_window, "http://127.0.0.1:%u/page_with_single_frame.html");
ASSERT_TRUE(root_connection);
ASSERT_EQ("Page with single frame",
GetFrameText(root_connection->application_connection()));
ASSERT_NO_FATAL_FAILURE(
frame_tree_delegate_->WaitForChildFrameCount(frame_tree_->root(), 1u));
ASSERT_EQ(1u, embed_window->children().size());
Frame* child_frame =
frame_tree_->root()->FindFrame(embed_window->children()[0]->id());
ASSERT_TRUE(child_frame);
ASSERT_EQ("child",
GetFrameText(static_cast<FrameConnection*>(child_frame->user_data())
->application_connection()));
}
// Creates two frames. The parent navigates the child frame by way of changing
// the location of the child frame.
// Crashes on linux_chromium_rel_ng only. http://crbug.com/567337
#if defined(OS_LINUX)
#define MAYBE_ChangeLocationOfChildFrame DISABLED_ChangeLocationOfChildFrame
#else
#define MAYBE_ChangeLocationOfChildFrame ChangeLocationOfChildFrame
#endif
TEST_F(HTMLFrameTest, MAYBE_ChangeLocationOfChildFrame) {
mus::Window* embed_window = window_manager()->NewWindow();
ASSERT_TRUE(InitFrameTree(
embed_window, "http://127.0.0.1:%u/page_with_single_frame.html"));
// page_with_single_frame contains a child frame. The child frame should
// create a new View and Frame.
ASSERT_NO_FATAL_FAILURE(
frame_tree_delegate_->WaitForChildFrameCount(frame_tree_->root(), 1u));
Frame* child_frame = frame_tree_->root()->children().back();
ASSERT_EQ("child",
GetFrameText(static_cast<FrameConnection*>(child_frame->user_data())
->application_connection()));
// Change the location and wait for the navigation to occur.
const char kNavigateFrame[] =
"window.frames[0].location = "
"'http://127.0.0.1:%u/empty_page2.html'";
frame_tree_delegate_->ClearGotNavigate(child_frame);
ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()),
AddPortToString(kNavigateFrame));
ASSERT_TRUE(frame_tree_delegate_->WaitForFrameNavigation(child_frame));
// There should still only be one frame.
ASSERT_EQ(1u, frame_tree_->root()->children().size());
// The navigation should have changed the text of the frame.
ASSERT_TRUE(child_frame->user_data());
ASSERT_EQ("child2",
GetFrameText(static_cast<FrameConnection*>(child_frame->user_data())
->application_connection()));
}
TEST_F(HTMLFrameTest, DynamicallyAddFrameAndVerifyParent) {
Frame* child_frame = LoadEmptyPageAndCreateFrame();
ASSERT_TRUE(child_frame);
mojo::ApplicationConnection* child_frame_connection =
ApplicationConnectionForFrame(child_frame);
ASSERT_EQ("child", GetFrameText(child_frame_connection));
// The child's parent should not be itself:
const char kGetWindowParentNameScript[] =
"window.parent == window ? 'parent is self' : 'parent not self';";
scoped_ptr<base::Value> parent_value(
ExecuteScript(child_frame_connection, kGetWindowParentNameScript));
ASSERT_TRUE(parent_value->IsType(base::Value::TYPE_LIST));
base::ListValue* parent_list;
ASSERT_TRUE(parent_value->GetAsList(&parent_list));
ASSERT_EQ(1u, parent_list->GetSize());
std::string parent_name;
ASSERT_TRUE(parent_list->GetString(0u, &parent_name));
EXPECT_EQ("parent not self", parent_name);
}
TEST_F(HTMLFrameTest, DynamicallyAddFrameAndSeeNameChange) {
Frame* child_frame = LoadEmptyPageAndCreateFrame();
ASSERT_TRUE(child_frame);
mojo::ApplicationConnection* child_frame_connection =
ApplicationConnectionForFrame(child_frame);
// Change the name of the child's window.
ExecuteScript(child_frame_connection, "window.name = 'new_child';");
// Eventually the parent should see the change. There is no convenient way
// to observe this change, so we repeatedly ask for it and timeout if we
// never get the right value.
const base::TimeTicks start_time(base::TimeTicks::Now());
std::string find_window_result;
do {
find_window_result.clear();
scoped_ptr<base::Value> script_value(
ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()),
"window.frames['new_child'] != null ? 'found frame' : "
"'unable to find frame';"));
if (script_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* script_value_as_list;
if (script_value->GetAsList(&script_value_as_list) &&
script_value_as_list->GetSize() == 1) {
script_value_as_list->GetString(0u, &find_window_result);
}
}
} while (find_window_result != "found frame" &&
base::TimeTicks::Now() - start_time <
TestTimeouts::action_timeout());
EXPECT_EQ("found frame", find_window_result);
}
// Triggers dynamic addition and removal of a frame.
TEST_F(HTMLFrameTest, FrameTreeOfThreeLevels) {
// Create a child frame, and in that child frame create another child frame.
Frame* child_frame = LoadEmptyPageAndCreateFrame();
ASSERT_TRUE(child_frame);
ASSERT_TRUE(CreateEmptyChildFrame(child_frame));
// Make sure the parent can see the child and child's child. There is no
// convenient way to observe this change, so we repeatedly ask for it and
// timeout if we never get the right value.
const char kGetChildChildFrameCount[] =
"if (window.frames.length > 0)"
" window.frames[0].frames.length.toString();"
"else"
" '0';";
const base::TimeTicks start_time(base::TimeTicks::Now());
std::string child_child_frame_count;
do {
child_child_frame_count.clear();
scoped_ptr<base::Value> script_value(
ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()),
kGetChildChildFrameCount));
if (script_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* script_value_as_list;
if (script_value->GetAsList(&script_value_as_list) &&
script_value_as_list->GetSize() == 1) {
script_value_as_list->GetString(0u, &child_child_frame_count);
}
}
} while (child_child_frame_count != "1" &&
base::TimeTicks::Now() - start_time <
TestTimeouts::action_timeout());
EXPECT_EQ("1", child_child_frame_count);
// Remove the child's child and make sure the root doesn't see it anymore.
const char kRemoveLastIFrame[] =
"document.body.removeChild(document.body.lastChild);";
ExecuteScript(ApplicationConnectionForFrame(child_frame), kRemoveLastIFrame);
do {
child_child_frame_count.clear();
scoped_ptr<base::Value> script_value(
ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()),
kGetChildChildFrameCount));
if (script_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* script_value_as_list;
if (script_value->GetAsList(&script_value_as_list) &&
script_value_as_list->GetSize() == 1) {
script_value_as_list->GetString(0u, &child_child_frame_count);
}
}
} while (child_child_frame_count != "0" &&
base::TimeTicks::Now() - start_time <
TestTimeouts::action_timeout());
ASSERT_EQ("0", child_child_frame_count);
}
// Verifies PostMessage() works across frames.
TEST_F(HTMLFrameTest, PostMessage) {
Frame* child_frame = LoadEmptyPageAndCreateFrame();
ASSERT_TRUE(child_frame);
mojo::ApplicationConnection* child_frame_connection =
ApplicationConnectionForFrame(child_frame);
ASSERT_EQ("child", GetFrameText(child_frame_connection));
// Register an event handler in the child frame.
const char kRegisterPostMessageHandler[] =
"window.messageData = null;"
"function messageFunction(event) {"
" window.messageData = event.data;"
"}"
"window.addEventListener('message', messageFunction, false);";
ExecuteScript(child_frame_connection, kRegisterPostMessageHandler);
// Post a message from the parent to the child.
const char kPostMessageFromParent[] =
"window.frames[0].postMessage('hello from parent', '*');";
ExecuteScript(ApplicationConnectionForFrame(frame_tree_->root()),
kPostMessageFromParent);
// Wait for the child frame to see the message.
const base::TimeTicks start_time(base::TimeTicks::Now());
std::string message_in_child;
do {
const char kGetMessageData[] = "window.messageData;";
scoped_ptr<base::Value> script_value(
ExecuteScript(child_frame_connection, kGetMessageData));
if (script_value->IsType(base::Value::TYPE_LIST)) {
base::ListValue* script_value_as_list;
if (script_value->GetAsList(&script_value_as_list) &&
script_value_as_list->GetSize() == 1) {
script_value_as_list->GetString(0u, &message_in_child);
}
}
} while (message_in_child != "hello from parent" &&
base::TimeTicks::Now() - start_time <
TestTimeouts::action_timeout());
EXPECT_EQ("hello from parent", message_in_child);
}
} // namespace mojo
| 19,043 | 5,929 |
/***************************************************************************
*
* $Id: StMemoryInfo.hh,v 1.5 2013/01/17 14:40:04 fisyak Exp $
*
* Author: Thomas Ullrich, June 1999
***************************************************************************
*
* Description:
*
***************************************************************************
*
* $Log: StMemoryInfo.hh,v $
* Revision 1.5 2013/01/17 14:40:04 fisyak
* Add APPLE
*
* Revision 1.4 2003/09/02 17:59:35 perev
* gcc 3.2 updates + WarnOff
*
* Revision 1.3 2000/01/04 14:57:54 ullrich
* Added friend declaration to avoid warning messages
* under Linux.
*
* Revision 1.2 1999/12/21 15:14:18 ullrich
* Modified to cope with new compiler version on Sun (CC5.0).
*
* Revision 1.1 1999/06/04 17:57:02 ullrich
* Initial Revision
*
**************************************************************************/
#ifndef StMemoryInfo_hh
#define StMemoryInfo_hh
#ifndef __APPLE__
#include <malloc.h>
#endif
#include <Stiostream.h>
class StMemoryInfo {
public:
static StMemoryInfo* instance();
void snapshot();
void print(ostream& = cout);
friend class nobody;
private:
StMemoryInfo();
StMemoryInfo(const StMemoryInfo &);
const StMemoryInfo & operator=(const StMemoryInfo &);
void printLine(ostream&, const char*, int, int, const char* = 0);
static StMemoryInfo* mMemoryInfo;
#ifndef __APPLE__
struct mallinfo mInfo;
struct mallinfo mOldInfo;
#endif
size_t mCounter;
};
#endif
| 1,554 | 555 |
/* +------------------------------------------------------------------------+
| Mobile Robot Programming Toolkit (MRPT) |
| http://www.mrpt.org/ |
| |
| Copyright (c) 2005-2018, Individual contributors, see AUTHORS file |
| See: http://www.mrpt.org/Authors - All rights reserved. |
| Released under BSD License. See details in http://www.mrpt.org/License |
+------------------------------------------------------------------------+ */
#include "vision-precomp.h" // Precompiled headers
#include <mrpt/vision/tracking.h>
#include <mrpt/vision/CFeatureExtraction.h>
// Universal include for all versions of OpenCV
#include <mrpt/otherlibs/do_opencv_includes.h>
using namespace mrpt;
using namespace mrpt::vision;
using namespace mrpt::img;
using namespace mrpt::tfest;
using namespace mrpt::math;
using namespace std;
// ------------------------------- internal helper templates
// ---------------------------------
namespace mrpt::vision::detail
{
template <typename FEATLIST>
inline void trackFeatures_checkResponses(
FEATLIST& featureList, const CImage& cur_gray,
const float minimum_KLT_response, const unsigned int KLT_response_half_win,
const unsigned int max_x, const unsigned int max_y);
template <>
inline void trackFeatures_checkResponses<CFeatureList>(
CFeatureList& featureList, const CImage& cur_gray,
const float minimum_KLT_response, const unsigned int KLT_response_half_win,
const unsigned int max_x, const unsigned int max_y)
{
const auto itFeatEnd = featureList.end();
for (auto itFeat = featureList.begin(); itFeat != itFeatEnd; ++itFeat)
{
CFeature* ft = itFeat->get();
if (ft->track_status != status_TRACKED)
continue; // Skip if it's not correctly tracked.
const unsigned int x = ft->x;
const unsigned int y = ft->y;
if (x > KLT_response_half_win && y > KLT_response_half_win &&
x < max_x && y < max_y)
{ // Update response:
ft->response = cur_gray.KLT_response(x, y, KLT_response_half_win);
// Is it good enough?
// http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5
if (ft->response < minimum_KLT_response)
{ // Nope!
ft->track_status = status_LOST;
}
}
else
{ // Out of bounds
ft->response = 0;
ft->track_status = status_OOB;
}
}
} // end of trackFeatures_checkResponses<>
template <class FEAT_LIST>
inline void trackFeatures_checkResponses_impl_simple(
FEAT_LIST& featureList, const CImage& cur_gray,
const float minimum_KLT_response, const unsigned int KLT_response_half_win,
const unsigned int max_x_, const unsigned int max_y_)
{
if (featureList.empty()) return;
using pixel_coord_t = typename FEAT_LIST::feature_t::pixel_coord_t;
const auto half_win = static_cast<pixel_coord_t>(KLT_response_half_win);
const auto max_x = static_cast<pixel_coord_t>(max_x_);
const auto max_y = static_cast<pixel_coord_t>(max_y_);
for (int N = featureList.size() - 1; N >= 0; --N)
{
typename FEAT_LIST::feature_t& ft = featureList[N];
if (ft.track_status != status_TRACKED)
continue; // Skip if it's not correctly tracked.
if (ft.pt.x > half_win && ft.pt.y > half_win && ft.pt.x < max_x &&
ft.pt.y < max_y)
{ // Update response:
ft.response =
cur_gray.KLT_response(ft.pt.x, ft.pt.y, KLT_response_half_win);
// Is it good enough?
// http://grooveshark.com/s/Goonies+Are+Good+Enough/2beBfO?src=5
if (ft.response < minimum_KLT_response)
{ // Nope!
ft.track_status = status_LOST;
}
}
else
{ // Out of bounds
ft.response = 0;
ft.track_status = status_OOB;
}
}
} // end of trackFeatures_checkResponses<>
template <>
inline void trackFeatures_checkResponses<TSimpleFeatureList>(
TSimpleFeatureList& featureList, const CImage& cur_gray,
const float minimum_KLT_response, const unsigned int KLT_response_half_win,
const unsigned int max_x, const unsigned int max_y)
{
trackFeatures_checkResponses_impl_simple<TSimpleFeatureList>(
featureList, cur_gray, minimum_KLT_response, KLT_response_half_win,
max_x, max_y);
}
template <>
inline void trackFeatures_checkResponses<TSimpleFeaturefList>(
TSimpleFeaturefList& featureList, const CImage& cur_gray,
const float minimum_KLT_response, const unsigned int KLT_response_half_win,
const unsigned int max_x, const unsigned int max_y)
{
trackFeatures_checkResponses_impl_simple<TSimpleFeaturefList>(
featureList, cur_gray, minimum_KLT_response, KLT_response_half_win,
max_x, max_y);
}
template <typename FEATLIST>
inline void trackFeatures_updatePatch(
FEATLIST& featureList, const CImage& cur_gray);
template <>
inline void trackFeatures_updatePatch<CFeatureList>(
CFeatureList& featureList, const CImage& cur_gray)
{
for (auto& itFeat : featureList)
{
CFeature* ft = itFeat.get();
if (ft->track_status != status_TRACKED)
continue; // Skip if it's not correctly tracked.
const size_t patch_width = ft->patch.getWidth();
const size_t patch_height = ft->patch.getHeight();
if (patch_width > 0 && patch_height > 0)
{
try
{
const int offset = (int)patch_width / 2; // + 1;
cur_gray.extract_patch(
ft->patch, round(ft->x) - offset, round(ft->y) - offset,
patch_width, patch_height);
}
catch (std::exception&)
{
ft->track_status = status_OOB; // Out of bounds!
}
}
}
} // end of trackFeatures_updatePatch<>
template <>
inline void trackFeatures_updatePatch<TSimpleFeatureList>(
TSimpleFeatureList& featureList, const CImage& cur_gray)
{
MRPT_UNUSED_PARAM(featureList);
MRPT_UNUSED_PARAM(cur_gray);
// This list type does not have patch stored explicitly
} // end of trackFeatures_updatePatch<>
template <>
inline void trackFeatures_updatePatch<TSimpleFeaturefList>(
TSimpleFeaturefList& featureList, const CImage& cur_gray)
{
MRPT_UNUSED_PARAM(featureList);
MRPT_UNUSED_PARAM(cur_gray);
// This list type does not have patch stored explicitly
} // end of trackFeatures_updatePatch<>
template <typename FEATLIST>
inline void trackFeatures_addNewFeats(
FEATLIST& featureList, const TSimpleFeatureList& new_feats,
const std::vector<size_t>& sorted_indices, const size_t nNewToCheck,
const size_t maxNumFeatures, const float minimum_KLT_response_to_add,
const double threshold_sqr_dist_to_add_new, const size_t patchSize,
const CImage& cur_gray, TFeatureID& max_feat_ID_at_input);
template <>
inline void trackFeatures_addNewFeats<CFeatureList>(
CFeatureList& featureList, const TSimpleFeatureList& new_feats,
const std::vector<size_t>& sorted_indices, const size_t nNewToCheck,
const size_t maxNumFeatures, const float minimum_KLT_response_to_add,
const double threshold_sqr_dist_to_add_new, const size_t patchSize,
const CImage& cur_gray, TFeatureID& max_feat_ID_at_input)
{
const TImageSize imgSize = cur_gray.getSize();
const int offset = (int)patchSize / 2 + 1;
const int w_off = int(imgSize.x - offset);
const int h_off = int(imgSize.y - offset);
for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures;
i++)
{
const TSimpleFeature& feat = new_feats[sorted_indices[i]];
if (feat.response < minimum_KLT_response_to_add) continue;
double min_dist_sqr = square(10000);
if (!featureList.empty())
{
// m_timlog.enter("[CGenericFeatureTracker] add new
// features.kdtree");
min_dist_sqr =
featureList.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y);
// m_timlog.leave("[CGenericFeatureTracker] add new
// features.kdtree");
}
if (min_dist_sqr > threshold_sqr_dist_to_add_new &&
feat.pt.x > offset && feat.pt.y > offset && feat.pt.x < w_off &&
feat.pt.y < h_off)
{
// Add new feature:
CFeature::Ptr ft = mrpt::make_aligned_shared<CFeature>();
ft->type = featFAST;
ft->ID = ++max_feat_ID_at_input;
ft->x = feat.pt.x;
ft->y = feat.pt.y;
ft->response = feat.response;
ft->orientation = 0;
ft->scale = 1;
ft->patchSize = patchSize; // The size of the feature patch
if (patchSize > 0)
cur_gray.extract_patch(
ft->patch, round(ft->x) - offset, round(ft->y) - offset,
patchSize,
patchSize); // Image patch surronding the feature
featureList.push_back(ft);
}
}
} // end of trackFeatures_addNewFeats<>
template <class FEAT_LIST>
inline void trackFeatures_addNewFeats_simple_list(
FEAT_LIST& featureList, const TSimpleFeatureList& new_feats,
const std::vector<size_t>& sorted_indices, const size_t nNewToCheck,
const size_t maxNumFeatures, const float minimum_KLT_response_to_add,
const double threshold_sqr_dist_to_add_new, const size_t patchSize,
const CImage& cur_gray, TFeatureID& max_feat_ID_at_input)
{
#if 0
// Brute-force version:
const int max_manhatan_dist = std::sqrt(2*threshold_sqr_dist_to_add_new);
for (size_t i=0;i<nNewToCheck && featureList.size()<maxNumFeatures;i++)
{
const TSimpleFeature &feat = new_feats[ sorted_indices[i] ];
if (feat.response<minimum_KLT_response_to_add) break; // continue;
// Check the min-distance:
int manh_dist = std::numeric_limits<int>::max();
for (size_t j=0;j<featureList.size();j++)
{
const TSimpleFeature &existing = featureList[j];
const int d = std::abs(existing.pt.x-feat.pt.x)+std::abs(existing.pt.y-feat.pt.y);
mrpt::keep_min(manh_dist, d);
}
if (manh_dist<max_manhatan_dist)
continue; // Already occupied! skip.
// OK: accept it
featureList.push_back_fast(feat.pt.x,feat.pt.y); // (x,y)
//featureList.mark_kdtree_as_outdated();
// Fill out the rest of data:
TSimpleFeature &newFeat = featureList.back();
newFeat.ID = ++max_feat_ID_at_input;
newFeat.response = feat.response;
newFeat.octave = 0;
/** Inactive: right after detection, and before being tried to track */
newFeat.track_status = status_IDLE;
}
#elif 0
// Version with an occupancy grid:
const int grid_cell_log2 = round(
std::log(std::sqrt(threshold_sqr_dist_to_add_new) * 0.5) /
std::log(2.0));
int grid_lx = 1 + (cur_gray.getWidth() >> grid_cell_log2);
int grid_ly = 1 + (cur_gray.getHeight() >> grid_cell_log2);
mrpt::math::CMatrixBool& occupied_sections =
featureList.getOccupiedSectionsMatrix();
occupied_sections.setSize(
grid_lx, grid_ly); // See the comments above for an explanation.
occupied_sections.fillAll(false);
for (size_t i = 0; i < featureList.size(); i++)
{
const TSimpleFeature& feat = featureList[i];
const int section_idx_x = feat.pt.x >> grid_cell_log2;
const int section_idx_y = feat.pt.y >> grid_cell_log2;
if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 1 ||
section_idx_y >= grid_ly - 1)
continue; // This may be too radical, but speeds up the logic
// below...
// Mark sections as occupied
bool* ptr1 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1);
bool* ptr2 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y);
bool* ptr3 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1);
ptr1[0] = ptr1[1] = ptr1[2] = true;
ptr2[0] = ptr2[1] = ptr2[2] = true;
ptr3[0] = ptr3[1] = ptr3[2] = true;
}
for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures;
i++)
{
const TSimpleFeature& feat = new_feats[sorted_indices[i]];
if (feat.response < minimum_KLT_response_to_add) break; // continue;
// Check the min-distance:
const int section_idx_x = feat.pt.x >> grid_cell_log2;
const int section_idx_y = feat.pt.y >> grid_cell_log2;
if (!section_idx_x || !section_idx_y || section_idx_x >= grid_lx - 2 ||
section_idx_y >= grid_ly - 2)
continue; // This may be too radical, but speeds up the logic
// below...
if (occupied_sections(section_idx_x, section_idx_y))
continue; // Already occupied! skip.
// Mark section as occupied
bool* ptr1 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y - 1);
bool* ptr2 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y);
bool* ptr3 =
&occupied_sections.get_unsafe(section_idx_x - 1, section_idx_y + 1);
ptr1[0] = ptr1[1] = ptr1[2] = true;
ptr2[0] = ptr2[1] = ptr2[2] = true;
ptr3[0] = ptr3[1] = ptr3[2] = true;
// OK: accept it
featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y)
// featureList.mark_kdtree_as_outdated();
// Fill out the rest of data:
TSimpleFeature& newFeat = featureList.back();
newFeat.ID = ++max_feat_ID_at_input;
newFeat.response = feat.response;
newFeat.octave = 0;
/** Inactive: right after detection, and before being tried to track */
newFeat.track_status = status_IDLE;
}
#else
MRPT_UNUSED_PARAM(patchSize);
MRPT_UNUSED_PARAM(cur_gray);
// Version with KD-tree
CFeatureListKDTree<typename FEAT_LIST::feature_t> kdtree(
featureList.getVector());
for (size_t i = 0; i < nNewToCheck && featureList.size() < maxNumFeatures;
i++)
{
const TSimpleFeature& feat = new_feats[sorted_indices[i]];
if (feat.response < minimum_KLT_response_to_add) break; // continue;
// Check the min-distance:
double min_dist_sqr = std::numeric_limits<double>::max();
if (!featureList.empty())
{
// m_timlog.enter("[CGenericFeatureTracker] add new
// features.kdtree");
min_dist_sqr =
kdtree.kdTreeClosestPoint2DsqrError(feat.pt.x, feat.pt.y);
// m_timlog.leave("[CGenericFeatureTracker] add new
// features.kdtree");
}
if (min_dist_sqr > threshold_sqr_dist_to_add_new)
{
// OK: accept it
featureList.push_back_fast(feat.pt.x, feat.pt.y); // (x,y)
kdtree.mark_as_outdated();
// Fill out the rest of data:
typename FEAT_LIST::feature_t& newFeat = featureList.back();
newFeat.ID = ++max_feat_ID_at_input;
newFeat.response = feat.response;
newFeat.octave = 0;
/** Inactive: right after detection, and before being tried to track
*/
newFeat.track_status = status_IDLE;
}
}
#endif
} // end of trackFeatures_addNewFeats<>
template <>
inline void trackFeatures_addNewFeats<TSimpleFeatureList>(
TSimpleFeatureList& featureList, const TSimpleFeatureList& new_feats,
const std::vector<size_t>& sorted_indices, const size_t nNewToCheck,
const size_t maxNumFeatures, const float minimum_KLT_response_to_add,
const double threshold_sqr_dist_to_add_new, const size_t patchSize,
const CImage& cur_gray, TFeatureID& max_feat_ID_at_input)
{
trackFeatures_addNewFeats_simple_list<TSimpleFeatureList>(
featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures,
minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize,
cur_gray, max_feat_ID_at_input);
}
template <>
inline void trackFeatures_addNewFeats<TSimpleFeaturefList>(
TSimpleFeaturefList& featureList, const TSimpleFeatureList& new_feats,
const std::vector<size_t>& sorted_indices, const size_t nNewToCheck,
const size_t maxNumFeatures, const float minimum_KLT_response_to_add,
const double threshold_sqr_dist_to_add_new, const size_t patchSize,
const CImage& cur_gray, TFeatureID& max_feat_ID_at_input)
{
trackFeatures_addNewFeats_simple_list<TSimpleFeaturefList>(
featureList, new_feats, sorted_indices, nNewToCheck, maxNumFeatures,
minimum_KLT_response_to_add, threshold_sqr_dist_to_add_new, patchSize,
cur_gray, max_feat_ID_at_input);
}
// Return the number of removed features
template <typename FEATLIST>
inline size_t trackFeatures_deleteOOB(
FEATLIST& trackedFeats, const size_t img_width, const size_t img_height,
const int MIN_DIST_MARGIN_TO_STOP_TRACKING);
template <typename FEATLIST>
inline size_t trackFeatures_deleteOOB_impl_simple_feat(
FEATLIST& trackedFeats, const size_t img_width, const size_t img_height,
const int MIN_DIST_MARGIN_TO_STOP_TRACKING)
{
if (trackedFeats.empty()) return 0;
std::vector<size_t> survival_idxs;
const size_t N = trackedFeats.size();
// 1st: Build list of survival indexes:
survival_idxs.reserve(N);
for (size_t i = 0; i < N; i++)
{
const typename FEATLIST::feature_t& ft = trackedFeats[i];
const TFeatureTrackStatus status = ft.track_status;
bool eras = (status_TRACKED != status && status_IDLE != status);
if (!eras)
{
// Also, check if it's too close to the image border:
const int x = ft.pt.x;
const int y = ft.pt.y;
if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING ||
y < MIN_DIST_MARGIN_TO_STOP_TRACKING ||
x > static_cast<int>(
img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) ||
y > static_cast<int>(
img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING))
{
eras = true;
}
}
if (!eras) survival_idxs.push_back(i);
}
// 2nd: Build updated list:
const size_t N2 = survival_idxs.size();
const size_t n_removed = N - N2;
for (size_t i = 0; i < N2; i++)
{
if (survival_idxs[i] != i)
trackedFeats[i] = trackedFeats[survival_idxs[i]];
}
trackedFeats.resize(N2);
return n_removed;
} // end of trackFeatures_deleteOOB
template <>
inline size_t trackFeatures_deleteOOB(
TSimpleFeatureList& trackedFeats, const size_t img_width,
const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING)
{
return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeatureList>(
trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING);
}
template <>
inline size_t trackFeatures_deleteOOB(
TSimpleFeaturefList& trackedFeats, const size_t img_width,
const size_t img_height, const int MIN_DIST_MARGIN_TO_STOP_TRACKING)
{
return trackFeatures_deleteOOB_impl_simple_feat<TSimpleFeaturefList>(
trackedFeats, img_width, img_height, MIN_DIST_MARGIN_TO_STOP_TRACKING);
}
template <>
inline size_t trackFeatures_deleteOOB(
CFeatureList& trackedFeats, const size_t img_width, const size_t img_height,
const int MIN_DIST_MARGIN_TO_STOP_TRACKING)
{
auto itFeat = trackedFeats.begin();
size_t n_removed = 0;
while (itFeat != trackedFeats.end())
{
const TFeatureTrackStatus status = (*itFeat)->track_status;
bool eras = (status_TRACKED != status && status_IDLE != status);
if (!eras)
{
// Also, check if it's too close to the image border:
const float x = (*itFeat)->x;
const float y = (*itFeat)->y;
if (x < MIN_DIST_MARGIN_TO_STOP_TRACKING ||
y < MIN_DIST_MARGIN_TO_STOP_TRACKING ||
x > (img_width - MIN_DIST_MARGIN_TO_STOP_TRACKING) ||
y > (img_height - MIN_DIST_MARGIN_TO_STOP_TRACKING))
{
eras = true;
}
}
if (eras) // Erase or keep?
{
itFeat = trackedFeats.erase(itFeat);
n_removed++;
}
else
++itFeat;
}
return n_removed;
} // end of trackFeatures_deleteOOB
} // namespace mrpt::vision::detail
// ---------------------------- end of internal helper templates
// -------------------------------
void CGenericFeatureTracker::trackFeatures_impl(
const CImage& old_img, const CImage& new_img,
TSimpleFeaturefList& inout_featureList)
{
MRPT_UNUSED_PARAM(old_img);
MRPT_UNUSED_PARAM(new_img);
MRPT_UNUSED_PARAM(inout_featureList);
THROW_EXCEPTION("Method not implemented by derived class!");
}
/** Perform feature tracking from "old_img" to "new_img", with a (possibly
*empty) list of previously tracked features "featureList".
* This is a list of parameters (in "extraParams") accepted by ALL
*implementations of feature tracker (see each derived class for more specific
*parameters).
* - "add_new_features" (Default=0). If set to "1", new features will be
*also
*added to the existing ones in areas of the image poor of features.
* This method actually first call the pure virtual "trackFeatures_impl"
*method, then implements the optional detection of new features if
*"add_new_features"!=0.
*/
template <typename FEATLIST>
void CGenericFeatureTracker::internal_trackFeatures(
const CImage& old_img, const CImage& new_img, FEATLIST& featureList)
{
m_timlog.enter(
"[CGenericFeatureTracker::trackFeatures] Complete iteration");
const size_t img_width = new_img.getWidth();
const size_t img_height = new_img.getHeight();
// Take the maximum ID of "old" features so new feats (if
// "add_new_features==true") will be id+1, id+2, ...
TFeatureID max_feat_ID_at_input = 0;
if (!featureList.empty()) max_feat_ID_at_input = featureList.getMaxID();
// Grayscale images
// =========================================
m_timlog.enter("[CGenericFeatureTracker] Convert grayscale");
const CImage prev_gray(old_img, FAST_REF_OR_CONVERT_TO_GRAY);
const CImage cur_gray(new_img, FAST_REF_OR_CONVERT_TO_GRAY);
m_timlog.leave("[CGenericFeatureTracker] Convert grayscale");
// =================================
// (1st STEP) Do the actual tracking
// =================================
m_newly_detected_feats.clear();
m_timlog.enter("[CGenericFeatureTracker] trackFeatures_impl");
trackFeatures_impl(prev_gray, cur_gray, featureList);
m_timlog.leave("[CGenericFeatureTracker] trackFeatures_impl");
// ========================================================
// (2nd STEP) For successfully followed features, check their KLT response??
// ========================================================
const int check_KLT_response_every =
extra_params.getWithDefaultVal("check_KLT_response_every", 0);
const float minimum_KLT_response =
extra_params.getWithDefaultVal("minimum_KLT_response", 5);
const unsigned int KLT_response_half_win =
extra_params.getWithDefaultVal("KLT_response_half_win", 4);
if (check_KLT_response_every > 0 &&
++m_check_KLT_counter >= size_t(check_KLT_response_every))
{
m_timlog.enter("[CGenericFeatureTracker] check KLT responses");
m_check_KLT_counter = 0;
const unsigned int max_x = img_width - KLT_response_half_win;
const unsigned int max_y = img_height - KLT_response_half_win;
detail::trackFeatures_checkResponses(
featureList, cur_gray, minimum_KLT_response, KLT_response_half_win,
max_x, max_y);
m_timlog.leave("[CGenericFeatureTracker] check KLT responses");
} // end check_KLT_response_every
// ============================================================
// (3rd STEP) Remove Out-of-bounds or badly tracked features
// or those marked as "bad" by their low KLT response
// ============================================================
const bool remove_lost_features =
extra_params.getWithDefaultVal("remove_lost_features", 0) != 0;
if (remove_lost_features)
{
m_timlog.enter("[CGenericFeatureTracker] removal of OOB");
static const int MIN_DIST_MARGIN_TO_STOP_TRACKING = 10;
const size_t nRemoved = detail::trackFeatures_deleteOOB(
featureList, img_width, img_height,
MIN_DIST_MARGIN_TO_STOP_TRACKING);
m_timlog.leave("[CGenericFeatureTracker] removal of OOB");
last_execution_extra_info.num_deleted_feats = nRemoved;
}
else
{
last_execution_extra_info.num_deleted_feats = 0;
}
// ========================================================
// (4th STEP) For successfully followed features, update its patch:
// ========================================================
const int update_patches_every =
extra_params.getWithDefaultVal("update_patches_every", 0);
if (update_patches_every > 0 &&
++m_update_patches_counter >= size_t(update_patches_every))
{
m_timlog.enter("[CGenericFeatureTracker] update patches");
m_update_patches_counter = 0;
// Update the patch for each valid feature:
detail::trackFeatures_updatePatch(featureList, cur_gray);
m_timlog.leave("[CGenericFeatureTracker] update patches");
} // end if update_patches_every
// ========================================================
// (5th STEP) Do detection of new features??
// ========================================================
const bool add_new_features =
extra_params.getWithDefaultVal("add_new_features", 0) != 0;
const double threshold_dist_to_add_new =
extra_params.getWithDefaultVal("add_new_feat_min_separation", 15);
// Additional operation: if "add_new_features==true", find new features and
// add them in
// areas spare of valid features:
if (add_new_features)
{
m_timlog.enter("[CGenericFeatureTracker] add new features");
// Look for new features and save in "m_newly_detected_feats", if
// they're not already computed:
if (m_newly_detected_feats.empty())
{
// Do the detection
CFeatureExtraction::detectFeatures_SSE2_FASTER12(
cur_gray, m_newly_detected_feats, m_detector_adaptive_thres);
}
const size_t N = m_newly_detected_feats.size();
last_execution_extra_info.raw_FAST_feats_detected =
N; // Extra out info.
// Update the adaptive threshold.
const size_t desired_num_features = extra_params.getWithDefaultVal(
"desired_num_features_adapt",
size_t((img_width * img_height) >> 9));
updateAdaptiveNewFeatsThreshold(N, desired_num_features);
// Use KLT response instead of the OpenCV's original "response" field:
{
const unsigned int max_x = img_width - KLT_response_half_win;
const unsigned int max_y = img_height - KLT_response_half_win;
for (size_t i = 0; i < N; i++)
{
const unsigned int x = m_newly_detected_feats[i].pt.x;
const unsigned int y = m_newly_detected_feats[i].pt.y;
if (x > KLT_response_half_win && y > KLT_response_half_win &&
x < max_x && y < max_y)
m_newly_detected_feats[i].response =
cur_gray.KLT_response(x, y, KLT_response_half_win);
else
m_newly_detected_feats[i].response = 0; // Out of bounds
}
}
// Sort them by "response": It's ~100 times faster to sort a list of
// indices "sorted_indices" than sorting directly the actual list
// of features "m_newly_detected_feats"
std::vector<size_t> sorted_indices(N);
for (size_t i = 0; i < N; i++) sorted_indices[i] = i;
std::sort(
sorted_indices.begin(), sorted_indices.end(),
KeypointResponseSorter<TSimpleFeatureList>(m_newly_detected_feats));
// For each new good feature, add it to the list of tracked ones only if
// it's pretty
// isolated:
const size_t nNewToCheck = std::min(size_t(1500), N);
const double threshold_sqr_dist_to_add_new =
square(threshold_dist_to_add_new);
const size_t maxNumFeatures =
extra_params.getWithDefaultVal("add_new_feat_max_features", 100);
const size_t patchSize =
extra_params.getWithDefaultVal("add_new_feat_patch_size", 11);
const float minimum_KLT_response_to_add =
extra_params.getWithDefaultVal("minimum_KLT_response_to_add", 10);
// Do it:
detail::trackFeatures_addNewFeats(
featureList, m_newly_detected_feats, sorted_indices, nNewToCheck,
maxNumFeatures, minimum_KLT_response_to_add,
threshold_sqr_dist_to_add_new, patchSize, cur_gray,
max_feat_ID_at_input);
m_timlog.leave("[CGenericFeatureTracker] add new features");
}
m_timlog.leave(
"[CGenericFeatureTracker::trackFeatures] Complete iteration");
} // end of CGenericFeatureTracker::trackFeatures
void CGenericFeatureTracker::trackFeatures(
const CImage& old_img, const CImage& new_img, CFeatureList& featureList)
{
internal_trackFeatures<CFeatureList>(old_img, new_img, featureList);
}
void CGenericFeatureTracker::trackFeatures(
const CImage& old_img, const CImage& new_img,
TSimpleFeatureList& featureList)
{
internal_trackFeatures<TSimpleFeatureList>(old_img, new_img, featureList);
}
void CGenericFeatureTracker::trackFeatures(
const CImage& old_img, const CImage& new_img,
TSimpleFeaturefList& featureList)
{
internal_trackFeatures<TSimpleFeaturefList>(old_img, new_img, featureList);
}
void CGenericFeatureTracker::updateAdaptiveNewFeatsThreshold(
const size_t nNewlyDetectedFeats, const size_t desired_num_features)
{
const size_t hysteresis_min_num_feats = desired_num_features * 0.9;
const size_t hysteresis_max_num_feats = desired_num_features * 1.1;
if (nNewlyDetectedFeats < hysteresis_min_num_feats)
m_detector_adaptive_thres = std::max(
2.0, std::min(
m_detector_adaptive_thres - 1.0,
m_detector_adaptive_thres * 0.8));
else if (nNewlyDetectedFeats > hysteresis_max_num_feats)
m_detector_adaptive_thres = std::max(
m_detector_adaptive_thres + 1.0, m_detector_adaptive_thres * 1.2);
}
/*------------------------------------------------------------
checkTrackedFeatures
-------------------------------------------------------------*/
void vision::checkTrackedFeatures(
CFeatureList& leftList, CFeatureList& rightList,
vision::TMatchingOptions options)
{
ASSERT_(leftList.size() == rightList.size());
// std::cout << std::endl << "Tracked features checking ..." << std::endl;
CFeatureList::iterator itLeft, itRight;
size_t u, v;
double res;
for (itLeft = leftList.begin(), itRight = rightList.begin();
itLeft != leftList.end();)
{
bool delFeat = false;
if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || // Out of bounds
(*itRight)->x < 0 || (*itRight)->y < 0 || // Out of bounds
fabs((*itLeft)->y - (*itRight)->y) >
options
.epipolar_TH) // Not fulfillment of the epipolar constraint
{
// Show reason
std::cout << "Bad tracked match:";
if ((*itLeft)->x < 0 || (*itLeft)->y < 0 || (*itRight)->x < 0 ||
(*itRight)->y < 0)
std::cout << " Out of bounds: (" << (*itLeft)->x << ","
<< (*itLeft)->y << " & (" << (*itRight)->x << ","
<< (*itRight)->y << ")" << std::endl;
if (fabs((*itLeft)->y - (*itRight)->y) > options.epipolar_TH)
std::cout << " Bad row checking: "
<< fabs((*itLeft)->y - (*itRight)->y) << std::endl;
delFeat = true;
}
else
{
// Compute cross correlation:
openCV_cross_correlation(
(*itLeft)->patch, (*itRight)->patch, u, v, res);
if (res < options.minCC_TH)
{
std::cout << "Bad tracked match (correlation failed):"
<< " CC Value: " << res << std::endl;
delFeat = true;
}
} // end if
if (delFeat) // Erase the pair of features
{
itLeft = leftList.erase(itLeft);
itRight = rightList.erase(itRight);
}
else
{
itLeft++;
itRight++;
}
} // end for
} // end checkTrackedFeatures
/*-------------------------------------------------------------
filterBadCorrsByDistance
-------------------------------------------------------------*/
void vision::filterBadCorrsByDistance(
TMatchingPairList& feat_list, unsigned int numberOfSigmas)
{
ASSERT_(numberOfSigmas > 0);
// MRPT_UNUSED_PARAM( numberOfSigmas );
MRPT_START
TMatchingPairList::iterator itPair;
CMatrix dist;
double v_mean, v_std;
unsigned int count = 0;
dist.setSize(feat_list.size(), 1);
// v_mean.resize(1);
// v_std.resize(1);
// Compute mean and standard deviation of the distance
for (itPair = feat_list.begin(); itPair != feat_list.end();
itPair++, count++)
{
// cout << "(" << itPair->other_x << "," << itPair->other_y << "," <<
// itPair->this_z << ")" << "- (" << itPair->this_x << "," <<
// itPair->this_y << "," << itPair->other_z << "): ";
// cout << sqrt( square( itPair->other_x - itPair->this_x ) + square(
// itPair->other_y - itPair->this_y ) + square( itPair->other_z -
// itPair->this_z ) ) << endl;
dist(count, 0) = sqrt(
square(itPair->other_x - itPair->this_x) +
square(itPair->other_y - itPair->this_y) +
square(itPair->other_z - itPair->this_z));
}
dist.meanAndStdAll(v_mean, v_std);
cout << endl
<< "*****************************************************" << endl;
cout << "Mean: " << v_mean << " - STD: " << v_std << endl;
cout << endl
<< "*****************************************************" << endl;
// Filter out bad points
unsigned int idx = 0;
// for( int idx = (int)feat_list.size()-1; idx >= 0; idx-- )
for (itPair = feat_list.begin(); itPair != feat_list.end(); idx++)
{
// if( dist( idx, 0 ) > 1.2 )
if (fabs(dist(idx, 0) - v_mean) > v_std * numberOfSigmas)
{
cout << "Outlier deleted: " << dist(idx, 0) << " vs "
<< v_std * numberOfSigmas << endl;
itPair = feat_list.erase(itPair);
}
else
itPair++;
}
MRPT_END
} // end filterBadCorrsByDistance
| 31,795 | 12,523 |
/*
Copyright(c) 2016-2021 Panos Karabelas
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.
*/
//= INCLUDES =========================
#include "Spartan.h"
#include "ImageImporter.h"
#define FREEIMAGE_LIB
#include <FreeImage.h>
#include <Utilities.h>
#include "../../Threading/Threading.h"
#include "../../RHI/RHI_Texture2D.h"
//====================================
//= NAMESPACES =====
using namespace std;
//==================
namespace Spartan
{
static FREE_IMAGE_FILTER filter_downsample = FREE_IMAGE_FILTER::FILTER_BOX;
// A struct that rescaling threads will work with
struct RescaleJob
{
uint32_t width = 0;
uint32_t height = 0;
uint32_t channel_count = 0;
RHI_Texture_Mip* mip = nullptr;
bool done = false;
RescaleJob(const uint32_t width, const uint32_t height, const uint32_t channel_count)
{
this->width = width;
this->height = height;
this->channel_count = channel_count;
}
};
static uint32_t get_bytes_per_channel(FIBITMAP* bitmap)
{
if (!bitmap)
{
LOG_ERROR_INVALID_PARAMETER();
return 0;
}
const auto type = FreeImage_GetImageType(bitmap);
uint32_t size = 0;
if (type == FIT_BITMAP)
{
size = sizeof(BYTE);
}
else if (type == FIT_UINT16 || type == FIT_RGB16 || type == FIT_RGBA16)
{
size = sizeof(WORD);
}
else if (type == FIT_FLOAT || type == FIT_RGBF || type == FIT_RGBAF)
{
size = sizeof(float);
}
return size;
}
static uint32_t get_channel_count(FIBITMAP* bitmap)
{
if (!bitmap)
{
LOG_ERROR_INVALID_PARAMETER();
return 0;
}
const uint32_t bytes_per_pixel = FreeImage_GetLine(bitmap) / FreeImage_GetWidth(bitmap);
const uint32_t channel_count = bytes_per_pixel / get_bytes_per_channel(bitmap);
return channel_count;
}
static RHI_Format get_rhi_format(const uint32_t bytes_per_channel, const uint32_t channel_count)
{
const uint32_t bits_per_channel = bytes_per_channel * 8;
if (channel_count == 1)
{
if (bits_per_channel == 8) return RHI_Format_R8_Unorm;
}
else if (channel_count == 2)
{
if (bits_per_channel == 8) return RHI_Format_R8G8_Unorm;
}
else if (channel_count == 3)
{
if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float;
}
else if (channel_count == 4)
{
if (bits_per_channel == 8) return RHI_Format_R8G8B8A8_Unorm;
if (bits_per_channel == 16) return RHI_Format_R16G16B16A16_Float;
if (bits_per_channel == 32) return RHI_Format_R32G32B32A32_Float;
}
LOG_ERROR("Could not deduce format");
return RHI_Format_Undefined;
}
static FIBITMAP* convert_to_32bits(FIBITMAP* bitmap)
{
if (!bitmap)
{
LOG_ERROR_INVALID_PARAMETER();
return nullptr;
}
const auto previous_bitmap = bitmap;
bitmap = FreeImage_ConvertTo32Bits(previous_bitmap);
if (!bitmap)
{
LOG_ERROR("Failed (%d bpp, %d channels).", FreeImage_GetBPP(previous_bitmap), get_channel_count(previous_bitmap));
return nullptr;
}
FreeImage_Unload(previous_bitmap);
return bitmap;
}
static FIBITMAP* apply_bitmap_corrections(FIBITMAP* bitmap)
{
SP_ASSERT(bitmap != nullptr);
// Convert to a standard bitmap. FIT_UINT16 and FIT_RGBA16 are processed without errors
// but show up empty in the editor. For now, we convert everything to a standard bitmap.
const FREE_IMAGE_TYPE type = FreeImage_GetImageType(bitmap);
if (type != FIT_BITMAP)
{
// FreeImage can't convert FIT_RGBF
if (type != FIT_RGBF)
{
const auto previous_bitmap = bitmap;
bitmap = FreeImage_ConvertToType(bitmap, FIT_BITMAP);
FreeImage_Unload(previous_bitmap);
}
}
// Convert it to 32 bits (if lower)
if (FreeImage_GetBPP(bitmap) < 32)
{
bitmap = convert_to_32bits(bitmap);
}
// Most GPUs can't use a 32 bit RGB texture as a color attachment.
// Vulkan tells you, your GPU doesn't support it.
// D3D11 seems to be doing some sort of emulation under the hood while throwing some warnings regarding sampling it.
// So to prevent that, we maintain the 32 bits and convert to an RGBA format.
const uint32_t image_bits_per_channel = get_bytes_per_channel(bitmap) * 8;
const uint32_t image_channels = get_channel_count(bitmap);
const bool is_r32g32b32_float = image_channels == 3 && image_bits_per_channel == 32;
if (is_r32g32b32_float)
{
const auto previous_bitmap = bitmap;
bitmap = FreeImage_ConvertToRGBAF(bitmap);
FreeImage_Unload(previous_bitmap);
}
// Convert BGR to RGB (if needed)
if (FreeImage_GetBPP(bitmap) == 32)
{
if (FreeImage_GetRedMask(bitmap) == 0xff0000 && get_channel_count(bitmap) >= 2)
{
if (!SwapRedBlue32(bitmap))
{
LOG_ERROR("Failed to swap red with blue channel");
}
}
}
// Flip it vertically
FreeImage_FlipVertical(bitmap);
return bitmap;
}
static FIBITMAP* rescale(FIBITMAP* bitmap, const uint32_t width, const uint32_t height)
{
if (!bitmap || width == 0 || height == 0)
{
LOG_ERROR_INVALID_PARAMETER();
return nullptr;
}
const auto previous_bitmap = bitmap;
bitmap = FreeImage_Rescale(previous_bitmap, width, height, filter_downsample);
if (!bitmap)
{
LOG_ERROR("Failed");
return previous_bitmap;
}
FreeImage_Unload(previous_bitmap);
return bitmap;
}
ImageImporter::ImageImporter(Context* context)
{
// Initialize
m_context = context;
FreeImage_Initialise();
// Register error handler
const auto free_image_error_handler = [](const FREE_IMAGE_FORMAT fif, const char* message)
{
const auto text = (message != nullptr) ? message : "Unknown error";
const auto format = (fif != FIF_UNKNOWN) ? FreeImage_GetFormatFromFIF(fif) : "Unknown";
LOG_ERROR("%s, Format: %s", text, format);
};
FreeImage_SetOutputMessage(free_image_error_handler);
// Get version
m_context->GetSubsystem<Settings>()->RegisterThirdPartyLib("FreeImage", FreeImage_GetVersion(), "http://freeimage.sourceforge.net/download.html");
}
ImageImporter::~ImageImporter()
{
FreeImage_DeInitialise();
}
bool ImageImporter::Load(const string& file_path, const uint32_t slice_index, RHI_Texture* texture)
{
SP_ASSERT(texture != nullptr);
if (!FileSystem::Exists(file_path))
{
LOG_ERROR("Path \"%s\" is invalid.", file_path.c_str());
return false;
}
// Acquire image format
FREE_IMAGE_FORMAT format = FreeImage_GetFileType(file_path.c_str(), 0);
format = (format == FIF_UNKNOWN) ? FreeImage_GetFIFFromFilename(file_path.c_str()) : format; // If the format is unknown, try to work it out from the file path
if (!FreeImage_FIFSupportsReading(format)) // If the format is still unknown, give up
{
LOG_ERROR("Unsupported format");
return false;
}
// Load the image
auto bitmap = FreeImage_Load(format, file_path.c_str());
if (!bitmap)
{
LOG_ERROR("Failed to load \"%s\"", file_path.c_str());
return false;
}
// Deduce image properties. Important that this is done here, before ApplyBitmapCorrections(), as after that, results for grayscale seem to be always false
const bool image_is_transparent = FreeImage_IsTransparent(bitmap);
const bool image_is_grayscale = FreeImage_GetColorType(bitmap) == FREE_IMAGE_COLOR_TYPE::FIC_MINISBLACK;
// Perform some fix ups
bitmap = apply_bitmap_corrections(bitmap);
if (!bitmap)
{
LOG_ERROR("Failed to apply bitmap corrections");
return false;
}
// Deduce image properties
const uint32_t image_bytes_per_channel = get_bytes_per_channel(bitmap);
const uint32_t image_channel_count = get_channel_count(bitmap);
const RHI_Format image_format = get_rhi_format(image_bytes_per_channel, image_channel_count);
// Perform any scaling (if necessary)
const auto user_define_dimensions = (texture->GetWidth() != 0 && texture->GetHeight() != 0);
const auto dimension_mismatch = (FreeImage_GetWidth(bitmap) != texture->GetWidth() && FreeImage_GetHeight(bitmap) != texture->GetHeight());
const auto scale = user_define_dimensions && dimension_mismatch;
bitmap = scale ? rescale(bitmap, texture->GetWidth(), texture->GetHeight()) : bitmap;
// Deduce image properties
const unsigned int image_width = FreeImage_GetWidth(bitmap);
const unsigned int image_height = FreeImage_GetHeight(bitmap);
// Fill RGBA vector with the data from the FIBITMAP
RHI_Texture_Mip& mip = texture->CreateMip(slice_index);
GetBitsFromFibitmap(&mip, bitmap, image_width, image_height, image_channel_count);
// If the texture supports mipmaps, generate them
if (texture->GetFlags() & RHI_Texture_GenerateMipsWhenLoading)
{
GenerateMipmaps(bitmap, texture, image_width, image_height, image_channel_count, slice_index);
}
// Free memory
FreeImage_Unload(bitmap);
// Fill RHI_Texture with image properties
texture->SetBitsPerChannel(image_bytes_per_channel * 8);
texture->SetWidth(image_width);
texture->SetHeight(image_height);
texture->SetChannelCount(image_channel_count);
texture->SetTransparency(image_is_transparent);
texture->SetFormat(image_format);
texture->SetGrayscale(image_is_grayscale);
return true;
}
bool ImageImporter::GetBitsFromFibitmap(RHI_Texture_Mip* mip, FIBITMAP* bitmap, const uint32_t width, const uint32_t height, const uint32_t channels) const
{
// Validate
SP_ASSERT(mip != nullptr);
SP_ASSERT(width != 0);
SP_ASSERT(height != 0);
SP_ASSERT(channels != 0);
// Compute expected data size and reserve enough memory
const size_t size_bytes = width * height * channels * get_bytes_per_channel(bitmap);
if (size_bytes != mip->bytes.size())
{
mip->bytes.clear();
mip->bytes.reserve(size_bytes);
mip->bytes.resize(size_bytes);
}
// Copy the data over to our vector
const auto bits = FreeImage_GetBits(bitmap);
memcpy(&mip->bytes[0], bits, size_bytes);
return true;
}
void ImageImporter::GenerateMipmaps(FIBITMAP* bitmap, RHI_Texture* texture, uint32_t width, uint32_t height, uint32_t channels, const uint32_t slice_index)
{
// Validate
SP_ASSERT(texture != nullptr);
// Create a RescaleJob for every mip that we need
vector<RescaleJob> jobs;
while (width > 1 && height > 1)
{
width = Math::Helper::Max(width / 2, static_cast<uint32_t>(1));
height = Math::Helper::Max(height / 2, static_cast<uint32_t>(1));
jobs.emplace_back(width, height, channels);
// Resize the RHI_Texture vector accordingly
const auto size = width * height * channels;
RHI_Texture_Mip& mip = texture->CreateMip(slice_index);
mip.bytes.reserve(size);
mip.bytes.resize(size);
}
// Pass data pointers (now that the RHI_Texture mip vector has been constructed)
for (uint32_t i = 0; i < jobs.size(); i++)
{
// reminder: i + 1 because the 0 mip is the default image size
jobs[i].mip = &texture->GetMip(0, i + 1);
}
// Parallelize mipmap generation using multiple threads (because FreeImage_Rescale() is expensive)
auto threading = m_context->GetSubsystem<Threading>();
for (auto& job : jobs)
{
threading->AddTask([this, &job, &bitmap]()
{
FIBITMAP* bitmap_scaled = FreeImage_Rescale(bitmap, job.width, job.height, filter_downsample);
if (!GetBitsFromFibitmap(job.mip, bitmap_scaled, job.width, job.height, job.channel_count))
{
LOG_ERROR("Failed to create mip level %dx%d", job.width, job.height);
}
FreeImage_Unload(bitmap_scaled);
job.done = true;
});
}
// Wait until all mipmaps have been generated
auto ready = false;
while (!ready)
{
ready = true;
for (const auto& job : jobs)
{
if (!job.done)
{
ready = false;
}
}
this_thread::sleep_for(chrono::milliseconds(16));
}
}
}
| 14,936 | 4,605 |
#include "logical_camera_plugin/logical_camera_plugin.hh"
#include <gazebo/physics/Link.hh>
#include <gazebo/physics/Model.hh>
#include <gazebo/physics/World.hh>
#include <gazebo/sensors/Sensor.hh>
#include <gazebo/sensors/SensorManager.hh>
#include "std_msgs/String.h"
#include "logical_camera_plugin/logicalImage.h"
#include <sstream>
#include <string>
#include <algorithm>
using namespace gazebo;
GZ_REGISTER_MODEL_PLUGIN(LogicalCameraPlugin);
LogicalCameraPlugin::LogicalCameraPlugin()
{
}
LogicalCameraPlugin::~LogicalCameraPlugin()
{
this->rosnode->shutdown();
}
void LogicalCameraPlugin::Load(physics::ModelPtr _parent, sdf::ElementPtr _sdf)
{
gzdbg << "Called Load!" << "\n";
initTable();
this->robotNamespace = "logical_camera";
if(_sdf->HasElement("robotNamespace"))
{
this->robotNamespace = _sdf->GetElement("robotNamespace")->Get<std::string>() + "/";
}
this->world = _parent->GetWorld();
this->name = _parent->GetName();
if (!ros::isInitialized())
{
ROS_FATAL_STREAM("A ROS node for Gazebo has not been initialized,"
<< "unable to load plugin. Load the Gazebo system plugin "
<< "'libgazebo_ros_api_plugin.so' in the gazebo_ros package)");
return;
}
this->modelFramePrefix = this->name + "_";
if (_sdf->HasElement("model_frame_prefix"))
{
this->modelFramePrefix = _sdf->GetElement("model_frame_prefix")->Get<std::string>();
}
gzdbg << "Using model frame prefix of: " << this->modelFramePrefix << std::endl;
this->model = _parent;
this->node = transport::NodePtr(new transport::Node());
this->node->Init(this->model->GetWorld()->GetName());
this->rosnode = new ros::NodeHandle(this->robotNamespace);
this->findLogicalCamera();
if ( !this->sensor)
{
gzerr << "No logical camera found on any link\n";
return;
}
for (int i=0;i<4;i++){
this->joint[i] = this->model->GetJoints()[i];
gzdbg << "Joints found are: " <<this->joint[i]->GetScopedName() << "\n";
}
std::string imageTopic_ros = this->name;
if (_sdf->HasElement("image_topic_ros"))
{
imageTopic_ros = _sdf->Get<std::string>("image_topic_ros");
}
this->imageSub = this->node->Subscribe(this->sensor->Topic(),
&LogicalCameraPlugin::onImage, this);
gzdbg << "Subscribing to gazebo topic: "<< this->sensor->Topic() << "\n";
imagePub = this->rosnode->advertise<logical_camera_plugin::logicalImage>("/objectsDetected", 1000);
gzdbg << "Publishing to ROS topic: " << imagePub.getTopic() << "\n";
transformBroadcaster = boost::shared_ptr<tf::TransformBroadcaster>(new tf::TransformBroadcaster());
}
void LogicalCameraPlugin::initTable()
{
gzdbg << "Initializing hash table!" << "\n";
this->matchModel.emplace("intersection_33","West_se101");
this->matchModel.emplace("intersection_33_clone","West_se102");
this->matchModel.emplace("intersection_33_clone_14","North_se104");
this->matchModel.emplace("intersection_33_clone_13","West_se104");
this->matchModel.emplace("intersection_33_clone_12","West_se105");
this->matchModel.emplace("intersection_33_clone_11","East_se106");
this->matchModel.emplace("intersection_33_clone_10","se110");
this->matchModel.emplace("intersection_33_clone_9","se111");
this->matchModel.emplace("intersection_33_clone_0","se112");
this->matchModel.emplace("intersection_33_clone_8","se113");
this->matchModel.emplace("intersection_33_clone_7","se114");
this->matchModel.emplace("intersection_33_clone_1","se115");
this->matchModel.emplace("intersection_33_clone_2","se116");
this->matchModel.emplace("intersection_33_clone_6","se119");
this->matchModel.emplace("intersection_33_clone_3","se117");
this->matchModel.emplace("intersection_33_clone_4","se118");
this->matchModel.emplace("intersection_33_clone_5","se118");
this->matchModel.emplace("intersection_32","intersection_East_1a");
this->matchModel.emplace("intersection_31","intersection_West_1b");
this->matchModel.emplace("intersection_29","intersection_East_1b");
this->matchModel.emplace("intersection_37","intersection_North_1b");
this->matchModel.emplace("intersection_28","intersection_West_1c");
this->matchModel.emplace("intersection_30","intersection_East_1c");
this->matchModel.emplace("intersection_0","intersection_North_1c");
this->matchModel.emplace("intersection_34","intersection_West_1d");
this->matchModel.emplace("intersection_2","intersection_North_1d");
this->matchModel.emplace("intersection_38","intersection_South_2a");
this->matchModel.emplace("intersection_56","intersection_North_2a");
this->matchModel.emplace("intersection_3","intersection_West_2a");
this->matchModel.emplace("intersection_46","intersection_South_2c");
this->matchModel.emplace("intersection_9","intersection_East_2c");
this->matchModel.emplace("intersection_45","intersection_North_2c");
this->matchModel.emplace("intersection_45_clone","intersection_South_2d");
this->matchModel.emplace("intersection_4","intersection_North_2d");
this->matchModel.emplace("intersection_8","intersection_West_2d");
this->matchModel.emplace("intersection_58","intersection_East6_101");
this->matchModel.emplace("intersection_40","intersection_South7_104");
this->matchModel.emplace("intersection_41","intersection_East_104");
this->matchModel.emplace("intersection_35","intersection_South__4i");
this->matchModel.emplace("intersection_36","intersection_North__4i");
this->matchModel.emplace("intersection_1","intersection_West__4i");
this->matchModel.emplace("intersection_36_clone","intersection_South__4h");
this->matchModel.emplace("intersection_39","intersection_North__4h");
this->matchModel.emplace("intersection_10","intersection_West__4h");
this->matchModel.emplace("corridor","corridor_1a");
this->matchModel.emplace("corridor_0","corridor_1b");
this->matchModel.emplace("corridor_1","corridor_1c");
this->matchModel.emplace("corridor_2","corridor_1d");
this->matchModel.emplace("corridor_22","corridor_2a");
this->matchModel.emplace("corridor_23","corridor_2b");
this->matchModel.emplace("corridor_19","corridor_2c");
this->matchModel.emplace("corridor_18","corridor_2d");
this->matchModel.emplace("corridor_13","corridor_2e");
this->matchModel.emplace("corridor_11","corridor_2f");
this->matchModel.emplace("corridor_10","corridor_2g");
this->matchModel.emplace("corridor_6","corridor_2h");
this->matchModel.emplace("corridor_4","corridor_3a");
this->matchModel.emplace("corridor_3","corridor_3b");
this->matchModel.emplace("corridor_5","corridor_3c");
this->matchModel.emplace("corridor_9","corridor_4a");
this->matchModel.emplace("corridor_8","corridor_4b");
this->matchModel.emplace("corridor_7","corridor_4c");
this->matchModel.emplace("corridor_14","corridor_4d");
this->matchModel.emplace("corridor_15","corridor_4e");
this->matchModel.emplace("corridor_16","corridor_4f");
this->matchModel.emplace("corridor_17","corridor_4g");
this->matchModel.emplace("corridor_20","corridor_4h");
this->matchModel.emplace("corridor_21","corridor_4i");
}
string LogicalCameraPlugin::checkIfRoom(string modelName){
unordered_map<string,string>::const_iterator map_find = this->matchModel.find(modelName);
if ( map_find == this->matchModel.end() )
{
gzdbg << "This is not a model to identify room: " << modelName << "!\n";
return modelName;
} else {
gzdbg << "Matched the model " << map_find->first << "for a room: " << map_find->second << "!\n";
return map_find->second;
}
}
void LogicalCameraPlugin::findLogicalCamera()
{
sensors::SensorManager* sensorManager = sensors::SensorManager::Instance();
for (physics::LinkPtr link : this->model->GetLinks())
{
for (unsigned int i =0; i < link->GetSensorCount(); ++i)
{
sensors::SensorPtr sensor = sensorManager->GetSensor(link->GetSensorName(i));
if (sensor->Type() == "logical_camera")
{
this->sensor = sensor;
break;
}
}
if (this->sensor)
{
this->cameraLink = link;
break;
}
}
}
void LogicalCameraPlugin::onImage(ConstLogicalCameraImagePtr &_msg)
{
gazebo::msgs::LogicalCameraImage imageMsg;
math::Vector3 modelPosition;
math::Quaternion modelOrientation;
math::Pose modelPose;
for (int i = 0;i < _msg->model_size();++i)
{
modelPosition = math::Vector3(msgs::ConvertIgn(_msg->model(i).pose().position()));
modelOrientation = math::Quaternion(msgs::ConvertIgn(_msg->model(i).pose().orientation()));
modelPose = math::Pose(modelPosition, modelOrientation);
std::string modelName = _msg->model(i).name();
std::string modelFrameId = this->modelFramePrefix + modelName + "harsha";
if ( modelName != "asphalt_plane" && modelName.find("jersey_barrier") ==string::npos && modelName != "ground_plane" ) {
//if ( modelName != "se1f1" ) {
gzdbg << "Model detected: " << modelName << "with pose" << modelPose << "\n";
//this->publishTF(modelPose, this->name,modelFrameId);
logical_camera_plugin::logicalImage msg;
string finModelName = checkIfRoom(modelName);
msg.modelName = finModelName;
msg.pose_pos_x = modelPose.pos.x;
msg.pose_pos_y = modelPose.pos.y;
msg.pose_pos_z = modelPose.pos.z;
msg.pose_rot_x = modelPose.rot.x;
msg.pose_rot_y = modelPose.rot.y;
msg.pose_rot_z = modelPose.rot.z;
msg.pose_rot_w = modelPose.rot.w;
this->imagePub.publish(msg);
}
}
}
void LogicalCameraPlugin::publishTF(
const math::Pose &pose, const std::string &parentFrame, const std::string &frame)
{
ros::Time currentTime = ros::Time::now();
tf::Quaternion qt(pose.rot.x, pose.rot.y, pose.rot.z, pose.rot.w);
tf::Vector3 vt(pose.pos.x, pose.pos.y, pose.pos.z);
tf::Transform transform(qt, vt);
transformBroadcaster->sendTransform(tf::StampedTransform(transform, currentTime, parentFrame, frame));
}
| 9,920 | 3,678 |
// nanorange/algorithm/min_element.hpp
//
// Copyright (c) 2018 Tristan Brindle (tcbrindle at gmail dot com)
// Distributed under the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#ifndef NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED
#define NANORANGE_ALGORITHM_MIN_ELEMENT_HPP_INCLUDED
#include <nanorange/ranges.hpp>
NANO_BEGIN_NAMESPACE
namespace detail {
struct min_element_fn {
private:
friend struct nth_element_fn;
template <typename I, typename S, typename Comp, typename Proj>
static constexpr I impl(I first, S last, Comp& comp, Proj& proj)
{
if (first == last) {
return first;
}
I i = nano::next(first);
while (i != last) {
if (nano::invoke(comp, nano::invoke(proj, *i),
nano::invoke(proj, *first))) {
first = i;
}
++i;
}
return first;
}
public:
template <typename I, typename S, typename Comp = ranges::less,
typename Proj = identity>
constexpr std::enable_if_t<
forward_iterator<I> && sentinel_for<S, I> &&
indirect_strict_weak_order<Comp, projected<I, Proj>>, I>
operator()(I first, S last, Comp comp = Comp{}, Proj proj = Proj{}) const
{
return min_element_fn::impl(std::move(first), std::move(last),
comp, proj);
}
template <typename Rng, typename Comp = ranges::less, typename Proj = identity>
constexpr std::enable_if_t<
forward_range<Rng> &&
indirect_strict_weak_order<Comp, projected<iterator_t<Rng>, Proj>>,
safe_iterator_t<Rng>>
operator()(Rng&& rng, Comp comp = Comp{}, Proj proj = Proj{}) const
{
return min_element_fn::impl(nano::begin(rng), nano::end(rng),
comp, proj);
}
};
}
NANO_INLINE_VAR(detail::min_element_fn, min_element)
NANO_END_NAMESPACE
#endif
| 2,028 | 710 |
#include <iostream>
using namespace std;
#define FOR(i, a, b) for(int (i) = (a); (i) <= (b); (i)++)
int main() {
int M, P, L, E, R, S, N;
int pre_M;
int pre_L;
int pre_P;
while (cin >> M && cin >> P && cin >> L && cin >> E && cin >> R && cin >> S && cin >> N) {
FOR(i, 0, N - 1) {
pre_M = M;
pre_L = L;
pre_P = P;
M -= pre_M;
L += pre_M * E;
L -= pre_L;
P += (int)(((1 / (double)R)) * pre_L);
P -= pre_P;
M += (int)(((1 / (double)S)) * pre_P);
}
cout << M << endl;
}
}
| 632 | 258 |
/*
* Copyright (C) 2019 Open Source Robotics Foundation
*
* 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 <ignition/msgs/boolean.pb.h>
#include <ignition/msgs/stringmsg.pb.h>
#include <iostream>
#include <ignition/common/Console.hh>
#include <ignition/gui/Application.hh>
#include <ignition/gui/MainWindow.hh>
#include <ignition/plugin/Register.hh>
#include <ignition/transport/Node.hh>
#include <ignition/transport/Publisher.hh>
#include "ignition/gazebo/components/Name.hh"
#include "ignition/gazebo/components/ParentEntity.hh"
#include "ignition/gazebo/EntityComponentManager.hh"
#include "ignition/gazebo/gui/GuiEvents.hh"
#include "TransformControl.hh"
namespace ignition::gazebo
{
class TransformControlPrivate
{
/// \brief Ignition communication node.
public: transport::Node node;
/// \brief Mutex to protect mode
public: std::mutex mutex;
/// \brief Transform control service name
public: std::string service;
};
}
using namespace ignition;
using namespace gazebo;
/////////////////////////////////////////////////
TransformControl::TransformControl()
: ignition::gui::Plugin(),
dataPtr(std::make_unique<TransformControlPrivate>())
{
}
/////////////////////////////////////////////////
TransformControl::~TransformControl() = default;
/////////////////////////////////////////////////
void TransformControl::LoadConfig(const tinyxml2::XMLElement *)
{
if (this->title.empty())
this->title = "Transform control";
// For transform requests
this->dataPtr->service = "/gui/transform_mode";
}
/////////////////////////////////////////////////
void TransformControl::OnSnapUpdate(
double _x, double _y, double _z,
double _roll, double _pitch, double _yaw,
double _scaleX, double _scaleY, double _scaleZ)
{
auto event = new gui::events::SnapIntervals(
math::Vector3d(_x, _y, _z), math::Vector3d(_roll, _pitch, _yaw),
math::Vector3d(_scaleX, _scaleY, _scaleZ));
ignition::gui::App()->sendEvent(
ignition::gui::App()->findChild<ignition::gui::MainWindow *>(), event);
}
/////////////////////////////////////////////////
void TransformControl::OnMode(const QString &_mode)
{
std::function<void(const ignition::msgs::Boolean &, const bool)> cb =
[](const ignition::msgs::Boolean &/*_rep*/, const bool _result)
{
if (!_result)
ignerr << "Error setting transform mode" << std::endl;
};
ignition::msgs::StringMsg req;
req.set_data(_mode.toStdString());
this->dataPtr->node.Request(this->dataPtr->service, req, cb);
}
// Register this plugin
IGNITION_ADD_PLUGIN(ignition::gazebo::TransformControl,
ignition::gui::Plugin)
| 3,179 | 982 |
#include<iostream>
#include<iomanip>
using namespace std;
int main(){
double x[100];
int i;
for(i=0;i<100;i++)cin >> x[i];
for(i=0;i<100;i++){
if(x[i]<=10){
cout << "A[" << i << "] = " << fixed << setprecision(1) << x[i] << endl;
}
}
return 0;
}
| 268 | 146 |
#include <windows.h>
#include <stdio.h>
#define THREADCOUNT 2
HANDLE ghMutex;
DWORD WINAPI WriteToDatabase( LPVOID );
int main( void )
{
HANDLE aThread[THREADCOUNT];
DWORD ThreadID;
int i;
// Create a mutex with no initial owner
ghMutex = CreateMutex(
NULL, // default security attributes
FALSE, // initially not owned
NULL); // unnamed mutex
if (ghMutex == NULL)
{
printf("CreateMutex error: %d\n", GetLastError());
return 1;
}
// Create worker threads
for( i=0; i < THREADCOUNT; i++ )
{
aThread[i] = CreateThread(
NULL, // default security attributes
0, // default stack size
(LPTHREAD_START_ROUTINE) WriteToDatabase,
NULL, // no thread function arguments
0, // default creation flags
&ThreadID); // receive thread identifier
if( aThread[i] == NULL )
{
printf("CreateThread error: %d\n", GetLastError());
return 1;
}
}
// Wait for all threads to terminate
WaitForMultipleObjects(THREADCOUNT, aThread, TRUE, INFINITE);
// Close thread and mutex handles
for( i=0; i < THREADCOUNT; i++ )
CloseHandle(aThread[i]);
CloseHandle(ghMutex);
return 0;
}
DWORD WINAPI WriteToDatabase( LPVOID lpParam )
{
// lpParam not used in this example
UNREFERENCED_PARAMETER(lpParam);
DWORD dwCount=0, dwWaitResult;
// Request ownership of mutex.
while( dwCount < 20 )
{
dwWaitResult = WaitForSingleObject(
ghMutex, // handle to mutex
INFINITE); // no time-out interval
switch (dwWaitResult)
{
// The thread got ownership of the mutex
case WAIT_OBJECT_0:
__try {
// TODO: Write to the database
printf("Thread %d writing to database...\n",
GetCurrentThreadId());
dwCount++;
}
__finally {
// Release ownership of the mutex object
if (! ReleaseMutex(ghMutex))
{
// Handle error.
}
}
break;
// The thread got ownership of an abandoned mutex
// The database is in an indeterminate state
case WAIT_ABANDONED:
return FALSE;
}
}
return TRUE;
} | 2,670 | 765 |
#include "file_util.hpp"
auto read_file(std::string_view path) -> std::string
{
std::ifstream file{path.data()};
if (!file.is_open()) {
spdlog::error("Cannot open file {}\n", path);
std::fflush(stdout);
}
std::stringstream ss;
// read file's buffer contents into streams
ss << file.rdbuf();
return ss.str();
}
| 336 | 126 |
#ifndef Rect_hpp
#define Rect_hpp
#include "SDL.hpp"
#include <vector>
#include <utility>
namespace SDL
{
using namespace std::rel_ops;
struct Size
{
int w, h;
};
using Point = SDL_Point;
using Rect = SDL_Rect;
using Points = std::vector<Point>;
using Rects = std::vector<Rect>;
using Line = std::pair<Point, Point>;
using Lines = std::vector<Line>;
using Sizes = std::vector<Size>;
inline bool operator!(Rect const &A)
{
return SDL_RectEmpty(&A);
}
inline bool operator<(Rect const &A, Rect const &B)
{
return A.w < B.w and A.h < B.h and A.x > B.x and A.y > B.y;
}
inline bool operator==(Rect const &A, Rect const &B)
{
return SDL_RectEquals(&A, &B);
}
inline bool operator&&(Rect const &A, Rect const &B)
{
return SDL_HasIntersection(&A, &B);
}
inline bool operator&&(Rect const &A, Point const &B)
{
return SDL_PointInRect(&B, &A);
}
inline bool operator&&(Rect const &A, Line B)
{
return SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y);
}
inline Line operator&(Rect const &A, Line B)
{
if (not SDL_IntersectRectAndLine(&A, &B.first.x, &B.first.y, &B.second.x, &B.second.y))
{
B.first.x = B.first.y = B.second.x = B.second.y = 0;
}
return B;
}
inline Rect operator&(Rect const &A, Rect const &B)
{
Rect C;
if (not SDL_IntersectRect(&A, &B, &C))
{
C.x = C.y = C.w = C.h = 0;
}
return C;
}
inline Rect operator|(Rect const &A, Rect const &B)
{
Rect C;
SDL_UnionRect(&A, &B, &C);
return C;
}
}
#endif // file
| 1,782 | 668 |
// system include files
#include <memory>
// user include files
#include "Calibration/EcalCalibAlgos/interface/ECALpedestalPCLHarvester.h"
#include "CondCore/DBOutputService/interface/PoolDBOutputService.h"
#include "FWCore/Framework/interface/ESHandle.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "CondFormats/EcalObjects/interface/EcalChannelStatus.h"
#include "CondFormats/EcalObjects/interface/EcalChannelStatusCode.h"
#include "CondFormats/DataRecord/interface/EcalPedestalsRcd.h"
#include "CondFormats/DataRecord/interface/EcalChannelStatusRcd.h"
#include "CommonTools/Utils/interface/StringToEnumValue.h"
#include <iostream>
#include <string>
ECALpedestalPCLHarvester::ECALpedestalPCLHarvester(const edm::ParameterSet& ps)
: currentPedestals_(nullptr), channelStatus_(nullptr) {
chStatusToExclude_ = StringToEnumValue<EcalChannelStatusCode::Code>(
ps.getParameter<std::vector<std::string> >("ChannelStatusToExclude"));
minEntries_ = ps.getParameter<int>("MinEntries");
checkAnomalies_ = ps.getParameter<bool>("checkAnomalies");
nSigma_ = ps.getParameter<double>("nSigma");
thresholdAnomalies_ = ps.getParameter<double>("thresholdAnomalies");
dqmDir_ = ps.getParameter<std::string>("dqmDir");
labelG6G1_ = ps.getParameter<std::string>("labelG6G1");
threshDiffEB_ = ps.getParameter<double>("threshDiffEB");
threshDiffEE_ = ps.getParameter<double>("threshDiffEE");
threshChannelsAnalyzed_ = ps.getParameter<double>("threshChannelsAnalyzed");
}
void ECALpedestalPCLHarvester::dqmEndJob(DQMStore::IBooker& ibooker_, DQMStore::IGetter& igetter_) {
// calculate pedestals and fill db record
EcalPedestals pedestals;
float kBarrelSize = 61200;
float kEndcapSize = 2 * 7324;
float skipped_channels_EB = 0;
float skipped_channels_EE = 0;
for (uint16_t i = 0; i < EBDetId::kSizeForDenseIndexing; ++i) {
std::string hname = dqmDir_ + "/EB/" + std::to_string(int(i / 100)) + "/eb_" + std::to_string(i);
MonitorElement* ch = igetter_.get(hname);
if (ch == nullptr) {
edm::LogWarning("MissingMonitorElement") << "failed to find MonitorElement " << hname;
entriesEB_[i] = 0;
continue;
}
double mean = ch->getMean();
double rms = ch->getRMS();
entriesEB_[i] = ch->getEntries();
DetId id = EBDetId::detIdFromDenseIndex(i);
EcalPedestal ped;
EcalPedestal oldped = *currentPedestals_->find(id.rawId());
EcalPedestal g6g1ped = *g6g1Pedestals_->find(id.rawId());
ped.mean_x12 = mean;
ped.rms_x12 = rms;
float diff = std::abs(mean - oldped.mean_x12);
// if bad channel or low stat skip or the difference is too large wrt to previous record
if (ch->getEntries() < minEntries_ || !checkStatusCode(id) || diff > threshDiffEB_) {
ped.mean_x12 = oldped.mean_x12;
ped.rms_x12 = oldped.rms_x12;
skipped_channels_EB++;
}
// copy g6 and g1 from the corressponding record
ped.mean_x6 = g6g1ped.mean_x6;
ped.rms_x6 = g6g1ped.rms_x6;
ped.mean_x1 = g6g1ped.mean_x1;
ped.rms_x1 = g6g1ped.rms_x1;
pedestals.setValue(id.rawId(), ped);
}
for (uint16_t i = 0; i < EEDetId::kSizeForDenseIndexing; ++i) {
std::string hname = dqmDir_ + "/EE/" + std::to_string(int(i / 100)) + "/ee_" + std::to_string(i);
MonitorElement* ch = igetter_.get(hname);
if (ch == nullptr) {
edm::LogWarning("MissingMonitorElement") << "failed to find MonitorElement " << hname;
entriesEE_[i] = 0;
continue;
}
double mean = ch->getMean();
double rms = ch->getRMS();
entriesEE_[i] = ch->getEntries();
DetId id = EEDetId::detIdFromDenseIndex(i);
EcalPedestal ped;
EcalPedestal oldped = *currentPedestals_->find(id.rawId());
EcalPedestal g6g1ped = *g6g1Pedestals_->find(id.rawId());
ped.mean_x12 = mean;
ped.rms_x12 = rms;
float diff = std::abs(mean - oldped.mean_x12);
// if bad channel or low stat skip or the difference is too large wrt to previous record
if (ch->getEntries() < minEntries_ || !checkStatusCode(id) || diff > threshDiffEE_) {
ped.mean_x12 = oldped.mean_x12;
ped.rms_x12 = oldped.rms_x12;
skipped_channels_EE++;
}
// copy g6 and g1 pedestals from corresponding record
ped.mean_x6 = g6g1ped.mean_x6;
ped.rms_x6 = g6g1ped.rms_x6;
ped.mean_x1 = g6g1ped.mean_x1;
ped.rms_x1 = g6g1ped.rms_x1;
pedestals.setValue(id.rawId(), ped);
}
bool enough_stat = false;
if ((kBarrelSize - skipped_channels_EB) / kBarrelSize > threshChannelsAnalyzed_ &&
(kEndcapSize - skipped_channels_EE) / kEndcapSize > threshChannelsAnalyzed_) {
enough_stat = true;
}
dqmPlots(pedestals, ibooker_);
// check if there are large variations wrt exisiting pedstals
if (checkAnomalies_) {
if (checkVariation(*currentPedestals_, pedestals)) {
edm::LogError("Large Variations found wrt to old pedestals, no file created");
return;
}
}
if (!enough_stat)
return;
// write out pedestal record
edm::Service<cond::service::PoolDBOutputService> poolDbService;
if (!poolDbService.isAvailable()) {
throw std::runtime_error("PoolDBService required.");
}
poolDbService->writeOne(&pedestals, poolDbService->currentTime(), "EcalPedestalsRcd");
}
// ------------ method fills 'descriptions' with the allowed parameters for the module ------------
void ECALpedestalPCLHarvester::fillDescriptions(edm::ConfigurationDescriptions& descriptions) {
edm::ParameterSetDescription desc;
desc.setUnknown();
descriptions.addDefault(desc);
}
void ECALpedestalPCLHarvester::endRun(edm::Run const& run, edm::EventSetup const& isetup) {
edm::ESHandle<EcalChannelStatus> chStatus;
isetup.get<EcalChannelStatusRcd>().get(chStatus);
channelStatus_ = chStatus.product();
edm::ESHandle<EcalPedestals> peds;
isetup.get<EcalPedestalsRcd>().get(peds);
currentPedestals_ = peds.product();
edm::ESHandle<EcalPedestals> g6g1peds;
isetup.get<EcalPedestalsRcd>().get(labelG6G1_, g6g1peds);
g6g1Pedestals_ = g6g1peds.product();
}
bool ECALpedestalPCLHarvester::checkStatusCode(const DetId& id) {
EcalChannelStatusMap::const_iterator dbstatusPtr;
dbstatusPtr = channelStatus_->getMap().find(id.rawId());
EcalChannelStatusCode::Code dbstatus = dbstatusPtr->getStatusCode();
std::vector<int>::const_iterator res = std::find(chStatusToExclude_.begin(), chStatusToExclude_.end(), dbstatus);
if (res != chStatusToExclude_.end())
return false;
return true;
}
bool ECALpedestalPCLHarvester::isGood(const DetId& id) {
EcalChannelStatusMap::const_iterator dbstatusPtr;
dbstatusPtr = channelStatus_->getMap().find(id.rawId());
if (dbstatusPtr == channelStatus_->getMap().end())
edm::LogError("Invalid DetId supplied");
EcalChannelStatusCode::Code dbstatus = dbstatusPtr->getStatusCode();
if (dbstatus == 0)
return true;
return false;
}
bool ECALpedestalPCLHarvester::checkVariation(const EcalPedestalsMap& oldPedestals,
const EcalPedestalsMap& newPedestals) {
uint32_t nAnomaliesEB = 0;
uint32_t nAnomaliesEE = 0;
for (uint16_t i = 0; i < EBDetId::kSizeForDenseIndexing; ++i) {
DetId id = EBDetId::detIdFromDenseIndex(i);
const EcalPedestal& newped = *newPedestals.find(id.rawId());
const EcalPedestal& oldped = *oldPedestals.find(id.rawId());
if (std::abs(newped.mean_x12 - oldped.mean_x12) > nSigma_ * oldped.rms_x12)
nAnomaliesEB++;
}
for (uint16_t i = 0; i < EEDetId::kSizeForDenseIndexing; ++i) {
DetId id = EEDetId::detIdFromDenseIndex(i);
const EcalPedestal& newped = *newPedestals.find(id.rawId());
const EcalPedestal& oldped = *oldPedestals.find(id.rawId());
if (std::abs(newped.mean_x12 - oldped.mean_x12) > nSigma_ * oldped.rms_x12)
nAnomaliesEE++;
}
if (nAnomaliesEB > thresholdAnomalies_ * EBDetId::kSizeForDenseIndexing ||
nAnomaliesEE > thresholdAnomalies_ * EEDetId::kSizeForDenseIndexing)
return true;
return false;
}
void ECALpedestalPCLHarvester::dqmPlots(const EcalPedestals& newpeds, DQMStore::IBooker& ibooker) {
ibooker.cd();
ibooker.setCurrentFolder(dqmDir_ + "/Summary");
MonitorElement* pmeb = ibooker.book2D("meaneb", "Pedestal Means EB", 360, 1., 361., 171, -85., 86.);
MonitorElement* preb = ibooker.book2D("rmseb", "Pedestal RMS EB ", 360, 1., 361., 171, -85., 86.);
MonitorElement* pmeep = ibooker.book2D("meaneep", "Pedestal Means EEP", 100, 1, 101, 100, 1, 101);
MonitorElement* preep = ibooker.book2D("rmseep", "Pedestal RMS EEP", 100, 1, 101, 100, 1, 101);
MonitorElement* pmeem = ibooker.book2D("meaneem", "Pedestal Means EEM", 100, 1, 101, 100, 1, 101);
MonitorElement* preem = ibooker.book2D("rmseem", "Pedestal RMS EEM", 100, 1, 101, 100, 1, 101);
MonitorElement* pmebd = ibooker.book2D("meanebdiff", "Abs Rel Pedestal Means Diff EB", 360, 1., 361., 171, -85., 86.);
MonitorElement* prebd = ibooker.book2D("rmsebdiff", "Abs Rel Pedestal RMS Diff E ", 360, 1., 361., 171, -85., 86.);
MonitorElement* pmeepd = ibooker.book2D("meaneepdiff", "Abs Rel Pedestal Means Diff EEP", 100, 1, 101, 100, 1, 101);
MonitorElement* preepd = ibooker.book2D("rmseepdiff", "Abs Rel Pedestal RMS Diff EEP", 100, 1, 101, 100, 1, 101);
MonitorElement* pmeemd = ibooker.book2D("meaneemdiff", "Abs Rel Pedestal Means Diff EEM", 100, 1, 101, 100, 1, 101);
MonitorElement* preemd = ibooker.book2D("rmseemdiff", "Abs RelPedestal RMS Diff EEM", 100, 1, 101, 100, 1, 101);
MonitorElement* poeb = ibooker.book2D("occeb", "Occupancy EB", 360, 1., 361., 171, -85., 86.);
MonitorElement* poeep = ibooker.book2D("occeep", "Occupancy EEP", 100, 1, 101, 100, 1, 101);
MonitorElement* poeem = ibooker.book2D("occeem", "Occupancy EEM", 100, 1, 101, 100, 1, 101);
MonitorElement* hdiffeb = ibooker.book1D("diffeb", "Pedestal Differences EB", 100, -2.5, 2.5);
MonitorElement* hdiffee = ibooker.book1D("diffee", "Pedestal Differences EE", 100, -2.5, 2.5);
for (int hash = 0; hash < EBDetId::kSizeForDenseIndexing; ++hash) {
EBDetId di = EBDetId::detIdFromDenseIndex(hash);
float mean = newpeds[di].mean_x12;
float rms = newpeds[di].rms_x12;
float cmean = (*currentPedestals_)[di].mean_x12;
float crms = (*currentPedestals_)[di].rms_x12;
if (!isGood(di))
continue; // only good channels are plotted
pmeb->Fill(di.iphi(), di.ieta(), mean);
preb->Fill(di.iphi(), di.ieta(), rms);
if (cmean)
pmebd->Fill(di.iphi(), di.ieta(), std::abs(mean - cmean) / cmean);
if (crms)
prebd->Fill(di.iphi(), di.ieta(), std::abs(rms - crms) / crms);
poeb->Fill(di.iphi(), di.ieta(), entriesEB_[hash]);
hdiffeb->Fill(mean - cmean);
}
for (int hash = 0; hash < EEDetId::kSizeForDenseIndexing; ++hash) {
EEDetId di = EEDetId::detIdFromDenseIndex(hash);
float mean = newpeds[di].mean_x12;
float rms = newpeds[di].rms_x12;
float cmean = (*currentPedestals_)[di].mean_x12;
float crms = (*currentPedestals_)[di].rms_x12;
if (!isGood(di))
continue; // only good channels are plotted
if (di.zside() > 0) {
pmeep->Fill(di.ix(), di.iy(), mean);
preep->Fill(di.ix(), di.iy(), rms);
poeep->Fill(di.ix(), di.iy(), entriesEE_[hash]);
if (cmean)
pmeepd->Fill(di.ix(), di.iy(), std::abs(mean - cmean) / cmean);
if (crms)
preepd->Fill(di.ix(), di.iy(), std::abs(rms - crms) / crms);
} else {
pmeem->Fill(di.ix(), di.iy(), mean);
preem->Fill(di.ix(), di.iy(), rms);
if (cmean)
pmeemd->Fill(di.ix(), di.iy(), std::abs(mean - cmean) / cmean);
poeem->Fill(di.ix(), di.iy(), entriesEE_[hash]);
if (crms)
preemd->Fill(di.ix(), di.iy(), std::abs(rms - crms) / crms);
}
hdiffee->Fill(mean - cmean);
}
}
| 11,793 | 4,957 |
/**
Given pointers start and end that point to the
first and past the last element of a segment inside
an array, reverse all elements in the segment.
*/
void reverse(int* start, int* end)
{
int * tempEnd = end-1;
while(start < tempEnd)
{
int temp = *start;
*start = *tempEnd;
*tempEnd = temp;
start++;
tempEnd--;
}
}
#include <iostream>
using namespace std;
void reverse(int* start, int* end);
void print(int* a, int n)
{
cout << "{";
for (int i = 0; i < n; i++)
{
cout << " " << a[i];
if (i < n - 1) cout << ",";
}
cout << " }" << endl;
}
int main()
{
int a[] = { 5, 1, 4, 9, -4, 8, -9, 0 };
reverse(a + 1, a + 5);
print(a, sizeof(a) / sizeof(a[0]));
cout << "Expected: { 5, -4, 9, 4, 1, 8, -9, 0 }" << endl;
int b[] = { 1, 4, 9, 0 };
reverse(b + 1, b + 4);
print(b, sizeof(b) / sizeof(b[0]));
cout << "Expected: { 1, 0, 9, 4 }" << endl;
int c[] = { 12, 13 };
reverse(c, c + 1);
print(c, sizeof(c) / sizeof(c[0]));
cout << "Expected: { 12, 13 }" << endl;
int d[] = { 14, 15 };
reverse(d, d);
print(d, sizeof(d) / sizeof(d[0]));
cout << "Expected: { 14, 15 }" << endl;
return 0;
}
| 1,313 | 577 |
#include <omwmm/extractor.hpp>
#include <filesystem>
#include <memory>
#include <string>
#include <string_view>
#include <unordered_map>
#include <algorithm>
#include <cctype>
#include <7zpp/7zpp.h>
#include <omwmm/exceptions.hpp>
using SevenZip::SevenZipLibrary;
using SevenZip::SevenZipExtractor;
using SevenZipString = SevenZip::TString;
using SevenZip::CompressionFormat;
using SevenZip::CompressionFormatEnum;
namespace fs = std::filesystem;
namespace omwmm {
using namespace exceptions;
Extractor::Extractor() : _data(SevenZipLibrary()) {
auto lzma_lib = std::any_cast<SevenZipLibrary>(&_data);
if (!lzma_lib->Load())
throw ExtractorException("Failed to load 7z dll");
}
static const std::unordered_map<std::string_view, CompressionFormatEnum>
extensions{
{".7z", CompressionFormat::SevenZip},
{".zip", CompressionFormat::Zip},
{".rar", CompressionFormat::Rar}
};
void Extractor::extract(const fs::path& source, const fs::path& dest) {
if (!fs::exists(source))
throw ExtractorException("Source file doesn't exist");
if (!fs::exists(dest))
fs::create_directory(dest);
auto lib = std::any_cast<SevenZipLibrary>(&_data);
auto str = fs::path(source).make_preferred().native();
SevenZipString name;
name.assign(str.begin(), str.end());
auto ext = SevenZipExtractor(*lib, name);
str.assign(dest.native());
name.assign(str.begin(), str.end());
if (!ext.DetectCompressionFormat()) {
auto sf = source.extension().string();
std::transform(sf.begin(), sf.end(), sf.begin(), std::tolower);
if (extensions.find(sf) != extensions.end())
ext.SetCompressionFormat(extensions.at(sf));
else
ext.SetCompressionFormat(CompressionFormat::Zip);
}
if (!ext.ExtractArchive(name))
throw ExtractorException("Failed to extract file");
}
} | 1,773 | 618 |
// <copyright file="Exceptions.cpp" company="Microsoft Corporation">
// Copyright (C) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE.txt in the project root for license information.
// </copyright>
#include "stdafx.h"
using namespace std;
wstring win32_error::format_message(_In_ int code)
{
const size_t max = 65536;
wstring err(max, wstring::value_type());
if (auto ch = ::FormatMessageW(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, code, 0, const_cast<LPWSTR>(err.c_str()), err.size(), NULL))
{
err.resize(ch);
return err;
}
return L"unknown error";
}
| 665 | 230 |
//
// Created by ubuntu on 2021/4/16.
//
#include <iostream>
#include "insert_demo.h"
void InsertDemo::InsertMap()
{
MElement element;
element.name = "element1";
map_.insert(std::make_pair("key_element1", element));
}
void InsertDemo::ShowMap()
{
std::map<std::string, MElement>::iterator it;
for (it = map_.begin(); it != map_.end(); it++) {
MElement element = std::move(it->second);
std::cout << ("element name :" + element.name) << std::endl;
}
}
MElement InsertDemo::FindKey()
{
std::map<std::string, MElement>::iterator iter;
iter = map_.find("key_element1");
return iter->second;
}
| 648 | 228 |
//===- Set.cpp - MLIR PresburgerSet Class ---------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Analysis/PresburgerSet.h"
#include "mlir/Analysis/Presburger/Simplex.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallBitVector.h"
using namespace mlir;
PresburgerSet::PresburgerSet(const FlatAffineConstraints &fac)
: nDim(fac.getNumDimIds()), nSym(fac.getNumSymbolIds()) {
unionFACInPlace(fac);
}
unsigned PresburgerSet::getNumFACs() const {
return flatAffineConstraints.size();
}
unsigned PresburgerSet::getNumDims() const { return nDim; }
unsigned PresburgerSet::getNumSyms() const { return nSym; }
ArrayRef<FlatAffineConstraints>
PresburgerSet::getAllFlatAffineConstraints() const {
return flatAffineConstraints;
}
const FlatAffineConstraints &
PresburgerSet::getFlatAffineConstraints(unsigned index) const {
assert(index < flatAffineConstraints.size() && "index out of bounds!");
return flatAffineConstraints[index];
}
/// Assert that the FlatAffineConstraints and PresburgerSet live in
/// compatible spaces.
static void assertDimensionsCompatible(const FlatAffineConstraints &fac,
const PresburgerSet &set) {
assert(fac.getNumDimIds() == set.getNumDims() &&
"Number of dimensions of the FlatAffineConstraints and PresburgerSet"
"do not match!");
assert(fac.getNumSymbolIds() == set.getNumSyms() &&
"Number of symbols of the FlatAffineConstraints and PresburgerSet"
"do not match!");
}
/// Assert that the two PresburgerSets live in compatible spaces.
static void assertDimensionsCompatible(const PresburgerSet &setA,
const PresburgerSet &setB) {
assert(setA.getNumDims() == setB.getNumDims() &&
"Number of dimensions of the PresburgerSets do not match!");
assert(setA.getNumSyms() == setB.getNumSyms() &&
"Number of symbols of the PresburgerSets do not match!");
}
/// Mutate this set, turning it into the union of this set and the given
/// FlatAffineConstraints.
void PresburgerSet::unionFACInPlace(const FlatAffineConstraints &fac) {
assertDimensionsCompatible(fac, *this);
flatAffineConstraints.push_back(fac);
}
/// Mutate this set, turning it into the union of this set and the given set.
///
/// This is accomplished by simply adding all the FACs of the given set to this
/// set.
void PresburgerSet::unionSetInPlace(const PresburgerSet &set) {
assertDimensionsCompatible(set, *this);
for (const FlatAffineConstraints &fac : set.flatAffineConstraints)
unionFACInPlace(fac);
}
/// Return the union of this set and the given set.
PresburgerSet PresburgerSet::unionSet(const PresburgerSet &set) const {
assertDimensionsCompatible(set, *this);
PresburgerSet result = *this;
result.unionSetInPlace(set);
return result;
}
/// A point is contained in the union iff any of the parts contain the point.
bool PresburgerSet::containsPoint(ArrayRef<int64_t> point) const {
for (const FlatAffineConstraints &fac : flatAffineConstraints) {
if (fac.containsPoint(point))
return true;
}
return false;
}
PresburgerSet PresburgerSet::getUniverse(unsigned nDim, unsigned nSym) {
PresburgerSet result(nDim, nSym);
result.unionFACInPlace(FlatAffineConstraints::getUniverse(nDim, nSym));
return result;
}
PresburgerSet PresburgerSet::getEmptySet(unsigned nDim, unsigned nSym) {
return PresburgerSet(nDim, nSym);
}
// Return the intersection of this set with the given set.
//
// We directly compute (S_1 or S_2 ...) and (T_1 or T_2 ...)
// as (S_1 and T_1) or (S_1 and T_2) or ...
PresburgerSet PresburgerSet::intersect(const PresburgerSet &set) const {
assertDimensionsCompatible(set, *this);
PresburgerSet result(nDim, nSym);
for (const FlatAffineConstraints &csA : flatAffineConstraints) {
for (const FlatAffineConstraints &csB : set.flatAffineConstraints) {
FlatAffineConstraints intersection(csA);
intersection.append(csB);
if (!intersection.isEmpty())
result.unionFACInPlace(std::move(intersection));
}
}
return result;
}
/// Return `coeffs` with all the elements negated.
static SmallVector<int64_t, 8> getNegatedCoeffs(ArrayRef<int64_t> coeffs) {
SmallVector<int64_t, 8> negatedCoeffs;
negatedCoeffs.reserve(coeffs.size());
for (int64_t coeff : coeffs)
negatedCoeffs.emplace_back(-coeff);
return negatedCoeffs;
}
/// Return the complement of the given inequality.
///
/// The complement of a_1 x_1 + ... + a_n x_ + c >= 0 is
/// a_1 x_1 + ... + a_n x_ + c < 0, i.e., -a_1 x_1 - ... - a_n x_ - c - 1 >= 0.
static SmallVector<int64_t, 8> getComplementIneq(ArrayRef<int64_t> ineq) {
SmallVector<int64_t, 8> coeffs;
coeffs.reserve(ineq.size());
for (int64_t coeff : ineq)
coeffs.emplace_back(-coeff);
--coeffs.back();
return coeffs;
}
/// Return the set difference b \ s and accumulate the result into `result`.
/// `simplex` must correspond to b.
///
/// In the following, V denotes union, ^ denotes intersection, \ denotes set
/// difference and ~ denotes complement.
/// Let b be the FlatAffineConstraints and s = (V_i s_i) be the set. We want
/// b \ (V_i s_i).
///
/// Let s_i = ^_j s_ij, where each s_ij is a single inequality. To compute
/// b \ s_i = b ^ ~s_i, we partition s_i based on the first violated inequality:
/// ~s_i = (~s_i1) V (s_i1 ^ ~s_i2) V (s_i1 ^ s_i2 ^ ~s_i3) V ...
/// And the required result is (b ^ ~s_i1) V (b ^ s_i1 ^ ~s_i2) V ...
/// We recurse by subtracting V_{j > i} S_j from each of these parts and
/// returning the union of the results. Each equality is handled as a
/// conjunction of two inequalities.
///
/// As a heuristic, we try adding all the constraints and check if simplex
/// says that the intersection is empty. Also, in the process we find out that
/// some constraints are redundant. These redundant constraints are ignored.
static void subtractRecursively(FlatAffineConstraints &b, Simplex &simplex,
const PresburgerSet &s, unsigned i,
PresburgerSet &result) {
if (i == s.getNumFACs()) {
result.unionFACInPlace(b);
return;
}
const FlatAffineConstraints &sI = s.getFlatAffineConstraints(i);
assert(sI.getNumLocalIds() == 0 &&
"Subtracting sets with divisions is not yet supported!");
unsigned initialSnapshot = simplex.getSnapshot();
unsigned offset = simplex.numConstraints();
simplex.intersectFlatAffineConstraints(sI);
if (simplex.isEmpty()) {
/// b ^ s_i is empty, so b \ s_i = b. We move directly to i + 1.
simplex.rollback(initialSnapshot);
subtractRecursively(b, simplex, s, i + 1, result);
return;
}
simplex.detectRedundant();
llvm::SmallBitVector isMarkedRedundant;
for (unsigned j = 0; j < 2 * sI.getNumEqualities() + sI.getNumInequalities();
j++)
isMarkedRedundant.push_back(simplex.isMarkedRedundant(offset + j));
simplex.rollback(initialSnapshot);
// Recurse with the part b ^ ~ineq. Note that b is modified throughout
// subtractRecursively. At the time this function is called, the current b is
// actually equal to b ^ s_i1 ^ s_i2 ^ ... ^ s_ij, and ineq is the next
// inequality, s_{i,j+1}. This function recurses into the next level i + 1
// with the part b ^ s_i1 ^ s_i2 ^ ... ^ s_ij ^ ~s_{i,j+1}.
auto recurseWithInequality = [&, i](ArrayRef<int64_t> ineq) {
size_t snapshot = simplex.getSnapshot();
b.addInequality(ineq);
simplex.addInequality(ineq);
subtractRecursively(b, simplex, s, i + 1, result);
b.removeInequality(b.getNumInequalities() - 1);
simplex.rollback(snapshot);
};
// For each inequality ineq, we first recurse with the part where ineq
// is not satisfied, and then add the ineq to b and simplex because
// ineq must be satisfied by all later parts.
auto processInequality = [&](ArrayRef<int64_t> ineq) {
recurseWithInequality(getComplementIneq(ineq));
b.addInequality(ineq);
simplex.addInequality(ineq);
};
// processInequality appends some additional constraints to b. We want to
// rollback b to its initial state before returning, which we will do by
// removing all constraints beyond the original number of inequalities
// and equalities, so we store these counts first.
unsigned originalNumIneqs = b.getNumInequalities();
unsigned originalNumEqs = b.getNumEqualities();
for (unsigned j = 0, e = sI.getNumInequalities(); j < e; j++) {
if (isMarkedRedundant[j])
continue;
processInequality(sI.getInequality(j));
}
offset = sI.getNumInequalities();
for (unsigned j = 0, e = sI.getNumEqualities(); j < e; ++j) {
const ArrayRef<int64_t> &coeffs = sI.getEquality(j);
// Same as the above loop for inequalities, done once each for the positive
// and negative inequalities that make up this equality.
if (!isMarkedRedundant[offset + 2 * j])
processInequality(coeffs);
if (!isMarkedRedundant[offset + 2 * j + 1])
processInequality(getNegatedCoeffs(coeffs));
}
// Rollback b and simplex to their initial states.
for (unsigned i = b.getNumInequalities(); i > originalNumIneqs; --i)
b.removeInequality(i - 1);
for (unsigned i = b.getNumEqualities(); i > originalNumEqs; --i)
b.removeEquality(i - 1);
simplex.rollback(initialSnapshot);
}
/// Return the set difference fac \ set.
///
/// The FAC here is modified in subtractRecursively, so it cannot be a const
/// reference even though it is restored to its original state before returning
/// from that function.
PresburgerSet PresburgerSet::getSetDifference(FlatAffineConstraints fac,
const PresburgerSet &set) {
assertDimensionsCompatible(fac, set);
assert(fac.getNumLocalIds() == 0 &&
"Subtracting sets with divisions is not yet supported!");
if (fac.isEmptyByGCDTest())
return PresburgerSet::getEmptySet(fac.getNumDimIds(),
fac.getNumSymbolIds());
PresburgerSet result(fac.getNumDimIds(), fac.getNumSymbolIds());
Simplex simplex(fac);
subtractRecursively(fac, simplex, set, 0, result);
return result;
}
/// Return the complement of this set.
PresburgerSet PresburgerSet::complement() const {
return getSetDifference(
FlatAffineConstraints::getUniverse(getNumDims(), getNumSyms()), *this);
}
/// Return the result of subtract the given set from this set, i.e.,
/// return `this \ set`.
PresburgerSet PresburgerSet::subtract(const PresburgerSet &set) const {
assertDimensionsCompatible(set, *this);
PresburgerSet result(nDim, nSym);
// We compute (V_i t_i) \ (V_i set_i) as V_i (t_i \ V_i set_i).
for (const FlatAffineConstraints &fac : flatAffineConstraints)
result.unionSetInPlace(getSetDifference(fac, set));
return result;
}
/// Two sets S and T are equal iff S contains T and T contains S.
/// By "S contains T", we mean that S is a superset of or equal to T.
///
/// S contains T iff T \ S is empty, since if T \ S contains a
/// point then this is a point that is contained in T but not S.
///
/// Therefore, S is equal to T iff S \ T and T \ S are both empty.
bool PresburgerSet::isEqual(const PresburgerSet &set) const {
assertDimensionsCompatible(set, *this);
return this->subtract(set).isIntegerEmpty() &&
set.subtract(*this).isIntegerEmpty();
}
/// Return true if all the sets in the union are known to be integer empty,
/// false otherwise.
bool PresburgerSet::isIntegerEmpty() const {
// The set is empty iff all of the disjuncts are empty.
for (const FlatAffineConstraints &fac : flatAffineConstraints) {
if (!fac.isIntegerEmpty())
return false;
}
return true;
}
bool PresburgerSet::findIntegerSample(SmallVectorImpl<int64_t> &sample) {
// A sample exists iff any of the disjuncts contains a sample.
for (const FlatAffineConstraints &fac : flatAffineConstraints) {
if (Optional<SmallVector<int64_t, 8>> opt = fac.findIntegerSample()) {
sample = std::move(*opt);
return true;
}
}
return false;
}
void PresburgerSet::print(raw_ostream &os) const {
os << getNumFACs() << " FlatAffineConstraints:\n";
for (const FlatAffineConstraints &fac : flatAffineConstraints) {
fac.print(os);
os << '\n';
}
}
void PresburgerSet::dump() const { print(llvm::errs()); }
| 12,586 | 4,100 |
/**
* @file
*/
#pragma once
#include "src/type/Type.hpp"
#include "src/type/EmptyType.hpp"
namespace birch {
/**
* Typed expression or statement.
*
* @ingroup common
*/
class Typed {
public:
/**
* Constructor.
*
* @param type Type.
*/
Typed(Type* type);
/**
* Type.
*/
Type* type;
};
}
| 321 | 128 |
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
#include "common.h"
#define MAX_BUF 512
int main(int argc, char *argv[]) {
if(argc != 2) {
printf("Usage: %s <file>\n", argv[0]);
exit(1);
}
std::ifstream fin(argv[1]);
if(!fin) {
println("Error opening file \"" << argv[1] << '"' << std::endl);
}
int temp = (EOF + 1);
fin.seekg(-1, fin.end);
int length = fin.tellg();
for(int i = length - 1; i >= EOF; i--) {
temp = fin.peek();
fin.seekg(i, fin.beg);
std::cout << ((char) temp);
}
println("");
}
| 624 | 255 |
/*! \file ramsesio.cxx
* \brief this file contains routines for ramses snapshot file io
*
* \todo need to check if amr file quantity ngrid_current is actually the number of cells in the file as
* an example fortran code I have been given seems to also use the ngridlevel array, which stores the number of cells
* at a given resolution level.
* \todo need to add in ability for multiple read threads and sends between read threads
*
*
* Edited by: Rodrigo Ca\~nas
* rodrigo.canas@icrar.org
*
* Last edited: 7 - Jun - 2017
*
*
*/
//-- RAMSES SPECIFIC IO
#include "stf.h"
#include "io.h"
#include "ramsesitems.h"
#include "endianutils.h"
int RAMSES_fortran_read(fstream &F, int &i){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.read((char*)&i,sizeof(int)); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
return byteoffset;
}
int RAMSES_fortran_read(fstream &F, RAMSESFLOAT &f){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.read((char*)&f,sizeof(RAMSESFLOAT)); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
return byteoffset;
}
int RAMSES_fortran_read(fstream &F, int *i){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.read((char*)i,dummy); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
return byteoffset;
}
int RAMSES_fortran_read(fstream &F, unsigned int *i){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int);
F.read((char*)i,dummy); byteoffset += dummy;
F.read((char*)&dummy, sizeof(dummy)); byteoffset += sizeof(int);
return byteoffset;
}
int RAMSES_fortran_read(fstream &F, long long *i){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.read((char*)i,dummy); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
return byteoffset;
}
int RAMSES_fortran_read(fstream &F, RAMSESFLOAT *f){
int dummy,byteoffset=0;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.read((char*)f,dummy); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
return byteoffset;
}
int RAMSES_fortran_skip(fstream &F, int nskips){
int dummy,byteoffset=0;
for (int i=0;i<nskips;i++) {
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
F.seekg(dummy,ios::cur); byteoffset+=dummy;
F.read((char*)&dummy, sizeof(dummy));byteoffset+=sizeof(int);
}
return byteoffset;
}
Int_t RAMSES_get_nbodies(char *fname, int ptype, Options &opt)
{
char buf[2000],buf1[2000],buf2[2000];
double * dummy_age, * dummy_mass;
double dmp_mass;
double OmegaM, OmegaB;
int totalghost = 0;
int totalstars = 0;
int totaldm = 0;
int alltotal = 0;
int ghoststars = 0;
string stringbuf;
int ninputoffset = 0;
sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname);
sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
else {
printf("Error. Can't find AMR data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2);
exit(9);
}
//if gas searched in some fashion then load amr/hydro data
if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) {
sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname);
sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
else {
printf("Error. Can't find Hydro data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2);
exit(9);
}
}
sprintf(buf1,"%s/part_%s.out00001",fname,opt.ramsessnapname);
sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
else {
printf("Error. Can't find Particle data \nneither as `%s'\nnor as `%s'\n\n", buf1, buf2);
exit(9);
}
fstream Framses;
RAMSES_Header ramses_header_info;
//buffers to load data
int intbuff[NRAMSESTYPE];
long long longbuff[NRAMSESTYPE];
int i,j,k,ireaderror=0;
Int_t nbodies=0;
//IntType inttype;
int dummy;
int nusetypes,usetypes[NRAMSESTYPE];
if (ptype==PSTALL) {nusetypes=4;usetypes[0]=RAMSESGASTYPE;usetypes[1]=RAMSESDMTYPE;usetypes[2]=RAMSESSTARTYPE;usetypes[3]=RAMSESBHTYPE;}
else if (ptype==PSTDARK) {nusetypes=1;usetypes[0]=RAMSESDMTYPE;}
else if (ptype==PSTGAS) {nusetypes=1;usetypes[0]=RAMSESGASTYPE;}
else if (ptype==PSTSTAR) {nusetypes=1;usetypes[0]=RAMSESSTARTYPE;}
else if (ptype==PSTBH) {nusetypes=1;usetypes[0]=RAMSESBHTYPE;}
for (j = 0; j < NRAMSESTYPE; j++) ramses_header_info.npartTotal[j] = 0;
//Open the specified file and the specified dataset in the file.
//first open amr data
sprintf(buf1,"%s/amr_%s.out00001",fname,opt.ramsessnapname);
sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Framses.open(buf, ios::binary|ios::in);
//read header info
//this is based on a ramsestotipsy fortran code that does not detail everything in the header block but at least its informative. The example has
/*
read(10)ncpu
read(10)ndim
read(10)nx,ny,nz
read(10)nlevelmax
read(10)ngridmax
read(10)nboundary
read(10)ngrid_current
read(10)boxlen
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)
read(10)msph
close(10)
*/
// Number of files
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.num_files, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
opt.num_files=ramses_header_info.num_files;
// Number of dimensions
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.ndim, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
//
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.nx, sizeof(int));
Framses.read((char*)&ramses_header_info.ny, sizeof(int));
Framses.read((char*)&ramses_header_info.nz, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
// Maximum refinement level
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.nlevelmax, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
//
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.ngridmax, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
//
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.nboundary, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
//this would be number of active grids but ignore for now
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Boxsize
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.BoxSize, sizeof(RAMSESFLOAT));
Framses.read((char*)&dummy, sizeof(dummy));
//now skip 10 blocks
for (i=0;i<10;i++) {
Framses.read((char*)&dummy, sizeof(dummy));
//skip block size given by dummy
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
}
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.mass[RAMSESGASTYPE], sizeof(RAMSESFLOAT));
Framses.read((char*)&dummy, sizeof(dummy));
Framses.close();
//reopen to get number of amr cells might need to alter to read grid information and what cells have no so-called son cells
if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) {
for (i=0;i<ramses_header_info.num_files;i++) {
sprintf(buf1,"%s/amr_%s.out%05d",fname,opt.ramsessnapname,i+1);
sprintf(buf2,"%s/amr_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Framses.open(buf, ios::binary|ios::in);
for (j=0;j<6;j++) {
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
}
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.npart[RAMSESGASTYPE], sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
ramses_header_info.npartTotal[RAMSESGASTYPE]+=ramses_header_info.npart[RAMSESGASTYPE];
}
//now hydro header data
sprintf(buf1,"%s/hydro_%s.out00001",fname,opt.ramsessnapname);
sprintf(buf2,"%s/hydro_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Framses.open(buf, ios::binary|ios::in);
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.nvarh, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
for (i=0;i<3;i++) {
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
}
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.gamma_index, sizeof(RAMSESFLOAT));
Framses.read((char*)&dummy, sizeof(dummy));
Framses.close();
}
//
// Compute Mass of DM particles in RAMSES code units
//
fstream Finfo;
sprintf(buf1,"%s/info_%s.txt", fname,opt.ramsessnapname);
Finfo.open(buf1, ios::in);
Finfo>>stringbuf>>stringbuf>>opt.num_files;
getline(Finfo,stringbuf);//ndim
getline(Finfo,stringbuf);//lmin
getline(Finfo,stringbuf);//lmax
getline(Finfo,stringbuf);//ngridmax
getline(Finfo,stringbuf);//nstep
getline(Finfo,stringbuf);//blank
getline(Finfo,stringbuf);//box
getline(Finfo,stringbuf);//time
getline(Finfo,stringbuf);//a
getline(Finfo,stringbuf);//hubble
Finfo>>stringbuf>>stringbuf>>OmegaM;
getline(Finfo,stringbuf);
getline(Finfo,stringbuf);
getline(Finfo,stringbuf);
Finfo>>stringbuf>>stringbuf>>OmegaB;
Finfo.close();
dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * (OmegaM - OmegaB) / OmegaM;
//now particle info
for (i=0;i<ramses_header_info.num_files;i++)
{
sprintf(buf1,"%s/part_%s.out%05d",fname,opt.ramsessnapname,i+1);
sprintf(buf2,"%s/part_%s.out",fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Framses.open(buf, ios::binary|ios::in);
ramses_header_info.npart[RAMSESDMTYPE] = 0;
ramses_header_info.npart[RAMSESSTARTYPE] = 0;
ramses_header_info.npart[RAMSESSINKTYPE] = 0;
//number of cpus
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
//number of dimensions
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Total number of LOCAL particles
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.npartlocal, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
// Random seeds
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Total number of Stars over all processors
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.nstarTotal, sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
// Total mass of stars
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Total lost mass of stars
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Number of sink particles over the whole simulation (all are included in
// all processors)
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&ramses_header_info.npartTotal[RAMSESSINKTYPE], sizeof(int));
Framses.read((char*)&dummy, sizeof(dummy));
//to determine how many particles of each type, need to look at the mass
// Skip pos, vel, mass
for (j = 0; j < 6; j++)
{
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
}
//allocate memory to store masses and ages
dummy_mass = new double [ramses_header_info.npartlocal];
dummy_age = new double [ramses_header_info.npartlocal];
// Read Mass
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&dummy_mass[0], dummy);
Framses.read((char*)&dummy, sizeof(dummy));
// Skip Id
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Skip level
Framses.read((char*)&dummy, sizeof(dummy));
Framses.seekg(dummy,ios::cur);
Framses.read((char*)&dummy, sizeof(dummy));
// Read Birth epoch
//necessary to separate ghost star particles with negative ages from real one
Framses.read((char*)&dummy, sizeof(dummy));
Framses.read((char*)&dummy_age[0], dummy);
Framses.read((char*)&dummy, sizeof(dummy));
ghoststars = 0;
for (j = 0; j < ramses_header_info.npartlocal; j++)
{
if (fabs((dummy_mass[j]-dmp_mass)/dmp_mass) < 1e-5)
ramses_header_info.npart[RAMSESDMTYPE]++;
else
if (dummy_age[j] != 0.0)
ramses_header_info.npart[RAMSESSTARTYPE]++;
else
ghoststars++;
}
delete [] dummy_age;
delete [] dummy_mass;
Framses.close();
totalghost += ghoststars;
totalstars += ramses_header_info.npart[RAMSESSTARTYPE];
totaldm += ramses_header_info.npart[RAMSESDMTYPE];
alltotal += ramses_header_info.npartlocal;
//now with information loaded, set totals
ramses_header_info.npartTotal[RAMSESDMTYPE]+=ramses_header_info.npart[RAMSESDMTYPE];
ramses_header_info.npartTotal[RAMSESSTARTYPE]+=ramses_header_info.npart[RAMSESSTARTYPE];
ramses_header_info.npartTotal[RAMSESSINKTYPE]+=ramses_header_info.npart[RAMSESSINKTYPE];
}
for(j=0, nbodies=0; j<nusetypes; j++) {
k=usetypes[j];
nbodies+=ramses_header_info.npartTotal[k];
//nbodies+=((long long)(ramses_header_info.npartTotalHW[k]) << 32);
}
for (j=0;j<NPARTTYPES;j++) opt.numpart[j]=0;
if (ptype==PSTALL || ptype==PSTDARK) opt.numpart[DARKTYPE]=ramses_header_info.npartTotal[RAMSESDMTYPE];
if (ptype==PSTALL || ptype==PSTGAS) opt.numpart[GASTYPE]=ramses_header_info.npartTotal[RAMSESGASTYPE];
if (ptype==PSTALL || ptype==PSTSTAR) opt.numpart[STARTYPE]=ramses_header_info.npartTotal[RAMSESSTARTYPE];
if (ptype==PSTALL || ptype==PSTBH) opt.numpart[BHTYPE]=ramses_header_info.npartTotal[RAMSESSINKTYPE];
return nbodies;
}
/// Reads a ramses file. If cosmological simulation uses cosmology (generally
/// assuming LCDM or small deviations from this) to estimate the mean interparticle
/// spacing and scales physical linking length passed by this distance. Also reads
/// header and overrides passed cosmological parameters with ones stored in header.
void ReadRamses(Options &opt, vector<Particle> &Part, const Int_t nbodies, Particle *&Pbaryons, Int_t nbaryons)
{
char buf[2000],buf1[2000],buf2[2000];
string stringbuf,orderingstring;
fstream Finfo;
fstream *Famr;
fstream *Fhydro;
fstream *Fpart, *Fpartvel,*Fpartid,*Fpartmass, *Fpartlevel, *Fpartage, *Fpartmet;
RAMSES_Header *header;
int intbuff[NRAMSESTYPE];
long long longbuff[NRAMSESTYPE];
int i,j,k,n,idim,ivar,igrid,ireaderror=0;
Int_t count2,bcount2;
//IntType inttype;
int dummy,byteoffset;
Double_t MP_DM=MAXVALUE,LN,N_DM,MP_B=0;
double z,aadjust,Hubble,Hubbleflow;
Double_t mscale,lscale,lvscale,rhoscale;
Double_t mtemp,utemp,rhotemp,Ztemp,Ttemp;
Coordinate xpos,vpos;
RAMSESFLOAT xtemp[3],vtemp[3];
RAMSESIDTYPE idval;
int typeval;
RAMSESFLOAT ageval,metval;
int *ngridlevel,*ngridbound,*ngridfile;
int lmin=1000000,lmax=0;
double dmp_mass;
int ninputoffset = 0;
int ifirstfile=0,ibuf=0;
std::vector<int> ireadfile;
Int_t ibufindex;
int *ireadtask,*readtaskID;
#ifndef USEMPI
int ThisTask=0,NProcs=1;
ireadfile = std::vector<int>(opt.num_files, 1);
#else
MPI_Bcast (&(opt.num_files), sizeof(opt.num_files), MPI_BYTE, 0, MPI_COMM_WORLD);
MPI_Barrier (MPI_COMM_WORLD);
#endif
///\todo because of the stupid fortran format, easier if chunksize is BIG so that
///number of particles local to a file are smaller
Int_t chunksize=RAMSESCHUNKSIZE,nchunk;
RAMSESFLOAT *xtempchunk, *vtempchunk, *mtempchunk, *sphtempchunk, *agetempchunk, *mettempchunk, *hydrotempchunk;
RAMSESIDTYPE *idvalchunk, *levelchunk;
int *icellchunk;
Famr = new fstream[opt.num_files];
Fhydro = new fstream[opt.num_files];
Fpart = new fstream[opt.num_files];
Fpartvel = new fstream[opt.num_files];
Fpartmass = new fstream[opt.num_files];
Fpartid = new fstream[opt.num_files];
Fpartlevel = new fstream[opt.num_files];
Fpartage = new fstream[opt.num_files];
Fpartmet = new fstream[opt.num_files];
header = new RAMSES_Header[opt.num_files];
Particle *Pbuf;
#ifdef USEMPI
MPI_Status status;
MPI_Comm mpi_comm_read;
vector<Particle> *Preadbuf;
//for parallel io
Int_t BufSize=opt.mpiparticlebufsize;
Int_t Nlocalbuf,*Nbuf, *Nreadbuf,*nreadoffset;
Int_t *Nlocalthreadbuf,Nlocaltotalbuf;
int *irecv, sendTask,recvTask,irecvflag, *mpi_irecvflag;
MPI_Request *mpi_request;
Int_t inreadsend,totreadsend;
Int_t *mpi_nsend_baryon;
Int_t *mpi_nsend_readthread;
Int_t *mpi_nsend_readthread_baryon;
if (opt.iBaryonSearch) mpi_nsend_baryon=new Int_t[NProcs*NProcs];
if (opt.nsnapread>1) {
mpi_nsend_readthread=new Int_t[opt.nsnapread*opt.nsnapread];
if (opt.iBaryonSearch) mpi_nsend_readthread_baryon=new Int_t[opt.nsnapread*opt.nsnapread];
}
Nbuf=new Int_t[NProcs];
nreadoffset=new Int_t[opt.nsnapread];
ireadtask=new int[NProcs];
readtaskID=new int[opt.nsnapread];
MPIDistributeReadTasks(opt,ireadtask,readtaskID);
MPI_Comm_split(MPI_COMM_WORLD, (ireadtask[ThisTask]>=0), ThisTask, &mpi_comm_read);
if (ireadtask[ThisTask]>=0)
{
//to temporarily store data
Pbuf=new Particle[BufSize*NProcs];
Nreadbuf=new Int_t[opt.nsnapread];
for (int j=0;j<NProcs;j++) Nbuf[j]=0;
for (int j=0;j<opt.nsnapread;j++) Nreadbuf[j]=0;
if (opt.nsnapread>1){
Preadbuf=new vector<Particle>[opt.nsnapread];
for (int j=0;j<opt.nsnapread;j++) Preadbuf[j].reserve(BufSize);
}
//to determine which files the thread should read
ireadfile = std::vector<int>(opt.num_files);
ifirstfile=MPISetFilesRead(opt,ireadfile,ireadtask);
inreadsend=0;
for (int j=0;j<opt.num_files;j++) inreadsend+=ireadfile[j];
MPI_Allreduce(&inreadsend,&totreadsend,1,MPI_Int_t,MPI_MIN,mpi_comm_read);
}
else {
Nlocalthreadbuf=new Int_t[opt.nsnapread];
irecv=new int[opt.nsnapread];
mpi_irecvflag=new int[opt.nsnapread];
for (i=0;i<opt.nsnapread;i++) irecv[i]=1;
mpi_request=new MPI_Request[opt.nsnapread];
}
Nlocal=0;
if (opt.iBaryonSearch) Nlocalbaryon[0]=0;
if (ireadtask[ThisTask]>=0) {
#endif
//first read cosmological information
sprintf(buf1,"%s/info_%s.txt",opt.fname,opt.ramsessnapname);
Finfo.open(buf1, ios::in);
getline(Finfo,stringbuf);//nfiles
getline(Finfo,stringbuf);//ndim
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].levelmin;
getline(Finfo,stringbuf);//lmax
getline(Finfo,stringbuf);//ngridmax
getline(Finfo,stringbuf);//nstep
getline(Finfo,stringbuf);//blank
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].BoxSize;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].time;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].aexp;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].HubbleParam;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegam;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].OmegaLambda;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegak;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].Omegab;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_l;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_d;
Finfo>>stringbuf>>stringbuf>>header[ifirstfile].scale_t;
//convert boxsize to comoving kpc/h
header[ifirstfile].BoxSize*=header[ifirstfile].scale_l/3.086e21/header[ifirstfile].aexp*header[ifirstfile].HubbleParam/100.0;
getline(Finfo,stringbuf);
Finfo>>stringbuf>>orderingstring;
getline(Finfo,stringbuf);
Finfo.close();
opt.p = header[ifirstfile].BoxSize;
opt.a = header[ifirstfile].aexp;
opt.Omega_m = header[ifirstfile].Omegam;
opt.Omega_Lambda = header[ifirstfile].OmegaLambda;
opt.Omega_b = header[ifirstfile].Omegab;
opt.h = header[ifirstfile].HubbleParam/100.0;
opt.Omega_cdm = opt.Omega_m-opt.Omega_b;
//set hubble unit to km/s/kpc
opt.H = 0.1;
//set Gravity to value for kpc (km/s)^2 / solar mass
opt.G = 4.30211349e-6;
//and for now fix the units
opt.lengthtokpc=opt.velocitytokms=opt.masstosolarmass=1.0;
//Hubble flow
if (opt.comove) aadjust=1.0;
else aadjust=opt.a;
CalcOmegak(opt);
Hubble=GetHubble(opt, aadjust);
CalcCriticalDensity(opt, aadjust);
CalcBackgroundDensity(opt, aadjust);
CalcVirBN98(opt,aadjust);
//if opt.virlevel<0, then use virial overdensity based on Bryan and Norman 1997 virialization level is given by
if (opt.virlevel<0) opt.virlevel=opt.virBN98;
PrintCosmology(opt);
//adjust length scale so that convert from 0 to 1 (box units) to kpc comoving
//to scale mpi domains correctly need to store in opt.lengthinputconversion the box size in comoving little h value
//opt.lengthinputconversion= opt.p*opt.h/opt.a;
opt.lengthinputconversion = header[ifirstfile].BoxSize;
//adjust velocity scale to that ramses is converted to km/s from which you can convert again;
opt.velocityinputconversion = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5;
//convert mass from code units to Solar Masses
mscale = header[ifirstfile].scale_d * (header[ifirstfile].scale_l * header[ifirstfile].scale_l * header[ifirstfile].scale_l) / 1.988e+33;
//convert length from code units to kpc (this lscale includes the physical box size)
lscale = header[ifirstfile].scale_l/3.086e21;
//convert velocity from code units to km/s
lvscale = header[ifirstfile].scale_l/header[ifirstfile].scale_t*1e-5;
//convert density to Msun/kpc^3
rhoscale = mscale/(lscale*lscale*lscale);
//ignore hubble flow
Hubbleflow=0.;
//for (int j=0;j<NPARTTYPES;j++) nbodies+=opt.numpart[j];
cout<<"Particle system contains "<<nbodies<<" particles (of interest) at is at time "<<opt.a<<" in a box of size "<<opt.p<<endl;
//number of DM particles
//NOTE: this assumes a uniform box resolution. However this is not used in the rest of this function
N_DM = opt.Neff*opt.Neff*opt.Neff;
//interparticle spacing (assuming a uniform resolution box)
LN = (lscale/(double)opt.Neff);
opt.ellxscale = LN;
//grab from the first particle file the dimensions of the arrays and also the number of cpus (should be number of files)
sprintf(buf1,"%s/part_%s.out00001",opt.fname,opt.ramsessnapname);
Fpart[ifirstfile].open(buf1, ios::binary|ios::in);
RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].nfiles);
RAMSES_fortran_read(Fpart[ifirstfile],header[ifirstfile].ndim);
//adjust the number of files
opt.num_files=header[ifirstfile].nfiles;
Fpart[ifirstfile].close();
#ifdef USEMPI
//now read tasks prepped and can read files to send information
}
#endif
#ifdef USEMPI
if (ireadtask[ThisTask]>=0)
{
#endif
dmp_mass = 1.0 / (opt.Neff*opt.Neff*opt.Neff) * opt.Omega_cdm / opt.Omega_m;
#ifdef USEMPI
}
MPI_Bcast (&dmp_mass, 1, MPI_DOUBLE, 0, MPI_COMM_WORLD);
#endif
//if not only gas being searched open particle data
count2=bcount2=0;
if (opt.partsearchtype!=PSTGAS) {
#ifdef USEMPI
if (ireadtask[ThisTask]>=0) {
inreadsend=0;
#endif
//read particle files consists of positions,velocities, mass, id, and level (along with ages and met if some flags set)
for (i=0;i<opt.num_files;i++) {
if (ireadfile[i]) {
sprintf(buf1,"%s/part_%s.out%05d",opt.fname,opt.ramsessnapname,i+1);
sprintf(buf2,"%s/part_%s.out",opt.fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Fpart[i].open(buf, ios::binary|ios::in);
Fpartvel[i].open(buf, ios::binary|ios::in);
Fpartmass[i].open(buf, ios::binary|ios::in);
Fpartid[i].open(buf, ios::binary|ios::in);
Fpartlevel[i].open(buf, ios::binary|ios::in);
Fpartage[i].open(buf, ios::binary|ios::in);
Fpartmet[i].open(buf, ios::binary|ios::in);
//skip header information in each file save for number in the file
//@{
byteoffset=0;
// ncpus
byteoffset+=RAMSES_fortran_skip(Fpart[i]);
// ndims
byteoffset+=RAMSES_fortran_skip(Fpart[i]);
// store number of particles locally in file
byteoffset+=RAMSES_fortran_read(Fpart[i],header[i].npartlocal);
// skip local seeds, nstartot, mstartot, mstarlost, nsink
byteoffset+=RAMSES_fortran_skip(Fpart[i],5);
//byteoffset now stores size of header offset for particles
Fpartvel[i].seekg(byteoffset,ios::cur);
Fpartmass[i].seekg(byteoffset,ios::cur);
Fpartid[i].seekg(byteoffset,ios::cur);
Fpartlevel[i].seekg(byteoffset,ios::cur);
Fpartage[i].seekg(byteoffset,ios::cur);
Fpartmet[i].seekg(byteoffset,ios::cur);
//skip positions
for(idim=0;idim<header[ifirstfile].ndim;idim++)
{
RAMSES_fortran_skip(Fpartvel[i]);
RAMSES_fortran_skip(Fpartmass[i]);
RAMSES_fortran_skip(Fpartid[i]);
RAMSES_fortran_skip(Fpartlevel[i]);
RAMSES_fortran_skip(Fpartage[i]);
RAMSES_fortran_skip(Fpartmet[i]);
}
//skip velocities
for(idim=0;idim<header[ifirstfile].ndim;idim++)
{
RAMSES_fortran_skip(Fpartmass[i]);
RAMSES_fortran_skip(Fpartid[i]);
RAMSES_fortran_skip(Fpartlevel[i]);
RAMSES_fortran_skip(Fpartage[i]);
RAMSES_fortran_skip(Fpartmet[i]);
}
//skip mass
RAMSES_fortran_skip(Fpartid[i]);
RAMSES_fortran_skip(Fpartlevel[i]);
RAMSES_fortran_skip(Fpartage[i]);
RAMSES_fortran_skip(Fpartmet[i]);
//skip ids;
RAMSES_fortran_skip(Fpartlevel[i]);
RAMSES_fortran_skip(Fpartage[i]);
RAMSES_fortran_skip(Fpartmet[i]);
//skip levels
RAMSES_fortran_skip(Fpartage[i]);
RAMSES_fortran_skip(Fpartmet[i]);
//skip ages
RAMSES_fortran_skip(Fpartmet[i]);
//@}
//data loaded into memory in chunks
chunksize = nchunk = header[i].npartlocal;
ninputoffset = 0;
xtempchunk = new RAMSESFLOAT [3*chunksize];
vtempchunk = new RAMSESFLOAT [3*chunksize];
mtempchunk = new RAMSESFLOAT [chunksize];
idvalchunk = new RAMSESIDTYPE [chunksize];
levelchunk = new RAMSESIDTYPE [chunksize];
agetempchunk = new RAMSESFLOAT [chunksize];
mettempchunk = new RAMSESFLOAT [chunksize];
for(idim=0;idim<header[ifirstfile].ndim;idim++)
{
RAMSES_fortran_read(Fpart[i],&xtempchunk[idim*nchunk]);
RAMSES_fortran_read(Fpartvel[i],&vtempchunk[idim*nchunk]);
}
RAMSES_fortran_read(Fpartmass[i], mtempchunk);
RAMSES_fortran_read(Fpartid[i], idvalchunk);
RAMSES_fortran_read(Fpartlevel[i], levelchunk);
RAMSES_fortran_read(Fpartage[i], agetempchunk);
RAMSES_fortran_read(Fpartmet[i], mettempchunk);
RAMSES_fortran_read(Fpartid[i],idvalchunk);
for (int nn=0;nn<nchunk;nn++)
{
if (fabs((mtempchunk[nn]-dmp_mass)/dmp_mass) > 1e-5 && (agetempchunk[nn] == 0.0))
{
// GHOST PARTIRCLE!!!
}
else
{
xtemp[0] = xtempchunk[nn];
xtemp[1] = xtempchunk[nn+nchunk];
xtemp[2] = xtempchunk[nn+2*nchunk];
vtemp[0] = vtempchunk[nn];
vtemp[1] = vtempchunk[nn+nchunk];
vtemp[2] = vtempchunk[nn+2*nchunk];
idval = idvalchunk[nn];
///Need to check this for correct 'endianness'
// for (int kk=0;kk<3;kk++) {xtemp[kk]=LittleRAMSESFLOAT(xtemp[kk]);vtemp[kk]=LittleRAMSESFLOAT(vtemp[kk]);}
#ifndef NOMASS
mtemp=mtempchunk[nn];
#else
mtemp=1.0;
#endif
ageval = agetempchunk[nn];
if (fabs((mtemp-dmp_mass)/dmp_mass) < 1e-5) typeval = DARKTYPE;
else typeval = STARTYPE;
/*
if (ageval==0 && idval>0) typeval=DARKTYPE;
else if (idval>0) typeval=STARTYPE;
else typeval=BHTYPE;
*/
#ifdef USEMPI
//determine processor this particle belongs on based on its spatial position
ibuf=MPIGetParticlesProcessor(opt, xtemp[0],xtemp[1],xtemp[2]);
ibufindex=ibuf*BufSize+Nbuf[ibuf];
#endif
//reset hydro quantities of buffer
#ifdef USEMPI
#ifdef GASON
Pbuf[ibufindex].SetU(0);
#ifdef STARON
Pbuf[ibufindex].SetSFR(0);
Pbuf[ibufindex].SetZmet(0);
#endif
#endif
#ifdef STARON
Pbuf[ibufindex].SetZmet(0);
Pbuf[ibufindex].SetTage(0);
#endif
#ifdef BHON
#endif
#endif
if (opt.partsearchtype==PSTALL) {
#ifdef USEMPI
Pbuf[ibufindex]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,typeval);
Pbuf[ibufindex].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[ibufindex].SetInputFileID(i);
Part[ibufindex].SetInputIndexInFile(nn+ninputoffset);
}
#endif
Nbuf[ibuf]++;
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf);
#else
Part[count2]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,typeval);
Part[count2].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[count2].SetInputFileID(i);
Part[count2].SetInputIndexInFile(nn+ninputoffset);
}
#endif
#endif
count2++;
}
else if (opt.partsearchtype==PSTDARK) {
if (!(typeval==STARTYPE||typeval==BHTYPE)) {
#ifdef USEMPI
Pbuf[ibufindex]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,DARKTYPE);
Pbuf[ibufindex].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbuf[ibufindex].SetInputFileID(i);
Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset);
}
#endif
//ensure that store number of particles to be sent to other reading threads
Nbuf[ibuf]++;
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf);
#else
Part[count2]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,typeval);
Part[count2].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[count2].SetInputFileID(i);
Part[count2].SetInputIndexInFile(nn+ninputoffset);
}
#endif
#endif
count2++;
}
else if (opt.iBaryonSearch) {
#ifdef USEMPI
Pbuf[ibufindex]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2);
Pbuf[ibufindex].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbuf[ibufindex].SetInputFileID(i);
Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset);
}
#endif
if (typeval==STARTYPE) Pbuf[ibufindex].SetType(STARTYPE);
else if (typeval==BHTYPE) Pbuf[ibufindex].SetType(BHTYPE);
//ensure that store number of particles to be sent to the reading threads
Nbuf[ibuf]++;
if (ibuf==ThisTask) {
if (k==RAMSESSTARTYPE) Nlocalbaryon[2]++;
else if (k==RAMSESSINKTYPE) Nlocalbaryon[3]++;
}
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf);
#else
Pbaryons[bcount2]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,typeval);
Pbaryons[bcount2].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[bcount2].SetInputFileID(i);
Part[bcount2].SetInputIndexInFile(nn+ninputoffset);
}
#endif
#endif
bcount2++;
}
}
else if (opt.partsearchtype==PSTSTAR) {
if (typeval==STARTYPE) {
#ifdef USEMPI
//if using MPI, determine proccessor and place in ibuf, store particle in particle buffer and if buffer full, broadcast data
//unless ibuf is 0, then just store locally
Pbuf[ibufindex]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,STARTYPE);
//ensure that store number of particles to be sent to the reading threads
Pbuf[ibufindex].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbuf[ibufindex].SetInputFileID(i);
Pbuf[ibufindex].SetInputIndexInFile(nn+ninputoffset);
}
#endif
Nbuf[ibuf]++;
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf);
#else
Part[count2]=Particle(mtemp*mscale,
xtemp[0]*lscale,xtemp[1]*lscale,xtemp[2]*lscale,
vtemp[0]*opt.velocityinputconversion+Hubbleflow*xtemp[0],
vtemp[1]*opt.velocityinputconversion+Hubbleflow*xtemp[1],
vtemp[2]*opt.velocityinputconversion+Hubbleflow*xtemp[2],
count2,typeval);
Part[count2].SetPID(idval);
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[count2].SetInputFileID(i);
Part[count2].SetInputIndexInFile(nn+ninputoffset);
}
#endif
#endif
count2++;
}
}
}//end of ghost particle check
}//end of loop over chunk
delete[] xtempchunk;
delete[] vtempchunk;
delete[] mtempchunk;
delete[] idvalchunk;
delete[] agetempchunk;
delete[] levelchunk;
delete[] mettempchunk;
Fpart[i].close();
Fpartvel[i].close();
Fpartmass[i].close();
Fpartid[i].close();
Fpartlevel[i].close();
Fpartage[i].close();
Fpartmet[i].close();
#ifdef USEMPI
//send information between read threads
if (opt.nsnapread>1&&inreadsend<totreadsend){
MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read);
MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon);
inreadsend++;
for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0;
}
#endif
}//end of whether reading a file
}//end of loop over file
#ifdef USEMPI
//once finished reading the file if there are any particles left in the buffer broadcast them
for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0)
{
MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD);
if (Nbuf[ibuf]>0) {
MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD);
Nbuf[ibuf]=0;
//last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast
MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD);
}
}
if (opt.nsnapread>1){
MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read);
MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon);
}
}//end of ireadtask[ibuf]>0
#endif
#ifdef USEMPI
else {
MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons);
}
#endif
}
//if gas searched in some fashion then load amr/hydro data
if (opt.partsearchtype==PSTGAS||opt.partsearchtype==PSTALL||(opt.partsearchtype==PSTDARK&&opt.iBaryonSearch)) {
#ifdef USEMPI
if (ireadtask[ThisTask]>=0) {
inreadsend=0;
#endif
for (i=0;i<opt.num_files;i++) if (ireadfile[i]) {
sprintf(buf1,"%s/amr_%s.out%05d",opt.fname,opt.ramsessnapname,i+1);
sprintf(buf2,"%s/amr_%s.out",opt.fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Famr[i].open(buf, ios::binary|ios::in);
sprintf(buf1,"%s/hydro_%s.out%05d",opt.fname,opt.ramsessnapname,i+1);
sprintf(buf2,"%s/hydro_%s.out",opt.fname,opt.ramsessnapname);
if (FileExists(buf1)) sprintf(buf,"%s",buf1);
else if (FileExists(buf2)) sprintf(buf,"%s",buf2);
Fhydro[i].open(buf, ios::binary|ios::in);
//read some of the amr header till get to number of cells in current file
//@{
byteoffset=0;
byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ndim);
header[i].twotondim=pow(2,header[i].ndim);
Famr[i].read((char*)&dummy, sizeof(dummy));
Famr[i].read((char*)&header[i].nx, sizeof(int));
Famr[i].read((char*)&header[i].ny, sizeof(int));
Famr[i].read((char*)&header[i].nz, sizeof(int));
Famr[i].read((char*)&dummy, sizeof(dummy));
byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nlevelmax);
byteoffset+=RAMSES_fortran_read(Famr[i],header[i].ngridmax);
byteoffset+=RAMSES_fortran_read(Famr[i],header[i].nboundary);
byteoffset+=RAMSES_fortran_read(Famr[i],header[i].npart[RAMSESGASTYPE]);
//then skip the rest
for (j=0;j<14;j++) RAMSES_fortran_skip(Famr[i]);
if (lmin>header[i].nlevelmax) lmin=header[i].nlevelmax;
if (lmax<header[i].nlevelmax) lmax=header[i].nlevelmax;
//@}
//read header info from hydro files
//@{
RAMSES_fortran_skip(Fhydro[i]);
RAMSES_fortran_read(Fhydro[i],header[i].nvarh);
RAMSES_fortran_skip(Fhydro[i]);
RAMSES_fortran_skip(Fhydro[i]);
RAMSES_fortran_skip(Fhydro[i]);
RAMSES_fortran_read(Fhydro[i],header[i].gamma_index);
//@}
}
for (i=0;i<opt.num_files;i++) if (ireadfile[i]) {
//then apparently read ngridlevels, which appears to be an array storing the number of grids at a given level
ngridlevel=new int[header[i].nlevelmax];
ngridfile=new int[(1+header[i].nboundary)*header[i].nlevelmax];
RAMSES_fortran_read(Famr[i],ngridlevel);
for (j=0;j<header[i].nlevelmax;j++) ngridfile[j]=ngridlevel[j];
//skip some more
RAMSES_fortran_skip(Famr[i]);
//if nboundary>0 then need two skip twice then read ngridbound
if(header[i].nboundary>0) {
ngridbound=new int[header[i].nboundary*header[i].nlevelmax];
RAMSES_fortran_skip(Famr[i]);
RAMSES_fortran_skip(Famr[i]);
//ngridbound is an array of some sort but I don't see what it is used for
RAMSES_fortran_read(Famr[i],ngridbound);
for (j=0;j<header[i].nlevelmax;j++) ngridfile[header[i].nlevelmax+j]=ngridbound[j];
}
//skip some more
RAMSES_fortran_skip(Famr[i],2);
//if odering list in info is bisection need to skip more
if (orderingstring==string("bisection")) RAMSES_fortran_skip(Famr[i],5);
else RAMSES_fortran_skip(Famr[i],4);
ninputoffset=0;
for (k=0;k<header[i].nboundary+1;k++) {
for (j=0;j<header[i].nlevelmax;j++) {
//first read amr for positions
chunksize=nchunk=ngridfile[k*header[i].nlevelmax+j];
if (chunksize>0) {
xtempchunk=new RAMSESFLOAT[3*chunksize];
//store son value in icell
icellchunk=new int[header[i].twotondim*chunksize];
//skip grid index, next index and prev index.
RAMSES_fortran_skip(Famr[i],3);
//now read grid centre
for (idim=0;idim<header[i].ndim;idim++) {
RAMSES_fortran_read(Famr[i],&xtempchunk[idim*chunksize]);
}
//skip father index, then neighbours index
RAMSES_fortran_skip(Famr[i],1+2*header[i].ndim);
//read son index to determine if a cell in a specific grid is at the highest resolution and needs to be represented by a particle
for (idim=0;idim<header[i].twotondim;idim++) {
RAMSES_fortran_read(Famr[i],&icellchunk[idim*chunksize]);
}
//skip cpu map and refinement map (2^ndim*2)
RAMSES_fortran_skip(Famr[i],2*header[i].twotondim);
}
RAMSES_fortran_skip(Fhydro[i]);
//then read hydro for other variables (first is density, then velocity, then pressure, then metallicity )
if (chunksize>0) {
hydrotempchunk=new RAMSESFLOAT[chunksize*header[i].twotondim*header[i].nvarh];
//first read velocities (for 2 cells per number of dimensions (ie: cell corners?))
for (idim=0;idim<header[i].twotondim;idim++) {
for (ivar=0;ivar<header[i].nvarh;ivar++) {
RAMSES_fortran_read(Fhydro[i],&hydrotempchunk[idim*chunksize*header[i].nvarh+ivar*chunksize]);
for (igrid=0;igrid<chunksize;igrid++) {
//once we have looped over all the hydro data then can start actually storing it into the particle structures
if (ivar==header[i].nvarh-1) {
//if cell has no internal cells or at maximum level produce a particle
if (icellchunk[idim*chunksize+igrid]==0 || j==header[i].nlevelmax-1) {
//first suggestion is to add some jitter to the particle positions
double dx = pow(0.5, j);
int ix, iy, iz;
//below assumes three dimensions with 8 corners (? maybe cells) per grid
iz = idim/4;
iy = (idim - (4*iz))/2;
ix = idim - (2*iy) - (4*iz);
// Calculate absolute coordinates + jitter, and generate particle
xpos[0] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid] + (double(ix)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ;
xpos[1] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+1*chunksize] + (double(iy)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ;
xpos[2] = ((((float)rand()/(float)RAND_MAX) * header[i].BoxSize * dx) +(header[i].BoxSize * (xtempchunk[igrid+2*chunksize] + (double(iz)-0.5) * dx )) - (header[i].BoxSize*dx/2.0)) ;
#ifdef USEMPI
//determine processor this particle belongs on based on its spatial position
ibuf=MPIGetParticlesProcessor(opt, xpos[0],xpos[1],xpos[2]);
ibufindex=ibuf*BufSize+Nbuf[ibuf];
#endif
vpos[0]=hydrotempchunk[idim*chunksize*header[i].nvarh+1*chunksize+igrid];
vpos[1]=hydrotempchunk[idim*chunksize*header[i].nvarh+2*chunksize+igrid];
vpos[2]=hydrotempchunk[idim*chunksize*header[i].nvarh+3*chunksize+igrid];
mtemp=dx*dx*dx*hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid];
//the self energy P/rho is given by
utemp=hydrotempchunk[idim*chunksize*header[i].nvarh+4*chunksize+igrid]/hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]/(header[i].gamma_index-1.0);
rhotemp=hydrotempchunk[idim*chunksize*header[i].nvarh+0*chunksize+igrid]*rhoscale;
Ztemp=hydrotempchunk[idim*chunksize*header[i].nvarh+5*chunksize+igrid];
if (opt.partsearchtype==PSTALL) {
#ifdef USEMPI
Pbuf[ibufindex]=Particle(mtemp*mscale,
xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale,
vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0],
vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1],
vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2],
count2,GASTYPE);
Pbuf[ibufindex].SetPID(idval);
#ifdef GASON
Pbuf[ibufindex].SetU(utemp);
Pbuf[ibufindex].SetSPHDen(rhotemp);
#ifdef STARON
Pbuf[ibufindex].SetZmet(Ztemp);
#endif
#endif
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbuf[ibufindex].SetInputFileID(i);
Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset);
}
#endif
//ensure that store number of particles to be sent to the threads involved with reading snapshot files
Nbuf[ibuf]++;
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocal, Part.data(), Nreadbuf, Preadbuf);
#else
Part[count2]=Particle(mtemp*mscale,
xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale,
vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0],
vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1],
vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2],
count2,GASTYPE);
Part[count2].SetPID(idval);
#ifdef GASON
Part[count2].SetU(utemp);
Part[count2].SetSPHDen(rhotemp);
#ifdef STARON
Part[count2].SetZmet(Ztemp);
#endif
#endif
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Part[count2].SetInputFileID(i);
Part[count2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset);
}
#endif
#endif
count2++;
}
else if (opt.partsearchtype==PSTDARK&&opt.iBaryonSearch) {
#ifdef USEMPI
Pbuf[ibufindex]=Particle(mtemp*mscale,
xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale,
vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0],
vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1],
vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2],
count2,GASTYPE);
Pbuf[ibufindex].SetPID(idval);
#ifdef GASON
Pbuf[ibufindex].SetU(utemp);
Pbuf[ibufindex].SetSPHDen(rhotemp);
#ifdef STARON
Pbuf[ibufindex].SetZmet(Ztemp);
#endif
#endif
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbuf[ibufindex].SetInputFileID(i);
Pbuf[ibufindex].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset);
}
#endif
//ensure that store number of particles to be sent to the reading threads
if (ibuf==ThisTask) {
Nlocalbaryon[1]++;
}
MPIAddParticletoAppropriateBuffer(opt, ibuf, ibufindex, ireadtask, BufSize, Nbuf, Pbuf, Nlocalbaryon[0], Pbaryons, Nreadbuf, Preadbuf);
#else
Pbaryons[bcount2]=Particle(mtemp*mscale,
xpos[0]*lscale,xpos[1]*lscale,xpos[2]*lscale,
vpos[0]*opt.velocityinputconversion+Hubbleflow*xpos[0],
vpos[1]*opt.velocityinputconversion+Hubbleflow*xpos[1],
vpos[2]*opt.velocityinputconversion+Hubbleflow*xpos[2],
count2,GASTYPE);
Pbaryons[bcount2].SetPID(idval);
#ifdef GASON
Pbaryons[bcount2].SetU(utemp);
Pbaryons[bcount2].SetSPHDen(rhotemp);
#ifdef STARON
Pbaryons[bcount2].SetZmet(Ztemp);
#endif
#endif
#ifdef EXTRAINPUTINFO
if (opt.iextendedoutput)
{
Pbaryons[bcount2].SetInputFileID(i);
Pbaryons[bcount2].SetInputIndexInFile(idim*chunksize*header[i].nvarh+0*chunksize+igrid+ninputoffset);
}
#endif
#endif
bcount2++;
}
}
}
}
}
}
}
if (chunksize>0) {
delete[] xtempchunk;
delete[] hydrotempchunk;
}
}
}
Famr[i].close();
#ifdef USEMPI
//send information between read threads
if (opt.nsnapread>1&&inreadsend<totreadsend){
MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read);
MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon);
inreadsend++;
for(ibuf = 0; ibuf < opt.nsnapread; ibuf++) Nreadbuf[ibuf]=0;
}
#endif
}
#ifdef USEMPI
//once finished reading the file if there are any particles left in the buffer broadcast them
for(ibuf = 0; ibuf < NProcs; ibuf++) if (ireadtask[ibuf]<0)
{
MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t, ibuf, ibuf+NProcs, MPI_COMM_WORLD);
if (Nbuf[ibuf]>0) {
MPI_Ssend(&Pbuf[ibuf*BufSize], sizeof(Particle)*Nbuf[ibuf], MPI_BYTE, ibuf, ibuf, MPI_COMM_WORLD);
MPISendHydroInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf);
MPISendStarInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf);
MPISendBHInfoFromReadThreads(opt, Nbuf[ibuf], &Pbuf[ibuf*BufSize], ibuf);
Nbuf[ibuf]=0;
//last broadcast with Nbuf[ibuf]=0 so that receiver knows no more particles are to be broadcast
MPI_Ssend(&Nbuf[ibuf],1,MPI_Int_t,ibuf,ibuf+NProcs,MPI_COMM_WORLD);
}
}
if (opt.nsnapread>1){
MPI_Allgather(Nreadbuf, opt.nsnapread, MPI_Int_t, mpi_nsend_readthread, opt.nsnapread, MPI_Int_t, mpi_comm_read);
MPISendParticlesBetweenReadThreads(opt, Preadbuf, Part.data(), ireadtask, readtaskID, Pbaryons, mpi_comm_read, mpi_nsend_readthread, mpi_nsend_readthread_baryon);
}
}//end of reading task
#endif
#ifdef USEMPI
//if not reading information than waiting to receive information
else {
MPIReceiveParticlesFromReadThreads(opt,Pbuf,Part.data(),readtaskID, irecv, mpi_irecvflag, Nlocalthreadbuf, mpi_request,Pbaryons);
}
#endif
}//end of check if gas loaded
//update info
opt.p*=opt.a/opt.h;
#ifdef HIGHRES
opt.zoomlowmassdm=MP_DM*mscale;
#endif
#ifdef USEMPI
MPI_Barrier(MPI_COMM_WORLD);
//update cosmological data and boundary in code units
MPI_Bcast(&(opt.p),sizeof(opt.p),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.a),sizeof(opt.a),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.Omega_cdm),sizeof(opt.Omega_cdm),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.Omega_b),sizeof(opt.Omega_b),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.Omega_m),sizeof(opt.Omega_m),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.Omega_Lambda),sizeof(opt.Omega_Lambda),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.h),sizeof(opt.h),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.rhocrit),sizeof(opt.rhocrit),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.rhobg),sizeof(opt.rhobg),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.virlevel),sizeof(opt.virlevel),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.virBN98),sizeof(opt.virBN98),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.ellxscale),sizeof(opt.ellxscale),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.lengthinputconversion),sizeof(opt.lengthinputconversion),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.velocityinputconversion),sizeof(opt.velocityinputconversion),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.massinputconversion),sizeof(opt.massinputconversion),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&(opt.G),sizeof(opt.G),MPI_BYTE,0,MPI_COMM_WORLD);
#ifdef NOMASS
MPI_Bcast(&(opt.MassValue),sizeof(opt.MassValue),MPI_BYTE,0,MPI_COMM_WORLD);
#endif
MPI_Bcast(&(Ntotal),sizeof(Ntotal),MPI_BYTE,0,MPI_COMM_WORLD);
MPI_Bcast(&opt.zoomlowmassdm,sizeof(opt.zoomlowmassdm),MPI_BYTE,0,MPI_COMM_WORLD);
#endif
//store how to convert input internal energies to physical output internal energies
//as we already convert ramses units to sensible output units, nothing to do.
opt.internalenergyinputconversion = 1.0;
//a bit of clean up
#ifdef USEMPI
MPI_Comm_free(&mpi_comm_read);
if (opt.iBaryonSearch) delete[] mpi_nsend_baryon;
if (opt.nsnapread>1) {
delete[] mpi_nsend_readthread;
if (opt.iBaryonSearch) delete[] mpi_nsend_readthread_baryon;
if (ireadtask[ThisTask]>=0) delete[] Preadbuf;
}
delete[] Nbuf;
if (ireadtask[ThisTask]>=0) {
delete[] Nreadbuf;
delete[] Pbuf;
}
delete[] ireadtask;
delete[] readtaskID;
#endif
}
| 61,762 | 21,777 |
/*
* Copyright (c) 2017-present Orlando Bassotto
*
* 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 "nx/nx.h"
#include "nxcompat/nxcompat.h"
#include <cstdio>
#include <cstdlib>
#include <memory>
#include <string>
#include <vector>
#define INVALID_XID (static_cast<uint64_t>(-1))
static void
usage(char const *progname)
{
fprintf(stderr, "usage: %s [-f|-x xid] [-kpq] device\n", progname);
}
enum action {
ACTION_PRINT_NAME,
ACTION_PRINT_UUID,
ACTION_CHECK
};
int
main(int argc, char **argv)
{
char const *progname = *argv;
bool first_xid = false;
uint64_t xid = INVALID_XID;
enum action action = ACTION_PRINT_NAME;
int c;
while ((c = getopt(argc, argv, "fkpqx:")) != EOF) {
switch (c) {
case 'p':
action = ACTION_PRINT_NAME;
break;
case 'k':
action = ACTION_PRINT_UUID;
break;
case 'q':
action = ACTION_CHECK;
break;
case 'f':
first_xid = true;
break;
case 'x':
xid = strtoull(optarg, nullptr, 0);
break;
default:
usage(progname);
exit(EXIT_FAILURE);
}
}
argc -= optind;
argv += optind;
if (argc < 1) {
usage(progname);
exit(EXIT_FAILURE);
}
std::string devname = argv[0];
//
// Is this a real path?
//
if (access(devname.c_str(), R_OK) != 0 && errno == ENOENT) {
std::string devname2 = "/dev/" + devname;
if (access(devname2.c_str(), R_OK) != 0) {
fprintf(stderr, "error: cannot find '%s' for reading: %s\n",
devname.c_str(), strerror(errno));
exit(EXIT_FAILURE);
}
devname = devname2;
}
nx::context context;
nx::device device;
context.set_main_device(&device);
if (!device.open(devname.c_str())) {
fprintf(stderr, "error: cannot open '%s' for reading: %s\n",
devname.c_str(), strerror(errno));
exit(EXIT_FAILURE);
}
auto container = new nx::container(&context);
bool opened;
if (xid != INVALID_XID) {
opened = container->open_at(xid);
} else {
opened = container->open(!first_xid);
}
if (!opened) {
exit(EXIT_FAILURE);
}
nx::container::info info;
if (!container->get_info(info)) {
exit(EXIT_FAILURE);
}
char buf[128];
auto vused = info.volumes - info.vfree;
if (vused > 1) {
auto uuid = container->get_uuid();
nx_uuid_format(&uuid, buf, sizeof(buf));
if (action == ACTION_PRINT_UUID) {
printf("%s\n", buf);
} else if (action == ACTION_PRINT_NAME) {
printf("APFS Container %s\n", buf);
}
} else {
auto volume = container->open_volume(0);
if (volume == nullptr) {
exit(EXIT_FAILURE);
}
if (action == ACTION_PRINT_UUID) {
auto uuid = volume->get_uuid();
nx_uuid_format(&uuid, buf, sizeof(buf));
printf("%s\n", buf);
} else if (action == ACTION_PRINT_NAME) {
printf("%s\n", volume->get_name());
}
delete volume;
}
delete container;
exit(EXIT_SUCCESS);
return EXIT_SUCCESS;
}
| 4,432 | 1,521 |
#include<iostream>
#include<map>
using namespace std;
int main(){
int answerNum;
cin>>answerNum;
map<int,int> correctAnswerNum;
int payment=0;
while(answerNum--){
int questionID;
bool correct,withExplanaion;
cin>>questionID>>correct>>withExplanaion;
if(correct){
if(withExplanaion)
payment+=40;
else
payment+=20;
if(correctAnswerNum.find(questionID)==correctAnswerNum.end())
correctAnswerNum[questionID]=1;
else{
payment+=10*correctAnswerNum[questionID];
correctAnswerNum[questionID]++;
}
}
else
payment+=10;
}
cout<<payment<<endl;
return 0;
} | 632 | 263 |
// Copyright 2015 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 <string>
#include "base/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/ui/browser_dialogs.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/views/bubble_anchor_util_views.h"
#include "chrome/browser/ui/views/device_chooser_content_view.h"
#include "chrome/browser/ui/views/location_bar/location_bar_bubble_delegate_view.h"
#include "chrome/browser/ui/views/title_origin_label.h"
#include "components/permissions/chooser_controller.h"
#include "extensions/buildflags/buildflags.h"
#include "ui/base/metadata/metadata_impl_macros.h"
#include "ui/views/bubble/bubble_dialog_delegate_view.h"
#include "ui/views/bubble/bubble_frame_view.h"
#include "ui/views/controls/button/label_button.h"
#include "ui/views/controls/styled_label.h"
#include "ui/views/controls/table/table_view_observer.h"
#include "ui/views/layout/fill_layout.h"
#include "ui/views/widget/widget.h"
#if BUILDFLAG(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/chrome_extension_chooser_dialog.h"
#include "extensions/browser/app_window/app_window_registry.h"
#endif
using bubble_anchor_util::AnchorConfiguration;
namespace {
AnchorConfiguration GetChooserAnchorConfiguration(Browser* browser) {
return bubble_anchor_util::GetPageInfoAnchorConfiguration(browser);
}
gfx::Rect GetChooserAnchorRect(Browser* browser) {
return bubble_anchor_util::GetPageInfoAnchorRect(browser);
}
} // namespace
///////////////////////////////////////////////////////////////////////////////
// View implementation for the chooser bubble.
class ChooserBubbleUiViewDelegate : public LocationBarBubbleDelegateView,
public views::TableViewObserver {
public:
METADATA_HEADER(ChooserBubbleUiViewDelegate);
ChooserBubbleUiViewDelegate(
Browser* browser,
content::WebContents* web_contents,
std::unique_ptr<permissions::ChooserController> chooser_controller);
ChooserBubbleUiViewDelegate(const ChooserBubbleUiViewDelegate&) = delete;
ChooserBubbleUiViewDelegate& operator=(const ChooserBubbleUiViewDelegate&) =
delete;
~ChooserBubbleUiViewDelegate() override;
// views::View:
void AddedToWidget() override;
// views::WidgetDelegate:
std::u16string GetWindowTitle() const override;
// views::DialogDelegate:
bool IsDialogButtonEnabled(ui::DialogButton button) const override;
views::View* GetInitiallyFocusedView() override;
// views::TableViewObserver:
void OnSelectionChanged() override;
// Updates the anchor's arrow and view. Also repositions the bubble so it's
// displayed in the correct location.
void UpdateAnchor(Browser* browser);
void UpdateTableView() const;
base::OnceClosure MakeCloseClosure();
void Close();
private:
raw_ptr<DeviceChooserContentView> device_chooser_content_view_ = nullptr;
base::WeakPtrFactory<ChooserBubbleUiViewDelegate> weak_ptr_factory_{this};
};
ChooserBubbleUiViewDelegate::ChooserBubbleUiViewDelegate(
Browser* browser,
content::WebContents* contents,
std::unique_ptr<permissions::ChooserController> chooser_controller)
: LocationBarBubbleDelegateView(
GetChooserAnchorConfiguration(browser).anchor_view,
contents) {
// ------------------------------------
// | Chooser bubble title |
// | -------------------------------- |
// | | option 0 | |
// | | option 1 | |
// | | option 2 | |
// | | | |
// | | | |
// | | | |
// | -------------------------------- |
// | [ Connect ] [ Cancel ] |
// |----------------------------------|
// | Get help |
// ------------------------------------
SetButtonLabel(ui::DIALOG_BUTTON_OK, chooser_controller->GetOkButtonLabel());
SetButtonLabel(ui::DIALOG_BUTTON_CANCEL,
chooser_controller->GetCancelButtonLabel());
SetLayoutManager(std::make_unique<views::FillLayout>());
device_chooser_content_view_ =
new DeviceChooserContentView(this, std::move(chooser_controller));
AddChildView(device_chooser_content_view_.get());
SetExtraView(device_chooser_content_view_->CreateExtraView());
SetAcceptCallback(
base::BindOnce(&DeviceChooserContentView::Accept,
base::Unretained(device_chooser_content_view_)));
SetCancelCallback(
base::BindOnce(&DeviceChooserContentView::Cancel,
base::Unretained(device_chooser_content_view_)));
SetCloseCallback(
base::BindOnce(&DeviceChooserContentView::Close,
base::Unretained(device_chooser_content_view_)));
chrome::RecordDialogCreation(chrome::DialogIdentifier::CHOOSER_UI);
}
ChooserBubbleUiViewDelegate::~ChooserBubbleUiViewDelegate() = default;
void ChooserBubbleUiViewDelegate::AddedToWidget() {
GetBubbleFrameView()->SetTitleView(CreateTitleOriginLabel(GetWindowTitle()));
}
std::u16string ChooserBubbleUiViewDelegate::GetWindowTitle() const {
return device_chooser_content_view_->GetWindowTitle();
}
views::View* ChooserBubbleUiViewDelegate::GetInitiallyFocusedView() {
return GetCancelButton();
}
bool ChooserBubbleUiViewDelegate::IsDialogButtonEnabled(
ui::DialogButton button) const {
return device_chooser_content_view_->IsDialogButtonEnabled(button);
}
void ChooserBubbleUiViewDelegate::OnSelectionChanged() {
DialogModelChanged();
}
void ChooserBubbleUiViewDelegate::UpdateAnchor(Browser* browser) {
AnchorConfiguration configuration = GetChooserAnchorConfiguration(browser);
SetAnchorView(configuration.anchor_view);
SetHighlightedButton(configuration.highlighted_button);
if (!configuration.anchor_view)
SetAnchorRect(GetChooserAnchorRect(browser));
SetArrow(configuration.bubble_arrow);
}
void ChooserBubbleUiViewDelegate::UpdateTableView() const {
device_chooser_content_view_->UpdateTableView();
}
base::OnceClosure ChooserBubbleUiViewDelegate::MakeCloseClosure() {
return base::BindOnce(&ChooserBubbleUiViewDelegate::Close,
weak_ptr_factory_.GetWeakPtr());
}
void ChooserBubbleUiViewDelegate::Close() {
if (GetWidget())
GetWidget()->CloseWithReason(views::Widget::ClosedReason::kUnspecified);
}
BEGIN_METADATA(ChooserBubbleUiViewDelegate, LocationBarBubbleDelegateView)
END_METADATA
namespace chrome {
base::OnceClosure ShowDeviceChooserDialog(
content::RenderFrameHost* owner,
std::unique_ptr<permissions::ChooserController> controller) {
auto* contents = content::WebContents::FromRenderFrameHost(owner);
#if BUILDFLAG(ENABLE_EXTENSIONS)
if (extensions::AppWindowRegistry::Get(owner->GetBrowserContext())
->GetAppWindowForWebContents(contents)) {
ShowConstrainedDeviceChooserDialog(contents, std::move(controller));
// This version of the chooser dialog does not support being closed by the
// code which created it.
return base::DoNothing();
}
#endif
auto* browser = chrome::FindBrowserWithWebContents(contents);
if (!browser)
return base::DoNothing();
if (browser->tab_strip_model()->GetActiveWebContents() != contents)
return base::DoNothing();
auto bubble = std::make_unique<ChooserBubbleUiViewDelegate>(
browser, contents, std::move(controller));
// Set |parent_window_| because some valid anchors can become hidden.
views::Widget* parent_widget = views::Widget::GetWidgetForNativeWindow(
browser->window()->GetNativeWindow());
gfx::NativeView parent = parent_widget->GetNativeView();
DCHECK(parent);
bubble->set_parent_window(parent);
bubble->UpdateAnchor(browser);
base::OnceClosure close_closure = bubble->MakeCloseClosure();
views::Widget* widget =
views::BubbleDialogDelegateView::CreateBubble(std::move(bubble));
if (browser->window()->IsActive())
widget->Show();
else
widget->ShowInactive();
return close_closure;
}
} // namespace chrome
| 8,237 | 2,471 |
class Solution {
public:
int maximumUniqueSubarray(vector<int>& nums) {
const int N = nums.size();
const int MAX_ELEM = *max_element(nums.begin(), nums.end());
int answer = 0;
vector<bool> vis(MAX_ELEM + 1, false);
for(int i = 0, j = 0, sum = 0; j < N; ++j){
while(vis[nums[j]]){
vis[nums[i]] = false;
sum -= nums[i];
i += 1;
}
vis[nums[j]] = true;
sum += nums[j];
answer = max(sum, answer);
}
return answer;
}
}; | 624 | 212 |
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/graph/while_context.h"
namespace tensorflow {
WhileContext::WhileContext(StringPiece frame_name,
std::vector<Node*> enter_nodes,
std::vector<Node*> exit_nodes,
OutputTensor cond_output,
std::vector<OutputTensor> body_inputs,
std::vector<OutputTensor> body_outputs)
: frame_name_(std::string(frame_name)),
enter_nodes_(std::move(enter_nodes)),
exit_nodes_(std::move(exit_nodes)),
cond_output_(cond_output),
body_inputs_(std::move(body_inputs)),
body_outputs_(std::move(body_outputs)) {
const size_t num_loop_vars = enter_nodes_.size();
DCHECK_EQ(exit_nodes_.size(), num_loop_vars);
DCHECK_EQ(body_inputs_.size(), num_loop_vars);
DCHECK_EQ(body_outputs_.size(), num_loop_vars);
}
} // namespace tensorflow
| 1,581 | 463 |
#include "pch.hpp"
#include "Renderer.hpp"
namespace Sq {
Renderer::OrthographicCameraMatrix* Renderer::m_RendererElements = new Renderer::OrthographicCameraMatrix;
void Renderer::Begin(OrthographicCamera& camera)
{
m_RendererElements->ViewProjectionMatrix = camera.GetViewProjectionMatrix();
}
void Renderer::Submit(const Ref<VertexArray>& vertexArray, const Ref<Shader>& shader)
{
shader->Bind();
vertexArray->Bind();
shader->SetMat4("u_ViewPorjectionMatrix", m_RendererElements->ViewProjectionMatrix);
RendererCommand::Draw(vertexArray);
}
} | 568 | 190 |
//**************************************************************************************************
//
// OSSIM Open Source Geospatial Data Processing Library
// See top level LICENSE.txt file for license information
//
//**************************************************************************************************
#include <iostream>
#include <sstream>
#include <map>
using namespace std;
#include <ossim/init/ossimInit.h>
#include <ossim/base/ossimArgumentParser.h>
#include <ossim/base/ossimApplicationUsage.h>
#include <ossim/base/ossimStdOutProgress.h>
#include <ossim/base/ossimTimer.h>
#include <ossim/base/ossimKeywordlist.h>
#include <ossim/util/ossimToolRegistry.h>
#include <ossim/base/ossimException.h>
#define CINFO ossimNotify(ossimNotifyLevel_INFO)
#define CWARN ossimNotify(ossimNotifyLevel_WARN)
#define CFATAL ossimNotify(ossimNotifyLevel_FATAL)
void showAvailableCommands()
{
ossimToolFactoryBase* factory = ossimToolRegistry::instance();
map<string, string> capabilities;
factory->getCapabilities(capabilities);
map<string, string>::iterator iter = capabilities.begin();
CINFO<<"\nAvailable commands:\n"<<endl;
for (;iter != capabilities.end(); ++iter)
CINFO<<" "<<iter->first<<" -- "<<iter->second<<endl;
CINFO<<endl;
}
void usage(char* appName)
{
CINFO << "\nUsages: \n"
<< " "<<appName<<" <command> [command options and parameters]\n"
<< " "<<appName<<" --spec <command-spec-file>\n"
<< " "<<appName<<" --version\n"
<< " "<<appName<<" help <command> -- To get help on specific command."<<endl;
showAvailableCommands();
}
bool runCommand(ossimArgumentParser& ap)
{
ossimString command = ap[1];
ap.remove(1);
ossimToolFactoryBase* factory = ossimToolRegistry::instance();
ossimRefPtr<ossimTool> utility = factory->createTool(command);
if (!utility.valid())
{
CWARN << "\nDid not understand command <"<<command<<">"<<endl;
showAvailableCommands();
return false;
}
ossimTimer* timer = ossimTimer::instance();
timer->setStartTick();
if (!utility->initialize(ap))
{
CWARN << "\nCould not execute command <"<<command<<"> with arguments and options "
"provided."<<endl;
return false;
}
if (utility->helpRequested())
return true;
if (!utility->execute())
{
CWARN << "\nAn error was encountered executing the command. Check options."<<endl;
return false;
}
//CINFO << "\nElapsed time after initialization: "<<timer->time_s()<<" s.\n"<<endl;
return true;
}
int main(int argc, char *argv[])
{
ossimArgumentParser ap (&argc, argv);
ap.getApplicationUsage()->setApplicationName(argv[0]);
bool status_ok = true;
try
{
// Initialize ossim stuff, factories, plugin, etc.
ossimInit::instance()->initialize(ap);
do
{
if (argc == 1)
{
// Blank command line:
usage(argv[0]);
break;
}
// Spec file provided containing command's arguments and options?
ossimString argv1 = argv[1];
if (( argv1 == "--spec") && (argc > 2))
{
// Command line provided in spec file:
ifstream ifs (argv[2]);
if (ifs.fail())
{
CWARN<<"\nCould not open the spec file at <"<<argv[2]<<">\n"<<endl;
status_ok = false;
break;
}
ossimString spec;
ifs >> spec;
ifs.close();
ossimArgumentParser new_ap(spec);
status_ok = runCommand(new_ap);
break;
}
// Need help with app or specific command?
if (argv1.contains("help"))
{
// If no command was specified, then general usage help shown:
if (argc == 2)
{
// Blank command line:
usage(argv[0]);
break;
}
else
{
// rearrange command line for individual utility help:
ostringstream cmdline;
cmdline<<argv[0]<<" "<<argv[2]<<" --help";
ossimArgumentParser new_ap(cmdline.str());
status_ok = runCommand(new_ap);
break;
}
}
if (argv1.string()[0] == '-')
{
// Treat as info call:
ap.insert(1, "info");
status_ok = runCommand(ap);
break;
}
// Conventional command line, just remove this app's name:
status_ok = runCommand(ap);
} while (false);
}
catch (const exception& e)
{
CFATAL<<e.what()<<endl;
exit(1);
}
if (status_ok)
exit(0);
exit(1);
}
| 4,804 | 1,465 |
// Copyright Epic Games, Inc. All Rights Reserved.
/*===========================================================================
Generated code exported from UnrealHeaderTool.
DO NOT modify this manually! Edit the corresponding .h files instead!
===========================================================================*/
#include "UObject/GeneratedCppIncludes.h"
#include "MultiplayerMovementPlugin/Public/MultiCharacter.h"
#ifdef _MSC_VER
#pragma warning (push)
#pragma warning (disable : 4883)
#endif
PRAGMA_DISABLE_DEPRECATION_WARNINGS
void EmptyLinkFunctionForGeneratedCodeMultiCharacter() {}
// Cross Module References
MULTIPLAYERMOVEMENTPLUGIN_API UClass* Z_Construct_UClass_AMultiCharacter_NoRegister();
MULTIPLAYERMOVEMENTPLUGIN_API UClass* Z_Construct_UClass_AMultiCharacter();
ENGINE_API UClass* Z_Construct_UClass_ACharacter();
UPackage* Z_Construct_UPackage__Script_MultiplayerMovementPlugin();
MULTIPLAYERMOVEMENTPLUGIN_API UClass* Z_Construct_UClass_UMyCharacterMovementComponent_NoRegister();
COREUOBJECT_API UScriptStruct* Z_Construct_UScriptStruct_FVector();
// End Cross Module References
DEFINE_FUNCTION(AMultiCharacter::execOnMovementUpdatedCustom)
{
P_GET_PROPERTY(FFloatProperty,Z_Param_DeltaSeconds);
P_GET_STRUCT_REF(FVector,Z_Param_Out_OldLocation);
P_GET_STRUCT_REF(FVector,Z_Param_Out_OldVelocity);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->OnMovementUpdatedCustom_Implementation(Z_Param_DeltaSeconds,Z_Param_Out_OldLocation,Z_Param_Out_OldVelocity);
P_NATIVE_END;
}
DEFINE_FUNCTION(AMultiCharacter::execGetMultiplayerMovementComponent)
{
P_FINISH;
P_NATIVE_BEGIN;
*(UMyCharacterMovementComponent**)Z_Param__Result=P_THIS->GetMultiplayerMovementComponent();
P_NATIVE_END;
}
DEFINE_FUNCTION(AMultiCharacter::execPhysNetCustom)
{
P_GET_PROPERTY(FFloatProperty,Z_Param_DeltaTime);
P_GET_PROPERTY(FIntProperty,Z_Param_Iterations);
P_FINISH;
P_NATIVE_BEGIN;
P_THIS->PhysNetCustom_Implementation(Z_Param_DeltaTime,Z_Param_Iterations);
P_NATIVE_END;
}
static FName NAME_AMultiCharacter_OnMovementUpdatedCustom = FName(TEXT("OnMovementUpdatedCustom"));
void AMultiCharacter::OnMovementUpdatedCustom(float DeltaSeconds, FVector const& OldLocation, FVector const& OldVelocity)
{
MultiCharacter_eventOnMovementUpdatedCustom_Parms Parms;
Parms.DeltaSeconds=DeltaSeconds;
Parms.OldLocation=OldLocation;
Parms.OldVelocity=OldVelocity;
ProcessEvent(FindFunctionChecked(NAME_AMultiCharacter_OnMovementUpdatedCustom),&Parms);
}
static FName NAME_AMultiCharacter_PhysNetCustom = FName(TEXT("PhysNetCustom"));
void AMultiCharacter::PhysNetCustom(float DeltaTime, int32 Iterations)
{
MultiCharacter_eventPhysNetCustom_Parms Parms;
Parms.DeltaTime=DeltaTime;
Parms.Iterations=Iterations;
ProcessEvent(FindFunctionChecked(NAME_AMultiCharacter_PhysNetCustom),&Parms);
}
void AMultiCharacter::StaticRegisterNativesAMultiCharacter()
{
UClass* Class = AMultiCharacter::StaticClass();
static const FNameNativePtrPair Funcs[] = {
{ "GetMultiplayerMovementComponent", &AMultiCharacter::execGetMultiplayerMovementComponent },
{ "OnMovementUpdatedCustom", &AMultiCharacter::execOnMovementUpdatedCustom },
{ "PhysNetCustom", &AMultiCharacter::execPhysNetCustom },
};
FNativeFunctionRegistrar::RegisterFunctions(Class, Funcs, UE_ARRAY_COUNT(Funcs));
}
struct Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics
{
struct MultiCharacter_eventGetMultiplayerMovementComponent_Parms
{
UMyCharacterMovementComponent* ReturnValue;
};
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_ReturnValue_MetaData[];
#endif
static const UE4CodeGen_Private::FObjectPropertyParams NewProp_ReturnValue;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::NewProp_ReturnValue_MetaData[] = {
{ "EditInline", "true" },
};
#endif
const UE4CodeGen_Private::FObjectPropertyParams Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::NewProp_ReturnValue = { "ReturnValue", nullptr, (EPropertyFlags)0x0010000000080588, UE4CodeGen_Private::EPropertyGenFlags::Object, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventGetMultiplayerMovementComponent_Parms, ReturnValue), Z_Construct_UClass_UMyCharacterMovementComponent_NoRegister, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::NewProp_ReturnValue_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::NewProp_ReturnValue_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::NewProp_ReturnValue,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::Function_MetaDataParams[] = {
{ "Category", "Smooth Network Movement" },
{ "ModuleRelativePath", "Public/MultiCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMultiCharacter, nullptr, "GetMultiplayerMovementComponent", nullptr, nullptr, sizeof(MultiCharacter_eventGetMultiplayerMovementComponent_Parms), Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x54020401, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics
{
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_DeltaSeconds;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OldLocation_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_OldLocation;
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam NewProp_OldVelocity_MetaData[];
#endif
static const UE4CodeGen_Private::FStructPropertyParams NewProp_OldVelocity;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_DeltaSeconds = { "DeltaSeconds", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventOnMovementUpdatedCustom_Parms, DeltaSeconds), METADATA_PARAMS(nullptr, 0) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldLocation_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldLocation = { "OldLocation", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventOnMovementUpdatedCustom_Parms, OldLocation), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldLocation_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldLocation_MetaData)) };
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldVelocity_MetaData[] = {
{ "NativeConst", "" },
};
#endif
const UE4CodeGen_Private::FStructPropertyParams Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldVelocity = { "OldVelocity", nullptr, (EPropertyFlags)0x0010000008000182, UE4CodeGen_Private::EPropertyGenFlags::Struct, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventOnMovementUpdatedCustom_Parms, OldVelocity), Z_Construct_UScriptStruct_FVector, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldVelocity_MetaData, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldVelocity_MetaData)) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_DeltaSeconds,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldLocation,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::NewProp_OldVelocity,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/MultiCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMultiCharacter, nullptr, "OnMovementUpdatedCustom", nullptr, nullptr, sizeof(MultiCharacter_eventOnMovementUpdatedCustom_Parms), Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08C20C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom_Statics::FuncParams);
}
return ReturnFunction;
}
struct Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics
{
static const UE4CodeGen_Private::FFloatPropertyParams NewProp_DeltaTime;
static const UE4CodeGen_Private::FIntPropertyParams NewProp_Iterations;
static const UE4CodeGen_Private::FPropertyParamsBase* const PropPointers[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Function_MetaDataParams[];
#endif
static const UE4CodeGen_Private::FFunctionParams FuncParams;
};
const UE4CodeGen_Private::FFloatPropertyParams Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::NewProp_DeltaTime = { "DeltaTime", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Float, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventPhysNetCustom_Parms, DeltaTime), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FIntPropertyParams Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::NewProp_Iterations = { "Iterations", nullptr, (EPropertyFlags)0x0010000000000080, UE4CodeGen_Private::EPropertyGenFlags::Int, RF_Public|RF_Transient|RF_MarkAsNative, 1, STRUCT_OFFSET(MultiCharacter_eventPhysNetCustom_Parms, Iterations), METADATA_PARAMS(nullptr, 0) };
const UE4CodeGen_Private::FPropertyParamsBase* const Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::PropPointers[] = {
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::NewProp_DeltaTime,
(const UE4CodeGen_Private::FPropertyParamsBase*)&Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::NewProp_Iterations,
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::Function_MetaDataParams[] = {
{ "ModuleRelativePath", "Public/MultiCharacter.h" },
};
#endif
const UE4CodeGen_Private::FFunctionParams Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::FuncParams = { (UObject*(*)())Z_Construct_UClass_AMultiCharacter, nullptr, "PhysNetCustom", nullptr, nullptr, sizeof(MultiCharacter_eventPhysNetCustom_Parms), Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::PropPointers, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::PropPointers), RF_Public|RF_Transient|RF_MarkAsNative, (EFunctionFlags)0x08020C00, 0, 0, METADATA_PARAMS(Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::Function_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::Function_MetaDataParams)) };
UFunction* Z_Construct_UFunction_AMultiCharacter_PhysNetCustom()
{
static UFunction* ReturnFunction = nullptr;
if (!ReturnFunction)
{
UE4CodeGen_Private::ConstructUFunction(ReturnFunction, Z_Construct_UFunction_AMultiCharacter_PhysNetCustom_Statics::FuncParams);
}
return ReturnFunction;
}
UClass* Z_Construct_UClass_AMultiCharacter_NoRegister()
{
return AMultiCharacter::StaticClass();
}
struct Z_Construct_UClass_AMultiCharacter_Statics
{
static UObject* (*const DependentSingletons[])();
static const FClassFunctionLinkInfo FuncInfo[];
#if WITH_METADATA
static const UE4CodeGen_Private::FMetaDataPairParam Class_MetaDataParams[];
#endif
static const FCppClassTypeInfoStatic StaticCppClassTypeInfo;
static const UE4CodeGen_Private::FClassParams ClassParams;
};
UObject* (*const Z_Construct_UClass_AMultiCharacter_Statics::DependentSingletons[])() = {
(UObject* (*)())Z_Construct_UClass_ACharacter,
(UObject* (*)())Z_Construct_UPackage__Script_MultiplayerMovementPlugin,
};
const FClassFunctionLinkInfo Z_Construct_UClass_AMultiCharacter_Statics::FuncInfo[] = {
{ &Z_Construct_UFunction_AMultiCharacter_GetMultiplayerMovementComponent, "GetMultiplayerMovementComponent" }, // 127238334
{ &Z_Construct_UFunction_AMultiCharacter_OnMovementUpdatedCustom, "OnMovementUpdatedCustom" }, // 1504068266
{ &Z_Construct_UFunction_AMultiCharacter_PhysNetCustom, "PhysNetCustom" }, // 58023847
};
#if WITH_METADATA
const UE4CodeGen_Private::FMetaDataPairParam Z_Construct_UClass_AMultiCharacter_Statics::Class_MetaDataParams[] = {
{ "HideCategories", "Navigation" },
{ "IncludePath", "MultiCharacter.h" },
{ "ModuleRelativePath", "Public/MultiCharacter.h" },
{ "ObjectInitializerConstructorDeclared", "" },
};
#endif
const FCppClassTypeInfoStatic Z_Construct_UClass_AMultiCharacter_Statics::StaticCppClassTypeInfo = {
TCppClassTypeTraits<AMultiCharacter>::IsAbstract,
};
const UE4CodeGen_Private::FClassParams Z_Construct_UClass_AMultiCharacter_Statics::ClassParams = {
&AMultiCharacter::StaticClass,
"Game",
&StaticCppClassTypeInfo,
DependentSingletons,
FuncInfo,
nullptr,
nullptr,
UE_ARRAY_COUNT(DependentSingletons),
UE_ARRAY_COUNT(FuncInfo),
0,
0,
0x009000A4u,
METADATA_PARAMS(Z_Construct_UClass_AMultiCharacter_Statics::Class_MetaDataParams, UE_ARRAY_COUNT(Z_Construct_UClass_AMultiCharacter_Statics::Class_MetaDataParams))
};
UClass* Z_Construct_UClass_AMultiCharacter()
{
static UClass* OuterClass = nullptr;
if (!OuterClass)
{
UE4CodeGen_Private::ConstructUClass(OuterClass, Z_Construct_UClass_AMultiCharacter_Statics::ClassParams);
}
return OuterClass;
}
IMPLEMENT_CLASS(AMultiCharacter, 2081226288);
template<> MULTIPLAYERMOVEMENTPLUGIN_API UClass* StaticClass<AMultiCharacter>()
{
return AMultiCharacter::StaticClass();
}
static FCompiledInDefer Z_CompiledInDefer_UClass_AMultiCharacter(Z_Construct_UClass_AMultiCharacter, &AMultiCharacter::StaticClass, TEXT("/Script/MultiplayerMovementPlugin"), TEXT("AMultiCharacter"), false, nullptr, nullptr, nullptr);
DEFINE_VTABLE_PTR_HELPER_CTOR(AMultiCharacter);
PRAGMA_ENABLE_DEPRECATION_WARNINGS
#ifdef _MSC_VER
#pragma warning (pop)
#endif
| 17,243 | 6,072 |
// Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED
#define SGE_CG_PARAMETER_DETAIL_CHECK_TYPE_HPP_INCLUDED
#include <sge/cg/detail/symbol.hpp>
#include <sge/cg/parameter/object_fwd.hpp>
#include <sge/cg/parameter/detail/pp_types.hpp>
#include <fcppt/config/external_begin.hpp>
#include <boost/preprocessor/seq/for_each.hpp>
#include <fcppt/config/external_end.hpp>
namespace sge::cg::parameter::detail
{
template <typename Type>
SGE_CG_DETAIL_SYMBOL void check_type(sge::cg::parameter::object const &);
}
#define SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE(seq, _, base_type) \
extern template SGE_CG_DETAIL_SYMBOL void sge::cg::parameter::detail::check_type<base_type>( \
sge::cg::parameter::object const &);
BOOST_PP_SEQ_FOR_EACH(
SGE_CG_PARAMETER_DETAIL_DECLARE_CHECK_TYPE, _, SGE_CG_PARAMETER_DETAIL_PP_TYPES)
#endif
| 1,065 | 448 |
#include "my_object.hpp"
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>
namespace my_object {
sol::table open_my_object(sol::this_state L) {
sol::state_view lua(L);
sol::table module = lua.create_table();
module.new_usertype<test>("test",
sol::constructors<test(), test(int)>(),
"value", &test::value
);
return module;
}
} // namespace my_object
extern "C" int luaopen_my_object(lua_State* L) {
// pass the lua_State,
// the index to start grabbing arguments from,
// and the function itself
// optionally, you can pass extra arguments to the function if that's necessary,
// but that's advanced usage and is generally reserved for internals only
return sol::stack::call_lua(L, 1, my_object::open_my_object );
}
| 745 | 275 |
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:44 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: Zenject.PlaceholderFactoryBase`1
#include "Zenject/PlaceholderFactoryBase_1.hpp"
// Including type: Zenject.IFactory`11
#include "Zenject/IFactory_11.hpp"
// Including type: System.Collections.Generic.IEnumerable`1
#include "System/Collections/Generic/IEnumerable_1.hpp"
// Including type: System.Collections.Generic.IEnumerator`1
#include "System/Collections/Generic/IEnumerator_1.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: Zenject
namespace Zenject {
// Skipping declaration: <get_ParamTypes>d__2 because it is already included!
}
// Forward declaring namespace: System
namespace System {
// Forward declaring type: Type
class Type;
}
// Completed forward declares
// Type namespace: Zenject
namespace Zenject {
// Autogenerated type: Zenject.PlaceholderFactory`11
template<typename TValue, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10>
class PlaceholderFactory_11 : public Zenject::PlaceholderFactoryBase_1<TValue>, public Zenject::IFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>, public Zenject::IFactory {
public:
// Nested type: Zenject::PlaceholderFactory_11::$get_ParamTypes$d__2<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>
class $get_ParamTypes$d__2;
// Autogenerated type: Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2
class $get_ParamTypes$d__2 : public ::Il2CppObject, public ::il2cpp_utils::il2cpp_type_check::NestedType, public System::Collections::Generic::IEnumerable_1<System::Type*>, public System::Collections::IEnumerable, public System::Collections::Generic::IEnumerator_1<System::Type*>, public System::Collections::IEnumerator, public System::IDisposable {
public:
using declaring_type = PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*;
// private System.Int32 <>1__state
// Offset: 0x0
int $$1__state;
// private System.Type <>2__current
// Offset: 0x0
System::Type* $$2__current;
// private System.Int32 <>l__initialThreadId
// Offset: 0x0
int $$l__initialThreadId;
// public System.Void .ctor(System.Int32 $$1__state)
// Offset: 0x15D5C40
static typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2* New_ctor(int $$1__state) {
return (typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<typename PlaceholderFactory_11<TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TValue>::$get_ParamTypes$d__2*>::get(), $$1__state));
}
// private System.Void System.IDisposable.Dispose()
// Offset: 0x15D5C80
// Implemented from: System.IDisposable
// Base method: System.Void IDisposable::Dispose()
void System_IDisposable_Dispose() {
CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.IDisposable.Dispose"));
}
// private System.Boolean MoveNext()
// Offset: 0x15D5C84
// Implemented from: System.Collections.IEnumerator
// Base method: System.Boolean IEnumerator::MoveNext()
bool MoveNext() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<bool>(this, "MoveNext"));
}
// private System.Type System.Collections.Generic.IEnumerator<System.Type>.get_Current()
// Offset: 0x15D6090
// Implemented from: System.Collections.Generic.IEnumerator`1
// Base method: T IEnumerator`1::get_Current()
System::Type* System_Collections_Generic_IEnumerator_1_get_Current() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Type*>(this, "System.Collections.Generic.IEnumerator<System.Type>.get_Current"));
}
// private System.Void System.Collections.IEnumerator.Reset()
// Offset: 0x15D6098
// Implemented from: System.Collections.IEnumerator
// Base method: System.Void IEnumerator::Reset()
void System_Collections_IEnumerator_Reset() {
CRASH_UNLESS(il2cpp_utils::RunMethod(this, "System.Collections.IEnumerator.Reset"));
}
// private System.Object System.Collections.IEnumerator.get_Current()
// Offset: 0x15D60F8
// Implemented from: System.Collections.IEnumerator
// Base method: System.Object IEnumerator::get_Current()
::Il2CppObject* System_Collections_IEnumerator_get_Current() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<::Il2CppObject*>(this, "System.Collections.IEnumerator.get_Current"));
}
// private System.Collections.Generic.IEnumerator`1<System.Type> System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator()
// Offset: 0x15D6100
// Implemented from: System.Collections.Generic.IEnumerable`1
// Base method: System.Collections.Generic.IEnumerator`1<T> IEnumerable`1::GetEnumerator()
System::Collections::Generic::IEnumerator_1<System::Type*>* System_Collections_Generic_IEnumerable_1_GetEnumerator() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerator_1<System::Type*>*>(this, "System.Collections.Generic.IEnumerable<System.Type>.GetEnumerator"));
}
// private System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
// Offset: 0x15D6194
// Implemented from: System.Collections.IEnumerable
// Base method: System.Collections.IEnumerator IEnumerable::GetEnumerator()
System::Collections::IEnumerator* System_Collections_IEnumerable_GetEnumerator() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::IEnumerator*>(this, "System.Collections.IEnumerable.GetEnumerator"));
}
}; // Zenject.PlaceholderFactory`11/<get_ParamTypes>d__2
// public TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10)
// Offset: 0x15D61B8
TValue Create(TParam1 param1, TParam2 param2, TParam3 param3, TParam4 param4, TParam5 param5, TParam6 param6, TParam7 param7, TParam8 param8, TParam9 param9, TParam10 param10) {
return CRASH_UNLESS(il2cpp_utils::RunMethod<TValue>(this, "Create", param1, param2, param3, param4, param5, param6, param7, param8, param9, param10));
}
// protected override System.Collections.Generic.IEnumerable`1<System.Type> get_ParamTypes()
// Offset: 0x15D64AC
// Implemented from: Zenject.PlaceholderFactoryBase`1
// Base method: System.Collections.Generic.IEnumerable`1<System.Type> PlaceholderFactoryBase`1::get_ParamTypes()
System::Collections::Generic::IEnumerable_1<System::Type*>* get_ParamTypes() {
return CRASH_UNLESS(il2cpp_utils::RunMethod<System::Collections::Generic::IEnumerable_1<System::Type*>*>(this, "get_ParamTypes"));
}
// public System.Void .ctor()
// Offset: 0x15D650C
// Implemented from: Zenject.PlaceholderFactoryBase`1
// Base method: System.Void PlaceholderFactoryBase`1::.ctor()
// Base method: System.Void Object::.ctor()
static PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>* New_ctor() {
return (PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*)CRASH_UNLESS(il2cpp_utils::New(il2cpp_utils::il2cpp_type_check::il2cpp_no_arg_class<PlaceholderFactory_11<TValue, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10>*>::get()));
}
}; // Zenject.PlaceholderFactory`11
}
DEFINE_IL2CPP_ARG_TYPE_GENERIC_CLASS(Zenject::PlaceholderFactory_11, "Zenject", "PlaceholderFactory`11");
#pragma pack(pop)
| 8,420 | 2,873 |