blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
50bc64526b3c049a274d3641b6ca1050fc70952c | c22ce18b600ffc80c3eb7ec7f9d14943c000e655 | /source/resonance_audio/base/misc_math.h | af974d4d957b497aa3513bdeaefa1d628a658e3a | [
"MIT"
] | permissive | sncheca/gyro | d44c75bb57271024776c87b950fd9fd109ba0a54 | b0f91d15179114816316299b8f71b0858d49f215 | refs/heads/master | 2022-12-27T15:30:15.371758 | 2020-09-30T19:33:35 | 2020-09-30T19:33:35 | 235,243,857 | 9 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,717 | h | /*
Copyright 2018 Google Inc. 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.
*/
#ifndef RESONANCE_AUDIO_BASE_MISC_MATH_H_
#define RESONANCE_AUDIO_BASE_MISC_MATH_H_
#ifndef _USE_MATH_DEFINES
#define _USE_MATH_DEFINES // Enable MSVC math constants (e.g., M_PI).
#endif // _USE_MATH_DEFINES
#include <algorithm>
#include <cmath>
#include <cstdint>
#include <limits>
#include <utility>
#include <vector>
#include "integral_types.h"
#include "third_party/eigen/Eigen/Dense"
#include "constants_and_types.h"
#include "logging.h"
namespace vraudio {
class WorldPosition : public Eigen::Matrix<float, 3, 1, Eigen::DontAlign> {
public:
// Inherits all constructors with 1-or-more arguments. Necessary because
// MSVC12 doesn't support inheriting constructors.
template <typename Arg1, typename... Args>
WorldPosition(const Arg1& arg1, Args&&... args)
: Matrix(arg1, std::forward<Args>(args)...) {}
// Constructs a zero vector.
WorldPosition();
// Returns True if other |WorldPosition| differs by at least |kEpsilonFloat|.
bool operator!=(const WorldPosition& other) const {
return std::abs(this->x() - other.x()) > kEpsilonFloat ||
std::abs(this->y() - other.y()) > kEpsilonFloat ||
std::abs(this->z() - other.z()) > kEpsilonFloat;
}
};
class WorldRotation : public Eigen::Quaternion<float, Eigen::DontAlign> {
public:
// Inherits all constructors with 1-or-more arguments. Necessary because
// MSVC12 doesn't support inheriting constructors.
template <typename Arg1, typename... Args>
WorldRotation(const Arg1& arg1, Args&&... args)
: Quaternion(arg1, std::forward<Args>(args)...) {}
// Constructs an identity rotation.
WorldRotation();
// Returns the shortest arc between two |WorldRotation|s in radians.
float AngularDifferenceRad(const WorldRotation& other) const {
const Quaternion difference = this->inverse() * other;
return static_cast<float>(Eigen::AngleAxisf(difference).angle());
}
};
typedef Eigen::AngleAxis<float> AngleAxisf;
typedef WorldPosition AudioPosition;
typedef WorldRotation AudioRotation;
// Converts |world_position| into an equivalent audio space position.
// The world space follows the typical CG coordinate system convention:
// Positive x points right, positive y points up, negative z points forward.
// The audio space follows the ambiX coordinate system convention that is
// commonly accepted in literature [http://goo.gl/XdYNm9]:
// Positive x points forward, negative y points right, positive z points up.
// Positions in both world space and audio space are in meters.
//
// @param world_position 3D position in world space.
// @param audio_position Output 3D position in audio space.
inline void ConvertAudioFromWorldPosition(const WorldPosition& world_position,
AudioPosition* audio_position) {
DCHECK(audio_position);
(*audio_position)(0) = -world_position[2];
(*audio_position)(1) = -world_position[0];
(*audio_position)(2) = world_position[1];
}
// Converts |audio_position| into an equivalent world space position.
// The world space follows the typical CG coordinate system convention:
// Positive x points right, positive y points up, negative z points forward.
// The audio space follows the ambiX coordinate system convention that is
// commonly accepted in literature [http://goo.gl/XdYNm9]:
// Positive x points forward, negative y points right, positive z points up.
// Positions in both world space and audio space are in meters.
//
// @param audio_position 3D position in audio space.
// @param world_position Output 3D position in world space.
inline void ConvertWorldFromAudioPosition(const AudioPosition& audio_position,
AudioPosition* world_position) {
DCHECK(world_position);
(*world_position)(0) = -audio_position[1];
(*world_position)(1) = audio_position[2];
(*world_position)(2) = -audio_position[0];
}
// Converts |world_rotation| into an equivalent audio space rotation.
// The world space follows the typical CG coordinate system convention:
// Positive x points right, positive y points up, negative z points forward.
// The audio space follows the ambiX coordinate system convention that is
// commonly accepted in literature [http://goo.gl/XdYNm9]:
// Positive x points forward, negative y points right, positive z points up.
// Positions in both world space and audio space are in meters.
//
// @param world_rotation 3D rotation in world space.
// @param audio_rotation Output 3D rotation in audio space.
inline void ConvertAudioFromWorldRotation(const WorldRotation& world_rotation,
AudioRotation* audio_rotation) {
DCHECK(audio_rotation);
audio_rotation->w() = world_rotation.w();
audio_rotation->x() = -world_rotation.x();
audio_rotation->y() = world_rotation.y();
audio_rotation->z() = -world_rotation.z();
}
// Returns the relative direction vector |from_position| and |to_position| by
// rotating the relative position vector with respect to |from_rotation|.
//
// @param from_position Origin position of the direction.
// @param from_rotation Origin orientation of the direction.
// @param to_position Target position of the direction.
// @param relative_direction Relative direction vector (not normalized).
inline void GetRelativeDirection(const WorldPosition& from_position,
const WorldRotation& from_rotation,
const WorldPosition& to_position,
WorldPosition* relative_direction) {
DCHECK(relative_direction);
*relative_direction =
from_rotation.conjugate() * (to_position - from_position);
}
// Returns the closest relative position in an axis-aligned bounding box to the
// given |relative_position|.
//
// @param position Input position relative to the center of the bounding box.
// @param aabb_dimensions Bounding box dimensions.
// @return aabb bounded position.
inline void GetClosestPositionInAabb(const WorldPosition& relative_position,
const WorldPosition& aabb_dimensions,
WorldPosition* closest_position) {
DCHECK(closest_position);
const WorldPosition aabb_offset = 0.5f * aabb_dimensions;
(*closest_position)[0] =
std::min(std::max(relative_position[0], -aabb_offset[0]), aabb_offset[0]);
(*closest_position)[1] =
std::min(std::max(relative_position[1], -aabb_offset[1]), aabb_offset[1]);
(*closest_position)[2] =
std::min(std::max(relative_position[2], -aabb_offset[2]), aabb_offset[2]);
}
// Returns true if given world |position| is in given axis-aligned bounding box.
//
// @param position Position to be tested.
// @param aabb_center Bounding box center.
// @param aabb_dimensions Bounding box dimensions.
// @return True if |position| is within bounding box, false otherwise.
inline bool IsPositionInAabb(const WorldPosition& position,
const WorldPosition& aabb_center,
const WorldPosition& aabb_dimensions) {
return std::abs(position[0] - aabb_center[0]) <= 0.5f * aabb_dimensions[0] &&
std::abs(position[1] - aabb_center[1]) <= 0.5f * aabb_dimensions[1] &&
std::abs(position[2] - aabb_center[2]) <= 0.5f * aabb_dimensions[2];
}
// Returns true if an integer overflow occurred during the calculation of
// x = a * b.
//
// @param a First multiplicand.
// @param b Second multiplicand.
// @param x Product.
// @return True if integer overflow occurred, false otherwise.
template <typename T>
inline bool DoesIntegerMultiplicationOverflow(T a, T b, T x) {
// Detects an integer overflow occurs by inverting the multiplication and
// testing for x / a != b.
return a == 0 ? false : (x / a != b);
}
// Returns true if an integer overflow occurred during the calculation of
// a + b.
//
// @param a First summand.
// @param b Second summand.
// @return True if integer overflow occurred, false otherwise.
template <typename T>
inline bool DoesIntegerAdditionOverflow(T a, T b) {
T x = a + b;
return x < b;
}
// Safely converts an int to a size_t.
//
// @param i Integer input.
// @param x Size_t output.
// @return True if integer overflow occurred, false otherwise.
inline bool DoesIntSafelyConvertToSizeT(int i, size_t* x) {
if (i < 0) {
return false;
}
*x = static_cast<size_t>(i);
return true;
}
// Safely converts a size_t to an int.
//
// @param i Size_t input.
// @param x Integer output.
// @return True if integer overflow occurred, false otherwise.
inline bool DoesSizeTSafelyConvertToInt(size_t i, int* x) {
if (i > static_cast<size_t>(std::numeric_limits<int>::max())) {
return false;
}
*x = static_cast<int>(i);
return true;
}
// Finds the greatest common divisor between two integer values using the
// Euclidean algorithm. Always returns a positive integer.
//
// @param a First of the two integer values.
// @param b second of the two integer values.
// @return The greatest common divisor of the two integer values.
inline int FindGcd(int a, int b) {
a = std::abs(a);
b = std::abs(b);
int temp_value = 0;
while (b != 0) {
temp_value = b;
b = a % b;
a = temp_value;
}
return a;
}
// Finds the next power of two from an integer. This method works with values
// representable by unsigned 32 bit integers.
//
// @param input Integer value.
// @return The next power of two from |input|.
inline size_t NextPowTwo(size_t input) {
// Ensure the value fits in a uint32_t.
DCHECK_LT(static_cast<uint64_t>(input),
static_cast<uint64_t>(std::numeric_limits<uint32_t>::max()));
uint32_t number = static_cast<uint32_t>(--input);
number |= number >> 1; // Take care of 2 bit numbers.
number |= number >> 2; // Take care of 4 bit numbers.
number |= number >> 4; // Take care of 8 bit numbers.
number |= number >> 8; // Take care of 16 bit numbers.
number |= number >> 16; // Take care of 32 bit numbers.
number++;
return static_cast<size_t>(number);
}
// Returns the factorial (!) of x. If x < 0, it returns 0.
inline float Factorial(int x) {
if (x < 0) return 0.0f;
float result = 1.0f;
for (; x > 0; --x) result *= static_cast<float>(x);
return result;
}
// Returns the double factorial (!!) of x.
// For odd x: 1 * 3 * 5 * ... * (x - 2) * x
// For even x: 2 * 4 * 6 * ... * (x - 2) * x
// If x < 0, it returns 0.
inline float DoubleFactorial(int x) {
if (x < 0) return 0.0f;
float result = 1.0f;
for (; x > 0; x -= 2) result *= static_cast<float>(x);
return result;
}
// This is a *safe* alternative to std::equal function as a workaround in order
// to avoid MSVC compiler warning C4996 for unchecked iterators (see
// https://msdn.microsoft.com/en-us/library/aa985965.aspx).
// Also note that, an STL equivalent of this function was introduced in C++14 to
// be replaced with this implementation (see version (5) in
// http://en.cppreference.com/w/cpp/algorithm/equal).
template <typename Iterator>
inline bool EqualSafe(const Iterator& lhs_begin, const Iterator& lhs_end,
const Iterator& rhs_begin, const Iterator& rhs_end) {
auto lhs_itr = lhs_begin;
auto rhs_itr = rhs_begin;
while (lhs_itr != lhs_end && rhs_itr != rhs_end) {
if (*lhs_itr != *rhs_itr) {
return false;
}
++lhs_itr;
++rhs_itr;
}
return lhs_itr == lhs_end && rhs_itr == rhs_end;
}
// Fast reciprocal of square-root. See: https://goo.gl/fqvstz for details.
//
// @param input The number to be inverse rooted.
// @return An approximation of the reciprocal square root of |input|.
inline float FastReciprocalSqrt(float input) {
const float kThreeHalfs = 1.5f;
const uint32_t kMagicNumber = 0x5f3759df;
// Approximate a logarithm by aliasing to an integer.
uint32_t integer = *reinterpret_cast<uint32_t*>(&input);
integer = kMagicNumber - (integer >> 1);
float approximation = *reinterpret_cast<float*>(&integer);
const float half_input = input * 0.5f;
// One iteration of Newton's method.
return approximation *
(kThreeHalfs - (half_input * approximation * approximation));
}
// Finds the best-fitting line to a given set of 2D points by minimizing the
// sum of the squares of the vertical (along y-axis) offsets. The slope and
// intercept of the fitted line are recorded, as well as the coefficient of
// determination, which gives the quality of the fitting.
// See http://mathworld.wolfram.com/LeastSquaresFitting.html for how to compute
// these values.
//
// @param x_array Array of the x coordinates of the points.
// @param y_array Array of the y coordinates of the points.
// @param slope Output slope of the fitted line.
// @param intercept Output slope of the fitted line.
// @param r_squared Coefficient of determination.
// @return False if the fitting fails.
bool LinearLeastSquareFitting(const std::vector<float>& x_array,
const std::vector<float>& y_array, float* slope,
float* intercept, float* r_squared);
// Computes |base|^|exp|, where |exp| is a *non-negative* integer, with the
// squared exponentiation (a.k.a double-and-add) method.
// When T is a floating point type, this has the same semantics as pow(), but
// is much faster.
// T can also be any integral type, in which case computations will be
// performed in the value domain of this integral type, and overflow semantics
// will be those of T.
// You can also use any type for which operator*= is defined.
// See :
// This method is reproduced here so vraudio classes don't need to depend on
// //util/math/mathutil.h
//
// @tparam base Input to the exponent function. Any type for which *= is
// defined.
// @param exp Integer exponent, must be greater than or equal to zero.
// @return |base|^|exp|.
template <typename T>
static inline T IntegerPow(T base, int exp) {
DCHECK_GE(exp, 0);
T result = static_cast<T>(1);
while (true) {
if (exp & 1) {
result *= base;
}
exp >>= 1;
if (!exp) break;
base *= base;
}
return result;
}
} // namespace vraudio
#endif // RESONANCE_AUDIO_BASE_MISC_MATH_H_
| [
"54961035+sncheca@users.noreply.github.com"
] | 54961035+sncheca@users.noreply.github.com |
a63d64e31a5795f864ec23d535d20989da13b947 | f3a9174535cd7e76d1c1e0f0fa1a3929751fb48d | /SDK/PVR_Shell_12Gauge_Alt_parameters.hpp | 262016ed9a79d74501b4a439f86084b07bf2e81e | [] | no_license | hinnie123/PavlovVRSDK | 9fcdf97e7ed2ad6c5cb485af16652a4c83266a2b | 503f8d9a6770046cc23f935f2df1f1dede4022a8 | refs/heads/master | 2020-03-31T05:30:40.125042 | 2020-01-28T20:16:11 | 2020-01-28T20:16:11 | 151,949,019 | 5 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,308 | hpp | #pragma once
// PavlovVR (Dumped by Hinnie) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace SDK
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Shell_12Gauge_Alt.Shell_12Gauge_Alt_C.GetImpulseVector
struct AShell_12Gauge_Alt_C_GetImpulseVector_Params
{
struct FVector ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Shell_12Gauge_Alt.Shell_12Gauge_Alt_C.UserConstructionScript
struct AShell_12Gauge_Alt_C_UserConstructionScript_Params
{
};
// Function Shell_12Gauge_Alt.Shell_12Gauge_Alt_C.ReceiveBeginPlay
struct AShell_12Gauge_Alt_C_ReceiveBeginPlay_Params
{
};
// Function Shell_12Gauge_Alt.Shell_12Gauge_Alt_C.ExecuteUbergraph_Shell_12Gauge_Alt
struct AShell_12Gauge_Alt_C_ExecuteUbergraph_Shell_12Gauge_Alt_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"hsibma02@gmail.com"
] | hsibma02@gmail.com |
5f06c36902eb1b909b63352bb85d9147464da772 | 75356e39f55b77a7c79ef0778d7212e05084e52f | /lib/WsDisplay/WsDisplay.h | de734b542344a172079c8127af7791ea88d0632e | [] | no_license | zgomori/180908-150154-nodemcuv2 | 39977df46abf8d8078923776d01cb5fa9a42a772 | 704e845d8b358711e734062ce7dadb78abb9acc1 | refs/heads/master | 2020-03-28T09:48:17.664527 | 2018-11-09T12:35:39 | 2018-11-09T12:35:39 | 148,061,044 | 0 | 0 | null | 2018-11-09T12:35:40 | 2018-09-09T20:00:32 | C++ | UTF-8 | C++ | false | false | 2,063 | h | #ifndef WS_DISPLAY_H
#define WS_DISPLAY_H
#include "Adafruit_ILI9341.h"
#define MAX_DISPLAY_BLOCKS 10
#define MAX_DATAFIELDS 15
class WsDisplay{
public:
enum align_enum {
LEFT = 'L',
RIGHT = 'R',
CENTER = 'C'
};
private:
typedef struct{
uint8_t x;
uint16_t y;
uint8_t w;
uint16_t h;
uint16_t fgColor;
const GFXfont *font;
align_enum align;
char *dataPtr;
int8_t blockIdx = -1;
void* fieldChain;
void* labelChain;
char type; // F - field; L - label
} TextElement;
typedef struct{
uint8_t x;
uint16_t y;
uint8_t w;
uint16_t h;
uint16_t bgColor;
int8_t screenIdx = -1;
TextElement* fieldChain;
TextElement* labelChain;
} DisplayBlock;
int8_t blockArrIdx = -1;
int8_t textElementArrIdx = -1;
Adafruit_ILI9341 *_tft;
DisplayBlock displayBlockArr[MAX_DISPLAY_BLOCKS];
TextElement textElementArr[MAX_DATAFIELDS];
int8_t currentScreenIdx = 0;
void defineTextElement(uint8_t _x, uint16_t _y, uint8_t _w, uint16_t _h, uint16_t _fgColor, const GFXfont *_font, align_enum _align, char *_dataPtr, int8_t _blockIdx, char type);
void showField(WsDisplay::TextElement* textElement, bool fill);
void showLabel(TextElement* textElement);
public:
WsDisplay(Adafruit_ILI9341 *tft);
uint8_t defineBlock(uint8_t _x, uint16_t _y, uint8_t _w, uint16_t _h, uint16_t _bgColor, int8_t _screenIdx);
uint8_t defineField(uint8_t _x, uint16_t _y, uint8_t _w, uint16_t _h, uint16_t _fgColor, const GFXfont *_font, align_enum _align, char *_dataPtr, int8_t _blockIdx);
uint8_t defineLabel(uint8_t _x, uint16_t _y, uint16_t _fgColor, const GFXfont *_font, char *_dataPtr, int8_t _blockIdx);
void showField(int8_t fieldIdx, bool fill);
void showBlock(int8_t blockIdx);
void showBlock(int8_t blockIdx, bool fill);
void showScreen();
void switchScreen(int8_t screenIdx);
int8_t getCurrentScreen();
};
#endif // WS_DISPLAY_H | [
"gomorizo@gmail.com"
] | gomorizo@gmail.com |
c9e3759fc35c01a777a2e43e0ec085036c8d4d2b | 03be6bde9d60747e05f420fdf54f4b1e2611a863 | /OpenBrokerReportAnalyzer.cpp | 92af394088d8da416c76c4803d4e82d3522e9997 | [] | no_license | javapowered/OpenBrokerReportAnalyzer | ca6d1af7173f1a210fc45d03c3edb83ff8b0dac9 | 267c543d60016077343f6b8f48245ccccb3c2863 | refs/heads/master | 2020-12-25T18:16:47.448526 | 2015-10-11T07:47:55 | 2015-10-11T07:47:55 | 17,968,345 | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 14,309 | cpp | #include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <iostream>
#include <sstream>
#include <unordered_map>
#include "boost/date_time/posix_time/posix_time.hpp"
using boost::property_tree::ptree;
namespace pt = boost::property_tree;
using namespace boost::gregorian;
using namespace boost::posix_time;
// empty ptree helper
const pt::ptree& empty_ptree()
{
static pt::ptree t;
return t;
}
double my_stod(const std::string &valueAsString) {
std::istringstream totalSString( valueAsString );
double valueAsDouble;
// maybe use some manipulators
totalSString >> valueAsDouble;
if(!totalSString)
throw std::runtime_error("Error converting to double");
return valueAsDouble;
}
struct stats {
stats() : stocks(0), profit(0), lastPrice(0), commision(0) {
}
int stocks;
double profit;
double lastPrice;
double commision;
};
std::unordered_map<std::string, stats> ticker2stats;
std::unordered_map<std::string, std::vector<stats>> ticker2AllStats;
std::unordered_map<std::string, date> ticker2lastDealDate;
double totalSpotCommision = 0;
double totalFortsCommision = 0;
boost::property_tree::ptree pt_spot;
boost::property_tree::ptree pt_forts;
// "from" - including
// "to" - excluding
// so if from == to - nothing
void finishSecurityStats(std::string& security_name, date& from, date& to)
{
day_iterator dayIt(from);
if (dayIt > to) {
std::cout << "Error, dayIt > to, exiting! " << to_simple_string(*dayIt) << " > " << to << std::endl;
exit(0);
}
std::vector<stats>& allStats = ticker2AllStats[security_name];
while (dayIt < to) {
stats statsCopy = ticker2stats[security_name];
allStats.push_back(statsCopy);
// std::cout << "finish stats for " << security_name << " date = " << to_simple_string(*dayIt) << std::endl;
++dayIt;
// std::cout << "check!! new dayIt " << to_simple_string(*dayIt) << " collection = " << ticker2lastDealDate[security_name] << std::endl;
}
}
date parseDate(const std::string& s) {
std::stringstream myStream(s);
int year;
int month;
int day;
// 2014-01-01T00:00:00
myStream >> year; myStream.ignore();
myStream >> month; myStream.ignore();
myStream >> day; myStream.ignore();
return date(year, month, day);
}
//////////////////////////////////////////////////////////////////////////////
// ovazhnev@gmail.com
//
// В личном кабинете открытия я выбираю конкретный счёт и субсчёт,
// работает ли на "все счета" не проверял
//
// parameters: t+n report file name, forts report filename
// Example:
// OpenBrokerReportAnalyzer.exe broker_report_20140101_20140219_t_n.xml broker_report_20140101_20140219_forts.xml
// TODO: по каждому дню по каждой акции надо сохранять изменение закрытие к открытию
// чтобы понять резки заработки из за того что хорошо наторговал или из за того что в позиции завис
int main(int argc, char* argv[])
{
using namespace boost::gregorian;
using namespace boost::posix_time;
setlocale(LC_ALL, "Russian");
const int nGroups = 3;
const int groupSize = 3;
std::string groups[nGroups][groupSize] =
{
{"LKOH-6.14", "LKOH-9.14", "LKOH-12.14"}, {"RTS-6.14", "RTS-9.14", "RTS-12.14"}, {"SBRF-6.14", "SBRF-9.14", "SBRF-12.14"}
};
boost::property_tree::xml_parser::read_xml(argv[1], pt_spot);
boost::property_tree::xml_parser::read_xml(argv[2], pt_forts);
date date_from;
date date_to;
totalSpotCommision = 0;
totalFortsCommision = 0;
for (auto const& rootNode : pt_spot)
{
const pt::ptree& rootAttributes = rootNode.second.get_child("<xmlattr>", empty_ptree());
for (auto const& rootAttr : rootAttributes) {
const std::string& attrName = rootAttr.first;
const std::string& attrVal = rootAttr.second.data();
// std::cout << attrName << " = " << attrVal << std::endl;
if (attrName == "date_from") {
date_from = parseDate(attrVal);
}
if (attrName == "date_to") {
date_to = parseDate(attrVal);
}
}
for (auto const& rootNode2 : rootNode.second)
{
if (rootNode2.first == "spot_main_deals_conclusion") {
for (auto const& itemNode : rootNode2.second) {
const pt::ptree& dealAttributes = itemNode.second.get_child("<xmlattr>", empty_ptree());
std::string security_name;
int stocks;
double price;
double broker_commission;
date dealDate;
bool skipItem = false;
for (auto const& dealAttr : dealAttributes)
{
const std::string& attrName = dealAttr.first;
const std::string& attrVal = dealAttr.second.data();
// std::cout << attrName << " = " << attrVal << std::endl;
if (attrName == "security_name") {
security_name = attrVal;
}
if (attrName == "buy_qnty") {
stocks = stoi(attrVal);
}
if (attrName == "sell_qnty") {
stocks = -stoi(attrVal);
}
if (attrName == "price") {
// price = std::stod(attrVal);
price = my_stod(attrVal);
// std::cout << "price converted! " << price << " " << attrVal << std::endl;
}
if (attrName == "broker_commission") {
//broker_commission = std::stod(attrVal);
broker_commission = my_stod(attrVal);
// std::cout << "broker_commission converted! " << broker_commission << " " << attrVal << std::endl;
}
if (attrName == "conclusion_date") {
dealDate = parseDate(attrVal);
}
if (attrName == "comment") {
// не надо анализировать
// comment="РПС, перенос позиции
if (attrVal.length() > 0) {
skipItem = true;
break;
}
}
}
if (skipItem) {
continue;
}
// std::cout << std::endl;
// std::cout << security_name << " " << stocks << " " << price << " " << broker_commission << " " << dealDate << std::endl << std::endl;
// need finish security stats before updating stats
// for example if old deal from 18 Jan and new deal from 19 Jan
// we should first store stats for 18 Jan and then count deal for 19 Jan
auto lastDealDateIt = ticker2lastDealDate.find(security_name);
if (lastDealDateIt == ticker2lastDealDate.end()) {
finishSecurityStats(security_name, date_from, dealDate);
ticker2lastDealDate[security_name] = dealDate;
} else {
date lastDealDate = lastDealDateIt->second;
finishSecurityStats(security_name, lastDealDate, dealDate);
ticker2lastDealDate[security_name] = dealDate;
}
stats& stats = ticker2stats[security_name];
stats.stocks += stocks;
stats.profit += -stocks * price - broker_commission;
stats.lastPrice = price;
stats.commision += broker_commission;
totalSpotCommision += broker_commission;
/*std::cout << security_name << " stats stocks = " << stats.stocks << " stats.profit = "
<< stats.profit << " stats.lastPrice = " << stats.lastPrice << " stats.commision = " << stats.commision << std::endl;*/
}
}
}
}
for (auto const& rootNode : pt_forts)
{
for (auto const& rootNode2 : rootNode.second)
{
if (rootNode2.first == "common_deal") {
for (auto const& itemNode : rootNode2.second) {
const pt::ptree& dealAttributes = itemNode.second.get_child("<xmlattr>", empty_ptree());
std::string security_name;
int stocks;
double price;
double commission;
date dealDate;
for (auto const& dealAttr : dealAttributes)
{
const std::string& attrName = dealAttr.first;
const std::string& attrVal = dealAttr.second.data();
// std::cout << attrName << " = " << attrVal << std::endl;
if (attrName == "security_code") {
security_name = attrVal;
}
if (attrName == "quantity") {
stocks = stoi(attrVal);
}
if (attrName == "deal_symbol") {
// полагаем что в репорте поле deal_symbol идёт после quantity
if (stocks == 0) {
std::cout << "Error stocks = 0!" << std::endl;
return 0;
}
if (attrVal[0] == 'S') {
stocks = -stocks;
}
}
if (attrName == "price_rur") {
price = my_stod(attrVal);
}
if (attrName == "comm_stock") {
commission = my_stod(attrVal);
}
if (attrName == "deal_date") {
dealDate = parseDate(attrVal);
}
}
// std::cout << security_name << " " << stocks << " " << price << " " << commission << " " << dealDate << std::endl << std::endl;
// небольшой хак. возможно чё-то попало с вечерки предыдущего дня
// просто считаем что эти сделки прошли в date_from
if (dealDate < date_from) {
dealDate = date_from;
}
auto lastDealDateIt = ticker2lastDealDate.find(security_name);
if (lastDealDateIt == ticker2lastDealDate.end()) {
finishSecurityStats(security_name, date_from, dealDate);
ticker2lastDealDate[security_name] = dealDate;
} else {
date lastDealDate = lastDealDateIt->second;
finishSecurityStats(security_name, lastDealDate, dealDate);
ticker2lastDealDate[security_name] = dealDate;
}
stats& stats = ticker2stats[security_name];
stats.stocks += stocks;
stats.profit += -stocks * price - commission;
stats.lastPrice = price;
stats.commision += commission;
totalFortsCommision += commission;
/*std::cout << security_name << " stats stocks = " << stats.stocks << " stats.profit = "
<< stats.profit << " stats.lastPrice = " << stats.lastPrice << " stats.commision = " << stats.commision << std::endl;*/
}
}
}
}
// не по всем инструментам в последний день были сделки
// но статистику нам надо построить по всем инструментам по всем дням
// так что завершаем построение статистики
for (auto value : ticker2stats) {
std::string security_name = value.first;
auto lastDealDateIt = ticker2lastDealDate.find(security_name);
if (lastDealDateIt == ticker2lastDealDate.end()) {
finishSecurityStats(security_name, date_from, date_to + days(1));
//ticker2lastDealDate[security_name] = date_to;
} else {
date lastDealDate = lastDealDateIt->second;
finishSecurityStats(security_name, lastDealDate, date_to + days(1));
//ticker2lastDealDate[security_name] = date_to;
}
}
// печатаем суммарную статистику по дням
day_iterator dayIt(date_from);
int n = 0;
while (dayIt <= date_to) {
std::cout << to_simple_string(*dayIt) << " " << dayIt->day_of_week() << " ";
double sumProfit = 0;
double sumCom = 0;
for (auto value : ticker2stats) {
std::string security_name = value.first;
std::vector<stats>& allStats = ticker2AllStats[security_name];
stats& curStats = allStats[n];
double profit = curStats.profit + curStats.lastPrice * curStats.stocks;
/*if (dayIt == date_to) {
std::cout << security_name << " profit = " << curStats.profit <<
" lastPrice = " << curStats.lastPrice << " stocks = " << curStats.stocks << std::endl;
}*/
/*std::cout << std::fixed << std::setw(15) << security_name << " " << std::setw(15) <<
profit << std::setw(15) << allStats[n].commision << std::endl;*/
sumProfit += profit;
sumCom += curStats.commision;
}
std::cout << std::fixed << std::setprecision(2) << " Profit: " << sumProfit
<< " Commission: " << sumCom << " n = " << n << std::endl;
++dayIt; ++n;
}
for (int groupNumber = 0; groupNumber < nGroups; ++groupNumber) {
day_iterator dayIt(date_from);
int n = 0;
while (dayIt <= date_to) {
std::cout << to_simple_string(*dayIt);
double sumProfit = 0;
double sumCom = 0;
for (int j = 0; j < groupSize; ++j) {
std::string& security_name = groups[groupNumber][j];
std::cout << std::fixed << std::setw(12) << security_name;
auto allStatsIt = ticker2AllStats.find(security_name);
if (allStatsIt == ticker2AllStats.end()) {
continue;
}
std::vector<stats>& allStats = allStatsIt->second;
stats& curStats = allStats[n];
double profit = curStats.profit + curStats.lastPrice * curStats.stocks;
sumProfit += profit;
sumCom += curStats.commision;
}
std::cout << std::setprecision(2) << " Prft: " << sumProfit
<< " Comm.: " << sumCom << std::endl;
++dayIt; ++n;
}
}
//// combined profit by group
for (int groupNumber = 0; groupNumber < nGroups; ++groupNumber) {
double profit = 0;
double commision = 0;
std::cout << std::setw(2) << groupNumber << " ";
for (int j = 0; j < groupSize; ++j) {
std::string& ticker = groups[groupNumber][j];
std::cout << std::fixed << std::setw(12) << ticker;
auto got = ticker2stats.find(ticker);
if (got == ticker2stats.end()) {
//std::cout << std::endl << ticker << " skipped, not found." << std::endl << std::endl;
std::cout << "$";
continue;
}
stats& stats = got->second;
if (stats.profit == 0) {
std::cout << "stats.profit == 0! ticker = " << ticker << std::endl;
}
profit += stats.profit + stats.lastPrice * stats.stocks;
commision += stats.commision;
}
std::cout << std::setw(12) << profit << std::setw(12) << commision << std::endl;
}
// печатаем суммарную статистику за последний день
std::cout << std::endl << std::fixed << std::setw(20) << "Security name" << std::setw(20) <<
"Profit > 0 good!" << std::setw(20) << "Commission" << std::endl << std::endl;
double totalProfit = 0;
for (auto value : ticker2stats) {
double profit = value.second.profit + value.second.lastPrice * value.second.stocks;
std::cout << std::fixed << std::setw(20) << value.first << " " << std::setw(20) <<
profit << std::setw(20) << value.second.commision << std::endl;
totalProfit += profit;
}
std::cout << std::endl << std::setprecision(2) << "Total profit: " << totalProfit
<< " Spot commision: " << totalSpotCommision << " Forts commision: "
<< totalFortsCommision << std::endl << std::endl;
return 0;
}
| [
"ovazhnev@gmail.com"
] | ovazhnev@gmail.com |
bbb56cd606ea595bbf904abfc10ed8e8d5e7f8b0 | 6a69d57c782e0b1b993e876ad4ca2927a5f2e863 | /vendor/samsung/common/packages/apps/SBrowser/src/ash/wm/default_state.cc | 14c4b3860fffa73dc3b42467278775b647bd453e | [
"BSD-3-Clause"
] | permissive | duki994/G900H-Platform-XXU1BOA7 | c8411ef51f5f01defa96b3381f15ea741aa5bce2 | 4f9307e6ef21893c9a791c96a500dfad36e3b202 | refs/heads/master | 2020-05-16T20:57:07.585212 | 2015-05-11T11:03:16 | 2015-05-11T11:03:16 | 35,418,464 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 13,053 | cc | // Copyright 2014 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 "ash/wm/default_state.h"
#include "ash/display/display_controller.h"
#include "ash/screen_util.h"
#include "ash/shell.h"
#include "ash/shell_window_ids.h"
#include "ash/wm/coordinate_conversion.h"
#include "ash/wm/window_animations.h"
#include "ash/wm/window_state.h"
#include "ash/wm/window_state_delegate.h"
#include "ash/wm/window_util.h"
#include "ash/wm/workspace/workspace_window_resizer.h"
#include "ui/aura/client/aura_constants.h"
#include "ui/aura/window.h"
#include "ui/aura/window_delegate.h"
#include "ui/gfx/display.h"
#include "ui/gfx/rect.h"
namespace ash {
namespace wm {
namespace {
bool IsPanel(aura::Window* window) {
return window->parent() &&
window->parent()->id() == internal::kShellWindowId_DockedContainer;
}
gfx::Rect BoundsWithScreenEdgeVisible(
aura::Window* window,
const gfx::Rect& restore_bounds) {
gfx::Rect max_bounds =
ash::ScreenUtil::GetMaximizedWindowBoundsInParent(window);
// If the restore_bounds are more than 1 grid step away from the size the
// window would be when maximized, inset it.
max_bounds.Inset(ash::internal::WorkspaceWindowResizer::kScreenEdgeInset,
ash::internal::WorkspaceWindowResizer::kScreenEdgeInset);
if (restore_bounds.Contains(max_bounds))
return max_bounds;
return restore_bounds;
}
void MoveToDisplayForRestore(WindowState* window_state) {
if (!window_state->HasRestoreBounds())
return;
const gfx::Rect& restore_bounds = window_state->GetRestoreBoundsInScreen();
// Move only if the restore bounds is outside of
// the display. There is no information about in which
// display it should be restored, so this is best guess.
// TODO(oshima): Restore information should contain the
// work area information like WindowResizer does for the
// last window location.
gfx::Rect display_area = Shell::GetScreen()->GetDisplayNearestWindow(
window_state->window()).bounds();
if (!display_area.Intersects(restore_bounds)) {
const gfx::Display& display =
Shell::GetScreen()->GetDisplayMatching(restore_bounds);
DisplayController* display_controller =
Shell::GetInstance()->display_controller();
aura::Window* new_root =
display_controller->GetRootWindowForDisplayId(display.id());
if (new_root != window_state->window()->GetRootWindow()) {
aura::Window* new_container =
Shell::GetContainer(new_root, window_state->window()->parent()->id());
new_container->AddChild(window_state->window());
}
}
}
} // namespace;
DefaultState::DefaultState() {}
DefaultState::~DefaultState() {}
void DefaultState::OnWMEvent(WindowState* window_state,
WMEvent event) {
if (ProcessCompoundEvents(window_state, event))
return;
WindowShowType next_show_type = SHOW_TYPE_NORMAL;
switch (event) {
case NORMAL:
next_show_type = SHOW_TYPE_NORMAL;
break;
case MAXIMIZE:
next_show_type = SHOW_TYPE_MAXIMIZED;
break;
case MINIMIZE:
next_show_type = SHOW_TYPE_MINIMIZED;
break;
case FULLSCREEN:
next_show_type = SHOW_TYPE_FULLSCREEN;
break;
case SNAP_LEFT:
next_show_type = SHOW_TYPE_LEFT_SNAPPED;
break;
case SNAP_RIGHT:
next_show_type = SHOW_TYPE_RIGHT_SNAPPED;
break;
case SHOW_INACTIVE:
next_show_type = SHOW_TYPE_INACTIVE;
break;
case TOGGLE_MAXIMIZE_CAPTION:
case TOGGLE_MAXIMIZE:
case TOGGLE_VERTICAL_MAXIMIZE:
case TOGGLE_HORIZONTAL_MAXIMIZE:
case TOGGLE_FULLSCREEN:
NOTREACHED() << "Compound event should not reach here:" << event;
return;
}
WindowShowType current = window_state->window_show_type();
if (current != next_show_type) {
window_state->UpdateWindowShowType(next_show_type);
window_state->NotifyPreShowTypeChange(current);
// TODO(oshima): Make docked window a state.
if (!window_state->IsDocked() && !IsPanel(window_state->window()))
UpdateBoundsFromShowType(window_state, current);
window_state->NotifyPostShowTypeChange(current);
}
};
// static
bool DefaultState::ProcessCompoundEvents(WindowState* window_state,
WMEvent event) {
aura::Window* window = window_state->window();
switch (event) {
case TOGGLE_MAXIMIZE_CAPTION:
if (window_state->IsFullscreen()) {
window_state->ToggleFullscreen();
} else if (window_state->IsMaximized()) {
window_state->Restore();
} else if (window_state->IsNormalShowType() ||
window_state->IsSnapped()) {
if (window_state->CanMaximize())
window_state->Maximize();
}
return true;
case TOGGLE_MAXIMIZE:
if (window_state->IsFullscreen())
window_state->ToggleFullscreen();
else if (window_state->IsMaximized())
window_state->Restore();
else if (window_state->CanMaximize())
window_state->Maximize();
return true;
case TOGGLE_VERTICAL_MAXIMIZE: {
gfx::Rect work_area =
ScreenUtil::GetDisplayWorkAreaBoundsInParent(window);
// Maximize vertically if:
// - The window does not have a max height defined.
// - The window has the normal show type. Snapped windows are excluded
// because they are already maximized vertically and reverting to the
// restored bounds looks weird.
if (window->delegate()->GetMaximumSize().height() != 0 ||
!window_state->IsNormalShowType()) {
return true;
}
if (window_state->HasRestoreBounds() &&
(window->bounds().height() == work_area.height() &&
window->bounds().y() == work_area.y())) {
window_state->SetAndClearRestoreBounds();
} else {
window_state->SaveCurrentBoundsForRestore();
window->SetBounds(gfx::Rect(window->bounds().x(),
work_area.y(),
window->bounds().width(),
work_area.height()));
}
return true;
}
case TOGGLE_HORIZONTAL_MAXIMIZE: {
// Maximize horizontally if:
// - The window does not have a max width defined.
// - The window is snapped or has the normal show type.
if (window->delegate()->GetMaximumSize().width() != 0)
return true;
if (!window_state->IsNormalShowType() && !window_state->IsSnapped())
return true;
gfx::Rect work_area =
ScreenUtil::GetDisplayWorkAreaBoundsInParent(window);
if (window_state->IsNormalShowType() &&
window_state->HasRestoreBounds() &&
(window->bounds().width() == work_area.width() &&
window->bounds().x() == work_area.x())) {
window_state->SetAndClearRestoreBounds();
} else {
gfx::Rect new_bounds(work_area.x(),
window->bounds().y(),
work_area.width(),
window->bounds().height());
gfx::Rect restore_bounds = window->bounds();
if (window_state->IsSnapped()) {
window_state->SetRestoreBoundsInParent(new_bounds);
window_state->Restore();
// The restore logic prevents a window from being restored to bounds
// which match the workspace bounds exactly so it is necessary to set
// the bounds again below.
}
window_state->SetRestoreBoundsInParent(restore_bounds);
window->SetBounds(new_bounds);
}
return true;
}
case TOGGLE_FULLSCREEN: {
// Window which cannot be maximized should not be fullscreened.
// It can, however, be restored if it was fullscreened.
bool is_fullscreen = window_state->IsFullscreen();
if (!is_fullscreen && !window_state->CanMaximize())
return true;
if (window_state->delegate() &&
window_state->delegate()->ToggleFullscreen(window_state)) {
return true;
}
if (is_fullscreen) {
window_state->Restore();
} else {
//
window_state->window()->SetProperty(aura::client::kShowStateKey,
ui::SHOW_STATE_FULLSCREEN);
}
return true;
}
case NORMAL:
case MAXIMIZE:
case MINIMIZE:
case FULLSCREEN:
case SNAP_LEFT:
case SNAP_RIGHT:
case SHOW_INACTIVE:
break;
}
return false;
}
// static
void DefaultState::UpdateBoundsFromShowType(WindowState* window_state,
WindowShowType old_show_type) {
aura::Window* window = window_state->window();
// Do nothing If this is not yet added to the container.
if (!window->parent())
return;
if (old_show_type != SHOW_TYPE_MINIMIZED &&
!window_state->HasRestoreBounds() &&
window_state->IsMaximizedOrFullscreen() &&
!IsMaximizedOrFullscreenWindowShowType(old_show_type)) {
window_state->SaveCurrentBoundsForRestore();
}
// When restoring from a minimized state, we want to restore to the previous
// bounds. However, we want to maintain the restore bounds. (The restore
// bounds are set if a user maximized the window in one axis by double
// clicking the window border for example).
gfx::Rect restore;
if (old_show_type == SHOW_TYPE_MINIMIZED &&
window_state->IsNormalShowState() &&
window_state->HasRestoreBounds() &&
!window_state->unminimize_to_restore_bounds()) {
restore = window_state->GetRestoreBoundsInScreen();
window_state->SaveCurrentBoundsForRestore();
}
if (window_state->IsMaximizedOrFullscreen())
MoveToDisplayForRestore(window_state);
WindowShowType show_type = window_state->window_show_type();
gfx::Rect bounds_in_parent;
switch (show_type) {
case SHOW_TYPE_DEFAULT:
case SHOW_TYPE_NORMAL:
case SHOW_TYPE_LEFT_SNAPPED:
case SHOW_TYPE_RIGHT_SNAPPED: {
gfx::Rect work_area_in_parent =
ScreenUtil::GetDisplayWorkAreaBoundsInParent(window_state->window());
if (window_state->HasRestoreBounds())
bounds_in_parent = window_state->GetRestoreBoundsInParent();
else
bounds_in_parent = window->bounds();
// Make sure that part of the window is always visible.
AdjustBoundsToEnsureMinimumWindowVisibility(
work_area_in_parent, &bounds_in_parent);
if (show_type == SHOW_TYPE_LEFT_SNAPPED ||
show_type == SHOW_TYPE_RIGHT_SNAPPED) {
window_state->AdjustSnappedBounds(&bounds_in_parent);
} else {
bounds_in_parent = BoundsWithScreenEdgeVisible(
window,
bounds_in_parent);
}
break;
}
case SHOW_TYPE_MAXIMIZED:
bounds_in_parent = ScreenUtil::GetMaximizedWindowBoundsInParent(window);
break;
case SHOW_TYPE_FULLSCREEN:
bounds_in_parent = ScreenUtil::GetDisplayBoundsInParent(window);
break;
case SHOW_TYPE_MINIMIZED:
break;
case SHOW_TYPE_INACTIVE:
case SHOW_TYPE_DETACHED:
case SHOW_TYPE_END:
case SHOW_TYPE_AUTO_POSITIONED:
return;
}
if (show_type != SHOW_TYPE_MINIMIZED) {
if (old_show_type == SHOW_TYPE_MINIMIZED ||
(window_state->IsFullscreen() &&
!window_state->animate_to_fullscreen())) {
window_state->SetBoundsDirect(bounds_in_parent);
} else if (window_state->IsMaximizedOrFullscreen() ||
IsMaximizedOrFullscreenWindowShowType(old_show_type)) {
CrossFadeToBounds(window, bounds_in_parent);
} else {
window_state->SetBoundsDirectAnimated(bounds_in_parent);
}
}
if (window_state->IsMinimized()) {
// Save the previous show state so that we can correctly restore it.
window_state->window()->SetProperty(aura::client::kRestoreShowStateKey,
ToWindowShowState(old_show_type));
views::corewm::SetWindowVisibilityAnimationType(
window_state->window(), WINDOW_VISIBILITY_ANIMATION_TYPE_MINIMIZE);
// Hide the window.
window_state->window()->Hide();
// Activate another window.
if (window_state->IsActive())
window_state->Deactivate();
} else if ((window_state->window()->TargetVisibility() ||
old_show_type == SHOW_TYPE_MINIMIZED) &&
!window_state->window()->layer()->visible()) {
// The layer may be hidden if the window was previously minimized. Make
// sure it's visible.
window_state->window()->Show();
if (old_show_type == SHOW_TYPE_MINIMIZED &&
!window_state->IsMaximizedOrFullscreen()) {
window_state->set_unminimize_to_restore_bounds(false);
}
}
if (window_state->IsNormalShowState())
window_state->ClearRestoreBounds();
// Set the restore rectangle to the previously set restore rectangle.
if (!restore.IsEmpty())
window_state->SetRestoreBoundsInScreen(restore);
}
} // namespace wm
} // namespace ash
| [
"duki994@gmail.com"
] | duki994@gmail.com |
58388bde95bef2a516adbb6af2da5f93cf4fae2e | b7a6e1ce9f58bb0f267dcbd679c9965b4fccf839 | /AMP_01/ampsLib/GUI/ampsWidgetFolderView - bak1.cpp | f1d95bdd0c9f9152fd58ef5b12dde94ba0553e10 | [] | no_license | qcheekwa/Projects | d9f64c303b345a98d05aee26473ce5eabea8f149 | 19ce9b0f9d36ffa26fc7522d6f1fb578208cb943 | refs/heads/master | 2021-01-02T08:33:50.689265 | 2014-05-06T07:27:55 | 2014-05-06T07:27:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,104 | cpp | /*
ampswIDGETFolderView.cpp
*/
#include "ampsWidgetFolderView.h"
/////////////////////////////////////////////////////////////////////////////////
//
// class ampsWidgetFolderView
//
/////////////////////////////////////////////////////////////////////////////////
ampsWidgetFolderView::ampsWidgetFolderView(const QWidget *parent) : MgWidget((QWidget *)parent)
{
m_UI.setupUi(this);
setFocusPolicy(Qt::WheelFocus);
}
ampsWidgetFolderView::~ampsWidgetFolderView()
{
}
/////////////////////////////////////////////////////////////////////////////////
//
// class ampsScrollWidgetFolderView
//
/////////////////////////////////////////////////////////////////////////////////
ampsScrollWidgetFolderView::ampsScrollWidgetFolderView(const QWidget *parent) : MgScrollArea((QWidget *)parent)
{
m_WidgetFolderView = new ampsWidgetFolderView(this);
setWidget(m_WidgetFolderView);
setFocusPolicy(Qt::WheelFocus);
}
ampsScrollWidgetFolderView::~ampsScrollWidgetFolderView()
{
}
/////////////////////////////////////////////////////////////////////////////////
//
// class ampsDockWidgetFolderView
//
/////////////////////////////////////////////////////////////////////////////////
ampsDockWidgetFolderView::ampsDockWidgetFolderView(const QWidget *parent) : ampsDockWidgetBase(parent)
{
m_ScrollWidgetFolderView = new ampsScrollWidgetFolderView;
setWidget(m_ScrollWidgetFolderView);
setFocusPolicy(Qt::WheelFocus);
setFeatures(QDockWidget::AllDockWidgetFeatures);
setWindowTitle("Folder View");
Init();
}
ampsDockWidgetFolderView::~ampsDockWidgetFolderView()
{
}
void ampsDockWidgetFolderView::Init(void)
{
m_FolderTreeView = new ampsTreeView;
m_FolderTreeView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_FolderTreeView->setDragEnabled(true);
m_FolderItemView = new ampsTreeView;
m_FolderItemView->setSelectionMode(QAbstractItemView::ExtendedSelection);
m_FolderItemView->setDragEnabled(true);
m_FolderItemView->setRootIsDecorated(false);
m_ScrollWidgetFolderView->m_WidgetFolderView->m_UI.m_scrollAreaTreeView->setWidget(m_FolderTreeView);
} | [
"quah_ck@pmail.ntu.edu.sg"
] | quah_ck@pmail.ntu.edu.sg |
a45866959f97141ac20aec7fe92552bf0f9fae6a | 3c1a424b7e71e203ce987f752dfa91af36114b89 | /src/firestorm_mock.cpp | 741ab7f6061fa53533faec96e7f6a6b8f787c229 | [
"MIT"
] | permissive | hugglesfox/firestorm | 007663328d6787f7f0f4c54ff09de7d578cd6288 | 46685ca3416af3326916653efe4e511e94c92ace | refs/heads/master | 2022-12-27T01:24:52.795585 | 2020-10-03T02:40:27 | 2020-10-03T02:40:27 | 291,934,593 | 4 | 0 | MIT | 2020-09-26T10:50:53 | 2020-09-01T07:58:56 | C++ | UTF-8 | C++ | false | false | 1,018 | cpp | #include "firestorm_mock.h"
MockRequest MockRequest::add_header(string header) {
request.headers.push_back(header);
return *this;
}
MockRequest MockRequest::add_cookie(Cookie cookie) {
cookies.push_back(cookie);
return *this;
}
MockRequest MockRequest::body(string body) {
request.body = body;
return *this;
};
MockRequest MockRequest::body(json body) {
request.body = json_to_string(body);
return *this;
}
MockRequest MockRequest::method(http_method method) {
request.method = method;
return *this;
}
MockRequest MockRequest::uri(string uri) {
request.uri = uri;
request.query_string = split_at_first(uri, '?').back();
return *this;
}
// Construct a http_request from a MockRequest
_http_request_data MockRequest::construct() {
if (cookies.size() > 0) {
string header = "Cookie: ";
for (Cookie cookie : cookies) {
header += cookie.name + "=" + cookie.value + "; ";
}
request.headers.push_back(header.substr(0, header.length() - 2));
}
return request;
}
| [
"hayley@foxes.systems"
] | hayley@foxes.systems |
1668935de36b0f5878c7ff2eef2820461e833a4c | e870a980c4b10dcd26f5456b23d5d62490b6281f | /Chapter 5/source/nestedcl.cpp | cc1218fe5caf7b29d018018cbcd08e5e77e9addf | [] | no_license | Jack-lss/C-_Primer_Plus | 041d464d5523bb5645de177d90fe5565bd71fc7d | 3daa6657f316bfbf5747810900a7fa5bf32ebed3 | refs/heads/master | 2022-11-27T22:10:58.062919 | 2020-08-11T14:09:53 | 2020-08-11T14:09:53 | 277,744,103 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | // nested.cpp -- nested loops and 2-D array
#include <iostream>
#include <string>
#include <array>
const int Cities = 5;
const int Years = 4;
int main()
{
using namespace std;
const string cities[Cities] = // array of pointers
{ // to 5 strings
"Gribble City",
"Gribbletown",
"New Gribble",
"San Gribble",
"Gribble Vista"};
array<array<int, Cities>, Years> maxtemps =
/* int maxtemps[Years][Cities] = // 2-D array */
{
96, 100, 87, 101, 105, // values for maxtemps[0]
96, 98, 91, 107, 104, // values for maxtemps[1]
97, 101, 93, 108, 107, // values for maxtemps[2]
98, 103, 95, 109, 108 // values for maxtemps[3]
};
cout << "Maximum temperatures for 2008 - 2011\n\n";
for (int city = 0; city < Cities; ++city)
{
cout << cities[city] << ":\t";
for (int year = 0; year < Years; ++year)
cout << maxtemps[year][city] << "\t";
cout << endl;
}
// cin.get();
system("pause");
return 0;
}
| [
"1349916452@qq.com"
] | 1349916452@qq.com |
d847624cb41251bd40941fce4532a0224b92beff | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/httpd/gumtree/httpd_new_log_3618.cpp | d2da263c04807329428fb038d090de75a720a04a | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 165 | cpp | ap_log_rerror(APLOG_MARK, APLOG_ERR, 0, r, APLOGNO(00604)
"The request body does not contain "
"an \"update\" element."); | [
"993273596@qq.com"
] | 993273596@qq.com |
c9712e6b6299150b4ef2098bb1933ee117636c10 | 52482fb96fe7f3eed874db7a88c889ecd5bc34c5 | /src/MuleCtrlItem.h | 4117bd37275fbebd0acb3e276db31f4494f34d51 | [] | no_license | rusingineer/EmulePlus | f3e29ca7ca853feea920c4cb5ffb0d0a13ed236e | 21955cd94d28cebdb3cf9c289f0aafa7a5cf3744 | refs/heads/master | 2021-01-17T11:54:26.925858 | 2016-06-20T12:22:32 | 2016-06-20T12:22:32 | 61,430,884 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,001 | h | //this file is part of eMule
//Copyright (C)2002 Merkur ( merkur-@users.sourceforge.net / http://www.emule-project.net )
//
//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 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
//GNU 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#pragma once
#pragma warning(push)
#pragma warning(disable:4702) // unreachable code
#include <map>
#include <vector>
#pragma warning(pop)
class CPartFile;
class CUpDownClient;
class CMuleCtrlItem
{
private:
DWORD m_dwUpdateTimer;
CBitmap m_bmpStatus;
bool m_bIsVisible;
public:
// Constructor
CMuleCtrlItem()
: m_dwUpdateTimer(0), m_bIsVisible(false) {}
virtual ~CMuleCtrlItem()
{ m_bmpStatus.DeleteObject(); }
// Accessors
DWORD GetUpdateTimer() const { return m_dwUpdateTimer; }
CBitmap &GetBitmap() { return m_bmpStatus; }
virtual CPartFile *GetFile() const = 0;
bool IsVisible() const { return m_bIsVisible; }
virtual void SetVisibility(bool bIsVisible) { m_bIsVisible = bIsVisible; }
// General methods
virtual void SetUpdateTimer(DWORD dwUpdate) { m_dwUpdateTimer = dwUpdate; }
virtual void ResetUpdateTimer() { m_dwUpdateTimer = 0; }
};
class CPartFileDLItem;
class CSourceDLItem : public CMuleCtrlItem
{
public:
CPartFileDLItem *m_pParentFileItem;
private:
CUpDownClient *m_pSource;
bool m_bIsAvailable;
CPartFile *m_pParentFile;
CPartFile *GetFile() const { return m_pParentFile; }
public:
CSourceDLItem(CUpDownClient *pSource,CPartFile *pParentFile,
CPartFileDLItem *pParentFileItem, bool bIsAvailable = true )
: m_pSource(pSource),m_pParentFile(pParentFile),m_pParentFileItem(pParentFileItem),
m_bIsAvailable(bIsAvailable) {}
~CSourceDLItem();
CUpDownClient* GetSource() const { return m_pSource; }
CPartFile* GetParentFile() const { return m_pParentFile; }
CPartFileDLItem* GetParentFileItem() const { return m_pParentFileItem; }
void SetAvailability(bool bIsAvailable) { m_bIsAvailable = bIsAvailable; }
bool IsAvailable() const { return m_bIsAvailable; }
bool IsAskedForAnotherFile() const;
};
class CPartFileDLItem : public CMuleCtrlItem
{
public:
typedef std::vector<CSourceDLItem*> SourceItemVector;
struct
{
bool m_bSrcsAreVisible;
bool m_bShowUploadingSources : 1;
bool m_bShowOnQueueSources : 1;
bool m_bShowFullQueueSources : 1;
bool m_bShowConnectedSources : 1;
bool m_bShowConnectingSources : 1;
bool m_bShowNNPSources : 1;
bool m_bShowWaitForFileReqSources : 1;
bool m_bShowLowToLowIDSources : 1;
bool m_bShowLowIDOnOtherSrvSources : 1;
bool m_bShowBannedSources : 1;
bool m_bShowErrorSources : 1;
bool m_bShowA4AFSources : 1;
bool m_bShowUnknownSources : 1;
};
private:
typedef map<CUpDownClient*, CSourceDLItem*> DLSourceMap;
typedef DLSourceMap::iterator SourceIter;
typedef pair<SourceIter,SourceIter> SourceRange;
CPartFile *m_pFile;
DLSourceMap m_mapSources;
void RemoveAllSources(void);
public:
CPartFileDLItem(CPartFile *pPartFile);
virtual ~CPartFileDLItem();
CPartFile *GetFile() const { return m_pFile; }
CSourceDLItem* CreateSourceItem(CUpDownClient *pSource,bool bIsAvailable);
bool DeleteSourceItem(CSourceDLItem *pSourceItem);
SourceIter FindSourceItem(CUpDownClient *pSource) { return(m_mapSources.find(pSource)); }
void FilterNoSources();
void FilterAllSources();
SourceItemVector *GetSources();
};
| [
"makani@inbox.ru"
] | makani@inbox.ru |
e5a1dffe5b3031e5ff1c41fda2f02d0e22ca85f0 | 88d330b3fb1e44c024fe39da4d023fc42c5f3f29 | /src/timer.cpp | d11642ad058a224184a38907453351b4cd27c962 | [] | no_license | stadanapisem/OS1 | e37cd37d432340717eddb9f1a8a65262c4d3927b | 4fd1ddbbff0d30bd9ddf96a659e6f09d46b3179a | refs/heads/master | 2021-01-20T11:29:43.102284 | 2016-09-18T10:53:01 | 2016-09-18T10:53:01 | 68,515,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,170 | cpp | #include <dos.h>
#include <stdio.h>
#include <iostream.h>
#include "pcb.h"
#include "scheduler.h"
#include "pcblist.h"
#include "semlist.h"
static unsigned oldTimerSEG, oldTimerOFF;
volatile unsigned TimeSlice;
static unsigned tsp, tss, tbp;
extern PCB * idle;
extern void tick();
void interrupt timer() {
//printf("%d %u %d\n", List.Empty(), Running->ID, Running->Status == BLOCKED);
if( !context_switch_request && !Running->Unlimited ) {
TimeSlice--;
}
if( !context_switch_request ) {
tick();
asm int 60h
}
if( !context_switch_request )
SemaphoreList.unblock();
if( ( (!TimeSlice && !Running->Unlimited) || context_switch_request) ) {
if( !lockFlag ) {
context_switch_request = 0;
asm {
mov tsp, sp
mov tss, ss
mov tbp, bp
}
Running->SS = tss;
Running->SP = tsp;
Running->BP = tbp;
if( Running->Status != IDLE && Running->Status != FINISHED && Running->Status != BLOCKED ) { // IF NOT IDLE, FINISHED, BLOCKED
Scheduler::put( (PCB*) Running);
Running->Status = READY;
}
Running = Scheduler::get();
if( Running )
Running->Status = RUNNING;
else if( !Running && !List.Empty() )
Running = idle;
tsp = Running->SP;
tss = Running->SS;
tbp = Running->BP;
TimeSlice = Running->timeSlice;
asm {
mov sp, tsp
mov ss, tss
mov bp, tbp
}
} else
context_switch_request = 1;
}
}
void InitializeTimer() {
LOCK
asm {
push es
push ax
mov ax, 0
mov es, ax
mov ax, word ptr es:0022h
mov word ptr oldTimerSEG, ax
mov ax, word ptr es:0020h
mov word ptr oldTimerOFF, ax
mov word ptr es:0022h, seg timer
mov word ptr es:0020h, offset timer
mov ax, oldTimerSEG
mov word ptr es:0182h, ax
mov ax, oldTimerOFF
mov word ptr es:0180h, ax
pop ax
pop es
}
UNLOCK
}
void RestoreTimer() {
LOCK
asm {
push es
push ax
mov ax, 0
mov es, ax
mov ax, word ptr oldTimerSEG
mov word ptr es:0022h, ax
mov ax, word ptr oldTimerOFF
mov word ptr es:0020h, ax
pop ax
pop es
}
UNLOCK
}
| [
"mitrovm@gmail.com"
] | mitrovm@gmail.com |
dd76a14339e7f4be6be8c7b9f9da0c3e8494a7db | 4fbbe06cef365e839d81353942babdbf16c14f49 | /MedicalInformationSystemServer/Tokenizer.h | 19abbe4e273439c65f8fc8b77262a08bdafa4c10 | [] | no_license | GabrielGhimici/MedicalInformationSystem | 1b210dfddee69b9df3fd8ccfff7b688f61131b93 | 4d1c48bb8dd323be8610b3cf553ed630fe3824cf | refs/heads/master | 2020-03-18T22:24:41.267685 | 2018-06-03T15:26:41 | 2018-06-03T15:26:41 | 135,341,277 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 295 | h | #ifndef TOKENIZER_H
#define TOKENIZER_H
#include <windows.h>
#include <iostream>
#include <vector>
namespace MedicalInformationSystemServer {
class Tokenizer
{
public:
Tokenizer();
~Tokenizer();
static std::vector<std::string> tokenize(std::string str, char delimiter);
};
}
#endif
| [
"gabriel.ghimici@teads.tv"
] | gabriel.ghimici@teads.tv |
8e4b0f58dc7a24ba9e4f854fa9a5089ce9520d11 | 2b23944ed854fe8d2b2e60f8c21abf6d1cfd42ac | /HDU/1237/6600208_AC_15ms_1500kB.cpp | 840732a988ffab66ac9780fb7aaf981b930c2369 | [] | no_license | weakmale/hhabb | 9e28b1f2ed34be1ecede5b34dc2d2f62588a5528 | 649f0d2b5796ec10580428d16921879aa380e1f2 | refs/heads/master | 2021-01-01T20:19:08.062232 | 2017-07-30T17:23:21 | 2017-07-30T17:23:21 | 98,811,298 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 916 | cpp | #include<cstdio>
#include<stack>
using namespace std;
int main(){
stack<double>cnt;
double a;
while (scanf("%lf",&a) != EOF)
{
cnt.push(a);
char c = getchar();
if (a == 0 && c == '\n')
{
break;
}
char o;
double b;
while(1){
scanf("%c %lf",&o,&a);
if(o=='+'){
cnt.push(a);
}
else if(o=='-'){
a=-a;
cnt.push(a);
}
else if(o=='*'){
b=cnt.top();
cnt.pop();
b*=a;
cnt.push(b);
}
else if(o=='/'){
b=cnt.top();
cnt.pop();
b/=a;
cnt.push(b);
}
if (getchar() == '\n')
{
break;
}
}
double sum=0;
while(!cnt.empty()){
a=cnt.top();
sum+=a;
cnt.pop();
}
printf("%.2lf\n",sum);
}
return 0;
} | [
"wuweak@gmail.com"
] | wuweak@gmail.com |
9faec0932b0c9f7f837784ad25e363c77b010e2d | b923489351cf438712ba91dc1ff937b57caa2450 | /lower/linkedList.h | 1d32d8383eddf8b645174eb568e74c7eff24ea5a | [] | no_license | pesiq/0102Lab02 | 20f9a8ad8efae4d7a8055e73c424c9b54755c34e | c259da065d1726f1a090f7f97f2b75d62fda4c36 | refs/heads/master | 2023-05-27T01:39:55.687915 | 2021-06-09T14:27:48 | 2021-06-09T14:27:48 | 370,109,015 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,779 | h | #ifndef LAB02_LINKEDLIST_H
#define LAB02_LINKEDLIST_H
#include <cstdlib>
#include "../exceptions/exceptions.h"
#include <ostream>
template <class T>
class linkedList{
private:
struct item{
T value;
struct item* next;
struct item* previous;
};
int size;
struct item* first;
struct item* last;
public:
//creation
linkedList(T* items, size_t amount); //create linkedList from static array
linkedList(); //create empty linkedList
linkedList(linkedList<T> const &list); // copy existing linkedList
//destruction
~linkedList();
void deleteList();
//decomposition
T getFirst(); //get first element
T getLast(); //get last element
T &get(int index); //get element at index
linkedList<T>& getSublist(size_t start, size_t end); //create linkedList of elements with index start to the element with index end
int length(); //get size of linkedList
//operations
void deleteItem(int index);
void set(T val, int index);
void append(T val); //add to the end
void prepend(T val); //add to the beginning
void insertAt(T val, int index); //add at the index
void concatenate(linkedList<T> list); //concatenate 2 lists
linkedList<T>& operator=(const linkedList<T>& list){
deleteList();
first = list.first;
last = list.last;
size= list.size;
return *this;
}
friend std::ostream &operator<< (std::ostream &temp, linkedList<T> &l1){
struct item *ptr = l1.first;
for (int i = 0; i < l1.size; i++) {
temp<<ptr->value;
if(i != l1.size-1) {
temp << " ";
}
ptr = ptr->next;
}
return temp;
}
};
#endif //LAB02_LINKEDLIST_H
| [
"russlan2002@inbox.ru"
] | russlan2002@inbox.ru |
843cefeb8668336991a585f7ffe11b5cba2263f3 | c8fac11cd88c17f2c8d334569e1bb422cfbaa321 | /WhaleSplash/PathOfExile.h | 5f9270646010f8d8ed18e901d50094a55b926dbf | [] | no_license | dpedigo/WhaleSplash | bf241949d89602a750167ba01159b11466b081c8 | 57df9c5980b47996bb2fc013286bc48058a6c02e | refs/heads/master | 2019-01-01T12:37:22.659429 | 2014-09-19T00:23:10 | 2014-09-19T00:23:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | h | #pragma once
#include "Process.h"
typedef struct _PLAYERHEALTH {
DWORD MaxHP;
DWORD CurHP;
DWORD ReservedHPFlat;
DWORD ReservedHPPercent;
BYTE Unknown1[20];
DWORD MaxMana;
DWORD CurtMana;
DWORD ReservedManaFlat;
DWORD ReservedManaPercent;
BYTE Unknown2[20];
DWORD MaxShield;
DWORD CurShield;
} PLAYERHEALTH;
typedef struct _PLAYEREXP {
DWORD Minimum;
DWORD Current;
DWORD Maximum;
DWORD CurrentLevel;
} PLAYEREXP;
class CPathOfExile : public CProcess
{
private:
static const TCHAR* s_ProcessName;
static const DWORD s_BaseOffset;
static const char* s_BaseMask;
static const BYTE s_BaseSignature[];
static const char* s_MapMask;
static const BYTE s_MapSignature[];
static const DWORD s_ExperienceThresholds[];
protected:
DWORD m_dwModuleSize;
DWORD m_dwModuleAddress;
DWORD m_dwManagerBase;
bool m_bWriteAccess;
public:
CPathOfExile();
~CPathOfExile();
bool Attach(bool bWriteAccess = false);
DWORD GetGameBase();
DWORD GetPlayerBase();
bool IsInGame();
bool GetPlayerHealth(PLAYERHEALTH* health);
bool GetPlayerExp(PLAYEREXP* exp);
bool EnableMapHack(bool bEnable);
}; | [
"dpedigo@gmail.com"
] | dpedigo@gmail.com |
5c8909e737f265689e56d8b49119165fc1229a80 | 524c0f8983fef4c282922a19a9437a320ccd0c45 | /aws-cpp-sdk-transcribe/include/aws/transcribe/model/UpdateCallAnalyticsCategoryRequest.h | dc25262acc7ad70d0a7cc61409df6360303d57a9 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | hardikmdev/aws-sdk-cpp | e79c39ad35433fbf41b3df7a90ac3b7bdb56728b | f34953a3f4cbd327db7c5340fcc140d63ac63e87 | refs/heads/main | 2023-09-06T03:43:07.646588 | 2021-11-16T20:27:23 | 2021-11-16T20:27:23 | 429,030,795 | 0 | 0 | Apache-2.0 | 2021-11-17T12:08:03 | 2021-11-17T12:08:02 | null | UTF-8 | C++ | false | false | 6,824 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/transcribe/TranscribeService_EXPORTS.h>
#include <aws/transcribe/TranscribeServiceRequest.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/transcribe/model/Rule.h>
#include <utility>
namespace Aws
{
namespace TranscribeService
{
namespace Model
{
/**
*/
class AWS_TRANSCRIBESERVICE_API UpdateCallAnalyticsCategoryRequest : public TranscribeServiceRequest
{
public:
UpdateCallAnalyticsCategoryRequest();
// Service request name is the Operation name which will send this request out,
// each operation should has unique request name, so that we can get operation's name from this request.
// Note: this is not true for response, multiple operations may have the same response name,
// so we can not get operation's name from response.
inline virtual const char* GetServiceRequestName() const override { return "UpdateCallAnalyticsCategory"; }
Aws::String SerializePayload() const override;
Aws::Http::HeaderValueCollection GetRequestSpecificHeaders() const override;
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline const Aws::String& GetCategoryName() const{ return m_categoryName; }
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline bool CategoryNameHasBeenSet() const { return m_categoryNameHasBeenSet; }
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline void SetCategoryName(const Aws::String& value) { m_categoryNameHasBeenSet = true; m_categoryName = value; }
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline void SetCategoryName(Aws::String&& value) { m_categoryNameHasBeenSet = true; m_categoryName = std::move(value); }
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline void SetCategoryName(const char* value) { m_categoryNameHasBeenSet = true; m_categoryName.assign(value); }
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline UpdateCallAnalyticsCategoryRequest& WithCategoryName(const Aws::String& value) { SetCategoryName(value); return *this;}
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline UpdateCallAnalyticsCategoryRequest& WithCategoryName(Aws::String&& value) { SetCategoryName(std::move(value)); return *this;}
/**
* <p>The name of the analytics category to update. The name is case sensitive. If
* you try to update a call analytics category with the same name as a previous
* category you will receive a <code>ConflictException</code> error.</p>
*/
inline UpdateCallAnalyticsCategoryRequest& WithCategoryName(const char* value) { SetCategoryName(value); return *this;}
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline const Aws::Vector<Rule>& GetRules() const{ return m_rules; }
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline bool RulesHasBeenSet() const { return m_rulesHasBeenSet; }
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline void SetRules(const Aws::Vector<Rule>& value) { m_rulesHasBeenSet = true; m_rules = value; }
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline void SetRules(Aws::Vector<Rule>&& value) { m_rulesHasBeenSet = true; m_rules = std::move(value); }
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline UpdateCallAnalyticsCategoryRequest& WithRules(const Aws::Vector<Rule>& value) { SetRules(value); return *this;}
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline UpdateCallAnalyticsCategoryRequest& WithRules(Aws::Vector<Rule>&& value) { SetRules(std::move(value)); return *this;}
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline UpdateCallAnalyticsCategoryRequest& AddRules(const Rule& value) { m_rulesHasBeenSet = true; m_rules.push_back(value); return *this; }
/**
* <p>The rules used for the updated analytics category. The rules that you provide
* in this field replace the ones that are currently being used. </p>
*/
inline UpdateCallAnalyticsCategoryRequest& AddRules(Rule&& value) { m_rulesHasBeenSet = true; m_rules.push_back(std::move(value)); return *this; }
private:
Aws::String m_categoryName;
bool m_categoryNameHasBeenSet;
Aws::Vector<Rule> m_rules;
bool m_rulesHasBeenSet;
};
} // namespace Model
} // namespace TranscribeService
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
aadbc577a82ab9568ebe5bedace02ac3d59bedc7 | de3004171247231e5901c8f6c41fafadba1ab813 | /NeteaseDX9HW/ArcAssetLoader.h | c0ee8ce98bf24c746758dfb341a292f6961fae57 | [] | no_license | Arcob/DX11Engine | 2d796b7edf3c03cc9ea4d7e99f0638e2e721ef82 | 8f4418ce5232a91b7c88900cea6d93d555665f6e | refs/heads/master | 2020-12-01T13:41:16.901277 | 2020-04-04T15:03:03 | 2020-04-04T15:03:03 | 230,643,100 | 4 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,235 | h | #pragma once
#include "ArcGraphicSetting.h"
#include "CommonHeaders.h"
#include "ArcTool.h"
#include "ArcStructures.h"
#include "ArcRHI.h"
#include "ArcMesh.h"
#include "ArcTexture.h"
#ifdef USING_DX11_ARC
#include <d3d11.h>
#include <d3dx11.h>
#include <direct.h>
#include "D3DCompiler.h"
#endif // USING_DX11
namespace DX11Engine {
class ArcAssetLoader //跨平台强相关,用于加载shader,texture,mesh等多种资源,加载好的资源存到ArcAsset中
{
public:
//shader
static bool LoadVertexShader(std::string filePath, const char* entry, const char* shaderModel, ID3DBlob **shaderBuffer, ID3D11VertexShader** vertexShader);
static bool LoadPixelShader(std::string filePath, const char* entry, const char* shaderModel, ID3DBlob **shaderBuffer, ID3D11PixelShader **pixelShader);
static bool ConfigInputLayout(D3D11_INPUT_ELEMENT_DESC* inputLayout, unsigned int inputLayoutNum, ID3DBlob **shaderBuffer, ID3D11InputLayout **pInputLayout);
static std::shared_ptr<ArcMesh> LoadMesh(std::string name, void* vertexs, unsigned int nodeLength, unsigned int nodeCount, unsigned int* indices, unsigned int indicesLength, ID3D11InputLayout *pInputLayout);
static std::shared_ptr<ArcMesh> LoadMesh(std::string name, void* vertexs, std::vector<float3>& posVector, unsigned int nodeLength, unsigned int nodeCount, unsigned int* indices, unsigned int indicesLength, ID3D11InputLayout *pInputLayout);
static std::shared_ptr<ArcTexture> LoadTexture(std::string name, std::string path);
static bool CreateConstantBuffer(ID3D11Device* device, D3D11_BUFFER_DESC* description, ID3D11Buffer** constantBuffer);
static void SetTexture(D3D11_SAMPLER_DESC* sampDescription, std::shared_ptr<ArcTexture> texture, unsigned int textureSlot, unsigned int descSlot);
static void SetSamlpler(D3D11_SAMPLER_DESC* sampDescription, unsigned int descSlot);
static std::shared_ptr<ArcMesh> LoadModelFromObj(std::string name, std::string fileName, std::string basePath);
const static std::string SHADER_PATH;
const static std::string TEXTURE_PATH;
const static std::string MODEL_PATH;
private:
static bool CompileD3DShader(std::string filePath, const char* entry, const char* shaderModel, ID3DBlob** buffer);
};
};
| [
"1241994554@qq.com"
] | 1241994554@qq.com |
351a837449bd34e3575a0ba47fd2909e2e311676 | 80d61237e473cb6a94309d2d5602f9e7a49087b3 | /test/executor_test_layout.inc | 168b11d00c8346d2197f9575abd4df03171f4210 | [
"MIT"
] | permissive | prg-titech/ikra-cpp | 046b16d3b2224f487730aa6cb5a8e1469b465b38 | 5b9dc816fe5c63ad1aa7464d3ce9ca612927423d | refs/heads/master | 2021-05-15T13:33:27.444312 | 2018-04-20T12:50:22 | 2018-04-20T12:50:22 | 107,105,651 | 21 | 0 | MIT | 2018-03-27T07:15:49 | 2017-10-16T09:20:36 | Assembly | UTF-8 | C++ | false | false | 476 | inc | class IKRA_TEST_CLASSNAME : public SoaLayout<IKRA_TEST_CLASSNAME,
kClassMaxInst,
IKRA_TEST_ADDRESS_MODE> {
public:
IKRA_INITIALIZE_CLASS
int_ field0;
int_ field1;
IKRA_TEST_CLASSNAME(int a, int b) : field0(a), field1(b) {}
void add_field1_and_a_to_field0(int a) {
field0 += field1 + a;
}
int sum_plus_delta(int delta) {
return field0 + field1 + delta;
}
};
| [
"me@matthiasspringer.de"
] | me@matthiasspringer.de |
4070598f1a0ea2abb3da329079ff5ab8f40581ed | e2400461ad0ee9db8a85a30c811e47d30e16e1c8 | /seleniumtestcases-qa/seleniumtestcases-qa/src/main/resources/firefox/win64/firefox-sdk/include/nsILoginManagerStorage.h | 6040a4884480e26ea78c54b3d0f3590f1b59768d | [] | no_license | pratikcactus/Insights | 720a00187858bbca5b2d8cc36aee23e50c74efbc | 0c3178a50d60ba4c14a07f6515a84f0ce22cdc8e | refs/heads/master | 2021-01-19T14:48:56.139872 | 2018-01-23T07:12:47 | 2018-01-23T07:12:47 | 100,924,200 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,633 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM ../../../dist/idl\nsILoginManagerStorage.idl
*/
#ifndef __gen_nsILoginManagerStorage_h__
#define __gen_nsILoginManagerStorage_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
#include "js/Value.h"
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIFile; /* forward declaration */
class nsILoginInfo; /* forward declaration */
class nsIPropertyBag; /* forward declaration */
/* starting interface: nsILoginManagerStorage */
#define NS_ILOGINMANAGERSTORAGE_IID_STR "5df81a93-25e6-4b45-a696-089479e15c7d"
#define NS_ILOGINMANAGERSTORAGE_IID \
{0x5df81a93, 0x25e6, 0x4b45, \
{ 0xa6, 0x96, 0x08, 0x94, 0x79, 0xe1, 0x5c, 0x7d }}
class NS_NO_VTABLE nsILoginManagerStorage : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ILOGINMANAGERSTORAGE_IID)
/* jsval initialize (); */
NS_IMETHOD Initialize(JS::MutableHandleValue _retval) = 0;
/* jsval terminate (); */
NS_IMETHOD Terminate(JS::MutableHandleValue _retval) = 0;
/* void addLogin (in nsILoginInfo aLogin); */
NS_IMETHOD AddLogin(nsILoginInfo *aLogin) = 0;
/* void removeLogin (in nsILoginInfo aLogin); */
NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) = 0;
/* void modifyLogin (in nsILoginInfo oldLogin, in nsISupports newLoginData); */
NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) = 0;
/* void removeAllLogins (); */
NS_IMETHOD RemoveAllLogins(void) = 0;
/* void getAllLogins ([optional] out unsigned long count, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHOD GetAllLogins(uint32_t *count, nsILoginInfo * **logins) = 0;
/* void searchLogins (out unsigned long count, in nsIPropertyBag matchData, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHOD SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins) = 0;
/* void getAllDisabledHosts ([optional] out unsigned long count, [array, size_is (count), retval] out wstring hostnames); */
NS_IMETHOD GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames) = 0;
/* boolean getLoginSavingEnabled (in AString aHost); */
NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, bool *_retval) = 0;
/* void setLoginSavingEnabled (in AString aHost, in boolean isEnabled); */
NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled) = 0;
/* void findLogins (out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHOD FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins) = 0;
/* unsigned long countLogins (in AString aHostname, in AString aActionURL, in AString aHttpRealm); */
NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval) = 0;
/* readonly attribute boolean uiBusy; */
NS_IMETHOD GetUiBusy(bool *aUiBusy) = 0;
/* readonly attribute boolean isLoggedIn; */
NS_IMETHOD GetIsLoggedIn(bool *aIsLoggedIn) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsILoginManagerStorage, NS_ILOGINMANAGERSTORAGE_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSILOGINMANAGERSTORAGE \
NS_IMETHOD Initialize(JS::MutableHandleValue _retval) override; \
NS_IMETHOD Terminate(JS::MutableHandleValue _retval) override; \
NS_IMETHOD AddLogin(nsILoginInfo *aLogin) override; \
NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) override; \
NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) override; \
NS_IMETHOD RemoveAllLogins(void) override; \
NS_IMETHOD GetAllLogins(uint32_t *count, nsILoginInfo * **logins) override; \
NS_IMETHOD SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins) override; \
NS_IMETHOD GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames) override; \
NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, bool *_retval) override; \
NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled) override; \
NS_IMETHOD FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins) override; \
NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval) override; \
NS_IMETHOD GetUiBusy(bool *aUiBusy) override; \
NS_IMETHOD GetIsLoggedIn(bool *aIsLoggedIn) override;
/* Use this macro when declaring the members of this interface when the
class doesn't implement the interface. This is useful for forwarding. */
#define NS_DECL_NON_VIRTUAL_NSILOGINMANAGERSTORAGE \
NS_METHOD Initialize(JS::MutableHandleValue _retval); \
NS_METHOD Terminate(JS::MutableHandleValue _retval); \
NS_METHOD AddLogin(nsILoginInfo *aLogin); \
NS_METHOD RemoveLogin(nsILoginInfo *aLogin); \
NS_METHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData); \
NS_METHOD RemoveAllLogins(void); \
NS_METHOD GetAllLogins(uint32_t *count, nsILoginInfo * **logins); \
NS_METHOD SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins); \
NS_METHOD GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames); \
NS_METHOD GetLoginSavingEnabled(const nsAString & aHost, bool *_retval); \
NS_METHOD SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled); \
NS_METHOD FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins); \
NS_METHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval); \
NS_METHOD GetUiBusy(bool *aUiBusy); \
NS_METHOD GetIsLoggedIn(bool *aIsLoggedIn);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSILOGINMANAGERSTORAGE(_to) \
NS_IMETHOD Initialize(JS::MutableHandleValue _retval) override { return _to Initialize(_retval); } \
NS_IMETHOD Terminate(JS::MutableHandleValue _retval) override { return _to Terminate(_retval); } \
NS_IMETHOD AddLogin(nsILoginInfo *aLogin) override { return _to AddLogin(aLogin); } \
NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) override { return _to RemoveLogin(aLogin); } \
NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) override { return _to ModifyLogin(oldLogin, newLoginData); } \
NS_IMETHOD RemoveAllLogins(void) override { return _to RemoveAllLogins(); } \
NS_IMETHOD GetAllLogins(uint32_t *count, nsILoginInfo * **logins) override { return _to GetAllLogins(count, logins); } \
NS_IMETHOD SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins) override { return _to SearchLogins(count, matchData, logins); } \
NS_IMETHOD GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames) override { return _to GetAllDisabledHosts(count, hostnames); } \
NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, bool *_retval) override { return _to GetLoginSavingEnabled(aHost, _retval); } \
NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled) override { return _to SetLoginSavingEnabled(aHost, isEnabled); } \
NS_IMETHOD FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins) override { return _to FindLogins(count, aHostname, aActionURL, aHttpRealm, logins); } \
NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval) override { return _to CountLogins(aHostname, aActionURL, aHttpRealm, _retval); } \
NS_IMETHOD GetUiBusy(bool *aUiBusy) override { return _to GetUiBusy(aUiBusy); } \
NS_IMETHOD GetIsLoggedIn(bool *aIsLoggedIn) override { return _to GetIsLoggedIn(aIsLoggedIn); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSILOGINMANAGERSTORAGE(_to) \
NS_IMETHOD Initialize(JS::MutableHandleValue _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Initialize(_retval); } \
NS_IMETHOD Terminate(JS::MutableHandleValue _retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->Terminate(_retval); } \
NS_IMETHOD AddLogin(nsILoginInfo *aLogin) override { return !_to ? NS_ERROR_NULL_POINTER : _to->AddLogin(aLogin); } \
NS_IMETHOD RemoveLogin(nsILoginInfo *aLogin) override { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveLogin(aLogin); } \
NS_IMETHOD ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData) override { return !_to ? NS_ERROR_NULL_POINTER : _to->ModifyLogin(oldLogin, newLoginData); } \
NS_IMETHOD RemoveAllLogins(void) override { return !_to ? NS_ERROR_NULL_POINTER : _to->RemoveAllLogins(); } \
NS_IMETHOD GetAllLogins(uint32_t *count, nsILoginInfo * **logins) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAllLogins(count, logins); } \
NS_IMETHOD SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SearchLogins(count, matchData, logins); } \
NS_IMETHOD GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAllDisabledHosts(count, hostnames); } \
NS_IMETHOD GetLoginSavingEnabled(const nsAString & aHost, bool *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetLoginSavingEnabled(aHost, _retval); } \
NS_IMETHOD SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled) override { return !_to ? NS_ERROR_NULL_POINTER : _to->SetLoginSavingEnabled(aHost, isEnabled); } \
NS_IMETHOD FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins) override { return !_to ? NS_ERROR_NULL_POINTER : _to->FindLogins(count, aHostname, aActionURL, aHttpRealm, logins); } \
NS_IMETHOD CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval) override { return !_to ? NS_ERROR_NULL_POINTER : _to->CountLogins(aHostname, aActionURL, aHttpRealm, _retval); } \
NS_IMETHOD GetUiBusy(bool *aUiBusy) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUiBusy(aUiBusy); } \
NS_IMETHOD GetIsLoggedIn(bool *aIsLoggedIn) override { return !_to ? NS_ERROR_NULL_POINTER : _to->GetIsLoggedIn(aIsLoggedIn); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsLoginManagerStorage : public nsILoginManagerStorage
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSILOGINMANAGERSTORAGE
nsLoginManagerStorage();
private:
~nsLoginManagerStorage();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS(nsLoginManagerStorage, nsILoginManagerStorage)
nsLoginManagerStorage::nsLoginManagerStorage()
{
/* member initializers and constructor code */
}
nsLoginManagerStorage::~nsLoginManagerStorage()
{
/* destructor code */
}
/* jsval initialize (); */
NS_IMETHODIMP nsLoginManagerStorage::Initialize(JS::MutableHandleValue _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* jsval terminate (); */
NS_IMETHODIMP nsLoginManagerStorage::Terminate(JS::MutableHandleValue _retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void addLogin (in nsILoginInfo aLogin); */
NS_IMETHODIMP nsLoginManagerStorage::AddLogin(nsILoginInfo *aLogin)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removeLogin (in nsILoginInfo aLogin); */
NS_IMETHODIMP nsLoginManagerStorage::RemoveLogin(nsILoginInfo *aLogin)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void modifyLogin (in nsILoginInfo oldLogin, in nsISupports newLoginData); */
NS_IMETHODIMP nsLoginManagerStorage::ModifyLogin(nsILoginInfo *oldLogin, nsISupports *newLoginData)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void removeAllLogins (); */
NS_IMETHODIMP nsLoginManagerStorage::RemoveAllLogins()
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void getAllLogins ([optional] out unsigned long count, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManagerStorage::GetAllLogins(uint32_t *count, nsILoginInfo * **logins)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void searchLogins (out unsigned long count, in nsIPropertyBag matchData, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManagerStorage::SearchLogins(uint32_t *count, nsIPropertyBag *matchData, nsILoginInfo * **logins)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void getAllDisabledHosts ([optional] out unsigned long count, [array, size_is (count), retval] out wstring hostnames); */
NS_IMETHODIMP nsLoginManagerStorage::GetAllDisabledHosts(uint32_t *count, char16_t * **hostnames)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean getLoginSavingEnabled (in AString aHost); */
NS_IMETHODIMP nsLoginManagerStorage::GetLoginSavingEnabled(const nsAString & aHost, bool *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void setLoginSavingEnabled (in AString aHost, in boolean isEnabled); */
NS_IMETHODIMP nsLoginManagerStorage::SetLoginSavingEnabled(const nsAString & aHost, bool isEnabled)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void findLogins (out unsigned long count, in AString aHostname, in AString aActionURL, in AString aHttpRealm, [array, size_is (count), retval] out nsILoginInfo logins); */
NS_IMETHODIMP nsLoginManagerStorage::FindLogins(uint32_t *count, const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, nsILoginInfo * **logins)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* unsigned long countLogins (in AString aHostname, in AString aActionURL, in AString aHttpRealm); */
NS_IMETHODIMP nsLoginManagerStorage::CountLogins(const nsAString & aHostname, const nsAString & aActionURL, const nsAString & aHttpRealm, uint32_t *_retval)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute boolean uiBusy; */
NS_IMETHODIMP nsLoginManagerStorage::GetUiBusy(bool *aUiBusy)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute boolean isLoggedIn; */
NS_IMETHODIMP nsLoginManagerStorage::GetIsLoggedIn(bool *aIsLoggedIn)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsILoginManagerStorage_h__ */
| [
"pratik.sidam@cactusglobal.com"
] | pratik.sidam@cactusglobal.com |
bd411c592ec78d34cf723eaa1c263aac915a898d | 536205b4438d409e2bc6349efaa19d4603622249 | /标程免费馅饼/main.cpp | bbc59ec58b1f60c125f95b3f97c86a90933ba7b4 | [] | no_license | cyendra/ACM_Training_Chapter_One | 78a8b38f6465dfe5e4238057830fed788769f5c4 | 8268a66edf1cc5ba9a0e5019b34b4ec97ce55268 | refs/heads/master | 2020-12-30T10:37:10.269991 | 2013-11-17T08:40:03 | 2013-11-17T08:40:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 446 | cpp | /*
#include <iostream>
#include <cstdio>
#include <cstdlib>
using namespace std;
int main()
{
FILE *f1;
int n,x,T;
f1=fopen("data.in","w");
for (int i=0;i<10;i++)
{
n=rand()%11111;
fprintf(f1,"%d\n",n);
for (int i=0;i<n;i++)
{
x=rand()%11;
T=rand()%11111;
fprintf(f1,"%d %d\n",x,T);
}
}
fprintf(f1,"0\n");
fclose(f1);
return 0;
}
*/
| [
"g1483335912@gmail.com"
] | g1483335912@gmail.com |
904da8cac4eb9e3e1c98d1bd75d7c3035044e4a0 | 5292a9ddd4cd92855d825a8bf06e69114fa36e7b | /VALIDBIN.CPP | 9ab60250be7ea368b40bc450ae1ac674042d3bc6 | [] | no_license | Kushagratandon12/Coding-Competition-Problems- | 9eb2d3be303f0d47ed78d439d9f54032105585bf | a6c9b0385affcb984d1ab1acabd9703b4e1a5757 | refs/heads/master | 2023-02-14T20:09:09.320631 | 2021-01-06T04:35:53 | 2021-01-06T04:35:53 | 243,587,963 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,579 | cpp | #include<iostream.h>
#include<conio.h>
struct Node
{
int data;
Node* left;
Node* right;
};
Node* new_node(int x)
{
Node* new_node = new Node();
new_node->data = x;
new_node->left=NULL;
new_node->right=NULL;
return new_node;
}
Node* insert(Node* root , int data)
{
if(root==NULL)
{
return new_node(data);
}
else
{
if(data<root->data)
root->left = insert(root->left,data);
else
root->right=insert(root->right,data);
}
return (root);
}
int check(Node*root)
{
int min=root->left->data;
int max=root->right->data;
if(root==NULL || root->left == NULL ||root->right==NULL )
return 1;
if(root->data==root->left->data || root->data==root->right->data)
return 1;
if(min < root->data && max > root->data)
{
return (check(root->left)&& check(root->right));
}
else
{
return 0;
}
}
void validate(Node * root)
{
int a;
a=check(root);
cout<<a;
// cout<<root->data;
// cout<<"\nPrimary Root Left Data\n "<<root->left->data;
// cout<<"\n Primary Root Right Data\n"<<root->right->data;
// root=root->right;
// cout<<"\nRight Root Traversal\n";
// cout<<"\nRight Node LEft Data\n"<<root->left->data;
// cout<<"\nRight Root Right Data\n"<<root->right->data;
}
void main()
{
clrscr();
Node* root = NULL;
root=insert(root,1);
insert(root,1);
// insert(root,1);
// insert(root,4);
// insert(root,7);
// insert(root,6);
// insert(root,9);
validate(root);
getch();
}
| [
"kushagra.tandon.124@gmail.com"
] | kushagra.tandon.124@gmail.com |
2c547791e5c9af288fc88467d8c906c21856be95 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/test/data/webui/gaia_auth_host/gaia_auth_host_browsertest.cc | e2a0107bce7f9886d280279294e7483225d0d59c | [
"GPL-3.0-only",
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 1,040 | cc | // Copyright 2023 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/common/webui_url_constants.h"
#include "chrome/test/base/web_ui_mocha_browser_test.h"
#include "content/public/test/browser_test.h"
class GaiaAuthHostTest : public WebUIMochaBrowserTest {
protected:
GaiaAuthHostTest() {
set_test_loader_host(chrome::kChromeUIChromeSigninHost);
}
};
IN_PROC_BROWSER_TEST_F(GaiaAuthHostTest, PasswordChangeAuthenticator) {
RunTest("gaia_auth_host/password_change_authenticator_test.js",
"mocha.run()");
}
IN_PROC_BROWSER_TEST_F(GaiaAuthHostTest, SamlPasswordAttributes) {
RunTest("gaia_auth_host/saml_password_attributes_test.js", "mocha.run()");
}
IN_PROC_BROWSER_TEST_F(GaiaAuthHostTest, SamlTimestamps) {
RunTest("gaia_auth_host/saml_timestamps_test.js", "mocha.run()");
}
IN_PROC_BROWSER_TEST_F(GaiaAuthHostTest, SamlUsernameAutofill) {
RunTest("gaia_auth_host/saml_username_autofill_test.js", "mocha.run()");
}
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
d33aadc3335e4b4f956a719f6ed9713ee3e92a62 | 70b35f2decbf84b001db830ceffc76e1d246e9ef | /common/MessageJunction.hpp | cebc59a630b32702b9fd4d8a66344cefd7a5a05d | [
"Zlib",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | mrkline/ece453 | b378691ba97561aaf4a70beed59eef0f313361f0 | 580880c89c42049ad079a26ec05f27ba2e6b0236 | refs/heads/master | 2020-11-26T17:05:35.897341 | 2014-05-09T02:40:57 | 2014-05-09T02:40:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 244 | hpp | #pragma once
#include "MessageQueue.hpp"
void runMessageJunction(MessageQueue& toSM, MessageQueue& fromSM,
MessageQueue& toUI, MessageQueue& fromUI,
MessageQueue& toSys, MessageQueue& fromSys);
| [
"slavik262@gmail.com"
] | slavik262@gmail.com |
395b771ced914f8bbab88d3d4779c040aec160c3 | 7a4640a884d513dc60e66617802e95be9fe9b3f5 | /Unity/Temp/il2cppOutput/il2cppOutput/mscorlib_System_Runtime_Remoting_SingletonIdentity1092918417.h | 0f6e6b617af3c4b62d0ff4f8330c326fb1837576 | [] | no_license | eray-z/Game-Engine-Benchmarks | 40e455c9eb04463fef1c9d11fdea80ecad4a6404 | 2b427d02a801a2c2c4fb496601a458634e646c8d | refs/heads/master | 2020-12-25T14:13:36.908703 | 2016-06-03T16:05:24 | 2016-06-03T16:05:24 | 60,355,376 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 568 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Runtime_Remoting_ServerIdentity571418633.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Runtime.Remoting.SingletonIdentity
struct SingletonIdentity_t1092918417 : public ServerIdentity_t571418633
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"erayzesen@gmail.com"
] | erayzesen@gmail.com |
90d2e9176321c64b3d14bb5b03c17ebed640c455 | 6314d764ebc2c817c1b7449d76951e6b4224f0a8 | /pb/interface.cc | 2f47458d5c90e1116b7d312ae072b98d9af15a33 | [] | no_license | irqlevel/kvs | 97c65fee9003baf1d096bc5a7eb0ac0b5b74b308 | 1eeec357d4944a8aabdf32e2cc9a04ba3adef9d6 | refs/heads/master | 2020-06-04T20:48:59.357119 | 2019-07-29T20:38:37 | 2019-07-29T20:38:37 | 192,186,666 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,489 | cc | #include "interface.h"
namespace Pb
{
#define ErrCantGetEncodedSize STDLIB_ERROR(1, "pb", "can't get encoded size")
#define ErrNoMemory STDLIB_ERROR(2, "pb", "no memory")
#define ErrEncode STDLIB_ERROR(3, "pb", "encode error")
#define ErrDecode STDLIB_ERROR(4, "pb", "decode error")
Stdlib::Result<Stdlib::ByteArray<u8>, Stdlib::Error> Encode(const pb_field_t pb_fields[], void *pb_struc)
{
size_t required_size;
Stdlib::ByteArray<u8> data;
if (!pb_get_encoded_size(&required_size, pb_fields, pb_struc))
return Stdlib::Result<Stdlib::ByteArray<u8>, Stdlib::Error>(ErrCantGetEncodedSize);
if (!data.ReserveAndUse(required_size))
return Stdlib::Result<Stdlib::ByteArray<u8>, Stdlib::Error>(ErrNoMemory);
auto stream = pb_ostream_from_buffer(data.GetBuf(), data.GetSize());
if (!pb_encode(&stream, pb_fields, pb_struc))
return Stdlib::Result<Stdlib::ByteArray<u8>, Stdlib::Error>(ErrEncode);
if (!data.Truncate(stream.bytes_written))
Stdlib::Abort();
return Stdlib::Result<Stdlib::ByteArray<u8>, Stdlib::Error>(Stdlib::Move(data), 0);
}
Stdlib::Error Decode(const Stdlib::ByteArray<u8> &data, const pb_field_t pb_fields[], void *pb_struc)
{
auto stream = pb_istream_from_buffer(data.GetConstBuf(), data.GetSize());
if (!pb_decode(&stream, pb_fields, pb_struc))
return ErrDecode;
return 0;
}
} | [
"irqlevel@gmail.com"
] | irqlevel@gmail.com |
c4ebe019781534f5b23f05820475277a71b94e94 | b1d642303a1faa701569587950fa1c5b133264d1 | /test/algorithms/math/test_hamming_weight.hpp | 07c8f1efbd961fa7bf55869a09c7b37c5d031a95 | [
"MIT"
] | permissive | cleybertandre/CppNotes | 469f98eab4b7fa7af5b97a8f5aa9a7f38d6a2b69 | 1c6318976f3dccb03f32145d6d839b47c006171d | refs/heads/master | 2020-03-31T22:01:28.778636 | 2018-10-02T11:00:17 | 2018-10-02T11:00:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,364 | hpp | #ifndef TEST_HAMMING_WEIGHT_HPP
#define TEST_HAMMING_WEIGHT_HPP
#include <boost/test/unit_test.hpp>
#include "algorithms/math/hamming_weight.hpp"
BOOST_AUTO_TEST_CASE(test_hw_str_empty_string)
{
HammingWeight::Solution solution;
BOOST_CHECK(0 == solution.HammingWeightForString(std::string()));
}
BOOST_AUTO_TEST_CASE(test_hw_str_non_empty_string)
{
HammingWeight::Solution solution;
BOOST_CHECK(1 == solution.HammingWeightForString("1"));
BOOST_CHECK(1 == solution.HammingWeightForString("0"));
BOOST_CHECK(1 == solution.HammingWeightForString("y"));
BOOST_CHECK(1 == solution.HammingWeightForString("!"));
BOOST_CHECK(7 == solution.HammingWeightForString("rty1:,."));
}
BOOST_AUTO_TEST_CASE(test_hw_str_zero_string)
{
HammingWeight::Solution solution;
BOOST_CHECK(0 == solution.HammingWeightForString(std::string(2, char(0))));
}
BOOST_AUTO_TEST_CASE(test_hw_int_null)
{
HammingWeight::Solution solution;
BOOST_CHECK(0 == solution.HammingWeightForInt(0));
}
BOOST_AUTO_TEST_CASE(test_hw_int_diff_values)
{
HammingWeight::Solution solution;
BOOST_CHECK(1 == solution.HammingWeightForInt(1));
BOOST_CHECK(1 == solution.HammingWeightForInt(2));
BOOST_CHECK(5 == solution.HammingWeightForInt(143));
BOOST_CHECK(28 == solution.HammingWeightForInt(-143));
}
#endif // TEST_HAMMING_WEIGHT_HPP
| [
"antony.cherepanov@gmail.com"
] | antony.cherepanov@gmail.com |
7c47c212be3b056e5794e18d53257bcbd14bea32 | 79f956e5831adb049e779c4d77c648cf2898f6bb | /MonsterList/MonsterNode.h | e47be990eac074794e84b12d178880b6ac37a406 | [] | no_license | JonjonHays/CS-19 | ac78d43d96c11cda243dbf27579f2aff47b2ea1d | 400e22a176636b4d43051bee3241aa0d9c7416b8 | refs/heads/master | 2021-04-03T08:35:45.116806 | 2018-03-08T22:57:32 | 2018-03-08T22:57:32 | 124,457,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 447 | h | // Jon Hays
// jhays
// mightyfancy@gmail.com
// MonsterNode.h
// assignment 5 (Care of Magical Creatures)
// MonsterNode class interface/implementation file (complete class)
// working/tested
#ifndef MONSTERNODE_H
#define MONSTERNODE_H
class MonsterNode {
friend class MonsterList;
public:
// Default constructor initializes node to null
MonsterNode() {next = 0; id = '\0';}
private:
MonsterNode* next;
char id;
};
#endif
| [
"jonhays@Jons-MacBook-Pro.local"
] | jonhays@Jons-MacBook-Pro.local |
2107b54f01496f9865ca8ff9a02085ffed60d890 | 3670f2ca6f5609e14cce8c31cb1348052d0b6358 | /xacro/perception_pcl/pcl_ros/include/pcl_ros/io/bag_io.h | 1ea5579e4040f86d8fbbd033f123050e2c5156bd | [] | no_license | jincheng-ai/ros-melodic-python3-opencv4 | b0f4d3860ab7ae3d683ade8aa03e74341eff7fcf | 47c74188560c2274b8304647722d0c9763299a4b | refs/heads/main | 2023-05-28T17:37:34.345164 | 2021-06-17T09:59:25 | 2021-06-17T09:59:25 | 377,856,153 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,574 | h | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2009, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* $Id: bag_io.h 35471 2011-01-25 06:50:00Z rusu $
*
*/
#ifndef PCL_ROS_IO_BAG_IO_H_
#define PCL_ROS_IO_BAG_IO_H_
#include <nodelet/nodelet.h>
#include <Eigen/Core>
#include <sensor_msgs/PointCloud2.h>
#include <rosbag/bag.h>
#include <rosbag/view.h>
namespace pcl_ros
{
////////////////////////////////////////////////////////////////////////////////////////////
/** \brief BAG PointCloud file format reader.
* \author Radu Bogdan Rusu
*/
class BAGReader: public nodelet::Nodelet
{
public:
typedef sensor_msgs::PointCloud2 PointCloud;
typedef PointCloud::Ptr PointCloudPtr;
typedef PointCloud::ConstPtr PointCloudConstPtr;
/** \brief Empty constructor. */
BAGReader () : publish_rate_ (0), output_ ()/*, cloud_received_ (false)*/ {};
/** \brief Set the publishing rate in seconds.
* \param publish_rate the publishing rate in seconds
*/
inline void setPublishRate (double publish_rate) { publish_rate_ = publish_rate; }
/** \brief Get the publishing rate in seconds. */
inline double getPublishRate () { return (publish_rate_); }
/** \brief Get the next point cloud dataset in the BAG file.
* \return the next point cloud dataset as read from the file
*/
inline PointCloudConstPtr
getNextCloud ()
{
if (it_ != view_.end ())
{
output_ = it_->instantiate<sensor_msgs::PointCloud2> ();
++it_;
}
return (output_);
}
/** \brief Open a BAG file for reading and select a specified topic
* \param file_name the BAG file to open
* \param topic_name the topic that we want to read data from
*/
bool open (const std::string &file_name, const std::string &topic_name);
/** \brief Close an open BAG file. */
inline void
close ()
{
bag_.close ();
}
/** \brief Nodelet initialization routine. */
virtual void onInit ();
private:
/** \brief The publishing interval in seconds. Set to 0 to publish once (default). */
double publish_rate_;
/** \brief The BAG object. */
rosbag::Bag bag_;
/** \brief The BAG view object. */
rosbag::View view_;
/** \brief The BAG view iterator object. */
rosbag::View::iterator it_;
/** \brief The name of the topic that contains the PointCloud data. */
std::string topic_name_;
/** \brief The name of the BAG file that contains the PointCloud data. */
std::string file_name_;
/** \brief The output point cloud dataset containing the points loaded from the file. */
PointCloudPtr output_;
/** \brief Signals that a new PointCloud2 message has been read from the file. */
//bool cloud_received_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
}
#endif //#ifndef PCL_ROS_IO_BAG_IO_H_
| [
"shuyuanhao@cetiti.com"
] | shuyuanhao@cetiti.com |
bba38eec67c6d4011b14d5b09d1e39a4f34eff84 | b39fb160ace6d43615af6867a16dc467802d6711 | /src/wul/error.hpp | 4824ad6b1c1515f39dd215f789b11f2bacb4fbff | [
"MIT"
] | permissive | OCEANOFANYTHING/writeurl | 14e87b4ed641feac0eb30464b088831b1075b867 | a3b43a6a6319cc0c46d355cc51319e2a8d1ad031 | refs/heads/master | 2023-03-26T06:20:04.178713 | 2021-02-07T14:19:34 | 2021-02-07T14:19:34 | 344,539,650 | 0 | 0 | MIT | 2021-03-04T16:34:00 | 2021-03-04T16:33:14 | JavaScript | UTF-8 | C++ | false | false | 864 | hpp | /*************************************************************
*
* Writeurl is an online collaborative editor.
*
* The MIT License (MIT)
* Copyright (c) 2017 Writeurl
*
************************************************************/
#ifndef WRITEURL_ERROR_H
#define WRITEURL_ERROR_H
#include <system_error>
namespace writeurl {
enum class Error {
file_no_exist = 1,
file_read_access_denied,
file_write_access_denied,
file_quota_exceeded,
file_size_limit_exceeded,
file_unspecified_error,
store_json_parser_error,
store_error,
};
const std::error_category& error_category() noexcept;
std::error_code make_error_code(Error) noexcept;
} // namespace writeurl
namespace std {
template <> struct is_error_code_enum<writeurl::Error> {
static const bool value = true;
};
} // namespace std
#endif // WRITEURL_ERROR_H
| [
"morten.krogh@amberbio.com"
] | morten.krogh@amberbio.com |
b50ade69ede74fd008edc6ff4696a17139a22377 | 04ab71b0d4d2aaf018f0ea5818cecf992eb9414e | /libaudio/AudioPolicyManager.cpp | 88cd1db47990f5452dc647810528f5030495a1d0 | [
"Apache-2.0"
] | permissive | os2sd/android_device_lge_msm7x27-common | 9b5238ec83b08ad9119162a2719f29e1bf4a3eca | 1a19d7f581a62a2c22f089a3bb37179fa5900bdd | refs/heads/cm-11.0 | 2021-01-15T21:50:10.865615 | 2016-12-28T08:37:36 | 2016-12-28T08:37:36 | 35,363,404 | 1 | 1 | null | 2015-05-10T08:36:54 | 2015-05-10T08:36:52 | null | UTF-8 | C++ | false | false | 22,478 | cpp | /*
* Copyright (C) 2009 The Android Open Source Project
* Copyright (c) 2012, Code Aurora Forum. All rights reserved.
* Copyright (c) 2012, The CyanogenMod Project
*
* 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.
*/
#define LOG_TAG "AudioPolicyManager"
//#define LOG_NDEBUG 0
#include <utils/Log.h>
#include "AudioPolicyManager.h"
#include <media/mediarecorder.h>
#include <fcntl.h>
#include <cutils/properties.h> // for property_get
#include "AudioHardware.h"
namespace android_audio_legacy {
// ----------------------------------------------------------------------------
// AudioPolicyManager for msm7k platform
// Common audio policy manager code is implemented in AudioPolicyManagerBase class
// ----------------------------------------------------------------------------
// --- class factory
extern "C" AudioPolicyInterface* createAudioPolicyManager(AudioPolicyClientInterface *clientInterface)
{
return new AudioPolicyManager(clientInterface);
}
extern "C" void destroyAudioPolicyManager(AudioPolicyInterface *interface)
{
delete interface;
}
audio_devices_t AudioPolicyManager::getDeviceForStrategy(routing_strategy strategy, bool fromCache)
{
uint32_t device = AUDIO_DEVICE_NONE;
if (fromCache) {
ALOGV("getDeviceForStrategy() from cache strategy %d, device %x", strategy, mDeviceForStrategy[strategy]);
return mDeviceForStrategy[strategy];
}
switch (strategy) {
case STRATEGY_SONIFICATION_RESPECTFUL:
if (isInCall()) {
device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
} else if (isStreamActive(AudioSystem::MUSIC, SONIFICATION_RESPECTFUL_AFTER_MUSIC_DELAY)) {
// while media is playing (or has recently played), use the same device
device = getDeviceForStrategy(STRATEGY_MEDIA, false /*fromCache*/);
} else {
// when media is not playing anymore, fall back on the sonification behavior
device = getDeviceForStrategy(STRATEGY_SONIFICATION, false /*fromCache*/);
}
break;
case STRATEGY_DTMF:
if (!isInCall()) {
// when off call, DTMF strategy follows the same rules as MEDIA strategy
device = getDeviceForStrategy(STRATEGY_MEDIA, false);
break;
}
// when in call, DTMF and PHONE strategies follow the same rules
// FALL THROUGH
case STRATEGY_PHONE:
// for phone strategy, we first consider the forced use and then the available devices by order
// of priority
switch (mForceUse[AudioSystem::FOR_COMMUNICATION]) {
case AudioSystem::FORCE_BT_SCO:
if (!isInCall() || strategy != STRATEGY_DTMF) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
if (device) break;
}
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO;
if (device) break;
// if SCO device is requested but no SCO device is available, fall back to default case
// FALL THROUGH
default: // FORCE_NONE
#ifdef WITH_A2DP
// when not in a phone call, phone strategy should route STREAM_VOICE_CALL to A2DP
if (mHasA2dp && !isInCall())
{
if ((mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
!mA2dpSuspended) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
if (device) break;
}
}
#endif
#if 0
if (mPhoneState != AudioSystem::MODE_IN_CALL) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_ACCESSORY;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_USB_DEVICE;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_DGTL_DOCK_HEADSET;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
if (device) break;
}
#endif
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
if (device) break;
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
if (device) break;
device = mDefaultOutputDevice;
if (device == AUDIO_DEVICE_NONE) {
ALOGE("getDeviceForStrategy() earpiece device not found");
}
break;
case AudioSystem::FORCE_SPEAKER:
if (!isInCall() || strategy != STRATEGY_DTMF) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT;
if (device) break;
}
#ifdef WITH_A2DP
// when not in a phone call, phone strategy should route STREAM_VOICE_CALL to
// A2DP speaker when forcing to speaker output
if (mHasA2dp && !isInCall() &&
(mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
(getA2dpOutput() != 0) && !mA2dpSuspended) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
if (device) break;
}
#endif
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
if (device) break;
device = mDefaultOutputDevice;
if (device == AUDIO_DEVICE_NONE) {
ALOGE("getDeviceForStrategy() speaker device not found");
}
break;
}
break;
case STRATEGY_SONIFICATION:
// If incall, just select the STRATEGY_PHONE device: The rest of the behavior is handled by
// handleIncallSonification().
if (isInCall()) {
device = getDeviceForStrategy(STRATEGY_PHONE, false);
break;
}
// FALL THROUGH
case STRATEGY_ENFORCED_AUDIBLE:
// strategy STRATEGY_ENFORCED_AUDIBLE uses same routing policy as STRATEGY_SONIFICATION
// except:
// - when in call where it doesn't default to STRATEGY_PHONE behavior
// - in countries where not enforced in which case it follows STRATEGY_MEDIA
if (strategy == STRATEGY_SONIFICATION ||
!mStreams[AUDIO_STREAM_ENFORCED_AUDIBLE].mCanBeMuted) {
device = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
if (device == 0) {
ALOGE("getDeviceForStrategy() speaker device not found for STRATEGY_SONIFICATION");
}
}
// The second device used for sonification is the same as the device used by media strategy
// FALL THROUGH
case STRATEGY_MEDIA: {
uint32_t device2 = AUDIO_DEVICE_NONE;
#ifdef HAVE_FM_RADIO
if (mForceUse[AudioSystem::FOR_MEDIA] == AudioSystem::FORCE_SPEAKER) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
}
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
}
#else
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_AUX_DIGITAL;
#endif
#ifdef WITH_A2DP
if ((device2 == AUDIO_DEVICE_NONE) &&
mHasA2dp && (mForceUse[AudioSystem::FOR_MEDIA] != AudioSystem::FORCE_NO_BT_A2DP) &&
(getA2dpOutput() != 0) && !mA2dpSuspended) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP;
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES;
}
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_SPEAKER;
}
}
#endif
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADPHONE;
}
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_WIRED_HEADSET;
}
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_SPEAKER;
}
if (device2 == AUDIO_DEVICE_NONE) {
device2 = mAvailableOutputDevices & AUDIO_DEVICE_OUT_EARPIECE;
}
// device is DEVICE_OUT_SPEAKER if we come from case STRATEGY_SONIFICATION or
// STRATEGY_ENFORCED_AUDIBLE, AUDIO_DEVICE_NONE otherwise
device |= device2;
if (!device) {
device = mDefaultOutputDevice;
}
if (device == AUDIO_DEVICE_NONE) {
ALOGE("getDeviceForStrategy() speaker device not found");
}
} break;
default:
ALOGW("getDeviceForStrategy() unknown strategy: %d", strategy);
break;
}
ALOGV("getDeviceForStrategy() strategy %d, device %x", strategy, device);
return (audio_devices_t)device;
}
status_t AudioPolicyManager::checkAndSetVolume(int stream, int index, audio_io_handle_t output, audio_devices_t device, int delayMs, bool force)
{
// do not change actual stream volume if the stream is muted
if (mOutputs.valueFor(output)->mMuteCount[stream] != 0) {
ALOGV("checkAndSetVolume() stream %d muted count %d", stream, mOutputs.valueFor(output)->mMuteCount[stream]);
return NO_ERROR;
}
// do not change in call volume if bluetooth is connected and vice versa
if ((stream == AudioSystem::VOICE_CALL && mForceUse[AudioSystem::FOR_COMMUNICATION] == AudioSystem::FORCE_BT_SCO) ||
(stream == AudioSystem::BLUETOOTH_SCO && mForceUse[AudioSystem::FOR_COMMUNICATION] != AudioSystem::FORCE_BT_SCO)) {
ALOGV("checkAndSetVolume() cannot set stream %d volume with force use = %d for comm",
stream, mForceUse[AudioSystem::FOR_COMMUNICATION]);
return INVALID_OPERATION;
}
float volume = computeVolume(stream, index, output, device);
// We actually change the volume if:
// - the float value returned by computeVolume() changed
// - the force flag is set
if (volume != mOutputs.valueFor(output)->mCurVolume[stream] ||
(stream == AudioSystem::VOICE_CALL) ||
#ifdef HAVE_FM_RADIO
(stream == AudioSystem::FM) ||
#endif
force) {
mOutputs.valueFor(output)->mCurVolume[stream] = volume;
ALOGV("setStreamVolume() for output %d stream %d, volume %f, delay %d", output, stream, volume, delayMs);
if (stream == AudioSystem::VOICE_CALL ||
stream == AudioSystem::DTMF ||
stream == AudioSystem::BLUETOOTH_SCO) {
// offset value to reflect actual hardware volume that never reaches 0
// 1% corresponds roughly to first step in VOICE_CALL stream volume setting (see AudioService.java)
volume = 0.01 + 0.99 * volume;
}
mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
}
if (stream == AudioSystem::VOICE_CALL ||
stream == AudioSystem::BLUETOOTH_SCO) {
float voiceVolume;
// Force voice volume to max for bluetooth SCO as volume is managed by the headset
if (stream == AudioSystem::VOICE_CALL) {
voiceVolume = (float)index/(float)mStreams[stream].mIndexMax;
} else {
voiceVolume = 1.0;
}
if ((voiceVolume >= 0 && output == mPrimaryOutput)
#ifdef HAVE_FM_RADIO
&& (!(mAvailableOutputDevices & AUDIO_DEVICE_OUT_FM))
#endif
) {
mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
mLastVoiceVolume = voiceVolume;
}
}
#ifdef HAVE_FM_RADIO
else if ((stream == AudioSystem::FM) && (mAvailableOutputDevices & AUDIO_DEVICE_OUT_FM)) {
float fmVolume = computeVolume(stream, index, output, device);
if (fmVolume >= 0) {
if (output == mPrimaryOutput)
mpClientInterface->setFmVolume(fmVolume, delayMs);
else if(mHasA2dp && output == getA2dpOutput())
mpClientInterface->setStreamVolume((AudioSystem::stream_type)stream, volume, output, delayMs);
}
}
#endif
return NO_ERROR;
}
status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
AudioSystem::device_connection_state state,
const char *device_address)
{
SortedVector <audio_io_handle_t> outputs;
ALOGV("setDeviceConnectionState() device: %x, state %d, address %s", device, state, device_address);
// connect/disconnect only 1 device at a time
if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
if (strlen(device_address) >= MAX_DEVICE_ADDRESS_LEN) {
ALOGE("setDeviceConnectionState() invalid address: %s", device_address);
return BAD_VALUE;
}
// handle output devices
if (audio_is_output_device(device)) {
if (!mHasA2dp && audio_is_a2dp_device(device)) {
ALOGE("setDeviceConnectionState() invalid A2DP device: %x", device);
return BAD_VALUE;
}
if (!mHasUsb && audio_is_usb_device(device)) {
ALOGE("setDeviceConnectionState() invalid USB audio device: %x", device);
return BAD_VALUE;
}
// save a copy of the opened output descriptors before any output is opened or closed
// by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
mPreviousOutputs = mOutputs;
switch (state)
{
// handle output device connection
case AudioSystem::DEVICE_STATE_AVAILABLE:
if (mAvailableOutputDevices & device) {
ALOGW("setDeviceConnectionState() device already connected: %x", device);
return INVALID_OPERATION;
}
ALOGV("setDeviceConnectionState() connecting device %x", device);
if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
return INVALID_OPERATION;
}
ALOGV("setDeviceConnectionState() checkOutputsForDevice() returned %d outputs",
outputs.size());
// register new device as available
mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices | device);
if (!outputs.isEmpty()) {
String8 paramStr;
if (mHasA2dp && audio_is_a2dp_device(device)) {
// handle A2DP device connection
AudioParameter param;
param.add(String8(AUDIO_PARAMETER_A2DP_SINK_ADDRESS), String8(device_address));
paramStr = param.toString();
mA2dpDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
mA2dpSuspended = false;
} else if (audio_is_bluetooth_sco_device(device)) {
// handle SCO device connection
mScoDeviceAddress = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
} else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
// handle USB device connection
mUsbCardAndDevice = String8(device_address, MAX_DEVICE_ADDRESS_LEN);
paramStr = mUsbCardAndDevice;
}
// not currently handling multiple simultaneous submixes: ignoring remote submix
// case and address
if (!paramStr.isEmpty()) {
for (size_t i = 0; i < outputs.size(); i++) {
mpClientInterface->setParameters(outputs[i], paramStr);
}
}
}
break;
// handle output device disconnection
case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
if (!(mAvailableOutputDevices & device)) {
ALOGW("setDeviceConnectionState() device not connected: %x", device);
return INVALID_OPERATION;
}
ALOGV("setDeviceConnectionState() disconnecting device %x", device);
// remove device from available output devices
mAvailableOutputDevices = (audio_devices_t)(mAvailableOutputDevices & ~device);
checkOutputsForDevice((audio_devices_t)device, state, outputs);
if (mHasA2dp && audio_is_a2dp_device(device)) {
// handle A2DP device disconnection
mA2dpDeviceAddress = "";
mA2dpSuspended = false;
} else if (audio_is_bluetooth_sco_device(device)) {
// handle SCO device disconnection
mScoDeviceAddress = "";
} else if (mHasUsb && audio_is_usb_device((audio_devices_t)device)) {
// handle USB device disconnection
mUsbCardAndDevice = "";
}
} break;
default:
ALOGE("setDeviceConnectionState() invalid state: %x", state);
return BAD_VALUE;
}
#ifdef QCOM_FM_ENABLED
if (device == AUDIO_DEVICE_OUT_FM) {
AudioOutputDescriptor *out = mOutputs.valueFor(mPrimaryOutput);
if (state == AudioSystem::DEVICE_STATE_AVAILABLE) {
out->changeRefCount(AudioSystem::FM, 1);
if (out->mRefCount[AudioSystem::FM] > 0)
mpClientInterface->setParameters(0, String8("fm_on=1"));
}
else {
out->changeRefCount(AudioSystem::FM, -1);
if (out->mRefCount[AudioSystem::FM] <= 0)
mpClientInterface->setParameters(0, String8("fm_off=1"));
}
}
#endif
checkA2dpSuspend();
checkOutputForAllStrategies();
// outputs must be closed after checkOutputForAllStrategies() is executed
if (!outputs.isEmpty()) {
for (size_t i = 0; i < outputs.size(); i++) {
// close unused outputs after device disconnection or direct outputs that have been
// opened by checkOutputsForDevice() to query dynamic parameters
if ((state == AudioSystem::DEVICE_STATE_UNAVAILABLE)) {
closeOutput(outputs[i]);
}
}
}
updateDevicesAndOutputs();
for (size_t i = 0; i < mOutputs.size(); i++) {
setOutputDevice(mOutputs.keyAt(i), getNewDevice(mOutputs.keyAt(i), true /*fromCache*/));
}
if (device == AUDIO_DEVICE_OUT_WIRED_HEADSET) {
device = AUDIO_DEVICE_IN_WIRED_HEADSET;
} else if (device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO ||
device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_HEADSET ||
device == AUDIO_DEVICE_OUT_BLUETOOTH_SCO_CARKIT) {
device = AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET;
} else {
return NO_ERROR;
}
}
// handle input devices
if (audio_is_input_device(device)) {
switch (state)
{
// handle input device connection
case AudioSystem::DEVICE_STATE_AVAILABLE: {
if (mAvailableInputDevices & device) {
ALOGW("setDeviceConnectionState() device already connected: %d", device);
return INVALID_OPERATION;
}
mAvailableInputDevices = mAvailableInputDevices | (device & ~AUDIO_DEVICE_BIT_IN);
}
break;
// handle input device disconnection
case AudioSystem::DEVICE_STATE_UNAVAILABLE: {
if (!(mAvailableInputDevices & device)) {
ALOGW("setDeviceConnectionState() device not connected: %d", device);
return INVALID_OPERATION;
}
mAvailableInputDevices = (audio_devices_t) (mAvailableInputDevices & ~device);
} break;
default:
ALOGE("setDeviceConnectionState() invalid state: %x", state);
return BAD_VALUE;
}
audio_io_handle_t activeInput = getActiveInput();
if (activeInput != 0) {
AudioInputDescriptor *inputDesc = mInputs.valueFor(activeInput);
audio_devices_t newDevice = getDeviceForInputSource(inputDesc->mInputSource);
if ((newDevice != AUDIO_DEVICE_NONE) && (newDevice != inputDesc->mDevice)) {
ALOGV("setDeviceConnectionState() changing device from %x to %x for input %d",
inputDesc->mDevice, newDevice, activeInput);
inputDesc->mDevice = newDevice;
AudioParameter param = AudioParameter();
param.addInt(String8(AudioParameter::keyRouting), (int)newDevice);
mpClientInterface->setParameters(activeInput, param.toString());
}
}
return NO_ERROR;
}
ALOGW("setDeviceConnectionState() invalid device: %x", device);
return BAD_VALUE;
}
bool AudioPolicyManager::isStreamActive(int stream, uint32_t inPastMs) const
{
nsecs_t sysTime = systemTime();
for (size_t i = 0; i < mOutputs.size(); i++) {
if (mOutputs.valueAt(i)->mRefCount[stream] != 0 ||
ns2ms(sysTime - mOutputs.valueAt(i)->mStopTime[stream]) < inPastMs) {
return true;
}
}
#ifdef QCOM_FM_ENABLED
if (stream == AudioSystem::MUSIC && (mAvailableOutputDevices & AUDIO_DEVICE_OUT_FM)) {
return true;
}
#endif
return false;
}
}; // namespace android_audio_legacy
| [
"hephappy@gmail.com"
] | hephappy@gmail.com |
1c822ec52b95a4e04d8f856e8479fcf96f425acd | 934f7ba52f4856129effe9948d4de5573307c776 | /Utils/Event Pump.cpp | edb9d180ec58915f25440fce3f1ce885f080d753 | [] | no_license | FluffyQuack/JA2-113 | 9663176a66610e7685e953aafe66b9fdfad0e474 | a53fb01b69ec12296b6022613e978ba713b90c32 | refs/heads/master | 2023-05-05T08:05:41.594371 | 2021-05-18T15:17:25 | 2021-05-18T15:17:25 | 368,576,923 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,877 | cpp | #ifdef PRECOMPILEDHEADERS
#include "Utils All.h"
#else
#include <stdio.h>
#include <time.h>
#include "sgp.h"
#include "container.h"
#include "wcheck.h"
#include "Event Pump.h"
#include "Timer.h"
#include "Sound Control.h"
#include "Overhead.h"
#include "weapons.h"
#include "Animation Control.h"
#include "opplist.h"
#include "Tactical Save.h"
#endif
#ifdef NETWORKED
#include "Networking.h"
#include "NetworkEvent.h"
#endif
UINT8 gubEncryptionArray4[ BASE_NUMBER_OF_ROTATION_ARRAYS * 3 ][ NEW_ROTATION_ARRAY_SIZE ] =
{
{
177,131,58,218,175,130,210,
59,25,190,170,189,227,245,
104,118,7,168,136,178,184,
4,27,64,199,101,160,24,
83,177,178,232,185,40,122,
109,38,253,160,14,133,106,
190,206,58,102,244,229,124
},
{
201,183,24,153,17,111,47,
19,116,248,160,215,143,180,
195,122,74,29,158,193,73,
159,193,93,140,172,31,38,
129,181,96,183,56,29,172,
191,252,183,91,214,254,247,
135,66,76,87,1,112,214
},
{
28,138,132,173,9,230,220,
57,32,166,202,153,246,49,
119,246,212,1,50,230,19,
135,20,173,235,182,61,143,
76,162,155,224,182,54,123,
29,223,119,200,175,10,66,
87,171,204,12,1,44,68
},
{
142,1,145,102,227,81,84,
108,1,120,168,9,14,135,
165,118,141,183,47,235,212,
109,85,167,185,255,89,18,
12,36,41,24,181,66,107,
96,5,160,235,87,33,173,
140,207,20,70,135,44,102
},
{
85,38,191,199,157,183,122,
186,2,236,106,181,53,100,
69,189,22,137,117,230,153,
150,211,184,157,220,165,234,
113,19,238,122,120,233,181,
130,182,140,76,219,162,90,
66,242,19,125,8,215,162
},
{
167,227,240,92,158,80,82,
18,222,92,51,44,252,34,
112,74,12,237,158,156,179,
48,154,47,61,204,24,36,
62,228,29,23,43,176,239,
144,117,131,97,219,129,138,
243,31,33,108,211,255,196
},
{
83,29,187,49,130,95,252,
214,6,223,87,149,168,140,
172,33,170,24,103,180,107,
63,212,92,143,155,126,129,
190,25,211,244,151,103,7,
51,227,119,104,18,177,110,
33,155,104,15,159,62,103
},
{
9,151,31,80,46,220,174,
147,4,3,76,83,157,9,
39,52,79,252,16,63,25,
215,131,90,79,128,143,128,
117,57,224,68,198,98,158,
191,90,222,94,135,106,238,
212,168,164,233,138,106,14
},
{
159,70,200,99,183,101,85,
117,251,218,149,119,199,12,
102,190,144,68,145,212,202,
250,32,118,13,149,136,91,
203,247,68,69,124,122,248,
92,125,154,189,60,160,12,
148,182,162,108,187,198,113
},
{
75,226,151,153,186,223,56,
174,53,4,212,8,241,147,
253,166,123,148,241,166,172,
118,103,6,219,178,187,41,
89,250,28,220,20,27,134,
77,125,14,40,175,125,114,
15,2,160,240,169,186,63
},
{
165,251,182,208,45,34,74,
41,106,244,193,205,160,100,
51,41,232,106,237,201,184,
35,112,98,118,238,38,211,
191,33,221,226,126,55,61,
224,82,255,19,252,131,188,
220,111,242,172,93,61,67
},
{
246,142,205,184,114,219,1,
246,63,229,6,41,167,187,
173,185,75,205,96,37,252,
142,135,8,82,240,138,254,
107,202,42,104,198,71,98,
173,197,100,156,37,180,190,
88,30,229,135,12,58,198
},
{
7,121,166,123,114,32,78,
223,125,21,155,124,116,240,
222,91,57,5,254,51,4,
161,122,236,49,146,88,235,
253,149,42,31,140,254,163,
71,253,70,242,115,10,171,
101,38,217,187,117,31,141
},
{
220,220,58,61,163,182,106,
201,38,91,53,99,7,253,
179,12,108,175,148,246,162,
217,7,36,146,193,22,3,
220,68,101,117,184,62,195,
25,94,226,155,28,43,110,
161,132,70,110,201,58,228
},
{
39,253,170,4,47,122,100,
182,223,98,128,205,167,103,
42,16,227,30,43,181,80,
212,194,100,164,123,181,97,
126,145,213,51,44,135,240,
100,105,151,106,174,180,134,
106,49,72,73,237,2,84
},
{
1,140,181,150,80,96,57,
214,115,209,143,122,31,162,
201,171,155,38,225,68,12,
219,180,253,105,97,208,19,
20,8,84,223,139,223,146,
150,53,161,187,167,163,61,
45,242,115,110,195,89,15
},
{
50,197,196,115,105,176,64,
87,141,157,64,185,202,118,
158,70,79,168,121,141,57,
163,128,141,228,192,195,115,
15,227,176,28,130,126,54,
75,200,45,202,7,158,179,
77,23,142,127,110,31,141
},
{
123,175,80,224,82,146,27,
61,247,16,236,96,150,244,
102,13,165,47,253,185,96,
178,149,204,82,2,235,182,
47,249,110,211,181,241,87,
93,208,215,155,65,168,65,
152,71,236,50,249,80,249
},
{
139,219,5,39,213,136,215,
228,108,228,169,234,173,243,
229,45,65,105,121,208,18,
202,118,209,11,19,178,162,
59,74,82,99,111,28,119,
6,217,203,9,252,227,146,
217,194,195,213,12,221,229
},
{
49,9,169,202,201,231,152,
102,226,150,26,173,50,161,
241,73,224,232,42,44,182,
48,85,6,112,192,109,58,
164,25,233,113,68,229,93,
83,32,42,74,152,119,240,
95,234,245,83,222,203,49
},
{
58,104,2,6,164,206,186,
224,222,73,218,87,103,158,
186,30,242,149,198,193,89,
94,43,38,197,36,33,64,
7,136,243,253,80,61,90,
223,72,116,47,46,190,94,
50,77,217,111,227,35,30
},
{
161,5,6,26,113,239,46,
35,195,65,36,225,119,8,
31,27,206,249,207,129,119,
218,138,239,90,154,78,217,
247,85,161,87,123,185,175,
152,74,2,181,30,66,9,
30,147,91,147,86,146,232
},
{
111,204,65,49,124,16,12,
149,51,137,89,252,190,203,
155,194,84,231,136,213,197,
202,212,73,251,17,80,12,
106,75,180,1,15,52,1,
36,27,194,180,13,226,151,
210,106,27,190,237,194,16
},
{
63,38,43,226,100,106,44,
100,72,214,138,170,142,137,
51,246,203,190,250,5,139,
146,105,90,117,73,83,168,
127,89,106,238,176,54,135,
79,97,13,229,87,119,110,
253,184,151,32,70,14,191
},
{
3,134,209,61,87,248,16,
140,69,243,241,249,240,83,
184,156,4,81,67,134,241,
25,176,185,228,181,65,200,
143,165,255,165,222,193,94,
146,188,178,68,171,218,177,
198,3,208,189,1,204,100
},
{
22,66,132,87,17,19,147,
142,42,56,105,247,102,68,
124,234,205,209,46,130,54,
254,10,162,22,63,87,26,
148,32,114,179,139,23,239,
128,191,233,238,76,251,218,
169,126,70,24,167,70,244
},
{
156,153,114,200,16,71,190,
214,189,154,249,102,57,40,
212,144,211,72,187,194,106,
32,131,241,173,161,83,169,
128,245,153,168,115,72,94,
90,15,107,218,206,232,88,
162,109,52,236,54,42,212
},
{
242,93,89,143,226,33,252,
126,83,174,156,75,156,21,
131,85,147,30,130,90,228,
40,2,178,7,79,138,196,
44,201,134,186,63,196,113,
28,89,156,53,96,166,205,
213,15,57,112,70,138,190
},
{
148,127,27,140,97,157,84,
2,67,71,99,182,13,250,
113,100,84,156,156,16,242,
216,176,107,248,176,40,208,
235,220,159,243,169,56,65,
159,199,244,77,142,201,210,
81,198,4,7,43,126,122
},
{
23,101,250,171,81,20,89,
128,51,189,208,81,88,108,
69,78,59,131,199,38,130,
102,215,54,7,153,251,58,
80,98,150,172,193,144,115,
212,46,119,19,184,10,188,
14,237,241,16,173,125,191
},
{
97,19,206,235,176,242,227,
101,12,97,196,163,218,152,
104,40,3,63,3,39,15,
31,4,138,217,199,156,12,
239,16,55,165,35,249,155,
252,132,220,53,22,68,104,
63,246,158,93,50,126,104
},
{
136,86,29,88,238,198,176,
148,161,188,49,187,54,131,
114,216,90,238,169,131,120,
150,234,162,232,205,105,255,
161,150,158,52,226,116,23,
23,218,114,33,50,169,53,
18,105,210,117,86,89,125
},
{
178,13,149,148,121,91,82,
38,29,64,153,12,44,11,
161,74,139,68,88,35,124,
42,191,86,119,137,56,127,
38,40,69,17,89,107,234,
226,90,137,67,200,96,232,
79,43,143,239,180,33,81
},
{
254,112,239,101,191,19,131,
123,153,174,191,181,101,3,
46,221,48,253,2,188,62,
48,225,85,249,74,118,101,
32,58,51,4,196,252,82,
178,127,201,119,193,107,155,
252,77,54,194,83,192,240
},
{
141,117,43,233,154,235,63,
50,253,75,91,22,195,180,
105,62,225,65,245,173,73,
222,82,82,21,138,31,105,
125,103,13,104,162,169,56,
165,203,198,233,117,38,240,
39,243,174,64,209,60,76
},
{
159,196,56,192,208,188,198,
122,162,99,117,240,187,85,
122,142,242,127,51,213,189,
170,210,194,148,133,133,29,
217,17,181,176,52,189,178,
36,200,26,107,114,103,92,
121,166,6,179,52,234,142
},
{
164,250,146,128,92,129,33,
77,59,62,251,236,133,203,
203,174,137,91,50,172,10,
10,235,227,82,61,235,101,
200,199,150,159,83,13,162,
42,100,220,210,25,21,56,
254,76,23,196,161,169,214
},
{
22,112,203,180,148,28,10,
150,46,218,99,193,146,186,
52,61,36,113,59,173,108,
178,223,233,55,161,52,50,
17,128,164,93,112,43,216,
202,37,131,180,130,100,82,
237,77,23,199,63,30,158
},
{
47,156,173,221,226,110,149,
164,39,71,206,74,250,7,
218,158,122,242,131,252,231,
165,119,158,248,92,168,3,
119,157,186,136,214,160,95,
7,206,124,253,149,155,145,
105,46,239,35,23,126,58
},
{
159,159,134,88,135,222,68,
64,110,148,41,201,20,219,
144,41,1,72,230,41,167,
16,194,210,133,8,165,130,
47,225,148,17,203,103,84,
43,236,41,98,94,76,91,
133,8,79,85,16,175,221
},
{
115,161,236,118,192,144,104,
255,59,191,32,78,18,14,
108,203,171,32,254,80,206,
178,84,132,206,60,193,226,
4,8,188,193,118,133,91,
87,13,9,191,67,23,181,
124,134,134,191,130,95,195
},
{
202,187,20,83,145,231,14,
74,153,208,76,200,34,106,
157,107,9,255,160,250,224,
5,251,57,230,149,200,39,
39,79,170,143,95,141,130,
62,7,170,74,174,17,85,
238,144,174,152,202,247,202
},
{
173,144,151,112,43,60,201,
219,175,238,226,103,153,58,
119,15,237,206,33,193,243,
253,102,63,183,24,77,166,
242,11,72,143,127,79,246,
188,238,128,118,67,87,183,
175,79,239,6,108,52,153
},
{
19,148,26,226,91,100,230,
169,250,250,171,233,136,16,
69,214,232,55,111,210,171,
116,246,96,204,142,82,166,
104,230,80,151,80,59,13,
94,247,35,244,34,181,156,
5,183,210,139,3,95,85
},
{
125,219,35,9,131,243,232,
189,133,142,219,41,228,14,
55,114,188,66,24,210,163,
124,99,75,61,165,94,228,
127,6,12,114,246,253,243,
77,231,101,85,4,164,200,
117,117,240,63,15,76,203
},
{
9,134,85,112,185,245,169,
239,37,166,32,55,179,23,
7,216,118,32,145,113,152,
81,254,2,110,33,225,26,
221,253,151,32,87,233,78,
155,18,169,163,207,196,34,
77,135,154,3,192,96,146
},
{
75,91,117,7,210,246,189,
146,84,107,248,11,41,245,
123,204,73,243,191,15,151,
245,1,109,44,157,204,112,
153,55,210,68,226,149,209,
80,22,29,254,243,76,121,
172,17,1,242,167,176,116
},
{
230,254,102,33,70,173,175,
228,171,233,19,239,231,124,
38,24,147,237,60,159,138,
243,245,16,215,222,97,60,
1,116,241,4,46,3,242,
237,32,9,197,54,119,77,
137,95,57,179,123,232,16
},
{
183,187,60,61,212,166,108,
187,190,151,215,122,188,39,
86,57,254,185,238,247,79,
142,209,107,232,255,138,122,
212,48,23,47,163,228,255,
32,224,187,246,195,5,116,
28,160,96,142,147,222,171
},
{
229,93,42,194,149,50,89,
58,204,91,225,69,212,47,
124,178,247,73,3,94,144,
13,244,241,225,151,159,73,
16,171,96,76,202,185,250,
174,10,152,121,68,111,6,
140,114,166,133,234,104,94
},
{
186,157,156,42,213,188,78,
242,32,136,103,58,86,99,
171,229,203,151,101,196,15,
109,148,140,4,130,208,135,
52,214,212,167,66,145,243,
54,61,240,104,223,212,87,
181,68,19,247,26,217,165
},
{
20,68,71,101,64,63,241,
25,177,222,2,32,2,140,
138,20,101,194,10,249,205,
25,11,29,236,53,13,41,
149,115,115,159,108,172,186,
56,97,223,149,79,240,33,
74,244,153,175,230,173,139
},
{
112,160,137,249,193,254,166,
20,237,27,169,28,25,166,
89,133,11,238,230,171,153,
149,249,253,37,58,38,48,
226,198,210,91,107,161,50,
129,73,109,104,128,240,157,
106,209,245,142,188,44,209
},
{
94,155,95,27,57,178,126,
126,85,239,193,85,88,143,
21,44,88,255,219,33,48,
160,202,89,107,12,103,123,
111,249,20,123,41,72,38,
150,235,92,3,204,197,84,
176,187,243,59,226,49,184
},
{
202,228,64,73,214,118,70,
4,246,243,163,181,137,217,
140,24,167,19,201,69,35,
1,179,95,32,201,86,26,
111,210,1,98,46,226,39,
226,217,237,225,141,89,245,
240,244,44,2,143,156,58
},
{
157,246,3,119,213,223,157,
231,63,233,113,19,222,44,
151,145,130,222,78,190,130,
93,215,44,86,109,232,234,
249,24,206,73,167,235,11,
22,201,8,161,6,173,196,
202,81,229,72,71,33,216
},
{
245,6,229,112,241,89,47,
99,172,118,22,20,193,113,
230,122,251,107,255,10,232,
55,158,24,188,30,159,178,
246,6,211,101,134,171,245,
216,223,48,231,212,198,167,
71,142,46,234,237,200,4
},
};
// GLobals used here, for each event structure used,
// Used as globals for stack reasons
EV_E_PLAYSOUND EPlaySound;
EV_S_CHANGESTATE SChangeState;
EV_S_CHANGEDEST SChangeDest;
EV_S_SETPOSITION SSetPosition;
EV_S_GETNEWPATH SGetNewPath;
EV_S_BEGINTURN SBeginTurn;
EV_S_CHANGESTANCE SChangeStance;
EV_S_SETDIRECTION SSetDirection;
EV_S_SETDESIREDDIRECTION SSetDesiredDirection;
EV_S_BEGINFIREWEAPON SBeginFireWeapon;
EV_S_FIREWEAPON SFireWeapon;
EV_S_WEAPONHIT SWeaponHit;
EV_S_STRUCTUREHIT SStructureHit;
EV_S_WINDOWHIT SWindowHit;
EV_S_MISS SMiss;
EV_S_NOISE SNoise;
EV_S_STOP_MERC SStopMerc;
EV_S_SENDPATHTONETWORK SUpdateNetworkSoldier;
extern BOOLEAN gfAmINetworked;
BOOLEAN AddGameEventToQueue( UINT32 uiEvent, UINT16 usDelay, PTR pEventData, UINT8 ubQueueID );
BOOLEAN ExecuteGameEvent( EVENT *pEvent );
BOOLEAN AddGameEvent( UINT32 uiEvent, UINT16 usDelay, PTR pEventData )
{
if (usDelay == DEMAND_EVENT_DELAY)
{
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("AddGameEvent: Sending Local and network #%d", uiEvent));
#ifdef NETWORKED
if(gfAmINetworked)
SendEventToNetwork(uiEvent, usDelay, pEventData);
#endif
return( AddGameEventToQueue( uiEvent, 0, pEventData, DEMAND_EVENT_QUEUE ) );
}
else if( uiEvent < EVENTS_LOCAL_AND_NETWORK)
{
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("AddGameEvent: Sending Local and network #%d", uiEvent));
#ifdef NETWORKED
if(gfAmINetworked)
SendEventToNetwork(uiEvent, usDelay, pEventData);
#endif
return( AddGameEventToQueue( uiEvent, usDelay, pEventData, PRIMARY_EVENT_QUEUE ) );
}
else if( uiEvent < EVENTS_ONLY_USED_LOCALLY)
{
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("AddGameEvent: Sending Local #%d", uiEvent));
return( AddGameEventToQueue( uiEvent, usDelay, pEventData, PRIMARY_EVENT_QUEUE ) );
}
else if( uiEvent < EVENTS_ONLY_SENT_OVER_NETWORK)
{
//DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("AddGameEvent: Sending network #%d", uiEvent));
#ifdef NETWORKED
if(gfAmINetworked)
SendEventToNetwork(uiEvent, usDelay, pEventData);
#endif
return(TRUE);
}
// There is an error with the event
else
return(FALSE);
}
BOOLEAN AddGameEventFromNetwork( UINT32 uiEvent, UINT16 usDelay, PTR pEventData )
{
return( AddGameEventToQueue( uiEvent, usDelay, pEventData, PRIMARY_EVENT_QUEUE ) );
}
BOOLEAN AddGameEventToQueue( UINT32 uiEvent, UINT16 usDelay, PTR pEventData, UINT8 ubQueueID )
{
UINT32 uiDataSize;
// Check range of Event ui
if ( uiEvent < 0 || uiEvent > NUM_EVENTS )
{
// Set debug message!
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Unknown event type");
return( FALSE );
}
// Switch on event type and set size accordingly
switch( uiEvent )
{
case E_PLAYSOUND:
uiDataSize = sizeof( EV_E_PLAYSOUND );
break;
case S_CHANGESTATE:
uiDataSize = sizeof( EV_S_CHANGESTATE );
break;
case S_CHANGEDEST:
uiDataSize = sizeof( EV_S_CHANGEDEST );
break;
case S_SETPOSITION:
uiDataSize = sizeof( EV_S_SETPOSITION );
break;
case S_GETNEWPATH:
uiDataSize = sizeof( EV_S_GETNEWPATH );
break;
case S_BEGINTURN:
uiDataSize = sizeof( EV_S_BEGINTURN );
break;
case S_CHANGESTANCE:
uiDataSize = sizeof( EV_S_CHANGESTANCE );
break;
case S_SETDIRECTION:
uiDataSize = sizeof( EV_S_SETDIRECTION );
break;
case S_SETDESIREDDIRECTION:
uiDataSize = sizeof( EV_S_SETDESIREDDIRECTION );
break;
case S_FIREWEAPON:
uiDataSize = sizeof( EV_S_FIREWEAPON );
break;
case S_BEGINFIREWEAPON:
uiDataSize = sizeof( EV_S_BEGINFIREWEAPON );
//Delay this event
break;
case S_WEAPONHIT:
uiDataSize = sizeof( EV_S_WEAPONHIT );
break;
case S_STRUCTUREHIT:
uiDataSize = sizeof( EV_S_STRUCTUREHIT );
break;
case S_WINDOWHIT:
uiDataSize = sizeof( EV_S_STRUCTUREHIT );
break;
case S_MISS:
uiDataSize = sizeof( EV_S_MISS );
break;
case S_NOISE:
uiDataSize = sizeof( EV_S_NOISE );
break;
case S_STOP_MERC:
uiDataSize = sizeof( EV_S_STOP_MERC );
break;
case S_SENDPATHTONETWORK:
uiDataSize = sizeof(EV_S_SENDPATHTONETWORK);
break;
case S_UPDATENETWORKSOLDIER:
uiDataSize = sizeof(EV_S_UPDATENETWORKSOLDIER);
break;
default:
// Set debug msg: unknown message!
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Event Type mismatch");
return( FALSE );
}
CHECKF( AddEvent( uiEvent, usDelay, pEventData, uiDataSize, ubQueueID ) );
// successful
return( TRUE );
}
BOOLEAN DequeAllGameEvents( BOOLEAN fExecute )
{
EVENT *pEvent;
UINT32 uiQueueSize, cnt;
BOOLEAN fCompleteLoop = FALSE;
// First dequeue all primary events
while( EventQueueSize( PRIMARY_EVENT_QUEUE ) > 0 )
{
// Get Event
if ( RemoveEvent( &pEvent, 0, PRIMARY_EVENT_QUEUE) == FALSE )
{
return( FALSE );
}
if ( fExecute )
{
// Check if event has a delay and add to secondary queue if so
if ( pEvent->usDelay > 0 )
{
AddGameEventToQueue( pEvent->uiEvent, pEvent->usDelay, pEvent->pData, SECONDARY_EVENT_QUEUE );
}
else
{
ExecuteGameEvent( pEvent );
}
}
// Delete event
FreeEvent( pEvent );
};
// NOW CHECK SECONDARY QUEUE FOR ANY EXPRIED EVENTS
// Get size of queue
uiQueueSize = EventQueueSize( SECONDARY_EVENT_QUEUE );
for ( cnt = 0; cnt < uiQueueSize; cnt++ )
{
if ( PeekEvent( &pEvent, cnt, SECONDARY_EVENT_QUEUE) == FALSE )
{
return( FALSE );
}
// Check time
if ( ( GetJA2Clock() - pEvent->TimeStamp ) > pEvent->usDelay )
{
if ( fExecute )
{
ExecuteGameEvent( pEvent );
}
// FLag as expired
pEvent->uiFlags = EVENT_EXPIRED;
}
}
do
{
uiQueueSize = EventQueueSize( SECONDARY_EVENT_QUEUE );
for ( cnt = 0; cnt < uiQueueSize; cnt++ )
{
if ( PeekEvent( &pEvent, cnt, SECONDARY_EVENT_QUEUE) == FALSE )
{
return( FALSE );
}
// Check time
if ( pEvent->uiFlags & EVENT_EXPIRED )
{
RemoveEvent( &pEvent, cnt, SECONDARY_EVENT_QUEUE );
FreeEvent( pEvent );
// Restart loop
break;
}
}
if ( cnt == uiQueueSize )
{
fCompleteLoop = TRUE;
}
} while( fCompleteLoop == FALSE );
return( TRUE );
}
BOOLEAN DequeueAllDemandGameEvents( BOOLEAN fExecute )
{
EVENT *pEvent;
// Dequeue all events on the demand queue (only)
while( EventQueueSize( DEMAND_EVENT_QUEUE ) > 0 )
{
// Get Event
if ( RemoveEvent( &pEvent, 0, DEMAND_EVENT_QUEUE) == FALSE )
{
return( FALSE );
}
if ( fExecute )
{
// Check if event has a delay and add to secondary queue if so
if ( pEvent->usDelay > 0 )
{
AddGameEventToQueue( pEvent->uiEvent, pEvent->usDelay, pEvent->pData, SECONDARY_EVENT_QUEUE );
}
else
{
ExecuteGameEvent( pEvent );
}
}
// Delete event
FreeEvent( pEvent );
};
return( TRUE );
}
BOOLEAN ExecuteGameEvent( EVENT *pEvent )
{
SOLDIERTYPE *pSoldier;
// Switch on event type
switch( pEvent->uiEvent )
{
case E_PLAYSOUND:
memcpy( &EPlaySound, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Play Sound");
PlayJA2Sample( EPlaySound.usIndex, EPlaySound.usRate, EPlaySound.ubVolume, EPlaySound.ubLoops, EPlaySound.uiPan );
break;
case S_CHANGESTATE:
memcpy( &SChangeState, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SChangeState.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SChangeState.uiUniqueId )
{
break;
}
// Call soldier function
// DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Event Pump: ChangeState %S (%d)", gAnimControl[ SChangeState.ubNewState ].zAnimStr, SChangeState.usSoldierID ) );
pSoldier->EVENT_InitNewSoldierAnim( SChangeState.usNewState, SChangeState.usStartingAniCode, SChangeState.fForce );
break;
case S_CHANGEDEST:
memcpy( &SChangeDest, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SChangeDest.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Event Pump: Invalid Soldier ID #%d", SChangeDest.usSoldierID) );
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SChangeDest.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Change Dest");
pSoldier->EVENT_SetSoldierDestination( (UINT8) SChangeDest.usNewDestination );
break;
case S_SETPOSITION:
memcpy( &SSetPosition, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SSetPosition.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SSetPosition.uiUniqueId )
{
break;
}
// Call soldier function
// DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: SetPosition ( %f %f ) ( %d )", SSetPosition.dNewXPos, SSetPosition.dNewYPos, SSetPosition.usSoldierID ) );
pSoldier->EVENT_SetSoldierPosition( SSetPosition.dNewXPos, SSetPosition.dNewYPos );
break;
case S_GETNEWPATH:
memcpy( &SGetNewPath, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SGetNewPath.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SGetNewPath.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: GetNewPath");
pSoldier->EVENT_GetNewSoldierPath( SGetNewPath.sDestGridNo, SGetNewPath.usMovementAnim );
break;
case S_BEGINTURN:
memcpy( &SBeginTurn, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SBeginTurn.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SBeginTurn.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: BeginTurn");
pSoldier->EVENT_BeginMercTurn( FALSE, 0 );
break;
case S_CHANGESTANCE:
memcpy( &SChangeStance, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SChangeStance.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SChangeStance.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: ChangeStance");
pSoldier->ChangeSoldierStance( SChangeStance.ubNewStance );
break;
case S_SETDIRECTION:
memcpy( &SSetDirection, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SSetDirection.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SSetDirection.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: SetDirection: Dir( %d )", SSetDirection.usNewDirection) );
pSoldier->EVENT_SetSoldierDirection( SSetDirection.usNewDirection );
break;
case S_SETDESIREDDIRECTION:
memcpy( &SSetDesiredDirection, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SSetDesiredDirection.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SSetDesiredDirection.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: SetDesiredDirection: Dir( %d )", SSetDesiredDirection.usDesiredDirection) );
pSoldier->EVENT_SetSoldierDesiredDirection( (UINT8) SSetDesiredDirection.usDesiredDirection );
break;
case S_BEGINFIREWEAPON:
memcpy( &SBeginFireWeapon, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SBeginFireWeapon.usSoldierID ) == FALSE )
{
pSoldier = NULL;
break;
// Handle Error?
// DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SBeginFireWeapon.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Begin Fire Weapon");
pSoldier->sTargetGridNo = SBeginFireWeapon.sTargetGridNo;
pSoldier->bTargetLevel = SBeginFireWeapon.bTargetLevel;
pSoldier->bTargetCubeLevel = SBeginFireWeapon.bTargetCubeLevel;
pSoldier->EVENT_FireSoldierWeapon( SBeginFireWeapon.sTargetGridNo );
break;
case S_FIREWEAPON:
memcpy( &SFireWeapon, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SFireWeapon.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
// check for error
if( pSoldier->uiUniqueSoldierIdValue != SFireWeapon.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: FireWeapon");
pSoldier->sTargetGridNo = SFireWeapon.sTargetGridNo;
pSoldier->bTargetLevel = SFireWeapon.bTargetLevel;
pSoldier->bTargetCubeLevel = SFireWeapon.bTargetCubeLevel;
FireWeapon( pSoldier, SFireWeapon.sTargetGridNo );
break;
case S_WEAPONHIT:
memcpy( &SWeaponHit, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: WeaponHit %d Damage", SWeaponHit.sDamage ) );
WeaponHit( SWeaponHit.usSoldierID, SWeaponHit.usWeaponIndex, SWeaponHit.sDamage, SWeaponHit.sBreathLoss, SWeaponHit.usDirection, SWeaponHit.sXPos, SWeaponHit.sYPos, SWeaponHit.sZPos, SWeaponHit.sRange, SWeaponHit.ubAttackerID, SWeaponHit.fHit, SWeaponHit.ubSpecial, SWeaponHit.ubLocation );
break;
case S_STRUCTUREHIT:
memcpy( &SStructureHit, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: StructureHit" ) );
StructureHit( SStructureHit.iBullet, SStructureHit.usWeaponIndex, SStructureHit.bWeaponStatus, SStructureHit.ubAttackerID, SStructureHit.sXPos, SStructureHit.sYPos, SStructureHit.sZPos, SStructureHit.usStructureID, SStructureHit.iImpact, TRUE );
break;
case S_WINDOWHIT:
memcpy( &SWindowHit, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: WindowHit" ) );
WindowHit( SWindowHit.sGridNo, SWindowHit.usStructureID, SWindowHit.fBlowWindowSouth, SWindowHit.fLargeForce );
break;
case S_MISS:
memcpy( &SMiss, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: Shot Miss ( obsolete )" ) );
//ShotMiss( SMiss.ubAttackerID );
break;
case S_NOISE:
memcpy( &SNoise, pEvent->pData, pEvent->uiDataSize );
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String( "Event Pump: Noise from %d at %d/%d, type %d volume %d", SNoise.ubNoiseMaker, SNoise.sGridNo, SNoise.bLevel, SNoise.ubNoiseType, SNoise.ubVolume ) );
OurNoise( SNoise.ubNoiseMaker, SNoise.sGridNo, SNoise.bLevel, SNoise.ubTerrType, SNoise.ubVolume, SNoise.ubNoiseType, SNoise.zNoiseMessage );
break;
case S_STOP_MERC:
memcpy( &SStopMerc, pEvent->pData, pEvent->uiDataSize );
// Get soldier pointer from ID
if ( GetSoldier( &pSoldier, SStopMerc.usSoldierID ) == FALSE )
{
// Handle Error?
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Soldier ID");
break;
}
if( pSoldier->uiUniqueSoldierIdValue != SStopMerc.uiUniqueId )
{
break;
}
// Call soldier function
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, String("Event Pump: Stop Merc at Gridno %d", SStopMerc.sGridNo ));
pSoldier->EVENT_StopMerc( SStopMerc.sGridNo, SStopMerc.ubDirection );
break;
default:
DebugMsg( TOPIC_JA2, DBG_LEVEL_3, "Event Pump: Invalid Event Received");
return( FALSE );
}
return( TRUE );
}
BOOLEAN ClearEventQueue( void )
{
// clear out the event queue
EVENT *pEvent;
while( EventQueueSize( PRIMARY_EVENT_QUEUE ) > 0 )
{
// Get Event
if ( RemoveEvent( &pEvent, 0, PRIMARY_EVENT_QUEUE) == FALSE )
{
return( FALSE );
}
}
return( TRUE );
}
| [
"git@fluffyquack.com"
] | git@fluffyquack.com |
b00c4bb0f8717c36d5da4ba9ffb600ed73d7a227 | 53eebacd00bedc8cccb5c652ca8a68febeff4044 | /Alto_Adventure/PowerUp.cpp | 4eb87fb79c83b01f48208cd2ffbc9062a7aab769 | [] | no_license | iop01447/alto-adventure | 0c4103228bc34cfda4e07283818829c0ccc2728a | b5cb8872f2f9fe54b1196c78641d835d34d5f10f | refs/heads/master | 2021-03-14T06:56:23.859702 | 2020-03-17T00:26:52 | 2020-03-17T00:26:52 | 246,747,974 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,837 | cpp | #include "stdafx.h"
#include "PowerUp.h"
#include "ObjMgr.h"
#include "TextureMgr.h"
CPowerUp::CPowerUp()
{
}
CPowerUp::~CPowerUp()
{
Release();
}
void CPowerUp::Initialize()
{
m_tInfo.vScale = { 0.15f, 0.15f, 0.f };
m_eGroupID = GROUPID::FOREWORD_GAMEOBJECT;
}
int CPowerUp::Update()
{
if (m_bDead)
return OBJ_DEAD;
m_tInfo.vPos.x -= (GET_INSTANCE(CObjMgr)->Get_Speed());
Update_Rect();
if (Fall())
m_tInfo.vPos.y -= 25;
return OBJ_NOEVENT;
}
void CPowerUp::Late_Update()
{
if (m_tInfo.vPos.x + m_tInfo.vSize.x * 0.5f < 0)
m_bDead = true;
if (GET_INSTANCE(CObjMgr)->Get_Obj(OBJID::PLAYER)->Get_MagnetON())
{
D3DXVECTOR3 vPlayer = GET_INSTANCE(CObjMgr)->Get_Obj(OBJID::PLAYER)->Get_Info().vPos;
vPlayer -= m_tInfo.vPos;
if (WINCX >> 1 > sqrtf((vPlayer.x * vPlayer.x) + (vPlayer.y * vPlayer.y)))
m_tInfo.vPos.x -= 15;
}
}
void CPowerUp::Render()
{
const TEXINFO* pTexInfo = GET_INSTANCE(CTextureMgr)->Get_TexInfo(L"PowerUp");
float fCenterX = pTexInfo->tImageInfo.Width * 0.5f;
float fCenterY = pTexInfo->tImageInfo.Height * 0.5f;
D3DXMATRIX matScale, matTrans, matWorld;
D3DXMatrixScaling(&matScale, m_tInfo.vScale.x, m_tInfo.vScale.y, 0.f);
m_tInfo.vSize = { pTexInfo->tImageInfo.Width * m_tInfo.vScale.x, pTexInfo->tImageInfo.Height * m_tInfo.vScale.y, 0.f };
D3DXMatrixTranslation(&matTrans, m_tInfo.vPos.x, m_tInfo.vPos.y, 0.f);
matWorld = matScale * matTrans;
CDevice::Get_Instance()->Get_Sprite()->SetTransform(&matWorld);
CDevice::Get_Instance()->Get_Sprite()->Draw(pTexInfo->pTexture,
nullptr,
&D3DXVECTOR3(fCenterX, fCenterY, 0.f),
nullptr,
D3DCOLOR_ARGB(255, 255, 255, 255));
}
void CPowerUp::Release()
{
}
void CPowerUp::Collision(CObj * pOther)
{
if (pOther->Get_ObjID() != OBJID::PLAYER)
return;
m_bDead = true;
}
| [
"twlls2@naver.com"
] | twlls2@naver.com |
2c109e4e22704c008b2f34fc72a8eea0dcf19dde | 057f2783821562579dea238c1073d0ba0839b402 | /RecognitionNLP - praca licencjacka/.localhistory/RecognitionNLP/1470139642$Recognitionnlp.cpp | e7a3fad310b8341af7791d362ee526a89d1c1816 | [] | no_license | KrzysztofKozubek/Projects | 6cafb2585796c907e8a818da4b51c97197ccbd11 | 66ef23fbc8a6e6cf3b6ef837b390d7f2113a9847 | refs/heads/master | 2023-02-07T12:24:49.155221 | 2022-10-08T18:39:58 | 2022-10-08T18:39:58 | 163,520,516 | 0 | 0 | null | 2023-02-04T17:46:12 | 2018-12-29T15:18:18 | null | UTF-8 | C++ | false | false | 42,154 | cpp | #include "Recognitionnlp.h"
RecognitionNLP::RecognitionNLP(QWidget *parent) : QMainWindow(parent) {
ui.setupUi(this);
setParameters();
fillVectorValue();
fillDefaultValue();
//load data
connect(ui.buttonLoadData, SIGNAL(released()), this, SLOT(clickLoadData()));
//clear list data
connect(ui.buttonLoadClearData, SIGNAL(released()), this, SLOT(clickClearData()));
//show sliders noising
connect(ui.rbPropertysContrast, SIGNAL(released()), this, SLOT(selectRBContrast()));
connect(ui.rbPropertysBlur, SIGNAL(released()), this, SLOT(selectRBBlur()));
connect(ui.rbPropertysGaussianBlur, SIGNAL(released()), this, SLOT(selectRBGaussianBlur()));
connect(ui.rbPropertysMedianBlur, SIGNAL(released()), this, SLOT(selectRBMedianBlur()));
connect(ui.rbPropertysBilateralFilter, SIGNAL(released()), this, SLOT(selectRBBilateralFilter()));
connect(ui.rbPropertysErode, SIGNAL(released()), this, SLOT(selectRBErode()));
connect(ui.rbPropertysDilate, SIGNAL(released()), this, SLOT(selectRBDilate()));
connect(ui.rbPropertysZoom, SIGNAL(released()), this, SLOT(selectRBZoom()));
connect(ui.rbPropertysFiltrTwoD, SIGNAL(released()), this, SLOT(selectRBFiltrTwoD()));
connect(ui.rbAffinePropertysTransformations,SIGNAL(released()), this, SLOT(selectRBAffineTransformations()));
//change value next to slider
for each (QSlider* var in vSliderValue)
connect(var, SIGNAL(sliderReleased()), this, SLOT(moveSlider()));
for each (QSlider* var in vSliderMisstakeValue)
connect(var, SIGNAL(sliderReleased()), this, SLOT(moveSlider()));
//add noising
connect(ui.buttonPropertysAddNoising, SIGNAL(released()), this, SLOT(clickAddNoising()));
//clear noising
connect(ui.buttonPropertysCleaerNoising, SIGNAL(released()), this, SLOT(clickClearNoising()));
//generate noising image
connect(ui.buttonPropertysNoising, SIGNAL(released()), this, SLOT(clickGenerateNosingImage()));
//segmentation
connect(ui.RBSegmetation1, SIGNAL(released()), this, SLOT(clickSegmentationErode()));
connect(ui.RBSegmetation2, SIGNAL(released()), this, SLOT(clickSegmentationContrast()));
connect(ui.RBSegmetation3, SIGNAL(released()), this, SLOT(clickSegmentationBW()));
connect(ui.RBSegmetation4, SIGNAL(released()), this, SLOT(clickSegmentationCutimage()));
connect(ui.RBSegmetation5, SIGNAL(released()), this, SLOT(clickSegmentationNegative()));
connect(ui.RBSegmetation6, SIGNAL(released()), this, SLOT(clickSegmentationSumControl()));
for each (QSlider* var in vHSSegmentation)
connect(var, SIGNAL(sliderReleased()), this, SLOT(SegmentationUpDatevParameters()));
//button pre processing
connect(ui.buttonPreProcessing, SIGNAL(released()), this, SLOT(preProcessing()));
//button segmentation
connect(ui.buttonSegmentation, SIGNAL(released()), this, SLOT(segmentation()));
//button training
connect(ui.buttonRunTest, SIGNAL(released()), this, SLOT(training()));
//buton test
connect(ui.buttonPredicleRunTest, SIGNAL(released()), this, SLOT(runTest()));
connect(ui.buttonCreatVF, SIGNAL(released()), this, SLOT(saveFileVectorFeauter()));
connect(ui.myTest, SIGNAL(released()), this, SLOT(myTest()));
connect(ui.buttonGeneratorSign, SIGNAL(released()), this, SLOT(generatorSign()));
}
RecognitionNLP::~RecognitionNLP() {}
#pragma region
void RecognitionNLP::setParameters() {
//find CSVM linear
if(0)
for (double c = 100000; c > 0.0001; c/=2) {
//CSVM::cmdRun("echo " + itos(c) + " >> C:\\Test\\linear.bat");
CSVM::cmdRun("echo C:\\Test\\svm-train.exe -s 1 -t 0 -c " + itos(c) + " -q C:\\Test\\SVF.txt C:\\Test\\SVFTraining.txt00.model >> C:\\Test\\linear.bat");
//CSVM::cmdRun("echo echo svm-train.exe -s 0 -t 0 -c " + itos(c) + " \>\> C:\\Test\\r.txt >> C:\\Test\\linear.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\SVFT1Zb1.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\linear.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\VF.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\linear.bat");
}
/*-g -r -d -c -e*/
if (0) {
for (double c = 100000; c > 0.0001; c /= 10) {
for (double g = 100; g > 0.0001; g /= 10) {
for (double d = 10; d > 0.01; d /= 10) {
if (0)
CSVM::cmdRun("echo " + itos(g) + " >> C:\\Test\\wielomian.bat");
if (0)
CSVM::cmdRun("echo " + itos(c) + " >> C:\\Test\\wielomian.bat");
if (0)
CSVM::cmdRun("echo " + itos(d) + " >> C:\\Test\\wielomian.bat");
if (0) {
CSVM::cmdRun("echo C:\\Test\\svm-train.exe -s 0 -t 2 -c " + itos(c) + " -g " + itos(g) + " -d " + itos(d) + " -q C:\\Test\\SVF.txt C:\\Test\\SVFTraining.txt00.model >> C:\\Test\\wielomian.bat");
//CSVM::cmdRun("echo echo svm-train.exe -s 0 -t 1 -c " + itos(c) + " \>\> C:\\Test\\r.txt >> C:\\Test\\rbf.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\SVFT1Zb1.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\wielomian.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\VF.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\wielomian.bat");
}
}
}
}
}
/*
SET "c=50"
SET "g=0.03"
SET "r=0.1
"*/
if(0)
for (double c = 100000; c > 0.0001; c /= 10) {
for (double g = 100; g > 0.0001; g /= 10) {
if(0)
CSVM::cmdRun("echo " + itos(g) + " >> C:\\Test\\rbf.bat");
if (0)
CSVM::cmdRun("echo " + itos(c) + " >> C:\\Test\\rbf.bat");
if (1){
CSVM::cmdRun("echo C:\\Test\\svm-train.exe -s 1 -t 2 -c " + itos(c) + " -g " + itos(g) + " -q C:\\Test\\SVF.txt C:\\Test\\SVFTraining.txt00.model >> C:\\Test\\rbf.bat");
//CSVM::cmdRun("echo echo svm-train.exe -s 0 -t 1 -c " + itos(c) + " \>\> C:\\Test\\r.txt >> C:\\Test\\rbf.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\SVFT1Zb1.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\rbf.bat");
CSVM::cmdRun("echo C:\\Test\\svm-predict.exe C:\\Test\\VF.txt C:\\Test\\SVFTraining.txt00.model C:\\Test\\result \>\> C:\\Test\\r.txt >> C:\\Test\\rbf.bat");
}
}
}
}
void RecognitionNLP::test() {
static const int NUMBER_SYMBOL = 35;
char sign[NUMBER_SYMBOL] = {
'0','1','2','3','4','5','6','7','8','9', //10
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //8
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //8
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' //9
};
int nrSign[NUMBER_SYMBOL] = {
0,0,0,0,0,0,0,0,0,0, //10
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0,0 //9
};
/* Path to main dictionary */
const string PATH_SCRIPTS = "SCRIPTS\\";
const string PATH_SET = "SET\\";
const string PATH_ALL_PLATE = PATH_SET + "NLP\\";
/* Path to dictionary libsvm */
const string PATH_LIBSVM = PATH_SCRIPTS + "libsvm\\";
const string PATH_CLASSIFIER = PATH_SCRIPTS + "Classifier\\";
/* Path to dictionary training data */
const string PATH_TRAINING = PATH_SET + "Training\\";
/* Path to dictionary test data */
const string PATH_SET_ONE = PATH_SET + "Test_I\\";
const string PATH_SET_TWO = PATH_SET + "Test_II\\";
/* CLEAR DATA IN DICTIONARY */
clearFolder()
}
void RecognitionNLP::myTest() {
static const int NUMBER_SYMBOL = 35;
const string PATH_TRAIN = "C:\\Test\\zbiory\\uczacy\\";
const string PATH_TESTI = "C:\\Test\\zbiory\\testI\\";
const string PATH_TESII = "C:\\Test\\zbiory\\testII\\";
char sign[NUMBER_SYMBOL] = {
'0','1','2','3','4','5','6','7','8','9', //10
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', //8
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', //8
'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z' //9
};
int nrSign[NUMBER_SYMBOL] = {
0,0,0,0,0,0,0,0,0,0, //10
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0,0 //9
};
/* LOAD DATA */
clearFolder("C:\\Test\\zbiory\\all\\");
clearFolder(PATH_TRAIN);
clearFolder(PATH_TESTI);
clearFolder(PATH_TESII);
/* SEGMENTATION */
vector<Mat> tmp;
Mat tmp2;
string help;
CSegmentation segmentation(&distorted, vParameters);
string tmpName;
/* SPLIT VECTORS FEATURES */
int limitSignT1 = 100;
int nrSignT1[NUMBER_SYMBOL] = {
0,0,0,0,0,0,0,0,0,0, //10
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0, //8
0,0,0,0,0,0,0,0,0 //9
};
int numberOfSign = 0;
vector<int> vLabelTrain;
vector<vector<float>> vTrainingTrain;
int nrT1Training = 0;
vector<int> vLabelTest;
vector<vector<float>> vTrainingTest;
int nrT1Zb1 = 0;
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<string> filesList = getListFileFrom(path);
for each(string var in filesList) {
tmp.clear();
tmp2 = imread(path + var);
distorted.distortingImg(tmp2);
tmp = segmentation.segmentationNLP(tmp2, vParameters, vParameters[10]);
imshow("MAIN", tmp2);
int numberSign = -1;
int ntmp = 0;
for (int i = 0; i < tmp.size() && i < var.size() - 4; i++) {
for (int j = 0; j < NUMBER_SYMBOL; j++) {
if (sign[j] == var[i])
numberSign = j;
}
if (numberSign != -1) {
if (limitSignT1 > nrSignT1[numberSign]) {
Mat result = segmentation.addAngle(tmp[i]);
nrSignT1[numberSign]++;
help = PATH_TRAIN;
help += sign[numberSign];
help += "_" + itos(nrT1Training) + "_" + itos(numberOfSign) + ".png";
imwrite(help, result);
nrT1Training++;
imshow(itos(ntmp), result);
ntmp++;
vLabelTrain.push_back(numberSign);
vTrainingTrain.push_back(*countMoment(result));
}
else {
Mat result = segmentation.addAngle(tmp[i], 1, 0);
help = PATH_TESTI;
help += sign[numberSign];
help += "_" + itos(nrT1Zb1) + "_" + itos(numberOfSign) + ".png";
imwrite(help, result);
nrT1Zb1++;
imshow(itos(ntmp), result);
ntmp++;
vLabelTest.push_back(numberSign);
vTrainingTest.push_back(*countMoment(result));
}
Mat result = segmentation.addAngle(tmp[i], 1, 0);
tmpName = "C:\\Test\\zbiory\\all\\";
tmpName += itos(i);
tmpName += ".png";
imwrite(tmpName, result);
}
}
numberOfSign++;
//waitKey();
}
//training test 1
int* labelT1Training = new int[vLabelTrain.size()];
float** trainingDataT1Training = new float*[vLabelTrain.size()];
//set 1 test 1
int* labelT1Zb1 = new int[vLabelTest.size()];
float** trainingDataT1Zb1 = new float*[vLabelTest.size()];
for (int i = 0; i < vLabelTrain.size(); i++) {
labelT1Training[i] = vLabelTrain[i];
trainingDataT1Training[i] = new float[vTrainingTrain[i].size()];
for (int j = 0; j < vTrainingTrain[i].size(); j++)
trainingDataT1Training[i][j] = vTrainingTrain[i][j];
}
for (int i = 0; i < vLabelTest.size(); i++) {
labelT1Zb1[i] = vLabelTest[i];
trainingDataT1Zb1[i] = new float[vTrainingTest[i].size()];
for (int j = 0; j < vTrainingTest[i].size(); j++)
trainingDataT1Zb1[i][j] = vTrainingTest[i][j];
}
/* SAVE VECTOR FEAUTERS TO FILE */
string pathTest = "C:\\Test\\skrypty\\";
string test1Training = "SVFT1Training.txt";
string test1Zb1 = "SVFT1Zb1.txt";
string test1Zb2 = "SVFT1Zb2.txt";
CSVM nu_svm;
//save test 1 SVF training
nu_svm.saveVectorToFile(labelT1Training, trainingDataT1Training, pathTest + test1Training, pathTest, nrT1Training);
//save test 2 SVF training
//nu_svm.saveVectorToFile(labelT2Training, trainingDataT2Training, pathTest + test2Training, nrT2Training, false);
//save test 1 SVF set 1
nu_svm.saveVectorToFile(labelT1Zb1, trainingDataT1Zb1, pathTest + test1Zb1, pathTest, nrT1Zb1);
//save test 1 SVF set 2
//nu_svm.saveVectorToFile(labelT1Zb1, trainingDataT1Zb1, pathTest + test1Zb2, nrT1Zb1, false);
//save test 2 SVF set 1
//nu_svm.saveVectorToFile(labelT2Zb1, trainingDataT2Zb1, pathTest + test2Zb1, nrT2Zb1, false);
//save test 2 SVF set 2
//nu_svm.saveVectorToFile(labelT2Zb2, trainingDataT2Zb2, pathTest + test2Zb2, nrT2Zb2, false);
/* CREAETE GRID SEARCH */
string GS_Linear = pathTest + "GSLinear.bat";
string GS_RBF = pathTest + "GSRBF.bat";
//Linear
CSVM::cmdRun("echo @echo OFF >> " + GS_Linear);
CSVM::cmdRun("echo SET \"svm=0\" >> " + GS_Linear);
CSVM::cmdRun("echo SET \"kernel=0\" >> " + GS_Linear);
for (int c = 1; c < 10000; c *= 2) {
CSVM::cmdRun("echo " + pathTest + "svm-train.exe -s %svm% -t %kernel% -c " + itos(c) + " -q " + pathTest + test1Training + " " + pathTest + test1Training + "00.model >> " + GS_Linear);
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb1 + " " + pathTest + test1Training + "00.model R.txt " + " >> " + GS_Linear);
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb2 + " " + pathTest + test1Training + "00.model R.txt " + " >> " + GS_Linear);
}
//RBF
CSVM::cmdRun("echo @echo OFF >> " + GS_RBF);
CSVM::cmdRun("echo SET \"svm=0\" >> " + GS_RBF);
CSVM::cmdRun("echo SET \"kernel=1\" >> " + GS_RBF);
for (int c = 1; c < 10000; c *= 2) {
for (double g = 0.001; g < 10; g *= 2) {
CSVM::cmdRun("echo " + pathTest + "svm-train.exe -s %svm% -t %kernel% -c " + itos(c) + " -g " + itos(g) + " -q " + pathTest + test1Training + " " + pathTest + test1Training + "02.model >> " + GS_RBF);
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb1 + " " + pathTest + test1Training + "02.model R.txt " + " >> " + GS_RBF);
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb2 + " " + pathTest + test1Training + "02.model R.txt " + " >> " + GS_RBF);
}
}
/* CREATE MODELS *//*
CSVM::cmdRun("echo @ECHO OFF >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"svm=0\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"kernel=0\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"e=1\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"c=1\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-train.exe -s %svm% -t %kernel% -e %e% -c %c% -q " + pathTest + test1Training + " " + pathTest + test1Training + "00.model >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"kernel=2\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"e=0.002\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"c=4\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo SET \"g=1\" >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-train.exe -s %svm% -t %kernel% -g %g% -e %e% -c %c% -q " + pathTest + test1Training + " " + pathTest + test1Training + "02.model >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo echo Test 1 SET 1 >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb1 + " " + pathTest + test1Training + "00.model " + pathTest + "result >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb2 + " " + pathTest + test1Training + "02.model " + pathTest + "result >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo echo Test 2 SET 1 >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb1 + " " + pathTest + test1Training + "00.model " + pathTest + "result >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo " + pathTest + "svm-predict.exe " + pathTest + test1Zb2 + " " + pathTest + test1Training + "02.model " + pathTest + "result >> " + pathTest + "skrypt.bat");
CSVM::cmdRun("echo PAUSE \>nul >> " + pathTest + "skrypt.bat");
CSVM::cmdRun(pathTest + "skrypt.bat");
*/
}
vector<float>* RecognitionNLP::countMoment(Mat image) {
vector<float>* trainingData = new vector<float>();
double hu[7];
if (CV_RGB2GRAY != image.type()) {
//cvtColor(image, image, CV_RGB2GRAY);
}
Moments m = moments(image);
HuMoments(m, hu);
trainingData->push_back(m.m00);
trainingData->push_back(m.m10);
trainingData->push_back(m.m01);
trainingData->push_back(m.m20);
trainingData->push_back(m.m11);
trainingData->push_back(m.m02);
trainingData->push_back(m.m30);
trainingData->push_back(m.m21);
trainingData->push_back(m.m12);
trainingData->push_back(m.m03);
trainingData->push_back(m.mu20);
trainingData->push_back(m.mu11);
trainingData->push_back(m.mu02);
trainingData->push_back(m.mu30);
trainingData->push_back(m.mu21);
trainingData->push_back(m.mu12);
trainingData->push_back(m.mu03);
trainingData->push_back(m.nu20);
trainingData->push_back(m.nu11);
trainingData->push_back(m.nu02);
trainingData->push_back(m.nu30);
trainingData->push_back(m.nu21);
trainingData->push_back(m.nu12);
trainingData->push_back(m.nu03);
trainingData->push_back(hu[0]);
trainingData->push_back(hu[1]);
trainingData->push_back(hu[2]);
trainingData->push_back(hu[3]);
trainingData->push_back(hu[4]);
trainingData->push_back(hu[5]);
trainingData->push_back(hu[6]);
return trainingData;
}
void RecognitionNLP::generatorSign() {
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<CImageSign> vNLP;
vector<string> filesList = getListFileFrom(path);
for each(string var in filesList)
vNLP.push_back(CImageSign(imread(path + var), var));
CSegmentation segmentation(&distorted, vParameters);
Mat tmpMat;
string tmpPath = "";
path = "D:\\Segmentation\\Result\\";
for (int j = 0; j < 100; j++)
segmentation.segmentationNLP(vNLP, vParameters[10], 1, 0, 1);
}
#pragma endregion My test
#pragma region
void RecognitionNLP::clickClearData() {
ui.listLoadData->clear();
distorted.clearAll();
ui.listPropertysNoising->clear();
}
void RecognitionNLP::clickLoadData() {
clickClearData();
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<string> filesList = getListFileFrom(path);
image = imread(path + filesList[0]);
int i = 1;
for each (string var in filesList){
ui.listLoadData->addItem(convertStringToQString(itos(i)+ var));
i++;
}
//turn on all scens
ui.GBSegmentation->setEnabled(true);
ui.GBPropertys->setEnabled(true);
ui.GBTest->setEnabled(true);
ui.GBPredict->setEnabled(true);
distorted.changeImage(image.clone());
UseDefaultValue();
SegmentationUpDateScens(vector<string>(0), vector<int>(0), vector<int>(0), vector<int>(0));
PropertysUpDateScens(vector<string>(0), vector<int>(0), vector<int>(0), vector<int>(0));
PropertysShowResultImage();
}
#pragma endregion It is tab LOAD DATA
#pragma region
void RecognitionNLP::PropertysUpDateScens(vector<string> vValues, vector<int> vMin, vector<int> vMax, vector<int> vDefault) {
/* TAB PROPERTYS */
//hiding all sliders
for (int i = 0; i < vLabelsValue.size(); i++) {
vSliderValue[i]->hide();
vSliderMisstakeValue[i]->hide();
vLabelsValue[i]->hide();
vLabelValueSlider[i]->hide();
vLabelMisstakeValueSlider[i]->hide();
}
//show only this slider what is need
for (int i = 0; i < vValues.size(); i++) {
vSliderValue[i]->show();
vSliderMisstakeValue[i]->show();
vLabelsValue[i]->show();
vLabelValueSlider[i]->show();
vLabelMisstakeValueSlider[i]->show();
}
//set max and min value and text
for (int i = 0; i < vValues.size(); i++) {
vSliderValue[i]->setMinimum(vMin[i]);
vSliderValue[i]->setMaximum(vMax[i]);
vSliderValue[i]->setValue(vDefault[i]);
vSliderMisstakeValue[i]->setMinimum(0);
vSliderMisstakeValue[i]->setMaximum(vMax[i]);
vSliderMisstakeValue[i]->setValue(0);
vLabelsValue[i]->setText(convertStringToQString(vValues[i]));
vLabelValueSlider[i]->setText(convertStringToQString(itos(vDefault[i])));
vLabelMisstakeValueSlider[i]->setText(convertStringToQString(itos(0)));
}
/* END TAB PROPERTYS */
}
void RecognitionNLP::PropertysShowResultImage(bool onRawFile) {
Mat img;
if (onRawFile)
img = distorted.getImage();
else
img = distorted.getImage().clone();
vector<int> vValue;
vector<int> vMissValue;
for (int i = 0; i < 6; i++) {
if (vSliderValue[i]->isEnabled()) {
vValue.push_back(vSliderValue[i]->value());
vMissValue.push_back(vSliderMisstakeValue[i]->value());
}
}
if (ui.rbAffinePropertysTransformations->isChecked()) {
CDistorted::noising(img, 9, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(9, vValue, vMissValue);
ui.listPropertysNoising->addItem("Affine Transformations");
}
}
if (ui.rbPropertysBilateralFilter->isChecked()) {
CDistorted::noising(img, 4, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(4, vValue, vMissValue);
ui.listPropertysNoising->addItem("Bilateral Filter");
}
}
if (ui.rbPropertysBlur->isChecked()) {
CDistorted::noising(img, 1, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(1, vValue, vMissValue);
ui.listPropertysNoising->addItem("Blur");
}
}
if (ui.rbPropertysContrast->isChecked()) {
CDistorted::noising(img, 0, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(0, vValue, vMissValue);
ui.listPropertysNoising->addItem("Contrast");
}
}
if (ui.rbPropertysDilate->isChecked()) {
CDistorted::noising(img, 6, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(6, vValue, vMissValue);
ui.listPropertysNoising->addItem("Dilate");
}
}
if (ui.rbPropertysErode->isChecked()) {
CDistorted::noising(img, 5, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(5, vValue, vMissValue);
ui.listPropertysNoising->addItem("Erode");
}
}
if (ui.rbPropertysFiltrTwoD->isChecked()) {
CDistorted::noising(img, 8, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(8, vValue, vMissValue);
ui.listPropertysNoising->addItem("Filtr TwoD");
}
}
if (ui.rbPropertysGaussianBlur->isChecked()) {
CDistorted::noising(img, 2, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(2, vValue, vMissValue);
ui.listPropertysNoising->addItem("Gaussian Blur");
}
}
if (ui.rbPropertysMedianBlur->isChecked()) {
CDistorted::noising(img, 3, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(3, vValue, vMissValue);
ui.listPropertysNoising->addItem("Median Blur");
}
}
if (ui.rbPropertysZoom->isChecked()) {
CDistorted::noising(img, 7, vValue, vMissValue);
if (onRawFile) {
distorted.addDistortion(7, vValue, vMissValue);
ui.listPropertysNoising->addItem("Zoom");
}
}
//imshow("A", img);
QPixmap pix = cvMatToQPixmap(img);
ui.labelPropertysResultImage->clear();
ui.labelPropertysResultImage->setPixmap(pix);
img.release();
if (onRawFile) PropertysShowResultImage();
}
void RecognitionNLP::UseDefaultValue(){
vector<int> p, mv;
p.push_back(1);
p.push_back(10);
mv.push_back(0);
mv.push_back(5);
distorted.addDistortion(0, p, mv);
ui.listPropertysNoising->addItem("Contrast");
p.clear();
mv.clear();
p.push_back(6);
mv.push_back(0);
distorted.addDistortion(2, p, mv);
ui.listPropertysNoising->addItem("Gaussian Blur");
p.clear();
mv.clear();
p.push_back(3);
mv.push_back(3);
distorted.addDistortion(4, p, mv);
ui.listPropertysNoising->addItem("BILATERAL FILTER");
p.clear();
mv.clear();
distorted.addDistortion(7, p, mv);
ui.listPropertysNoising->addItem("Zoom");
int min = 0;
int max = 0;
p.push_back(min);
p.push_back(min);
p.push_back(min);
p.push_back(min);
p.push_back(min);
p.push_back(min);
mv.push_back(max);
mv.push_back(max);
mv.push_back(max);
mv.push_back(max);
mv.push_back(max);
mv.push_back(max);
//distorted.addDistortion(9, p, mv);
//ui.listPropertysNoising->addItem("Affine Transformations");
p.clear();
mv.clear();
}
/* CLICK METHODS */
void RecognitionNLP::clickAddNoising() {
PropertysShowResultImage(true);
SegmentationShowResultImages();
}
void RecognitionNLP::clickClearNoising() {
ui.listPropertysNoising->clear();
distorted.clearAll();
PropertysShowResultImage();
}
void RecognitionNLP::moveSlider() {
PropertysShowResultImage();
}
void RecognitionNLP::clickGenerateNosingImage() {
/* LOAD DATA */
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<CImageSign> NLP;
vector<string> filesList = getListFileFrom(path);
system("mkdir distorted");
for (int i = 1; i < filesList.size(); i++)
imwrite("distorted\\" + filesList[i], distorted.distortingImgage(imread(path + filesList[i])));
}
void RecognitionNLP::selectRBContrast() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Alpha", 1, 3, 1);
setVector(v, min, max, def, "Beta", 1, 100, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBBlur() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 100, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBGaussianBlur() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 31, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBMedianBlur() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
//tylko parzyste
setVector(v, min, max, def, "Size", 1, 6, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBBilateralFilter() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Sigma", 1, 31, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBErode() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Operation", 0, 2, 0);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBDilate() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Operation", 0, 2, 0);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBZoom() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Zoom", 2, 2, 2);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBFiltrTwoD() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 100, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
void RecognitionNLP::selectRBAffineTransformations() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> def;
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Size", 1, 100, 1);
setVector(v, min, max, def, "Size", 1, 100, 1);
PropertysUpDateScens(v, min, max, def);
PropertysShowResultImage();
}
/* END CLICK METHODS */
#pragma endregion It is tab PROPERTYS
#pragma region
void RecognitionNLP::SegmentationUpDateScens(vector<string> vValues, vector<int> vMin, vector<int> vMax, vector<int> vDefault) {
/* TAB SEGMENTATION */
//hiding all sliders
for (int i = 0; i < 4; i++) {
vLabelsSegmentation[i]->hide();
vLabelsSegmetationValue[i]->hide();
vHSSegmentation[i]->hide();
}
//show only this slider what is need
for (int i = 0; i < vValues.size(); i++) {
vLabelsSegmentation[i]->show();
vLabelsSegmetationValue[i]->show();
vHSSegmentation[i]->show();
}
//set max and min value and text
for (int i = 0; i < vValues.size(); i++) {
vHSSegmentation[i]->setMinimum(vMin[i]);
vHSSegmentation[i]->setMaximum(vMax[i]);
vHSSegmentation[i]->setValue(vDefault[i]);
vLabelsSegmentation[i]->setText(convertStringToQString(vValues[i]));
}
/* END TAB SEGMENTATION */
SegmentationShowResultImages();
}
void RecognitionNLP::SegmentationShowResultImages() {
vector<Mat> imageAfterSegmentation;
CSegmentation segmentation(&distorted, vParameters);
imageAfterSegmentation = segmentation.segmentationNLP(distorted.getImage().clone(), vParameters, vParameters[10]);
for (int i = 0; i < 7; i++) {
if(i < vLabelsSegmentationResult.size() && i < imageAfterSegmentation.size()){
QPixmap pix = cvMatToQPixmap(imageAfterSegmentation[i]);
vLabelsSegmentationResult[i]->setText("");
vLabelsSegmentationResult[i]->clear();
vLabelsSegmentationResult[i]->setPixmap(pix);
imageAfterSegmentation[i].release();
}
else {
vLabelsSegmentationResult[i]->setText("Error");
vLabelsSegmentationResult[i]->clear();
}
}
segmentation.~CSegmentation();
}
/* CLICK METHODS */
void RecognitionNLP::clickSegmentationErode() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Size", 0, 100, vParameters[0]);
setVector(v, min, max, val, "Operation", 0, 2, vParameters[1]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::clickSegmentationContrast() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Beta", 0, 100, vParameters[2]);
setVector(v, min, max, val, "Alpha", 0, 2, vParameters[3]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::clickSegmentationBW() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Sum light pix", 1, 255, vParameters[4]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::clickSegmentationCutimage() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Left", 0, 40, vParameters[5]);
setVector(v, min, max, val, "Top", 0, 40, vParameters[6]);
setVector(v, min, max, val, "Right", 0, 40, vParameters[7]);
setVector(v, min, max, val, "Bottom", 0, 40, vParameters[8]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::clickSegmentationNegative() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Negative", 0, 1, vParameters[9]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::clickSegmentationSumControl() {
vector<string> v;
vector<int> max;
vector<int> min;
vector<int> val;
setVector(v, min, max, val, "Value", -100, 300, vParameters[10]);
SegmentationUpDateScens(v, min, max, val);
SegmentationShowResultImages();
}
void RecognitionNLP::preProcessing() {
/* LOAD DATA */
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<CImageSign> NLP;
vector<string> filesList = getListFileFrom(path);
Mat matTmp;
system("mkdir preProcessing");
for (int i = 1; i < filesList.size(); i++) {
matTmp = imread(path + filesList[i]);
CPreProcessing::introductoryProcessing(matTmp, vParameters);
imwrite("preProcessing\\" + filesList[i], matTmp);
matTmp.release();
}
}
void RecognitionNLP::segmentation() {
clearFolder("Segmentation\\");
/* LOAD DATA */
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<CImageSign> NLP;
vector<string> filesList = getListFileFrom(path);
for each(string var in filesList)
NLP.push_back(CImageSign(imread(path + var), var));
/* SEGMENTATION */
CSegmentation segmentation(&distorted, vParameters);
segmentation.segmentationNLP(NLP, vParameters[10], true, true, true);
segmentation.~CSegmentation();
}
void RecognitionNLP::SegmentationUpDatevParameters() {
if (vRBSegmentation[0]->isChecked()) {
vParameters[0] = vHSSegmentation[0]->value();
vParameters[1] = vHSSegmentation[1]->value();
}
if (vRBSegmentation[1]->isChecked()) {
vParameters[2] = vHSSegmentation[0]->value();
vParameters[3] = vHSSegmentation[1]->value();
}
if (vRBSegmentation[2]->isChecked()) {
vParameters[4] = vHSSegmentation[0]->value();
}
if (vRBSegmentation[3]->isChecked()) {
vParameters[5] = vHSSegmentation[0]->value();
vParameters[6] = vHSSegmentation[1]->value();
vParameters[7] = vHSSegmentation[2]->value();
vParameters[8] = vHSSegmentation[3]->value();
}
if (vRBSegmentation[4]->isChecked()) {
vParameters[9] = vHSSegmentation[0]->value();
}
if (vRBSegmentation[5]->isChecked()) {
vParameters[10] = vHSSegmentation[0]->value();
}
SegmentationShowResultImages();
}
/* END CLICK METHODS */
#pragma endregion It is tab SEGMENTATION
//clibbord
#pragma region
void RecognitionNLP::fillDefaultValue() {
/* s t d g r c n p m e h b wi */
double defaultValue[] = { 1, 0, 2, 0.5, 2, 2, 1, 0.1, 100, 1, 1, 0, 5 };
double minValue[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, };
double maxValue[] = { 4, 4, 10000, 10000, 10000, 10000, 10000, 100000, 100000, 10000, 1, 1, 1000 };
for (int i = 0; i < 13; i++) {
vSpinBoxValueTest[i]->setMinimum(minValue[i]);
vSpinBoxValueTest[i]->setMaximum(maxValue[i]);
vSpinBoxValueTest[i]->setValue(defaultValue[i]);
}
}
void RecognitionNLP::saveFileVectorFeauter() {
/* LOAD DATA */
string path = convertQStringToString(ui.inputLoadPath->text());
if ('\\' != path[path.length()])
path += "\\";
vector<CImageSign> NLP;
vector<string> filesList = getListFileFrom(path);
for each(string var in filesList)
NLP.push_back(CImageSign(imread(path + var, 0), var));
/* SEGMENTATION */
CSegmentation segmentation(&distorted, vParameters);
segmentation.segmentationNLP(NLP, vParameters[10], 0, 0);
vector<int> vLabel = segmentation.getVLabel();
vector<vector<float>> vTrainingData = segmentation.getVTraingData();
segmentation.~CSegmentation();
/* Training */
int* label = new int[vLabel.size()];
float** trainingData = new float*[vTrainingData.size()];
for (int i = 0; i < vLabel.size(); i++)
label[i] = vLabel[i];
for (int i = 0; i < vTrainingData.size(); i++) {
trainingData[i] = new float[vTrainingData[i].size()];
for (int j = 0; j < vTrainingData[i].size(); j++)
trainingData[i][j] = vTrainingData[i][j];
}
CSVM nu_svm;
nu_svm.saveVectorToFile(label, trainingData, "libsvm\\VF.txt", "", vLabel.size());
nu_svm.~CSVM();
}
void RecognitionNLP::training() {
saveFileVectorFeauter();
/* Training */
CSVM nu_svm;
nu_svm.trainByLibsvm(vSpinBoxValueTest[0]->value(), vSpinBoxValueTest[1]->value(), vSpinBoxValueTest[2]->value(), vSpinBoxValueTest[3]->value(), vSpinBoxValueTest[4]->value(), vSpinBoxValueTest[5]->value(), vSpinBoxValueTest[6]->value(), vSpinBoxValueTest[7]->value(), vSpinBoxValueTest[8]->value(), vSpinBoxValueTest[9]->value(), vSpinBoxValueTest[10]->value(), vSpinBoxValueTest[11]->value(), vSpinBoxValueTest[12]->value());
nu_svm.~CSVM();
}
void RecognitionNLP::runTest() {
saveFileVectorFeauter();
CSVM nu_svm;
nu_svm.setLabel(ui.labelPredictResult);
nu_svm.predict("SVF.txt");
nu_svm.~CSVM();
}
double* RecognitionNLP::getValueFromTest() {
double* parameters = new double[vSpinBoxValueTest.size()];
for (int i = 0; i < vSpinBoxValueTest.size(); i++)
parameters[i] = vSpinBoxValueTest[i]->value();
return parameters;
}
#pragma endregion It is tab Test
#pragma region
void RecognitionNLP::clearFolder(string path) {
if ('\\' != path[path.length()])
path += "\\";
vector<string> fileToRemove = getListFileFrom(path);
string fileToRemoveTmp;
for each(string var in fileToRemove) {
fileToRemoveTmp = path + var;
const char* tmpChar = fileToRemoveTmp.c_str();
remove(tmpChar);
}
fileToRemove.clear();
}
void RecognitionNLP::setVector(vector<string>& str, vector<int>& vmin, vector<int>& vmax, vector<int>& vval, string parametr, int min, int max, int val) {
str.push_back(parametr);
vmin.push_back(min);
vmax.push_back(max);
vval.push_back(val);
}
void RecognitionNLP::setHorizontalSlider(QSlider* slider, int min, int max, int value) {
slider->setMinimum(min);
slider->setMaximum(max);
slider->setValue(value);
}
void RecognitionNLP::fillVectorValue() {
/* tab propertys */
vSliderValue.push_back(ui.HSPropertys1);
vSliderValue.push_back(ui.HSPropertys2);
vSliderValue.push_back(ui.HSPropertys3);
vSliderValue.push_back(ui.HSPropertys4);
vSliderValue.push_back(ui.HSPropertys5);
vSliderValue.push_back(ui.HSPropertys6);
vSliderMisstakeValue.push_back(ui.HSPropertys11);
vSliderMisstakeValue.push_back(ui.HSPropertys22);
vSliderMisstakeValue.push_back(ui.HSPropertys33);
vSliderMisstakeValue.push_back(ui.HSPropertys44);
vSliderMisstakeValue.push_back(ui.HSPropertys55);
vSliderMisstakeValue.push_back(ui.HSPropertys66);
vRBChanges.push_back(ui.rbPropertysContrast);
vRBChanges.push_back(ui.rbPropertysBlur);
vRBChanges.push_back(ui.rbPropertysGaussianBlur);
vRBChanges.push_back(ui.rbPropertysMedianBlur);
vRBChanges.push_back(ui.rbPropertysBilateralFilter);
vRBChanges.push_back(ui.rbPropertysErode);
vRBChanges.push_back(ui.rbPropertysDilate);
vRBChanges.push_back(ui.rbPropertysFiltrTwoD);
vRBChanges.push_back(ui.rbAffinePropertysTransformations);
vLabelsValue.push_back(ui.labelPropertysV1);
vLabelsValue.push_back(ui.labelPropertysV2);
vLabelsValue.push_back(ui.labelPropertysV3);
vLabelsValue.push_back(ui.labelPropertysV4);
vLabelsValue.push_back(ui.labelPropertysV5);
vLabelsValue.push_back(ui.labelPropertysV6);
vLabelValueSlider.push_back(ui.labelPropertysVS1);
vLabelValueSlider.push_back(ui.labelPropertysVS2);
vLabelValueSlider.push_back(ui.labelPropertysVS3);
vLabelValueSlider.push_back(ui.labelPropertysVS4);
vLabelValueSlider.push_back(ui.labelPropertysVS5);
vLabelValueSlider.push_back(ui.labelPropertysVS6);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS11);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS22);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS33);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS44);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS55);
vLabelMisstakeValueSlider.push_back(ui.labelPropertysVS66);
/* END tab propertys */
/* tab segmentation */
//erode
vParameters.push_back(0);
vParameters.push_back(0);
//ccontrast
vParameters.push_back(0);
vParameters.push_back(0);
//B&W
vParameters.push_back(100);
//cut image
vParameters.push_back(20);
vParameters.push_back(5);
vParameters.push_back(0);
vParameters.push_back(5);
//negative
vParameters.push_back(1);
//sum control
vParameters.push_back(1);
vRBSegmentation.push_back(ui.RBSegmetation1);
vRBSegmentation.push_back(ui.RBSegmetation2);
vRBSegmentation.push_back(ui.RBSegmetation3);
vRBSegmentation.push_back(ui.RBSegmetation4);
vRBSegmentation.push_back(ui.RBSegmetation5);
vRBSegmentation.push_back(ui.RBSegmetation6);
vLabelsSegmentation.push_back(ui.labelSegmentation1);
vLabelsSegmentation.push_back(ui.labelSegmentation2);
vLabelsSegmentation.push_back(ui.labelSegmentation3);
vLabelsSegmentation.push_back(ui.labelSegmentation4);
vLabelsSegmetationValue.push_back(ui.labelSegmentationValue1);
vLabelsSegmetationValue.push_back(ui.labelSegmentationValue2);
vLabelsSegmetationValue.push_back(ui.labelSegmentationValue3);
vLabelsSegmetationValue.push_back(ui.labelSegmentationValue4);
vHSSegmentation.push_back(ui.HSSegmentation1);
vHSSegmentation.push_back(ui.HSSegmentation2);
vHSSegmentation.push_back(ui.HSSegmentation3);
vHSSegmentation.push_back(ui.HSSegmentation4);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult1);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult2);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult3);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult4);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult5);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult6);
vLabelsSegmentationResult.push_back(ui.labelSegmentationResult7);
/* END tab segmentation */
/* tab test */
vLabelTest.push_back(ui.labelParameter1);
vLabelTest.push_back(ui.labelParameter2);
vLabelTest.push_back(ui.labelParameter3);
vLabelTest.push_back(ui.labelParameter4);
vLabelTest.push_back(ui.labelParameter5);
vLabelTest.push_back(ui.labelParameter6);
vLabelTest.push_back(ui.labelParameter7);
vLabelTest.push_back(ui.labelParameter8);
vLabelTest.push_back(ui.labelParameter9);
vLabelTest.push_back(ui.labelParameter10);
vLabelTest.push_back(ui.labelParameter11);
vLabelTest.push_back(ui.labelParameter12);
vLabelTest.push_back(ui.labelParameter13);
vSpinBoxValueTest.push_back(ui.SBTest1);
vSpinBoxValueTest.push_back(ui.SBTest2);
vSpinBoxValueTest.push_back(ui.SBTest3);
vSpinBoxValueTest.push_back(ui.SBTest4);
vSpinBoxValueTest.push_back(ui.SBTest5);
vSpinBoxValueTest.push_back(ui.SBTest6);
vSpinBoxValueTest.push_back(ui.SBTest7);
vSpinBoxValueTest.push_back(ui.SBTest8);
vSpinBoxValueTest.push_back(ui.SBTest9);
vSpinBoxValueTest.push_back(ui.SBTest10);
vSpinBoxValueTest.push_back(ui.SBTest11);
vSpinBoxValueTest.push_back(ui.SBTest12);
vSpinBoxValueTest.push_back(ui.SBTest13);
/* END tab test */
}
vector<string> RecognitionNLP::getListFileFrom(string path) {
vector<string> direcroriesName;
const char* chPath = path.c_str();
struct dirent* file;
DIR* directories;
if (directories = opendir(chPath)) {
while (file = readdir(directories)) {
if (file->d_name[0] != '.')
direcroriesName.push_back(file->d_name);
}
}
return direcroriesName;
}
bool RecognitionNLP::fileExists(const string& fileName) {
fstream plik;
plik.open(fileName.c_str(), ios::in | ios::_Nocreate);
if (plik.is_open()) {
plik.close();
return true;
}
plik.close();
return false;
}
string RecognitionNLP::readFile(string path) {
ifstream file(path);
string result((istreambuf_iterator<char>(file)), istreambuf_iterator<char>());
return result;
}
#pragma endregion Methods Help
| [
"krzysztof.kozubek135@gmail.com"
] | krzysztof.kozubek135@gmail.com |
7f497573a41c8d8e608513155ee699010b256565 | 49fdf14349368d84cd1708b62f6ba3adc6789015 | /gtp/scene/Octree.cpp | 59d476a4b81459857b8011747a397782c5bece23 | [] | no_license | superwills/gtp | 11d2896a699920cbd3aaf032ef7fde363d32fbb5 | 1e658fc5ed38ff08af748d2b6734d68308609e4f | refs/heads/master | 2021-09-27T02:21:32.161676 | 2021-09-25T18:13:34 | 2021-09-25T18:13:34 | 7,979,097 | 17 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 10,295 | cpp | #include "Octree.h"
#include "../window/GTPWindow.h" // DEBUG
#include "../geometry/Shape.h"
#include "../geometry/Mesh.h"
bool Octree<Shape*>::useKDDivisions = false ;
bool Octree<PhantomTriangle*>::useKDDivisions = false ;
// The trade off is, the more ONodes you create, the longer the
// ONODE intersection takes. If you don't have enough ONodes,
// then severe slow down on high poly models happens.
int ONode<Shape*>::maxItems = 15 ;
int ONode<Shape*>::maxDepth = 3 ;
bool ONode<Shape*>::splitting = false ; // you don't split non triangular primitives
int ONode<PhantomTriangle*>::maxItems = 15 ;
int ONode<PhantomTriangle*>::maxDepth = 7 ;
bool ONode<PhantomTriangle*>::splitting = true ;
#pragma region global functions
bool tryPutAway( PhantomTriangle* pTri,
vector<AABB>& aabbCandChildren,
map< AABB*, list<PhantomTriangle*> >& aabbsAndTheirContainedItems )
{
for( int i = 0 ; i < aabbCandChildren.size() ; i++ )
if( aabbCandChildren[i].containsAlmost( pTri ) )
//if( aabbCandChildren[i].containsIn( pTri ) )
{
// add pTri as being in the AABB:
aabbsAndTheirContainedItems[ &aabbCandChildren[i] ].push_back( pTri ) ;
//drawTri( pTri, Vector( .5,.25, .04 ) ) ;
return true ; // it put away
}
// tri didn't fit in any of available child nodes
return false ;
}
bool tryPutAway( list<PhantomTriangle*>& pTris,
vector<AABB>& aabbCandChildren,
map< AABB*, list<PhantomTriangle*> >& aabbsAndTheirContainedItems )
{
// try and put away the new tris into the
// child aabbs.
bool allAway = true ;
for( list<PhantomTriangle*>::iterator iter = pTris.begin() ; iter != pTris.end() ; )
{
if( tryPutAway( *iter, aabbCandChildren, aabbsAndTheirContainedItems ) )
{
// it put away.
// these 2 lines aren't strictly necessary but I need
// to know the tris that didn't place for debug purposes.
// they actually get put back in root (if there are problems for whatever reason)
// if they don't get put away
iter = pTris.erase( iter ) ;// remove it
//info( "Tri put away, %d remain", pTris.size() ) ;
}
else
{
allAway = false ; // at least one didn't get put away into a child box
++iter;
}
}
//info( "Total tris remain: %d", pTris.size() ) ;
return allAway ;
}
// REMOVES TRIS COINCIDENT WITH PLANE FROM toSPLIT
// AND PLACES THEM IN coincidentTRIS
void removeCoincidentTris( Plane plane, list<PhantomTriangle*> & toSplit, list<PhantomTriangle*> & coincidentTris )
{
//static Vector call = 0 ;
//call.y+=.01;
for( list<PhantomTriangle*>::iterator iter = toSplit.begin() ; iter != toSplit.end() ; )
{
PhantomTriangle* pTri = *iter ;
int aV = plane.iSide( pTri->a ) ;
int bV = plane.iSide( pTri->b ) ;
int cV = plane.iSide( pTri->c ) ;
// a really bad case is |aV|, |bV|, and |cV| all
// near 0. this means the points of the triangle are
// all shavingly close to the plane (ie almost parallel).
//if( IsNear(aV,0.0,1e-11) && IsNear(bV,0.0,1e-11) && IsNear(cV,0.0,1e-11) )
if( aV==0&&bV==0&&cV==0 )
{
// Do not split this triangle on this plane. take it out.
coincidentTris.push_back( pTri ) ;
//drawTri( call, pTri, Vector(1,0,1) ) ;
iter = toSplit.erase( iter ) ; // ADVANCES ITER
}
else
{
//drawTri( call, pTri, Vector(0,0,1) ) ;
++iter ;
}
}
}
// SPLIT toSPLIT LIST OF PHANTOMTRIANGLE'S ON PLANE.
// Uses a variant of the Sutherland-Hodgman algorithm.
void splitTris( Plane plane, list<PhantomTriangle*> & toSplit, list<PhantomTriangle*> & newTris )
{
// We create 9 pointers, but only 3 will be used.
// Each of the 3 points a,b,c of each tri needs
// to be classified as negative-side, +-side, or
// ON the splitting plane.
Vector *nS[3] ;
Vector *pS[3] ; // ptr to the vert on the _other_ side,
Vector *on[3] ;
int origTris = toSplit.size() ;
for( list<PhantomTriangle*>::iterator iter = toSplit.begin() ; iter != toSplit.end() ; )
{
// these are counters for how many
// vertices so far were on what side of the plane.
int pSide=0, nSide=0, onPlane=0 ;
PhantomTriangle* pTri = *iter ;
Vector* triVectors = &pTri->a ; // start here
// test 3 vertices
for( int i = 0 ; i < 3 ; i++ )
{
int v = plane.iSide( triVectors[i] ) ;
//triVectors[i].print() ;
//printf( " v=%f\n", v ) ;
if( v == 0 ) on[onPlane++]= &triVectors[i];
else if( v < 0 ) nS[nSide++]= &triVectors[i];
else pS[pSide++]= &triVectors[i] ;
}
///info( "pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;
if( nSide>=1 && pSide>=1 ) // split.
{
// NOT keeping the winding order. it doesn't matter anyway because
// these are intersectable, not renderable.
// the first ray finds the intersection between the negative side and the ps,
Intersection i1 ;
//---|+++
// o |
// |\|--->N
// | |\
// o-X-o
// Make a ray FROM a point on the negative side,
// to a point on the +side of the plane
Ray r1( *(nS[0]), *(pS[0]) ) ;
// use the plane to get the intersection point
plane.intersectsPlane( r1, &i1 ) ;
///pTri->tri->intersects( r1, &mi1 ) ; // use the original tri to get the 3d space intersection point
// A vertex is on or very near the plane, so
// we'll split AT the vertex (cut only one edge)
if( onPlane==1 )
{
// split using the VERTEX on the plane as the splitter.
// gen 2 tris.
// 1) nS, D, ONPLANE,
// 2) pS, ONPLANE, D.
PhantomTriangle *pt1 = new PhantomTriangle( *(nS[0]), i1.point, *(on[0]), pTri->tri ) ;
PhantomTriangle *pt2 = new PhantomTriangle( *(pS[0]), *(on[0]), i1.point, pTri->tri ) ;
if( pt1->isDegenerate() || pt2->isDegenerate() )
{
// This is a very important error to catch, because it happens
// when something is terribly screwed up.
window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
error( "split fail." ) ;
delete pt1 ; delete pt2 ;
++iter ;
continue ;
}
newTris.push_back( pt1 ) ;
newTris.push_back( pt2 ) ;
}
else
{
// 2 points on nSide
// We cut 2 edges.
// if there are 2 nsides, use nS[1] and pS[0]. If 2 psides, nS[0],ps[1].
// get the side with 2 verts on it
Vector** sideWith2 = (pSide>nSide)?pS:nS;
Vector** sideWith1 = (pSide<nSide)?pS:nS;
// Get the second intersection point, from sideWith2[1] to sidewith1[0]
Ray r2( *(sideWith2[1]), *(sideWith1[0]) ) ;
Intersection i2 ;
plane.intersectsPlane( r2, &i2 ) ;
// 3 tris.
// *
// / \
// /___\
// / __/ \
// /_/ \
// *---------*
//
// LET D be mi1.point, E mi2.point
// 1) sw2[0],D,E
// 2) sw2[0],E,sw2[1]
// 3) E,D,sw1[0]
PhantomTriangle *pt1 = new PhantomTriangle( *(sideWith2[0]), i1.point, i2.point, pTri->tri ) ;
PhantomTriangle *pt2 = new PhantomTriangle( *(sideWith2[0]), i2.point, *(sideWith2[1]), pTri->tri ) ;
PhantomTriangle *pt3 = new PhantomTriangle( i2.point, i1.point, *(sideWith1[0]), pTri->tri ) ;
if( pt1->isDegenerate() || pt2->isDegenerate() || pt3->isDegenerate() )
{
// This is a very important error to catch, because it happens
// when something is terribly screwed up.
window->addSolidDebugTri( pTri, Vector(1,0,0) ) ;
error( "split fail." ) ; // split fail.
delete pt1 ; delete pt2 ; delete pt3 ;
++iter ;
continue ;
}
newTris.push_back( pt1 ) ;
newTris.push_back( pt2 ) ;
newTris.push_back( pt3 ) ;
}
// destroy the old PhantomTriangle that got split,
// we don't need it anymore.
DESTROY( *iter ) ;
iter = toSplit.erase( iter ) ; // ADVANCES ITER
}
else
{
// Here you cannot split the polygon, either because
// all 3 are on one side, or one is on the plane and the
// other 2 are on the same side.
// I mean this is not a big deal and it is expected to happen a lot,
// because a lot of tris you try to split will be on one side of the plane,
// more rarely all 3 verts will be IN the plane.
// if it does happen then like ASUS RMA you get the same triangle back.
///info( "Could not split the polygon, pSide=%d, nSide=%d, onPlane=%d", pSide, nSide, onPlane ) ;
++iter ; // advance iterator
}
}
// Splits fail a lot, because this gets called 3x per division.
////info( "%d tris became %d tris, %d remain", origTris, newTris.size(), toSplit.size() ) ;
}
void getMeanStdDev( const list<PhantomTriangle*>& items, Vector& mean, Vector& stddev )
{
for( auto pt : items )
mean += pt->a + pt->b + pt->c ;
mean /= 3*items.size() ;
for( auto pt : items )
{
Vector diffa = (pt->a - mean) ;
Vector diffb = (pt->b - mean) ;
Vector diffc = (pt->c - mean) ;
stddev += diffa.componentSquared() +
diffb.componentSquared() +
diffc.componentSquared() ;
}
}
#pragma endregion
void drawRay( const Ray& ray, const Vector& color )
{
window->addDebugRayLock( ray, color, color*2 ) ;
}
void drawTri( const Vector& offset, PhantomTriangle * pTri, const Vector& color )
{
window->addSolidDebugTri( offset, pTri, color ) ;
}
void drawTri( PhantomTriangle * pTri, const Vector& color )
{
drawTri( 0, pTri, color ) ;
}
void drawTris( list<PhantomTriangle *>& pTri, const Vector& stain )
{
for( list<PhantomTriangle*>::iterator iter = pTri.begin() ; iter != pTri.end(); ++ iter )
drawTri( *iter, stain ) ;
}
void drawTris( list<PhantomTriangle *>& pTri )
{
drawTris( pTri, Vector(1,1,1) ) ;
}
| [
"bill.sherif@gmail.com"
] | bill.sherif@gmail.com |
8d417b55933c5b31f8576f2b19d608595611cc69 | 4eb8cff1a970cf39fbb903c5b9d302af23eb74d9 | /leetcode/0216-combination-sum-iii.cpp | 3ff57b74020b207ee58fd45c5d1d9d1e1025e9c8 | [] | no_license | chchwy/leetcode | b66296c6674f55cb4da5e10bb4a770d0456b2277 | b40a879262a638b596043db0aacb8fab47597703 | refs/heads/master | 2022-06-18T15:54:49.180522 | 2022-06-16T08:59:58 | 2022-06-16T08:59:58 | 73,970,689 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,447 | cpp | // 216. Combination Sum III
// Backtracking
#include <vector>
#include <iostream>
using std::vector;
class Solution {
public:
int max(int a, int b) { return (a > b) ? a : b; }
void backtrack(vector<int>& path, int next, int sum, int k, int n, vector<vector<int>>& combinations) {
if (sum > n) return;
if (path.size() == k) {
if (sum == n) {
combinations.push_back(path);
return;
}
}
for (int i = next; i <= 9; ++i) {
sum += i;
path.push_back(i);
backtrack(path, i + 1, sum, k, n, combinations);
path.pop_back();
sum -= i;
}
}
vector<vector<int>> combinationSum3(int k, int n) {
vector<vector<int>> combinations;
// pick k numbers
// the sum is n
for (int i = 1; i <= (9 - k + 1); ++i) {
vector<int> path;
std::cout << i << std::endl;
path.push_back(i);
backtrack(path, i + 1, i, k, n, combinations);
path.pop_back();
}
return combinations;
}
};
int main() {
Solution sln;
auto results = sln.combinationSum3(3, 7);
for (auto& cmb : results) {
for (int i : cmb) {
std::cout << i << ", ";
}
std::cout << std::endl;
}
return 0;
} | [
"chchwy@gmail.com"
] | chchwy@gmail.com |
43cccf63f60f8b27975b82e0955c06539760faba | 7df1849682a1c3fbee378b622fe29f12927cc1dd | /DigitalInput.cpp | fe96595705e819d2bf80726a6e863fe3017b0869 | [] | no_license | Saurbaum/doorbell | 798108523aea37e8c9eb41aec1f151fe11a8cf69 | 1a1229978e06a12d40cc962fcbe163210f1ed425 | refs/heads/master | 2021-01-23T04:09:07.364439 | 2017-03-25T15:11:56 | 2017-03-25T15:11:56 | 86,159,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 204 | cpp | #include "DigitalInput.h"
DigitalInput::DigitalInput(int pinId) : StateMachine(), m_pinId(pinId)
{
pinMode(m_pinId, INPUT_PULLUP);
};
int DigitalInput::GetState()
{
return digitalRead(m_pinId);
};
| [
"saurbaum@gmail.com"
] | saurbaum@gmail.com |
b3a9a671bf3047cf0202337dcd3b206ba0b9c40f | e506e55518f5a3e0c546c16fbfe2a13533600911 | /CppPrimer/Hello.cpp | 640b3a07e2a8edbe63eb521ec04265040ad9d656 | [] | no_license | sdubrz/CppPrimer | 7249f97d2a56084b297be4c20c624ad42f052561 | 427de050e836a1c27f50e37628eb7aa801fb4310 | refs/heads/master | 2020-06-12T23:50:00.176453 | 2019-07-10T08:56:01 | 2019-07-10T08:56:01 | 194,464,403 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,084 | cpp | #include <iostream>
using namespace std;
int add50to100(){
//练习1.9 编写程序,使用while循环将50到100的整数相加
cout << endl;
cout << "练习1.9:" << endl;
int val = 50;
int sum = 0;
while (val <= 100) {
sum += val;
val++;
}
cout << "50到100之间的整数的和为 " << sum << endl;
return 0;
}
int print10to0() {
//编写程序,使用递减运算符在循环中按递减顺序打印出10到0之间的整数
cout << endl;
cout << "练习1.10:" << endl;
int val = 10;
while (val >= 0) {
cout << val << "\t";
val--;
}
cout << endl;
return 0;
}
int printInt() {
//提示用户输入两个整数,打印出这两个整数所指定的范围内的所有整数
cout << endl;
cout << "练习1.11:" << endl;
cout << "请输入起始整数和终止整数的值:" << endl;
int start, end;
cin >> start >> end;
int i = start;
while (i <= end) {
cout << i << "\t";
i++;
}
cout << endl;
return 0;
}
//int main() {
//
// add50to100();
// print10to0();
// printInt();
//
// int i;
// cin >> i;
// return 0;
//}
| [
"sdu2014@126.com"
] | sdu2014@126.com |
c3ff19995ca17d06c4cedf080b1bdeb734c6b33f | 30379ac1cc88763307a8406e9b82987e4a41fd52 | /external/boost/regex/v4/basic_regex_creator.hpp | c4b1c048d097247c0229a4d7d1f2b69f9d6a626b | [
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-warranty-disclaimer",
"BSL-1.0"
] | permissive | kohnakagawa/sdhash | c538ae2e525d6d23c70762cc226185493db30b90 | b16bc83a74ed360293350815daf713f5457ce117 | refs/heads/master | 2020-05-03T07:07:28.609996 | 2019-04-05T14:59:23 | 2019-04-05T14:59:23 | 178,489,648 | 0 | 0 | Apache-2.0 | 2019-03-29T23:53:23 | 2019-03-29T23:53:23 | null | UTF-8 | C++ | false | false | 52,830 | hpp | /*
*
* Copyright (c) 2004
* John Maddock
*
* Use, modification and distribution are 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)
*
*/
/*
* LOCATION: see http://www.boost.org for most recent version.
* FILE basic_regex_creator.cpp
* VERSION see <boost/version.hpp>
* DESCRIPTION: Declares template class basic_regex_creator which fills in
* the data members of a regex_data object.
*/
#ifndef BOOST_REGEX_V4_BASIC_REGEX_CREATOR_HPP
#define BOOST_REGEX_V4_BASIC_REGEX_CREATOR_HPP
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_PREFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#ifdef BOOST_MSVC
# pragma warning(push)
# pragma warning(disable: 4800)
#endif
namespace boost{
namespace re_detail{
template <class charT>
struct digraph : public std::pair<charT, charT>
{
digraph() : std::pair<charT, charT>(0, 0){}
digraph(charT c1) : std::pair<charT, charT>(c1, 0){}
digraph(charT c1, charT c2) : std::pair<charT, charT>(c1, c2)
{}
#if !BOOST_WORKAROUND(BOOST_MSVC, < 1300)
digraph(const digraph<charT>& d) : std::pair<charT, charT>(d.first, d.second){}
#endif
template <class Seq>
digraph(const Seq& s) : std::pair<charT, charT>()
{
BOOST_ASSERT(s.size() <= 2);
BOOST_ASSERT(s.size());
this->first = s[0];
this->second = (s.size() > 1) ? s[1] : 0;
}
};
template <class charT, class traits>
class basic_char_set
{
public:
typedef digraph<charT> digraph_type;
typedef typename traits::string_type string_type;
typedef typename traits::char_class_type mask_type;
basic_char_set()
{
m_negate = false;
m_has_digraphs = false;
m_classes = 0;
m_negated_classes = 0;
m_empty = true;
}
void add_single(const digraph_type& s)
{
m_singles.insert(m_singles.end(), s);
if(s.second)
m_has_digraphs = true;
m_empty = false;
}
void add_range(const digraph_type& first, const digraph_type& end)
{
m_ranges.insert(m_ranges.end(), first);
m_ranges.insert(m_ranges.end(), end);
if(first.second)
{
m_has_digraphs = true;
add_single(first);
}
if(end.second)
{
m_has_digraphs = true;
add_single(end);
}
m_empty = false;
}
void add_class(mask_type m)
{
m_classes |= m;
m_empty = false;
}
void add_negated_class(mask_type m)
{
m_negated_classes |= m;
m_empty = false;
}
void add_equivalent(const digraph_type& s)
{
m_equivalents.insert(m_equivalents.end(), s);
if(s.second)
{
m_has_digraphs = true;
add_single(s);
}
m_empty = false;
}
void negate()
{
m_negate = true;
//m_empty = false;
}
//
// accessor functions:
//
bool has_digraphs()const
{
return m_has_digraphs;
}
bool is_negated()const
{
return m_negate;
}
typedef typename std::vector<digraph_type>::const_iterator list_iterator;
list_iterator singles_begin()const
{
return m_singles.begin();
}
list_iterator singles_end()const
{
return m_singles.end();
}
list_iterator ranges_begin()const
{
return m_ranges.begin();
}
list_iterator ranges_end()const
{
return m_ranges.end();
}
list_iterator equivalents_begin()const
{
return m_equivalents.begin();
}
list_iterator equivalents_end()const
{
return m_equivalents.end();
}
mask_type classes()const
{
return m_classes;
}
mask_type negated_classes()const
{
return m_negated_classes;
}
bool empty()const
{
return m_empty;
}
private:
std::vector<digraph_type> m_singles; // a list of single characters to match
std::vector<digraph_type> m_ranges; // a list of end points of our ranges
bool m_negate; // true if the set is to be negated
bool m_has_digraphs; // true if we have digraphs present
mask_type m_classes; // character classes to match
mask_type m_negated_classes; // negated character classes to match
bool m_empty; // whether we've added anything yet
std::vector<digraph_type> m_equivalents; // a list of equivalence classes
};
template <class charT, class traits>
class basic_regex_creator
{
public:
basic_regex_creator(regex_data<charT, traits>* data);
std::ptrdiff_t getoffset(void* addr)
{
return getoffset(addr, m_pdata->m_data.data());
}
std::ptrdiff_t getoffset(const void* addr, const void* base)
{
return static_cast<const char*>(addr) - static_cast<const char*>(base);
}
re_syntax_base* getaddress(std::ptrdiff_t off)
{
return getaddress(off, m_pdata->m_data.data());
}
re_syntax_base* getaddress(std::ptrdiff_t off, void* base)
{
return static_cast<re_syntax_base*>(static_cast<void*>(static_cast<char*>(base) + off));
}
void init(unsigned l_flags)
{
m_pdata->m_flags = l_flags;
m_icase = l_flags & regex_constants::icase;
}
regbase::flag_type flags()
{
return m_pdata->m_flags;
}
void flags(regbase::flag_type f)
{
m_pdata->m_flags = f;
if(m_icase != static_cast<bool>(f & regbase::icase))
{
m_icase = static_cast<bool>(f & regbase::icase);
}
}
re_syntax_base* append_state(syntax_element_type t, std::size_t s = sizeof(re_syntax_base));
re_syntax_base* insert_state(std::ptrdiff_t pos, syntax_element_type t, std::size_t s = sizeof(re_syntax_base));
re_literal* append_literal(charT c);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set, mpl::false_*);
re_syntax_base* append_set(const basic_char_set<charT, traits>& char_set, mpl::true_*);
void finalize(const charT* p1, const charT* p2);
protected:
regex_data<charT, traits>* m_pdata; // pointer to the basic_regex_data struct we are filling in
const ::boost::regex_traits_wrapper<traits>&
m_traits; // convenience reference to traits class
re_syntax_base* m_last_state; // the last state we added
bool m_icase; // true for case insensitive matches
unsigned m_repeater_id; // the state_id of the next repeater
bool m_has_backrefs; // true if there are actually any backrefs
unsigned m_backrefs; // bitmask of permitted backrefs
boost::uintmax_t m_bad_repeats; // bitmask of repeats we can't deduce a startmap for;
bool m_has_recursions; // set when we have recursive expresisons to fixup
std::vector<bool> m_recursion_checks; // notes which recursions we've followed while analysing this expression
typename traits::char_class_type m_word_mask; // mask used to determine if a character is a word character
typename traits::char_class_type m_mask_space; // mask used to determine if a character is a word character
typename traits::char_class_type m_lower_mask; // mask used to determine if a character is a lowercase character
typename traits::char_class_type m_upper_mask; // mask used to determine if a character is an uppercase character
typename traits::char_class_type m_alpha_mask; // mask used to determine if a character is an alphabetic character
private:
basic_regex_creator& operator=(const basic_regex_creator&);
basic_regex_creator(const basic_regex_creator&);
void fixup_pointers(re_syntax_base* state);
void fixup_recursions(re_syntax_base* state);
void create_startmaps(re_syntax_base* state);
int calculate_backstep(re_syntax_base* state);
void create_startmap(re_syntax_base* state, unsigned char* l_map, unsigned int* pnull, unsigned char mask);
unsigned get_restart_type(re_syntax_base* state);
void set_all_masks(unsigned char* bits, unsigned char);
bool is_bad_repeat(re_syntax_base* pt);
void set_bad_repeat(re_syntax_base* pt);
syntax_element_type get_repeat_type(re_syntax_base* state);
void probe_leading_repeat(re_syntax_base* state);
};
template <class charT, class traits>
basic_regex_creator<charT, traits>::basic_regex_creator(regex_data<charT, traits>* data)
: m_pdata(data), m_traits(*(data->m_ptraits)), m_last_state(0), m_repeater_id(0), m_has_backrefs(false), m_backrefs(0), m_has_recursions(false)
{
m_pdata->m_data.clear();
m_pdata->m_status = ::boost::regex_constants::error_ok;
static const charT w = 'w';
static const charT s = 's';
static const charT l[5] = { 'l', 'o', 'w', 'e', 'r', };
static const charT u[5] = { 'u', 'p', 'p', 'e', 'r', };
static const charT a[5] = { 'a', 'l', 'p', 'h', 'a', };
m_word_mask = m_traits.lookup_classname(&w, &w +1);
m_mask_space = m_traits.lookup_classname(&s, &s +1);
m_lower_mask = m_traits.lookup_classname(l, l + 5);
m_upper_mask = m_traits.lookup_classname(u, u + 5);
m_alpha_mask = m_traits.lookup_classname(a, a + 5);
m_pdata->m_word_mask = m_word_mask;
BOOST_ASSERT(m_word_mask != 0);
BOOST_ASSERT(m_mask_space != 0);
BOOST_ASSERT(m_lower_mask != 0);
BOOST_ASSERT(m_upper_mask != 0);
BOOST_ASSERT(m_alpha_mask != 0);
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_state(syntax_element_type t, std::size_t s)
{
// if the state is a backref then make a note of it:
if(t == syntax_element_backref)
this->m_has_backrefs = true;
// append a new state, start by aligning our last one:
m_pdata->m_data.align();
// set the offset to the next state in our last one:
if(m_last_state)
m_last_state->next.i = m_pdata->m_data.size() - getoffset(m_last_state);
// now actually extent our data:
m_last_state = static_cast<re_syntax_base*>(m_pdata->m_data.extend(s));
// fill in boilerplate options in the new state:
m_last_state->next.i = 0;
m_last_state->type = t;
return m_last_state;
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::insert_state(std::ptrdiff_t pos, syntax_element_type t, std::size_t s)
{
// append a new state, start by aligning our last one:
m_pdata->m_data.align();
// set the offset to the next state in our last one:
if(m_last_state)
m_last_state->next.i = m_pdata->m_data.size() - getoffset(m_last_state);
// remember the last state position:
std::ptrdiff_t off = getoffset(m_last_state) + s;
// now actually insert our data:
re_syntax_base* new_state = static_cast<re_syntax_base*>(m_pdata->m_data.insert(pos, s));
// fill in boilerplate options in the new state:
new_state->next.i = s;
new_state->type = t;
m_last_state = getaddress(off);
return new_state;
}
template <class charT, class traits>
re_literal* basic_regex_creator<charT, traits>::append_literal(charT c)
{
re_literal* result;
// start by seeing if we have an existing re_literal we can extend:
if((0 == m_last_state) || (m_last_state->type != syntax_element_literal))
{
// no existing re_literal, create a new one:
result = static_cast<re_literal*>(append_state(syntax_element_literal, sizeof(re_literal) + sizeof(charT)));
result->length = 1;
*static_cast<charT*>(static_cast<void*>(result+1)) = m_traits.translate(c, m_icase);
}
else
{
// we have an existing re_literal, extend it:
std::ptrdiff_t off = getoffset(m_last_state);
m_pdata->m_data.extend(sizeof(charT));
m_last_state = result = static_cast<re_literal*>(getaddress(off));
charT* characters = static_cast<charT*>(static_cast<void*>(result+1));
characters[result->length] = m_traits.translate(c, m_icase);
++(result->length);
}
return result;
}
template <class charT, class traits>
inline re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set)
{
typedef mpl::bool_< (sizeof(charT) == 1) > truth_type;
return char_set.has_digraphs()
? append_set(char_set, static_cast<mpl::false_*>(0))
: append_set(char_set, static_cast<truth_type*>(0));
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set, mpl::false_*)
{
typedef typename traits::string_type string_type;
typedef typename basic_char_set<charT, traits>::list_iterator item_iterator;
typedef typename traits::char_class_type mask_type;
re_set_long<mask_type>* result = static_cast<re_set_long<mask_type>*>(append_state(syntax_element_long_set, sizeof(re_set_long<mask_type>)));
//
// fill in the basics:
//
result->csingles = static_cast<unsigned int>(::boost::re_detail::distance(char_set.singles_begin(), char_set.singles_end()));
result->cranges = static_cast<unsigned int>(::boost::re_detail::distance(char_set.ranges_begin(), char_set.ranges_end())) / 2;
result->cequivalents = static_cast<unsigned int>(::boost::re_detail::distance(char_set.equivalents_begin(), char_set.equivalents_end()));
result->cclasses = char_set.classes();
result->cnclasses = char_set.negated_classes();
if(flags() & regbase::icase)
{
// adjust classes as needed:
if(((result->cclasses & m_lower_mask) == m_lower_mask) || ((result->cclasses & m_upper_mask) == m_upper_mask))
result->cclasses |= m_alpha_mask;
if(((result->cnclasses & m_lower_mask) == m_lower_mask) || ((result->cnclasses & m_upper_mask) == m_upper_mask))
result->cnclasses |= m_alpha_mask;
}
result->isnot = char_set.is_negated();
result->singleton = !char_set.has_digraphs();
//
// remember where the state is for later:
//
std::ptrdiff_t offset = getoffset(result);
//
// now extend with all the singles:
//
item_iterator first, last;
first = char_set.singles_begin();
last = char_set.singles_end();
while(first != last)
{
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (first->second ? 3 : 2)));
p[0] = m_traits.translate(first->first, m_icase);
if(first->second)
{
p[1] = m_traits.translate(first->second, m_icase);
p[2] = 0;
}
else
p[1] = 0;
++first;
}
//
// now extend with all the ranges:
//
first = char_set.ranges_begin();
last = char_set.ranges_end();
while(first != last)
{
// first grab the endpoints of the range:
digraph<charT> c1 = *first;
c1.first = this->m_traits.translate(c1.first, this->m_icase);
c1.second = this->m_traits.translate(c1.second, this->m_icase);
++first;
digraph<charT> c2 = *first;
c2.first = this->m_traits.translate(c2.first, this->m_icase);
c2.second = this->m_traits.translate(c2.second, this->m_icase);
++first;
string_type s1, s2;
// different actions now depending upon whether collation is turned on:
if(flags() & regex_constants::collate)
{
// we need to transform our range into sort keys:
#if BOOST_WORKAROUND(__GNUC__, < 3)
string_type in(3, charT(0));
in[0] = c1.first;
in[1] = c1.second;
s1 = this->m_traits.transform(in.c_str(), (in[1] ? in.c_str()+2 : in.c_str()+1));
in[0] = c2.first;
in[1] = c2.second;
s2 = this->m_traits.transform(in.c_str(), (in[1] ? in.c_str()+2 : in.c_str()+1));
#else
charT a1[3] = { c1.first, c1.second, charT(0), };
charT a2[3] = { c2.first, c2.second, charT(0), };
s1 = this->m_traits.transform(a1, (a1[1] ? a1+2 : a1+1));
s2 = this->m_traits.transform(a2, (a2[1] ? a2+2 : a2+1));
#endif
if(s1.size() == 0)
s1 = string_type(1, charT(0));
if(s2.size() == 0)
s2 = string_type(1, charT(0));
}
else
{
if(c1.second)
{
s1.insert(s1.end(), c1.first);
s1.insert(s1.end(), c1.second);
}
else
s1 = string_type(1, c1.first);
if(c2.second)
{
s2.insert(s2.end(), c2.first);
s2.insert(s2.end(), c2.second);
}
else
s2.insert(s2.end(), c2.first);
}
if(s1 > s2)
{
// Oops error:
return 0;
}
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (s1.size() + s2.size() + 2) ) );
re_detail::copy(s1.begin(), s1.end(), p);
p[s1.size()] = charT(0);
p += s1.size() + 1;
re_detail::copy(s2.begin(), s2.end(), p);
p[s2.size()] = charT(0);
}
//
// now process the equivalence classes:
//
first = char_set.equivalents_begin();
last = char_set.equivalents_end();
while(first != last)
{
string_type s;
if(first->second)
{
#if BOOST_WORKAROUND(__GNUC__, < 3)
string_type in(3, charT(0));
in[0] = first->first;
in[1] = first->second;
s = m_traits.transform_primary(in.c_str(), in.c_str()+2);
#else
charT cs[3] = { first->first, first->second, charT(0), };
s = m_traits.transform_primary(cs, cs+2);
#endif
}
else
s = m_traits.transform_primary(&first->first, &first->first+1);
if(s.empty())
return 0; // invalid or unsupported equivalence class
charT* p = static_cast<charT*>(this->m_pdata->m_data.extend(sizeof(charT) * (s.size()+1) ) );
re_detail::copy(s.begin(), s.end(), p);
p[s.size()] = charT(0);
++first;
}
//
// finally reset the address of our last state:
//
m_last_state = result = static_cast<re_set_long<mask_type>*>(getaddress(offset));
return result;
}
namespace{
template<class T>
inline bool char_less(T t1, T t2)
{
return t1 < t2;
}
template<>
inline bool char_less<char>(char t1, char t2)
{
return static_cast<unsigned char>(t1) < static_cast<unsigned char>(t2);
}
template<>
inline bool char_less<signed char>(signed char t1, signed char t2)
{
return static_cast<unsigned char>(t1) < static_cast<unsigned char>(t2);
}
}
template <class charT, class traits>
re_syntax_base* basic_regex_creator<charT, traits>::append_set(
const basic_char_set<charT, traits>& char_set, mpl::true_*)
{
typedef typename traits::string_type string_type;
typedef typename basic_char_set<charT, traits>::list_iterator item_iterator;
re_set* result = static_cast<re_set*>(append_state(syntax_element_set, sizeof(re_set)));
bool negate = char_set.is_negated();
std::memset(result->_map, 0, sizeof(result->_map));
//
// handle singles first:
//
item_iterator first, last;
first = char_set.singles_begin();
last = char_set.singles_end();
while(first != last)
{
for(unsigned int i = 0; i < (1 << CHAR_BIT); ++i)
{
if(this->m_traits.translate(static_cast<charT>(i), this->m_icase)
== this->m_traits.translate(first->first, this->m_icase))
result->_map[i] = true;
}
++first;
}
//
// OK now handle ranges:
//
first = char_set.ranges_begin();
last = char_set.ranges_end();
while(first != last)
{
// first grab the endpoints of the range:
charT c1 = this->m_traits.translate(first->first, this->m_icase);
++first;
charT c2 = this->m_traits.translate(first->first, this->m_icase);
++first;
// different actions now depending upon whether collation is turned on:
if(flags() & regex_constants::collate)
{
// we need to transform our range into sort keys:
charT c3[2] = { c1, charT(0), };
string_type s1 = this->m_traits.transform(c3, c3+1);
c3[0] = c2;
string_type s2 = this->m_traits.transform(c3, c3+1);
if(s1 > s2)
{
// Oops error:
return 0;
}
BOOST_ASSERT(c3[1] == charT(0));
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
c3[0] = static_cast<charT>(i);
string_type s3 = this->m_traits.transform(c3, c3 +1);
if((s1 <= s3) && (s3 <= s2))
result->_map[i] = true;
}
}
else
{
if(char_less<charT>(c2, c1))
{
// Oops error:
return 0;
}
// everything in range matches:
std::memset(result->_map + static_cast<unsigned char>(c1), true, 1 + static_cast<unsigned char>(c2) - static_cast<unsigned char>(c1));
}
}
//
// and now the classes:
//
typedef typename traits::char_class_type mask_type;
mask_type m = char_set.classes();
if(flags() & regbase::icase)
{
// adjust m as needed:
if(((m & m_lower_mask) == m_lower_mask) || ((m & m_upper_mask) == m_upper_mask))
m |= m_alpha_mask;
}
if(m != 0)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
if(this->m_traits.isctype(static_cast<charT>(i), m))
result->_map[i] = true;
}
}
//
// and now the negated classes:
//
m = char_set.negated_classes();
if(flags() & regbase::icase)
{
// adjust m as needed:
if(((m & m_lower_mask) == m_lower_mask) || ((m & m_upper_mask) == m_upper_mask))
m |= m_alpha_mask;
}
if(m != 0)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
if(0 == this->m_traits.isctype(static_cast<charT>(i), m))
result->_map[i] = true;
}
}
//
// now process the equivalence classes:
//
first = char_set.equivalents_begin();
last = char_set.equivalents_end();
while(first != last)
{
string_type s;
BOOST_ASSERT(static_cast<charT>(0) == first->second);
s = m_traits.transform_primary(&first->first, &first->first+1);
if(s.empty())
return 0; // invalid or unsupported equivalence class
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
charT c[2] = { (static_cast<charT>(i)), charT(0), };
string_type s2 = this->m_traits.transform_primary(c, c+1);
if(s == s2)
result->_map[i] = true;
}
++first;
}
if(negate)
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
{
result->_map[i] = !(result->_map[i]);
}
}
return result;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::finalize(const charT* p1, const charT* p2)
{
if(this->m_pdata->m_status)
return;
// we've added all the states we need, now finish things off.
// start by adding a terminating state:
append_state(syntax_element_match);
// extend storage to store original expression:
std::ptrdiff_t len = p2 - p1;
m_pdata->m_expression_len = len;
charT* ps = static_cast<charT*>(m_pdata->m_data.extend(sizeof(charT) * (1 + (p2 - p1))));
m_pdata->m_expression = ps;
re_detail::copy(p1, p2, ps);
ps[p2 - p1] = 0;
// fill in our other data...
// successful parsing implies a zero status:
m_pdata->m_status = 0;
// get the first state of the machine:
m_pdata->m_first_state = static_cast<re_syntax_base*>(m_pdata->m_data.data());
// fixup pointers in the machine:
fixup_pointers(m_pdata->m_first_state);
if(m_has_recursions)
{
m_pdata->m_has_recursions = true;
fixup_recursions(m_pdata->m_first_state);
if(this->m_pdata->m_status)
return;
}
else
m_pdata->m_has_recursions = false;
// create nested startmaps:
create_startmaps(m_pdata->m_first_state);
// create main startmap:
std::memset(m_pdata->m_startmap, 0, sizeof(m_pdata->m_startmap));
m_pdata->m_can_be_null = 0;
m_bad_repeats = 0;
if(m_has_recursions)
m_recursion_checks.assign(1 + m_pdata->m_mark_count, false);
create_startmap(m_pdata->m_first_state, m_pdata->m_startmap, &(m_pdata->m_can_be_null), mask_all);
// get the restart type:
m_pdata->m_restart_type = get_restart_type(m_pdata->m_first_state);
// optimise a leading repeat if there is one:
probe_leading_repeat(m_pdata->m_first_state);
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::fixup_pointers(re_syntax_base* state)
{
while(state)
{
switch(state->type)
{
case syntax_element_recurse:
m_has_recursions = true;
if(state->next.i)
state->next.p = getaddress(state->next.i, state);
else
state->next.p = 0;
break;
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
// set the state_id of this repeat:
static_cast<re_repeat*>(state)->state_id = m_repeater_id++;
// fall through:
case syntax_element_alt:
std::memset(static_cast<re_alt*>(state)->_map, 0, sizeof(static_cast<re_alt*>(state)->_map));
static_cast<re_alt*>(state)->can_be_null = 0;
// fall through:
case syntax_element_jump:
static_cast<re_jump*>(state)->alt.p = getaddress(static_cast<re_jump*>(state)->alt.i, state);
// fall through again:
default:
if(state->next.i)
state->next.p = getaddress(state->next.i, state);
else
state->next.p = 0;
}
state = state->next.p;
}
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::fixup_recursions(re_syntax_base* state)
{
re_syntax_base* base = state;
while(state)
{
switch(state->type)
{
case syntax_element_assert_backref:
{
// just check that the index is valid:
int idx = static_cast<const re_brace*>(state)->index;
if(idx < 0)
{
idx = -idx-1;
if(idx >= 10000)
{
idx = m_pdata->get_id(idx);
if(idx <= 0)
{
// check of sub-expression that doesn't exist:
if(0 == this->m_pdata->m_status) // update the error code if not already set
this->m_pdata->m_status = boost::regex_constants::error_bad_pattern;
//
// clear the expression, we should be empty:
//
this->m_pdata->m_expression = 0;
this->m_pdata->m_expression_len = 0;
//
// and throw if required:
//
if(0 == (this->flags() & regex_constants::no_except))
{
std::string message = "Encountered a forward reference to a marked sub-expression that does not exist.";
boost::regex_error e(message, boost::regex_constants::error_bad_pattern, 0);
e.raise();
}
}
}
}
}
break;
case syntax_element_recurse:
{
bool ok = false;
re_syntax_base* p = base;
std::ptrdiff_t idx = static_cast<re_jump*>(state)->alt.i;
if(idx > 10000)
{
//
// There may be more than one capture group with this hash, just do what Perl
// does and recurse to the leftmost:
//
idx = m_pdata->get_id(static_cast<int>(idx));
}
while(p)
{
if((p->type == syntax_element_startmark) && (static_cast<re_brace*>(p)->index == idx))
{
//
// We've found the target of the recursion, set the jump target:
//
static_cast<re_jump*>(state)->alt.p = p;
ok = true;
//
// Now scan the target for nested repeats:
//
p = p->next.p;
int next_rep_id = 0;
while(p)
{
switch(p->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
next_rep_id = static_cast<re_repeat*>(p)->state_id;
break;
case syntax_element_endmark:
if(static_cast<const re_brace*>(p)->index == idx)
next_rep_id = -1;
break;
default:
break;
}
if(next_rep_id)
break;
p = p->next.p;
}
if(next_rep_id > 0)
{
static_cast<re_recurse*>(state)->state_id = next_rep_id - 1;
}
break;
}
p = p->next.p;
}
if(!ok)
{
// recursion to sub-expression that doesn't exist:
if(0 == this->m_pdata->m_status) // update the error code if not already set
this->m_pdata->m_status = boost::regex_constants::error_bad_pattern;
//
// clear the expression, we should be empty:
//
this->m_pdata->m_expression = 0;
this->m_pdata->m_expression_len = 0;
//
// and throw if required:
//
if(0 == (this->flags() & regex_constants::no_except))
{
std::string message = "Encountered a forward reference to a recursive sub-expression that does not exist.";
boost::regex_error e(message, boost::regex_constants::error_bad_pattern, 0);
e.raise();
}
}
}
default:
break;
}
state = state->next.p;
}
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::create_startmaps(re_syntax_base* state)
{
// non-recursive implementation:
// create the last map in the machine first, so that earlier maps
// can make use of the result...
//
// This was originally a recursive implementation, but that caused stack
// overflows with complex expressions on small stacks (think COM+).
// start by saving the case setting:
bool l_icase = m_icase;
std::vector<std::pair<bool, re_syntax_base*> > v;
while(state)
{
switch(state->type)
{
case syntax_element_toggle_case:
// we need to track case changes here:
m_icase = static_cast<re_case*>(state)->icase;
state = state->next.p;
continue;
case syntax_element_alt:
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
// just push the state onto our stack for now:
v.push_back(std::pair<bool, re_syntax_base*>(m_icase, state));
state = state->next.p;
break;
case syntax_element_backstep:
// we need to calculate how big the backstep is:
static_cast<re_brace*>(state)->index
= this->calculate_backstep(state->next.p);
if(static_cast<re_brace*>(state)->index < 0)
{
// Oops error:
if(0 == this->m_pdata->m_status) // update the error code if not already set
this->m_pdata->m_status = boost::regex_constants::error_bad_pattern;
//
// clear the expression, we should be empty:
//
this->m_pdata->m_expression = 0;
this->m_pdata->m_expression_len = 0;
//
// and throw if required:
//
if(0 == (this->flags() & regex_constants::no_except))
{
std::string message = "Invalid lookbehind assertion encountered in the regular expression.";
boost::regex_error e(message, boost::regex_constants::error_bad_pattern, 0);
e.raise();
}
}
// fall through:
default:
state = state->next.p;
}
}
// now work through our list, building all the maps as we go:
while(v.size())
{
// Initialize m_recursion_checks if we need it:
if(m_has_recursions)
m_recursion_checks.assign(1 + m_pdata->m_mark_count, false);
const std::pair<bool, re_syntax_base*>& p = v.back();
m_icase = p.first;
state = p.second;
v.pop_back();
// Build maps:
m_bad_repeats = 0;
create_startmap(state->next.p, static_cast<re_alt*>(state)->_map, &static_cast<re_alt*>(state)->can_be_null, mask_take);
m_bad_repeats = 0;
if(m_has_recursions)
m_recursion_checks.assign(1 + m_pdata->m_mark_count, false);
create_startmap(static_cast<re_alt*>(state)->alt.p, static_cast<re_alt*>(state)->_map, &static_cast<re_alt*>(state)->can_be_null, mask_skip);
// adjust the type of the state to allow for faster matching:
state->type = this->get_repeat_type(state);
}
// restore case sensitivity:
m_icase = l_icase;
}
template <class charT, class traits>
int basic_regex_creator<charT, traits>::calculate_backstep(re_syntax_base* state)
{
typedef typename traits::char_class_type mask_type;
int result = 0;
while(state)
{
switch(state->type)
{
case syntax_element_startmark:
if((static_cast<re_brace*>(state)->index == -1)
|| (static_cast<re_brace*>(state)->index == -2))
{
state = static_cast<re_jump*>(state->next.p)->alt.p->next.p;
continue;
}
else if(static_cast<re_brace*>(state)->index == -3)
{
state = state->next.p->next.p;
continue;
}
break;
case syntax_element_endmark:
if((static_cast<re_brace*>(state)->index == -1)
|| (static_cast<re_brace*>(state)->index == -2))
return result;
break;
case syntax_element_literal:
result += static_cast<re_literal*>(state)->length;
break;
case syntax_element_wild:
case syntax_element_set:
result += 1;
break;
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_backref:
case syntax_element_rep:
case syntax_element_combining:
case syntax_element_long_set_rep:
case syntax_element_backstep:
{
re_repeat* rep = static_cast<re_repeat *>(state);
// adjust the type of the state to allow for faster matching:
state->type = this->get_repeat_type(state);
if((state->type == syntax_element_dot_rep)
|| (state->type == syntax_element_char_rep)
|| (state->type == syntax_element_short_set_rep))
{
if(rep->max != rep->min)
return -1;
result += static_cast<int>(rep->min);
state = rep->alt.p;
continue;
}
else if((state->type == syntax_element_long_set_rep))
{
BOOST_ASSERT(rep->next.p->type == syntax_element_long_set);
if(static_cast<re_set_long<mask_type>*>(rep->next.p)->singleton == 0)
return -1;
if(rep->max != rep->min)
return -1;
result += static_cast<int>(rep->min);
state = rep->alt.p;
continue;
}
}
return -1;
case syntax_element_long_set:
if(static_cast<re_set_long<mask_type>*>(state)->singleton == 0)
return -1;
result += 1;
break;
case syntax_element_jump:
state = static_cast<re_jump*>(state)->alt.p;
continue;
case syntax_element_alt:
{
int r1 = calculate_backstep(state->next.p);
int r2 = calculate_backstep(static_cast<re_alt*>(state)->alt.p);
if((r1 < 0) || (r1 != r2))
return -1;
return result + r1;
}
default:
break;
}
state = state->next.p;
}
return -1;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::create_startmap(re_syntax_base* state, unsigned char* l_map, unsigned int* pnull, unsigned char mask)
{
int not_last_jump = 1;
re_syntax_base* recursion_start = 0;
int recursion_sub = 0;
re_syntax_base* recursion_restart = 0;
// track case sensitivity:
bool l_icase = m_icase;
while(state)
{
switch(state->type)
{
case syntax_element_toggle_case:
l_icase = static_cast<re_case*>(state)->icase;
state = state->next.p;
break;
case syntax_element_literal:
{
// don't set anything in *pnull, set each element in l_map
// that could match the first character in the literal:
if(l_map)
{
l_map[0] |= mask_init;
charT first_char = *static_cast<charT*>(static_cast<void*>(static_cast<re_literal*>(state) + 1));
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(m_traits.translate(static_cast<charT>(i), l_icase) == first_char)
l_map[i] |= mask;
}
}
return;
}
case syntax_element_end_line:
{
// next character must be a line separator (if there is one):
if(l_map)
{
l_map[0] |= mask_init;
l_map['\n'] |= mask;
l_map['\r'] |= mask;
l_map['\f'] |= mask;
l_map[0x85] |= mask;
}
// now figure out if we can match a NULL string at this point:
if(pnull)
create_startmap(state->next.p, 0, pnull, mask);
return;
}
case syntax_element_recurse:
{
if(state->type == syntax_element_startmark)
recursion_sub = static_cast<re_brace*>(state)->index;
else
recursion_sub = 0;
if(m_recursion_checks[recursion_sub])
{
// Infinite recursion!!
if(0 == this->m_pdata->m_status) // update the error code if not already set
this->m_pdata->m_status = boost::regex_constants::error_bad_pattern;
//
// clear the expression, we should be empty:
//
this->m_pdata->m_expression = 0;
this->m_pdata->m_expression_len = 0;
//
// and throw if required:
//
if(0 == (this->flags() & regex_constants::no_except))
{
std::string message = "Encountered an infinite recursion.";
boost::regex_error e(message, boost::regex_constants::error_bad_pattern, 0);
e.raise();
}
}
else if(recursion_start == 0)
{
recursion_start = state;
recursion_restart = state->next.p;
state = static_cast<re_jump*>(state)->alt.p;
m_recursion_checks[recursion_sub] = true;
break;
}
m_recursion_checks[recursion_sub] = true;
// fall through, can't handle nested recursion here...
}
case syntax_element_backref:
// can be null, and any character can match:
if(pnull)
*pnull |= mask;
// fall through:
case syntax_element_wild:
{
// can't be null, any character can match:
set_all_masks(l_map, mask);
return;
}
case syntax_element_match:
{
// must be null, any character can match:
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
case syntax_element_word_start:
{
// recurse, then AND with all the word characters:
create_startmap(state->next.p, l_map, pnull, mask);
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(!m_traits.isctype(static_cast<charT>(i), m_word_mask))
l_map[i] &= static_cast<unsigned char>(~mask);
}
}
return;
}
case syntax_element_word_end:
{
// recurse, then AND with all the word characters:
create_startmap(state->next.p, l_map, pnull, mask);
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(m_traits.isctype(static_cast<charT>(i), m_word_mask))
l_map[i] &= static_cast<unsigned char>(~mask);
}
}
return;
}
case syntax_element_buffer_end:
{
// we *must be null* :
if(pnull)
*pnull |= mask;
return;
}
case syntax_element_long_set:
if(l_map)
{
typedef typename traits::char_class_type mask_type;
if(static_cast<re_set_long<mask_type>*>(state)->singleton)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
charT c = static_cast<charT>(i);
if(&c != re_is_set_member(&c, &c + 1, static_cast<re_set_long<mask_type>*>(state), *m_pdata, l_icase))
l_map[i] |= mask;
}
}
else
set_all_masks(l_map, mask);
}
return;
case syntax_element_set:
if(l_map)
{
l_map[0] |= mask_init;
for(unsigned int i = 0; i < (1u << CHAR_BIT); ++i)
{
if(static_cast<re_set*>(state)->_map[
static_cast<unsigned char>(m_traits.translate(static_cast<charT>(i), l_icase))])
l_map[i] |= mask;
}
}
return;
case syntax_element_jump:
// take the jump:
state = static_cast<re_alt*>(state)->alt.p;
not_last_jump = -1;
break;
case syntax_element_alt:
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
re_alt* rep = static_cast<re_alt*>(state);
if(rep->_map[0] & mask_init)
{
if(l_map)
{
// copy previous results:
l_map[0] |= mask_init;
for(unsigned int i = 0; i <= UCHAR_MAX; ++i)
{
if(rep->_map[i] & mask_any)
l_map[i] |= mask;
}
}
if(pnull)
{
if(rep->can_be_null & mask_any)
*pnull |= mask;
}
}
else
{
// we haven't created a startmap for this alternative yet
// so take the union of the two options:
if(is_bad_repeat(state))
{
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
set_bad_repeat(state);
create_startmap(state->next.p, l_map, pnull, mask);
if((state->type == syntax_element_alt)
|| (static_cast<re_repeat*>(state)->min == 0)
|| (not_last_jump == 0))
create_startmap(rep->alt.p, l_map, pnull, mask);
}
}
return;
case syntax_element_soft_buffer_end:
// match newline or null:
if(l_map)
{
l_map[0] |= mask_init;
l_map['\n'] |= mask;
l_map['\r'] |= mask;
}
if(pnull)
*pnull |= mask;
return;
case syntax_element_endmark:
// need to handle independent subs as a special case:
if(static_cast<re_brace*>(state)->index < 0)
{
// can be null, any character can match:
set_all_masks(l_map, mask);
if(pnull)
*pnull |= mask;
return;
}
else if(recursion_start && (recursion_sub != 0) && (recursion_sub == static_cast<re_brace*>(state)->index))
{
// recursion termination:
recursion_start = 0;
state = recursion_restart;
break;
}
//
// Normally we just go to the next state... but if this sub-expression is
// the target of a recursion, then we might be ending a recursion, in which
// case we should check whatever follows that recursion, as well as whatever
// follows this state:
//
if(m_pdata->m_has_recursions && static_cast<re_brace*>(state)->index)
{
bool ok = false;
re_syntax_base* p = m_pdata->m_first_state;
while(p)
{
if((p->type == syntax_element_recurse))
{
re_brace* p2 = static_cast<re_brace*>(static_cast<re_jump*>(p)->alt.p);
if((p2->type == syntax_element_startmark) && (p2->index == static_cast<re_brace*>(state)->index))
{
ok = true;
break;
}
}
p = p->next.p;
}
if(ok)
{
create_startmap(p->next.p, l_map, pnull, mask);
}
}
state = state->next.p;
break;
case syntax_element_startmark:
// need to handle independent subs as a special case:
if(static_cast<re_brace*>(state)->index == -3)
{
state = state->next.p->next.p;
break;
}
// otherwise fall through:
default:
state = state->next.p;
}
++not_last_jump;
}
}
template <class charT, class traits>
unsigned basic_regex_creator<charT, traits>::get_restart_type(re_syntax_base* state)
{
//
// find out how the machine starts, so we can optimise the search:
//
while(state)
{
switch(state->type)
{
case syntax_element_startmark:
case syntax_element_endmark:
state = state->next.p;
continue;
case syntax_element_start_line:
return regbase::restart_line;
case syntax_element_word_start:
return regbase::restart_word;
case syntax_element_buffer_start:
return regbase::restart_buf;
case syntax_element_restart_continue:
return regbase::restart_continue;
default:
state = 0;
continue;
}
}
return regbase::restart_any;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::set_all_masks(unsigned char* bits, unsigned char mask)
{
//
// set mask in all of bits elements,
// if bits[0] has mask_init not set then we can
// optimise this to a call to memset:
//
if(bits)
{
if(bits[0] == 0)
(std::memset)(bits, mask, 1u << CHAR_BIT);
else
{
for(unsigned i = 0; i < (1u << CHAR_BIT); ++i)
bits[i] |= mask;
}
bits[0] |= mask_init;
}
}
template <class charT, class traits>
bool basic_regex_creator<charT, traits>::is_bad_repeat(re_syntax_base* pt)
{
switch(pt->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
unsigned state_id = static_cast<re_repeat*>(pt)->state_id;
if(state_id > sizeof(m_bad_repeats) * CHAR_BIT)
return true; // run out of bits, assume we can't traverse this one.
static const boost::uintmax_t one = 1uL;
return m_bad_repeats & (one << state_id);
}
default:
return false;
}
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::set_bad_repeat(re_syntax_base* pt)
{
switch(pt->type)
{
case syntax_element_rep:
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
{
unsigned state_id = static_cast<re_repeat*>(pt)->state_id;
static const boost::uintmax_t one = 1uL;
if(state_id <= sizeof(m_bad_repeats) * CHAR_BIT)
m_bad_repeats |= (one << state_id);
}
default:
break;
}
}
template <class charT, class traits>
syntax_element_type basic_regex_creator<charT, traits>::get_repeat_type(re_syntax_base* state)
{
typedef typename traits::char_class_type mask_type;
if(state->type == syntax_element_rep)
{
// check to see if we are repeating a single state:
if(state->next.p->next.p->next.p == static_cast<re_alt*>(state)->alt.p)
{
switch(state->next.p->type)
{
case re_detail::syntax_element_wild:
return re_detail::syntax_element_dot_rep;
case re_detail::syntax_element_literal:
return re_detail::syntax_element_char_rep;
case re_detail::syntax_element_set:
return re_detail::syntax_element_short_set_rep;
case re_detail::syntax_element_long_set:
if(static_cast<re_detail::re_set_long<mask_type>*>(state->next.p)->singleton)
return re_detail::syntax_element_long_set_rep;
break;
default:
break;
}
}
}
return state->type;
}
template <class charT, class traits>
void basic_regex_creator<charT, traits>::probe_leading_repeat(re_syntax_base* state)
{
// enumerate our states, and see if we have a leading repeat
// for which failed search restarts can be optimised;
do
{
switch(state->type)
{
case syntax_element_startmark:
if(static_cast<re_brace*>(state)->index >= 0)
{
state = state->next.p;
continue;
}
if((static_cast<re_brace*>(state)->index == -1)
|| (static_cast<re_brace*>(state)->index == -2))
{
// skip past the zero width assertion:
state = static_cast<const re_jump*>(state->next.p)->alt.p->next.p;
continue;
}
if(static_cast<re_brace*>(state)->index == -3)
{
// Have to skip the leading jump state:
state = state->next.p->next.p;
continue;
}
return;
case syntax_element_endmark:
case syntax_element_start_line:
case syntax_element_end_line:
case syntax_element_word_boundary:
case syntax_element_within_word:
case syntax_element_word_start:
case syntax_element_word_end:
case syntax_element_buffer_start:
case syntax_element_buffer_end:
case syntax_element_restart_continue:
state = state->next.p;
break;
case syntax_element_dot_rep:
case syntax_element_char_rep:
case syntax_element_short_set_rep:
case syntax_element_long_set_rep:
if(this->m_has_backrefs == 0)
static_cast<re_repeat*>(state)->leading = true;
// fall through:
default:
return;
}
}while(state);
}
} // namespace re_detail
} // namespace boost
#ifdef BOOST_MSVC
# pragma warning(pop)
#endif
#ifdef BOOST_MSVC
#pragma warning(push)
#pragma warning(disable: 4103)
#endif
#ifdef BOOST_HAS_ABI_HEADERS
# include BOOST_ABI_SUFFIX
#endif
#ifdef BOOST_MSVC
#pragma warning(pop)
#endif
#endif
| [
"candice@818d6d3f-7dde-412f-b1db-fda94a19c49a"
] | candice@818d6d3f-7dde-412f-b1db-fda94a19c49a |
d54297cb9a2d0a8f066e4989373b1445903cfcd3 | fc2c2e0f5b1f905316d46523cdaa0b27005ff4ca | /algo/suffix_array.cpp | e5baf4b1f2dff860180294a8d203c0b96344dc70 | [] | no_license | gaurav172/codes | 198ef6377c4da28f985b92c4e1ebfe407517e259 | c049d99e85961a07e0eb41d144c3b6f5342498f0 | refs/heads/master | 2022-07-10T18:25:03.219752 | 2020-05-17T08:12:15 | 2020-05-17T08:12:15 | 264,613,131 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,134 | cpp | #include <bits/stdc++.h>
using namespace std;
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define ll int
#define ld double
#define ff first
#define ss second
#define pb push_back
#define mp make_pair
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
const ll M=1e5+5;
ll p[M][20],phi[M],LCP[M],PLCP[M],csum[M];
std::vector<ll> ct2[M];
std::vector<pair<ll,ll> > ct1[M];
std::vector<ll> SA;
string s;
void computSA()
{
ll n=sz(s);
for(ll i=0;i<n;i++)
p[i][0]=s[i]-'a'+1;
for(ll j=1;j<20;j++)
{
for(ll i=0;i<M;i++)
{
ct1[i].clear();
ct2[i].clear();
}
for(ll i=0;i<n;i++)
{
ll z=i+(1<<(j-1));
if(z>=n)
ct2[0].pb(i);
else
ct2[p[z][j-1]].pb(i);
}
for(ll i=0;i<M;i++)
{
for(ll k=0;k<sz(ct2[i]);k++)
{
ll z=ct2[i][k];
ct1[p[z][j-1]].pb(mp(z,i));
}
}
ll rk=0;
for(ll i=0;i<M;i++)
{
for(ll k=0;k<sz(ct1[i]);k++)
{
if(k)
{
if(ct1[i][k].ss!=ct1[i][k-1].ss)
rk++;
}
p[ct1[i][k].ff][j]=rk;
}
rk++;
}
}
for(ll i=0;i<M;i++)
for(ll k=0;k<sz(ct1[i]);k++)
SA.pb(ct1[i][k].ff);
}
void computeLCP()
{
ll n=sz(s);
phi[SA[0]]=-1;
for(ll i=1;i<n;i++)
phi[SA[i]]=SA[i-1];
ll L=0;
for(ll i=0;i<n;i++)
{
if(phi[i]==-1)
{
PLCP[i]=0;
continue;
}
while(s[i+L]==s[phi[i]+L])
L++;
PLCP[i]=L;
L=max(L-1,(ll)0);
}
for(ll i=0;i<n;i++)
LCP[i]=PLCP[SA[i]]; // Longest common prefix between suffixes SA[i] and SA[i-1].
}
int main()
{
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
ll type;
cin>>type;
if(type==1)
{
cout<<"abcabc\n";
return 0;
}
cin>>s;
ll n1=sz(s);
// string str;
// cin>>str;
// ll n2=sz(str);
// s=s+'0'+str;
computSA();
for(auto u:SA)
cout<<u<<" ";
cout<<"\n";
return 0;
} | [
"gaurav.sultane@rubrik.com"
] | gaurav.sultane@rubrik.com |
4227f63f93bd5237a4020278a722ccf0e6b9647c | 6e2f3b5c27df0cbcc6174bf926be729aa63ef1ea | /Include/xsim/fmt.hpp | 47bf724f3e58f72487cc7f7793013077018a4b25 | [
"LicenseRef-scancode-object-form-exception-to-mit",
"MIT",
"BSL-1.0"
] | permissive | raving-bots/expansim-sdk | 349b18875c9530bb4a5b32c5fd063036ce1ae269 | 22f5c794523abbe9c27688963b607b13671ff118 | refs/heads/master | 2021-10-22T10:21:00.872874 | 2021-10-18T19:58:47 | 2021-10-18T19:58:47 | 223,376,080 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 882 | hpp | // Copyright Raving Bots 2018-2020
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file SDK-LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt)
#pragma once
#include <string>
#include <string_view>
#include <fmt/format.h>
#include <fmt/ostream.h>
#define XSIM_WIDE_LITERAL2(t) L ## t
#define XSIM_WIDE_LITERAL(t) XSIM_WIDE_LITERAL2(t)
#define XSIM_FMT_LITERAL(t) ::xsim::detail::SelectLiteral<Char>(t, XSIM_WIDE_LITERAL(t))
namespace xsim::detail
{
template <typename Char>
constexpr const Char* SelectLiteral(const char* narrow, const wchar_t* wide) = delete;
template <>
constexpr const char* SelectLiteral<char>(const char* narrow, const wchar_t*)
{
return narrow;
}
template <>
constexpr const wchar_t* SelectLiteral<wchar_t>(const char*, const wchar_t* wide)
{
return wide;
}
}
| [
"me@catpp.eu"
] | me@catpp.eu |
706a9b0f8fa6ffec88fd7cbdcb5232b357cc72f0 | cf1911723d07048c4180ace63afbd6ae60727eb0 | /nnnLib/commonOverrap.h | dd333fead19e9754030627bf7f8d190844426403 | [] | no_license | tinyan/SystemNNN | 57490606973d95aa1e65d6090957b0e25c5b89f8 | 07e18ded880a0998bf5560c05c112b5520653e19 | refs/heads/master | 2023-05-04T17:30:42.406037 | 2023-04-16T03:38:40 | 2023-04-16T03:38:40 | 7,564,789 | 13 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 839 | h | //
// Overrap.h
//
#if !defined __NNNLIB_COMMONOVERRAP__
#define __NNNLIB_COMMONOVERRAP__
class CCommonGeneral;
class CGameCallBack;
class CPicture;
class CCommonOverrap : public CCommonGeneral
{
public:
CCommonOverrap(CGameCallBack* lpGame);
virtual ~CCommonOverrap();
virtual void End(void);
virtual int Init(void);
virtual int Calcu(void);
virtual int Print(void);
virtual void ResetShakin(void);
virtual int GetShakin(void);
protected:
virtual void BeforeInit(void) {}
virtual void AfterInit(void) {}
virtual void BeforeCalcu(void){}
virtual void AfterCalcu(void){}
virtual void BeforePrint(void){}
virtual void AfterPrint(void){}
private:
CPicture* m_pic1;
CPicture* m_pic2;
int m_type;
int m_length;
int m_count;
int m_shakin;
int m_optionButtonPrintFlag;
int m_sceneButtonPrintFlag;
};
#endif
/*_*/
| [
"tinyan@mri.biglobe.ne.jp"
] | tinyan@mri.biglobe.ne.jp |
2a1e37e3984175b714dcb89279c23497080101fd | 6d6d5a7856a31896c90cf589ee4491ce3f72caf7 | /EyeEvolution/Environment.h | 3ac495f1e4ee1d6fd6d3013a2f5dfa08a572e995 | [
"BSD-3-Clause"
] | permissive | godofecht/Eye-Evolution | 6ad908fc10baa86c0d5e0fd65f6b81773e58626f | 4ec23738d1592118f99f8ca94cf17a3eb650be6a | refs/heads/main | 2023-02-19T11:44:30.011921 | 2021-01-19T10:13:23 | 2021-01-19T10:13:23 | 318,799,701 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,122 | h | #ifndef ENVIRONMENT_H
#define ENVIRONMENT_H
#pragma once
#include "prey.h"
#include "predator.h"
#include <SFML/Graphics.hpp>
#include "FitnessTables.h"
class Food
{
public:
sf::CircleShape shape;
Food()
{
shape.setFillColor(Color::Yellow);
shape.setRadius(10);
shape.setOrigin(Vector2f(shape.getRadius(), shape.getRadius()));
shape.setRotation(45);
}
};
class Environment
{
public:
int NUM_ITERATIONS = 0;
bool bCaught = false;
bool bTimedOut = false;
vector<Prey*> preyVector;
vector<Prey*> preySoloVector;
vector<Predator*> predatorVector;
vector<Predator*> predatorSoloVector;
sf::RenderWindow* window;
int NUM_EYES = 2;
int timeElapsed = 0;
int TEST_Duration = 4000;
bool bShouldDraw = true;
bool bOver = false;
int num_prey = 10;
int num_predators = 10;
bool bAllPreyDead = false;
bool bAllPredatorsDead = false;
vector<Food*> foodVector;
sf::Text Iteration_Counter;
bool bBatchTest = false;
bool bSoloTest = false;
Environment()
{
if (NUM_ITERATIONS > 0)
bShouldDraw = true;
else
bShouldDraw = true;
Iteration_Counter.setPosition(100, 100);
// Iteration_Counter.setFont(font); // font is a sf::Font
// Iteration_Counter.setString(to_string(NUM_ITERATIONS));
Iteration_Counter.setCharacterSize(50); // in pixels, not points!
Iteration_Counter.setFillColor(sf::Color::Blue);
// Iteration_Counter.setStyle(sf::Text::Bold | sf::Text::Underlined);
for (int i = 0; i < num_prey; i++)
{
preyVector.push_back(new Prey(NUM_EYES));
}
for (int i = 0; i < num_predators; i++)
{
predatorVector.push_back(new Predator(NUM_EYES));
}
for (int i = 0; i < num_prey; i++)
{
for (int j = 0; j < num_predators; j++)
preyVector[i]->chasingPredator.push_back(&predatorVector[j]->shape);
cout << num_prey;
}
for (int i = 0; i < num_predators; i++)
{
predatorVector[i]->chasedPrey = preyVector;
}
}
void InitializeTest()
{
for (int i = 0; i < num_prey; i++)
{
preyVector[i]->bCaught = false;
preyVector[i]->shape.setPosition(Vector2f(700, 700));
preyVector[i]->fitness = 0;
preyVector[i]->shape.setRotation(0);
}
for (int i = 0; i < num_predators; i++)
{
predatorVector[i]->bCaught = false;
predatorVector[i]->shape.setPosition(Vector2f(200, 200));
predatorVector[i]->fitness = 0;
predatorVector[i]->shape.setRotation(0);
}
timeElapsed = 0;
bCaught = false;
bTimedOut = false;
NUM_ITERATIONS++;
}
void Run()
{
for (int i = 0; i < num_prey; i++)
{
if (preyVector[i]->bCaught)
preyVector[i]->Die();
}
for (int i = 0; i < num_prey; i++)
{
if (!preyVector[i]->bCaught) //if prey not caught, i.e. still alive
{
bAllPreyDead = false;
}
}
for (int i = 0; i < num_predators; i++)
{
if (!predatorVector[i]->bCaught) //if prey not caught, i.e. still alive
{
bAllPredatorsDead = false;
}
}
if (bAllPredatorsDead || bAllPreyDead)
{
cout << "yo";
// bTimedOut = true;
bOver = true;
End();
}
if (!bCaught && !bTimedOut)
{
if (timeElapsed > TEST_Duration)
{
bTimedOut = true;
return;
}
if (bTimedOut)
{
// for(int i=0;i<prey.size();i++)
// if(!prey[i]->bCaught)
// prey[i]->fitness += 10000;
return;
}
// for (int i = 0; i < preyVector.size(); i++)
// if (!preyVector[i]->bCaught)
// preyVector[i]->fitness++;
// for (int i = 0; i < predatorVector.size(); i++)
// predatorVector[i]->fitness--;
if (timeElapsed % 300 == 0)
{
GenerateFood();
}
vector<CircleShape*> foodVec;
for (int prey_i = 0; prey_i < num_prey; prey_i++)
{
for (int food_i = 0; food_i < foodVector.size(); food_i++)
{
foodVec.push_back(&(foodVector[food_i]->shape));
}
preyVector[prey_i]->foodVector = foodVec;
foodVec.clear();
// preyVector[prey_i]->fitness += 1; // fitness increment;
preyVector[prey_i]->Behave();
if (bShouldDraw)
{
window->draw(preyVector[prey_i]->shape);
for (int i = 0; i < preyVector[prey_i]->num_eyes; i++)
{
window->draw(preyVector[prey_i]->rays[i].line);
}
}
for (int predator_i = 0; predator_i < num_predators; predator_i++)
{
if (preyVector[prey_i]->shape.getGlobalBounds().intersects(predatorVector[predator_i]->shape.getGlobalBounds()))
{
// predator[predator_i]->fitness += 100000; //predator gets a big reward if he catches prey
preyVector[prey_i]->bCaught = true;
preyVector[prey_i]->fitness -= 1000;
predatorVector[predator_i]->fitness += 1000;
predatorVector[predator_i]->bCaught = true;
}
}
//food foraging stuff
for(int food_i = 0; food_i <foodVector.size(); food_i++)
{
if (preyVector[prey_i]->shape.getGlobalBounds().intersects(foodVector[food_i]->shape.getGlobalBounds()))
{
//rewards prey
preyVector[prey_i]->fitness += 1000;
//destroys food
foodVector.erase(foodVector.begin() + food_i);
}
}
}
for (int predator_i = 0; predator_i < num_predators; predator_i++)
{
predatorVector[predator_i]->Behave();
if (bShouldDraw)
{
window->draw(predatorVector[predator_i]->shape);
for (int i = 0; i < predatorVector[predator_i]->num_eyes; i++)
window->draw(predatorVector[predator_i]->rays[i].line);
}
}
timeElapsed++;
}
else
{
bOver = true;
End();
}
for (int i = 0; i < foodVector.size(); i++)
{
window->draw(foodVector[i]->shape);
}
// inside the main loop, between window.clear() and window.display()
// Iteration_Counter.setString(to_string(NUM_ITERATIONS));
Iteration_Counter.setString(to_string(NUM_ITERATIONS));
window->draw(Iteration_Counter);
}
void GenerateFood()
{
foodVector.push_back(new Food());
foodVector[foodVector.size() - 1]->shape.setPosition(Vector2f(rand() % 1000,rand() % 1000));
}
void End()
{
if(bBatchTest)
RunGeneticAlgorithm(preyVector,predatorVector,preyVector,predatorVector);
if (bSoloTest)
{
for (int i = 0; i < preyVector.size(); i++)
{
preySoloVector.push_back(preyVector[i]);
}
for (int i = 0; i < predatorVector.size(); i++)
{
predatorSoloVector.push_back(predatorVector[i]);
}
if (NUM_ITERATIONS % 10 == 0) //change 10 to number_of_runs or something
{
RunGeneticAlgorithm(preySoloVector, predatorSoloVector, preyVector, predatorVector);
preySoloVector.clear();
predatorSoloVector.clear();
foodVector.clear();
}
else
{
InitializeTest();
bOver = false;
}
}
}
void RunGeneticAlgorithm(vector<Prey*> &prey,vector<Predator*> &predator, vector<Prey*>& destPrey, vector<Predator*>& destPredator)
{
vector<Prey*> sortedPrey;
vector<Predator*> sortedPredators;
vector<Prey*> newPrey;
vector<Predator*> newPredators;
Prey preyA(NUM_EYES);
Prey preyB(NUM_EYES);
Predator predatorA(NUM_EYES);
Predator predatorB(NUM_EYES);
PreyTable preyTable;
PredatorTable predatorTable;
int current_env_index = 0;
bool bAllTestsOver;
cout << "not even started";
for (int l = 0; l < 1; l++) //get rid of this loop entirely
{
for (int prey_i = 0; prey_i < prey.size(); prey_i++)
preyTable.Add(prey[prey_i], prey[prey_i]->fitness);
for (int predator_i = 0; predator_i < prey.size(); predator_i++)
predatorTable.Add(predator[predator_i], predator[predator_i]->fitness);
preyTable.Sort();
predatorTable.Sort();
sortedPrey = preyTable.getTable();
sortedPredators = predatorTable.getTable();
cout << "sorted";
//Perform Roulette Wheel Selections and obtain new weights by crossing over using the genetic algorithm.
for (int i = 0; i < sortedPrey.size(); i += 2)
{
preyA = rouletteWheel(sortedPrey, preyTable.fitness_sum);
preyB = rouletteWheel(sortedPrey, preyTable.fitness_sum);
ChildrenPair children = GeneticAlgorithm::Crossover(preyA.gene, preyB.gene);
// newPrey.push_back(Prey(NUM_EYES));
newPrey.push_back(new Prey(NUM_EYES));
newPrey[i]->brain.SetWeights(children.gene1.weights);
int ki = i + 1;
if ((ki) < sortedPrey.size())
{
newPrey.push_back(new Prey(NUM_EYES));
// newPrey.push_back(Prey(NUM_EYES));
newPrey[ki]->brain.SetWeights(children.gene2.weights);
}
}
cout << "rouletted";
//Update existing brains with the new values
for (int i = 0; i < newPrey.size(); i++)
{
for (int prey_i = 0; prey_i < destPrey.size(); prey_i++)
{
destPrey[prey_i]->fitness = 0;
destPrey[prey_i]->brain.SetWeights(newPrey[i]->brain.GetWeights());
}
cout << "prey updated";
}
//PREDATOR GOES HERE
//Perform Roulette Wheel Selections and obtain new weights by crossing over using the genetic algorithm.
for (int i = 0; i < sortedPredators.size(); i += 2)
{
predatorA = rouletteWheelpred(sortedPredators, predatorTable.fitness_sum);
predatorB = rouletteWheelpred(sortedPredators, predatorTable.fitness_sum);
ChildrenPair children = GeneticAlgorithm::Crossover(predatorA.gene, predatorB.gene);
newPredators.push_back(new Predator(NUM_EYES));
// newPredators[i] = sortedPredators[i];
newPredators[i]->brain.SetWeights(children.gene1.weights);
if ((i + 1) < sortedPredators.size())
{
newPredators.push_back(new Predator(NUM_EYES));
// newPredators[i] = sortedPredators[i];
newPredators[i + 1]->brain.SetWeights(children.gene2.weights);
}
}
//Update existing brains with the new values
for (int i = 0; i < newPredators.size(); i++)
{
for (int predator_i = 0; predator_i < destPredator.size(); predator_i++)
{
destPredator[predator_i]->fitness = 0;
destPredator[predator_i]->brain.SetWeights(newPredators[i]->brain.GetWeights());
}
}
cout<<"predator updated";
current_env_index = 0;
preyTable.clear();
predatorTable.clear();
sortedPrey.clear();
sortedPredators.clear();
newPrey.clear();
newPredators.clear();
bOver = false;
InitializeTest();
}
}
};
#endif | [
"abhishek.shivakumar@gmail.com"
] | abhishek.shivakumar@gmail.com |
7932d1a10684371479491ebe51e396ee0fea960a | e1951b7f7a739b96e961797f8849e58dcb41f00d | /falcon/utility/swap.hpp | e98cc49690f391b92c0d9e9ddcc2c35464433707 | [
"MIT"
] | permissive | jonathanpoelen/falcon | fcf2a92441bb2a7fc0c025ff25a197d24611da71 | 5b60a39787eedf15b801d83384193a05efd41a89 | refs/heads/master | 2021-01-17T10:21:17.492484 | 2016-03-27T23:28:50 | 2016-03-27T23:28:50 | 6,459,776 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 709 | hpp | #ifndef FALCON_UTILITY_SWAP_HPP
#define FALCON_UTILITY_SWAP_HPP
#if __cplusplus >= 201103L
# include <utility>
#else
# include <algorithm>
#endif
#include <falcon/c++/noexcept.hpp>
namespace falcon_swap_impl {
using std::swap;
template<class T>
void swap_impl(T & a, T & b) CPP_NOEXCEPT_OPERATOR2(swap(a,b)) {
swap(a,b);
}
}
namespace falcon {
template<typename T>
void swap(T& x, T& y)
CPP_NOEXCEPT_OPERATOR2(::falcon_swap_impl::swap_impl(x,y))
{ ::falcon_swap_impl::swap_impl(x,y); }
#if __cplusplus < 201103L
template<typename T, std::size_t N>
void swap(T(&x)[N], T(&y)[N])
{
for (std::size_t i = 0; i < N; ++i) {
::falcon_swap_impl::swap_impl(x[i], y[i]);
}
}
#endif
}
#endif
| [
"jonathan.poelen@gmail.com"
] | jonathan.poelen@gmail.com |
2b9c3a9a235c37c0da464da09169d2d3fdb2d0d0 | 38510337385b3fb26c5cd8e0c45b9b56c2443779 | /JustAsk/JustAsk.cpp | d8afe407e0708793b3c90f3b9fd09b21e2b34512 | [] | no_license | ouerkakaChango/JustAsk | 50251717d3c1abda7afdcb5c557158999d1310ae | bc3a8cac7177799645f8bcdb092fa35122043cb1 | refs/heads/master | 2021-04-28T02:12:48.224463 | 2018-03-22T07:27:04 | 2018-03-22T07:27:04 | 122,297,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 496 | cpp | //main
#include "StandardHuman.h"
#include "Computer.h"
#include "Connector.h"
#include "God.h"
#ifdef _WIN32
#include "windows.h"
#endif // _WIN32
int main()
{
//test...
StandardHuman* user1=GOD.Create<StandardHuman>("user1");
Computer* pc1=GOD.Create<Computer>("pc1");
Connector* keyBoard1=GOD.Create<Connector>("keyBoard1");
//"user1", "pc1"
keyBoard1->SetConnection("user1", "pc1");
user1->Ask("Demand1.json");
#ifdef _WIN32
system("pause");
#endif // _WIN32
return 0;
}
| [
"2293933523@qq.com"
] | 2293933523@qq.com |
850eaa7bc5b65ac45e06111580d556c03fd4bd3f | 3f4197b01dbc1f065d759c79e603c7deb31a2599 | /external/android/include/21/frameworks/av/include/media/stagefright/foundation/AMessage.h | a9e235b29d63c5b34f399b55a009c082f4095acb | [
"Apache-2.0"
] | permissive | nova-video-player/aos-avos | 543477be60e8a2a546f027dd0a97b3bf170585e7 | 2b79168e639f8088ef5d1e3a8d09f5523c063801 | refs/heads/nova | 2023-08-09T21:09:13.446561 | 2023-07-07T20:00:31 | 2023-07-07T20:00:31 | 133,509,761 | 10 | 6 | Apache-2.0 | 2020-02-05T22:19:25 | 2018-05-15T11:59:28 | C | UTF-8 | C++ | false | false | 5,021 | h | /*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef A_MESSAGE_H_
#define A_MESSAGE_H_
#include <media/stagefright/foundation/ABase.h>
#include <media/stagefright/foundation/ALooper.h>
#include <utils/KeyedVector.h>
#include <utils/RefBase.h>
namespace android {
struct ABuffer;
struct AString;
struct Parcel;
struct AMessage : public RefBase {
AMessage(uint32_t what = 0, ALooper::handler_id target = 0);
static sp<AMessage> FromParcel(const Parcel &parcel);
void writeToParcel(Parcel *parcel) const;
void setWhat(uint32_t what);
uint32_t what() const;
void setTarget(ALooper::handler_id target);
ALooper::handler_id target() const;
void clear();
void setInt32(const char *name, int32_t value);
void setInt64(const char *name, int64_t value);
void setSize(const char *name, size_t value);
void setFloat(const char *name, float value);
void setDouble(const char *name, double value);
void setPointer(const char *name, void *value);
void setString(const char *name, const char *s, ssize_t len = -1);
void setString(const char *name, const AString &s);
void setObject(const char *name, const sp<RefBase> &obj);
void setBuffer(const char *name, const sp<ABuffer> &buffer);
void setMessage(const char *name, const sp<AMessage> &obj);
void setRect(
const char *name,
int32_t left, int32_t top, int32_t right, int32_t bottom);
bool contains(const char *name) const;
bool findInt32(const char *name, int32_t *value) const;
bool findInt64(const char *name, int64_t *value) const;
bool findSize(const char *name, size_t *value) const;
bool findFloat(const char *name, float *value) const;
bool findDouble(const char *name, double *value) const;
bool findPointer(const char *name, void **value) const;
bool findString(const char *name, AString *value) const;
bool findObject(const char *name, sp<RefBase> *obj) const;
bool findBuffer(const char *name, sp<ABuffer> *buffer) const;
bool findMessage(const char *name, sp<AMessage> *obj) const;
bool findRect(
const char *name,
int32_t *left, int32_t *top, int32_t *right, int32_t *bottom) const;
void post(int64_t delayUs = 0);
// Posts the message to its target and waits for a response (or error)
// before returning.
status_t postAndAwaitResponse(sp<AMessage> *response);
// If this returns true, the sender of this message is synchronously
// awaiting a response, the "replyID" can be used to send the response
// via "postReply" below.
bool senderAwaitsResponse(uint32_t *replyID) const;
void postReply(uint32_t replyID);
// Performs a deep-copy of "this", contained messages are in turn "dup'ed".
// Warning: RefBase items, i.e. "objects" are _not_ copied but only have
// their refcount incremented.
sp<AMessage> dup() const;
AString debugString(int32_t indent = 0) const;
enum Type {
kTypeInt32,
kTypeInt64,
kTypeSize,
kTypeFloat,
kTypeDouble,
kTypePointer,
kTypeString,
kTypeObject,
kTypeMessage,
kTypeRect,
kTypeBuffer,
};
size_t countEntries() const;
const char *getEntryNameAt(size_t index, Type *type) const;
protected:
virtual ~AMessage();
private:
uint32_t mWhat;
ALooper::handler_id mTarget;
struct Rect {
int32_t mLeft, mTop, mRight, mBottom;
};
struct Item {
union {
int32_t int32Value;
int64_t int64Value;
size_t sizeValue;
float floatValue;
double doubleValue;
void *ptrValue;
RefBase *refValue;
AString *stringValue;
Rect rectValue;
} u;
const char *mName;
size_t mNameLength;
Type mType;
void setName(const char *name, size_t len);
};
enum {
kMaxNumItems = 64
};
Item mItems[kMaxNumItems];
size_t mNumItems;
Item *allocateItem(const char *name);
void freeItemValue(Item *item);
const Item *findItem(const char *name, Type type) const;
void setObjectInternal(
const char *name, const sp<RefBase> &obj, Type type);
size_t findItemIndex(const char *name, size_t len) const;
DISALLOW_EVIL_CONSTRUCTORS(AMessage);
};
} // namespace android
#endif // A_MESSAGE_H_
| [
"noury@archos.com"
] | noury@archos.com |
e3f06466fac60497908de5b6b165b825305b2c25 | dc2bc0a04f53af8e46f4273182a996efc8e00f64 | /UnitTest/UnitTestCaseObserver.h | be925222cd7daa4d7ece712b79776fee174fd5d7 | [] | no_license | rikkus/unittestframework | 4417318f46ff94bc8747a0cd2882f016f31483d0 | f07a0a23db0f3daba9923518cf46a50a3a0da787 | refs/heads/master | 2020-07-10T07:55:34.685699 | 2019-08-24T20:46:03 | 2019-08-24T20:46:03 | 204,210,781 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | h | // vim:tabstop=2:shiftwidth=2:expandtab:cinoptions=(s,U1,m1
// Copyright (C) 2004 Rik Hemsley (rikkus) <rik@kde.org>
#ifndef UNIT_TEST_CASE_OBSERVER_H
#define UNIT_TEST_CASE_OBSERVER_H
#include "UnitTestBase.h"
namespace Unit
{
class TestCaseObserver
{
public:
virtual void aboutToRunTest(TestBase *)
{
// Empty.
}
virtual void testFinished(TestBase *)
{
// Empty.
}
};
}
#endif // UNIT_TEST_CASE_OBSERVER_H
| [
"rik@hemsley.cc"
] | rik@hemsley.cc |
34162c97913b6bcb072fad8c3c90262fb7a3a475 | 8253a91b75577c53f97f40ccc5cbe77f728ec09e | /Sat_Sun_20_9.cpp | 0e8ac42b6af3b125e1f9e6f5a4375ddfb913c82b | [] | no_license | aditya-10012002/DSA_Assignments | 2e8d7833fd27ef24fbc23ac1347b9f0d4a49ed39 | 987c09d08d60f4a6b6ff0318e1bf409f04a09661 | refs/heads/master | 2023-01-02T17:30:04.071568 | 2020-10-14T15:32:50 | 2020-10-14T15:32:50 | 301,300,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,927 | cpp | /*
Week days are working days
Weekends are hard working days for 'Winners' */
#include<iostream>
using namespace std;
struct node {
int data;
node *next;
};
typedef node *lptr;
void insert(lptr P, int num) {
lptr T;
T = new(node);
T->data = num;
T->next = nullptr;
while(P->next != nullptr)
P = P->next;
P->next = T;
}
int count_nodes(lptr P) {
int c=0;
while(P != nullptr) {
c++;
P = P->next;
}
return c;
}
void Delete_front(lptr &P) {
lptr active = P;
P = P->next;
active->next = nullptr;
free(active);
}
void Delete(lptr &P, int k) {
if(k == P->data) {
Delete_front(P);
} else {
lptr active, T1 = P;
while(P->next->data != k)
P = P->next;
active = P->next;
P->next = P->next->next;
active->next = nullptr;
free(active);
P = T1;
}
}
void Delete_pos(lptr &P, int pos) {
if(pos == 0) {
Delete_front(P);
} else {
lptr active, T1 = P;
while(pos-- > 1)
P = P->next;
active = P->next;
P->next = P->next->next;
active->next = nullptr;
free(active);
P = T1;
}
}
bool palindrome(lptr P) {
lptr T;
int c = count_nodes(P);
int pos = c/2 + c%2;
for(int i=0;i<pos;i++) {
T = P;
for(int j=0;j<c-1;j++)
T = T->next;
if(T->data != P->data)
return false;
c -= 2;
P = P->next;
}
return true;
}
void rem_duplicates_sorted(lptr &P) {
if(P->next != nullptr) {
if(P->data == P->next->data) {
Delete(P, P->data);
rem_duplicates_sorted(P);
} else {
rem_duplicates_sorted(P->next);
}
}
}
void rem_duplicates_unsorted(lptr &P) {
lptr T1 = P, T2;
int num, n = count_nodes(P);
for(int i=0;i<n-1;i++) {
num = T1->data;
T2 = T1->next;
for(int j=i+1;j<n;j++) {
if(T2->data == num) {
T2 = T2->next;
Delete_pos(P, j);
n--;
} else
T2 = T2->next;
}
T1 = T1->next;
}
}
void rem_last_duplicate(lptr &P) {
lptr T1 = P, T2;
int num, pos, n = count_nodes(P);
for(int i=0;i<n-1;i++) {
num = T1->data;
T2 = T1->next;
pos = -1;
for(int j=i+1;j<n;j++) {
if(T2->data == num) {
T2 = T2->next;
pos = j;
} else
T2 = T2->next;
}
if(pos != -1) {
Delete_pos(P, pos);
n--;
}
T1 = T1->next;
}
}
void even_odd(lptr P) {
lptr T1, T2;
int temp, temp1;
while(P->next != nullptr) {
if(P->data%2 != 0) {
T1 = P->next;
while(T1 != nullptr && T1->data%2 != 0) {
T1 = T1->next;
}
if(T1 == nullptr)
break;
T2 = P;
temp = T2->data;
T2->data = T1->data;
T2 = T2->next;
while(T1 != T2) {
temp1 = T2->data;
T2->data = temp;
temp = temp1;
T2 = T2->next;
}
T1->data = temp;
}
P = P->next;
}
}
void Add_front(lptr &P, int k) {
lptr T;
T = new(node);
T->data = k;
T->next = P;
P = T;
}
void Add_before(lptr &P, int x, int y) {
lptr T;
T = new(node);
T->data = x;
if(y == P->data) {
Add_front(P, x);
} else {
lptr T1 = P;
while(P->next->data != y)
P = P->next;
T->next = P->next;
P->next = T;
P = T1;
}
}
void insertion_sort(lptr &P) {
lptr T1 = P;
int data;
while(T1->next != nullptr) {
if(T1->next->data < T1->data) {
data = T1->next->data;
Delete(P, T1->next->data);
Add_before(P, data, T1->data);
}
T1 = T1->next;
}
}
void rev(lptr &P1, lptr T1) {
if(T1 != nullptr) {
rev(P1, T1->next);
P1->data = T1->data;
P1 = P1->next;
}
}
void reverse(lptr P) {
int i=1, j = count_nodes(P);
lptr T, P1=P;
T = new(node);
j -= i;
while(i-- > 1) {
P = P->next;
P1 = P1->next;
}
T->data = P1->data;
T->next = nullptr;
while(j-- > 0) {
P1 = P1->next;
insert(T, P1->data);
}
rev(P, T);
}
void swap_nodes(lptr P, int k) {
lptr T1, T2;
T1 = P;
for(int i=1;i<k;i++)
T1 = T1->next;
int n = count_nodes(P)-k+1;
T2 = P;
for(int i=1;i<n;i++)
T2 = T2->next;
int temp = T1->data;
T1->data = T2->data;
T2->data = temp;
}
int check_present(lptr P1, lptr P2) {
lptr T1=P1, T2=P2;
int c=0;
while(P1 != nullptr) {
if(P2->data != P1->data)
P1 = P1->next;
else {
T2 = P2;
T1 = P1;
c=0;
while(T2 != nullptr && T1->data == T2->data) {
c++;
T1 = T1->next;
T2 = T2->next;
}
if(c == count_nodes(P2))
return 1;
P1 = P1->next;
}
}
return 0;
}
lptr merge(lptr L1, lptr L2) {
lptr L3;
L3 = new(node);
L3->data = L1->data;
L3->next = nullptr;
insert(L3, L2->data);
L1 = L1->next;
L2 = L2->next;
while(L1 != nullptr && L2 != nullptr) {
insert(L3, L1->data);
insert(L3, L2->data);
L1 = L1->next;
L2 = L2->next;
}
while(L1 != nullptr) {
insert(L3, L1->data);
L1 = L1->next;
}
while(L2 != nullptr) {
insert(L3, L2->data);
L2 = L2->next;
}
return L3;
}
void print(lptr P) {
while(P != nullptr) {
cout << P->data << " ";
P = P->next;
}
cout << endl;
}
lptr make_list(lptr L1) {
L1 = nullptr;
int n;
L1 = new(node);
cin >> n;
L1->data = n;
L1->next = nullptr;
cin >> n;
while(n != -1) {
insert(L1, n);
cin >> n;
}
return L1;
}
int main() {
lptr L1, L2;
int k;
/*L1 = make_list(L1);
cout << palindrome(L1) << endl;
L1 = make_list(L1);
rem_duplicates_sorted(L1);
print(L1);
L1 = make_list(L1);
rem_duplicates_unsorted(L1);
print(L1);
L1 = make_list(L1);
rem_last_duplicate(L1);
print(L1);
L1 = make_list(L1);
even_odd(L1);
print(L1);*/
L1 = make_list(L1);
insertion_sort(L1);
print(L1);
/*L1 = make_list(L1);
reverse(L1);
print(L1);
L1 = make_list(L1);
cin >> k;
swap_nodes(L1, k);
print(L1);
L1 = make_list(L1);
L2 = make_list(L2);
cout << check_present(L1, L2) << endl;
L1 = make_list(L1);
L2 = make_list(L2);
lptr L3 = merge(L1, L2);
print(L3);*/
return 0;
}
| [
"adityakr1001@gmail.com"
] | adityakr1001@gmail.com |
53a31216bdee17bdd411b95f13a4a13ef56b5777 | 1f13a1e8e92cce9d1d63d9eb9dd2c05767ab802e | /BpTree/src/Main.cpp | bd85e8b2d7995e8b45a4301caa668ea76876021e | [] | no_license | tlhallock/indexer | da6b2478ad35cc15caf3608b59c65cc7bf6cfac1 | bf20564f1436ef97b41102e8c6a1ba6d5b62d727 | refs/heads/master | 2021-01-21T23:04:42.259001 | 2014-06-20T22:13:23 | 2014-06-20T22:13:23 | 20,203,974 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | cpp | /*
* Main.cpp
*
* Created on: May 29, 2014
* Author: thallock
*/
int main(int argc, char **argv)
{
}
| [
"this.address.does.not.exist@gmail.com"
] | this.address.does.not.exist@gmail.com |
db7a186b6d65af0a3bed7c3c04fc3599d773a947 | 59aac6a277088f58bf708284b7cabbf61ae2b226 | /CocosCoreCpp/cocos2d/external/protobuf-2.5.0/vsprojects/Debug/errorcode.pb.cc | 66e3a2c674fb0fdd18ca56511daacd64c432cfd2 | [
"MIT",
"LicenseRef-scancode-protobuf"
] | permissive | qingyin/GameCoreCpp | 7afbcc6716b05a6dc65d627a779775a030fa7102 | dcef7287856d50e62fed14148709ed7ecf1e6f8f | refs/heads/master | 2021-01-01T18:43:29.145340 | 2017-08-01T04:13:44 | 2017-08-01T04:13:44 | 98,411,168 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | true | 3,543 | cc | // Generated by the protocol buffer compiler. DO NOT EDIT!
// source: errorcode.proto
#define INTERNAL_SUPPRESS_PROTOBUF_FIELD_DEPRECATION
#include "errorcode.pb.h"
#include <algorithm>
#include <google/protobuf/stubs/common.h>
#include <google/protobuf/stubs/once.h>
#include <google/protobuf/io/coded_stream.h>
#include <google/protobuf/wire_format_lite_inl.h>
#include <google/protobuf/descriptor.h>
#include <google/protobuf/generated_message_reflection.h>
#include <google/protobuf/reflection_ops.h>
#include <google/protobuf/wire_format.h>
// @@protoc_insertion_point(includes)
namespace pb {
namespace {
const ::google::protobuf::EnumDescriptor* ErrorCode_descriptor_ = NULL;
} // namespace
void protobuf_AssignDesc_errorcode_2eproto() {
protobuf_AddDesc_errorcode_2eproto();
const ::google::protobuf::FileDescriptor* file =
::google::protobuf::DescriptorPool::generated_pool()->FindFileByName(
"errorcode.proto");
GOOGLE_CHECK(file != NULL);
ErrorCode_descriptor_ = file->enum_type(0);
}
namespace {
GOOGLE_PROTOBUF_DECLARE_ONCE(protobuf_AssignDescriptors_once_);
inline void protobuf_AssignDescriptorsOnce() {
::google::protobuf::GoogleOnceInit(&protobuf_AssignDescriptors_once_,
&protobuf_AssignDesc_errorcode_2eproto);
}
void protobuf_RegisterTypes(const ::std::string&) {
protobuf_AssignDescriptorsOnce();
}
} // namespace
void protobuf_ShutdownFile_errorcode_2eproto() {
}
void protobuf_AddDesc_errorcode_2eproto() {
static bool already_here = false;
if (already_here) return;
already_here = true;
GOOGLE_PROTOBUF_VERIFY_VERSION;
::google::protobuf::DescriptorPool::InternalAddGeneratedFile(
"\n\017errorcode.proto\022\002pb*\276\003\n\tErrorCode\022\016\n\nE"
"RROR_NONE\020\000\022\030\n\024ERROR_SERVER_CLOSING\020\001\022\034\n"
"\030ERROR_SERVER_MAINTAINING\020\002\022\026\n\022ERROR_SYS"
"TEM_ERROR\020\005\022\025\n\021ERROR_BAD_REQUEST\020\006\022\034\n\030ER"
"ROR_PROTOCOL_UNMATCHED\020\007\022\033\n\027ERROR_SYSTEM"
"_NOT_UNLOCK\020\010\022\030\n\024ERROR_USER_NOT_LOGIN\020\013\022"
"\030\n\024ERROR_USER_FORBIDDEN\020\014\022\037\n\033ERROR_USER_"
"WAITING_RESPONSE\020\r\022\032\n\026ERROR_PLAYER_NOT_E"
"XIST\020\024\022\032\n\026ERROR_PLAYERNAME_EXIST\020\025\022 \n\034ER"
"ROR_PLAYER_ALREADY_CREATED\020\026\022\032\n\026ERROR_NI"
"CKNAME_INVALID\020\027\022\032\n\026ERROR_PLAYER_NOT_LOG"
"IN\020\030\022\030\n\024ERROR_NICKNAME_EXIST\020\031", 470);
::google::protobuf::MessageFactory::InternalRegisterGeneratedFile(
"errorcode.proto", &protobuf_RegisterTypes);
::google::protobuf::internal::OnShutdown(&protobuf_ShutdownFile_errorcode_2eproto);
}
// Force AddDescriptors() to be called at static initialization time.
struct StaticDescriptorInitializer_errorcode_2eproto {
StaticDescriptorInitializer_errorcode_2eproto() {
protobuf_AddDesc_errorcode_2eproto();
}
} static_descriptor_initializer_errorcode_2eproto_;
const ::google::protobuf::EnumDescriptor* ErrorCode_descriptor() {
protobuf_AssignDescriptorsOnce();
return ErrorCode_descriptor_;
}
bool ErrorCode_IsValid(int value) {
switch(value) {
case 0:
case 1:
case 2:
case 5:
case 6:
case 7:
case 8:
case 11:
case 12:
case 13:
case 20:
case 21:
case 22:
case 23:
case 24:
case 25:
return true;
default:
return false;
}
}
// @@protoc_insertion_point(namespace_scope)
} // namespace pb
// @@protoc_insertion_point(global_scope)
| [
"sunchuankui@163.com"
] | sunchuankui@163.com |
017a9bee859eb4a3c67c6f610c9efa60666b56f0 | 9802284a0f2f13a6a7ac93278f8efa09cc0ec26b | /SDK/AnimBP_ImprovisedRifle9mm_classes.h | 53de776168ef43cd8a7fb23e362047fefd5ad85a | [] | no_license | Berxz/Scum-SDK | 05eb0a27eec71ce89988636f04224a81a12131d8 | 74887c5497b435f535bbf8608fcf1010ff5e948c | refs/heads/master | 2021-05-17T15:38:25.915711 | 2020-03-31T06:32:10 | 2020-03-31T06:32:10 | 250,842,227 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,496 | h | #pragma once
// Name: SCUM, Version: 3.75.21350
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// AnimBlueprintGeneratedClass AnimBP_ImprovisedRifle9mm.AnimBP_ImprovisedRifle9mm_C
// 0x0570 (0x08F0 - 0x0380)
class UAnimBP_ImprovisedRifle9mm_C : public UWeaponAnimInstance
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0380(0x0008) (Transient, DuplicateTransient)
struct FAnimNode_Root AnimGraphNode_Root_F8E584CE44927992138151A5451D48BD; // 0x0388(0x0048)
struct FAnimNode_Slot AnimGraphNode_Slot_111DA3514A2593A65EB5FBB7F85F8465; // 0x03D0(0x0070)
struct FAnimNode_Slot AnimGraphNode_Slot_6574A6174B4708D7F7AF6297FCD63386; // 0x0440(0x0070)
struct FAnimNode_Slot AnimGraphNode_Slot_F48D0D834A419F66425DF5966B620DE6; // 0x04B0(0x0070)
struct FAnimNode_Slot AnimGraphNode_Slot_15253F734E1881938402D886A1176FE9; // 0x0520(0x0070)
struct FAnimNode_BlendListByEnum AnimGraphNode_BlendListByEnum_522474C6449B9486694881837ACAB472;// 0x0590(0x00E0)
struct FAnimNode_UseCachedPose AnimGraphNode_UseCachedPose_3F855B624BA43143FDB269A804F58B1D;// 0x0670(0x0050)
struct FAnimNode_UseCachedPose AnimGraphNode_UseCachedPose_168E0A0B41C8DFDE377DDFBA49F5D331;// 0x06C0(0x0050)
struct FAnimNode_UseCachedPose AnimGraphNode_UseCachedPose_FBAE707A4D639D7908F17E9F696B418D;// 0x0710(0x0050)
struct FAnimNode_SaveCachedPose AnimGraphNode_SaveCachedPose_830AE180478A9551BC39ABA61DF06745;// 0x0760(0x00E0)
struct FAnimNode_SequencePlayer AnimGraphNode_SequencePlayer_4D1316204460D2A12D12FFB9741C927C;// 0x0840(0x00B0)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("AnimBlueprintGeneratedClass AnimBP_ImprovisedRifle9mm.AnimBP_ImprovisedRifle9mm_C");
return ptr;
}
void EvaluateGraphExposedInputs_ExecuteUbergraph_AnimBP_ImprovisedRifle9mm_AnimGraphNode_BlendListByEnum_522474C6449B9486694881837ACAB472();
void ExecuteUbergraph_AnimBP_ImprovisedRifle9mm(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"37065724+Berxz@users.noreply.github.com"
] | 37065724+Berxz@users.noreply.github.com |
875d13ca2337a6dab92d1174e715beb21719b38c | 47dc060913bf6e22117c2a18c90d6a5c740e264d | /Searching/searching-methods/linear-search.h | d36f14e9c107c057d006cc3f7f6d1ea4f0210f4d | [
"MIT"
] | permissive | hoanghai1803/DataStructures_Algorithms | 9c9c8d74d618b6dfa4c3103deb488a1707b01c16 | b5e8ccb3deba7566b915b21c6b7e9435cfe55301 | refs/heads/main | 2023-03-23T13:45:10.792737 | 2021-03-21T13:40:27 | 2021-03-21T13:40:27 | 343,241,827 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 500 | h | #include <vector>
/* ========== LINEAR SEARCH IMPLEMENTATION ========== */
// The below implementation of linear search will search and
// return the index of the first occurrence of the given target
// in range [L, R].
// If the given target does not exist in array, return -1.
// Time complexity: O(n).
template<class T>
int linearSearch(std::vector<T> arr, int L, int R, T target) {
for (int i = L; i <= R; i++)
if (arr[i] == target) return i;
return -1;
}
| [
"hoanghai123098@gmail.com"
] | hoanghai123098@gmail.com |
65bb5878e02e2964295ed6512a71bba99c7d6781 | a0423109d0dd871a0e5ae7be64c57afd062c3375 | /Aplicacion Movil/generated/bundles/login-transition/build/Android/Preview/app/src/main/include/Fuse.Input.Pointer.PELHolder.h | 159bc94b9966714cd4e1ae8d1a1ebdedf9978c02 | [
"Apache-2.0"
] | permissive | marferfer/SpinOff-LoL | 1c8a823302dac86133aa579d26ff90698bfc1ad6 | a9dba8ac9dd476ec1ef94712d9a8e76d3b45aca8 | refs/heads/master | 2020-03-29T20:09:20.322768 | 2018-10-09T10:19:33 | 2018-10-09T10:19:33 | 150,298,258 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 799 | h | // This file was generated based on C:/Users/JuanJose/AppData/Local/Fusetools/Packages/Fuse.Nodes/1.9.0/Input/Pointer.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.Object.h>
namespace g{namespace Fuse{namespace Input{struct Pointer__PELHolder;}}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{
namespace Fuse{
namespace Input{
// private sealed class Pointer.PELHolder :676
// {
uType* Pointer__PELHolder_typeof();
void Pointer__PELHolder__ctor__fn(Pointer__PELHolder* __this);
void Pointer__PELHolder__New1_fn(Pointer__PELHolder** __retval);
struct Pointer__PELHolder : uObject
{
uStrong< ::g::Fuse::Visual*> Visual;
int32_t Status;
void ctor_();
static Pointer__PELHolder* New1();
};
// }
}}} // ::g::Fuse::Input
| [
"mariofdezfdez@hotmail.com"
] | mariofdezfdez@hotmail.com |
f84597f2a8587a5fd85b9245e4b22fb15122526c | 77835ddebc40f3f39cc3161bc2ae0b80baf214c2 | /lbfgs/include/cuda_checking.h | 2322b40c0d02a74edba3babf4665cd4d4f271f03 | [
"Apache-2.0"
] | permissive | wei-tan/CUDA-MLlib | 38c2128bd3e4532fe842476c4b88ec8a523c81a5 | 4b035369ea52e6d6bba06b1109b9e9aa77f1512a | refs/heads/master | 2021-01-18T13:15:31.633571 | 2016-05-25T18:15:32 | 2016-05-25T18:15:32 | 56,883,948 | 7 | 4 | null | 2016-05-25T18:15:33 | 2016-04-22T20:40:29 | Cuda | UTF-8 | C++ | false | false | 1,381 | h | /*
* 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.
*/
#ifndef CUDA_CHECKING_H_
#define CUDA_CHECKING_H_
#include <string>
#include <cuda.h>
#include <cublas_v2.h>
extern const char *cublasGetErrorString(cublasStatus_t e);
#define checkCublasErrors(err) __cublasCheckError( err, __FILE__, __LINE__ )
inline void __cublasCheckError( cublasStatus_t err, const char *file, const int line )
{
#ifdef CUBLAS_ERROR_CHECK
if ( CUBLAS_STATUS_SUCCESS != err )
{
fprintf( stderr, "CUBLAS call failed at %s:%i : %s\n",
file, line, cublasGetErrorString( err ) );
exit( -1 );
}
#endif
}
#endif
| [
"bherta@us.ibm.com"
] | bherta@us.ibm.com |
c710a12b8a1022b0988069ae0fde202efbdf2c9b | 1f5a9449af3ed163406f62dc32381502eb9631f3 | /src/CScheduleAlgorithmTestMigration.h | e1a0e5686d7ea790320bc89ad1cffc51c8f45a31 | [
"BSD-2-Clause",
"CC0-1.0"
] | permissive | aw32/sched | 9ec3994576fa0e957bbf7a38e3c23867a0f70f57 | b6ef35c5b517875a5954c70e2dc366fab3721a60 | refs/heads/master | 2021-01-08T13:09:58.337135 | 2020-02-21T02:08:51 | 2020-02-21T02:08:51 | 242,034,418 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 833 | h | // Copyright 2019, Alex Wiens <awiens@mail.upb.de>, Achim Lösch <achim.loesch@upb.de>
// SPDX-License-Identifier: BSD-2-Clause
#define __CSCHEDULEALGORITHMTESTMIGRATION_H__
#ifdef __CSCHEDULEALGORITHMTESTMIGRATION_H__
#include <unordered_map>
#include "CScheduleAlgorithm.h"
namespace sched {
namespace algorithm {
class CEstimation;
class CScheduleAlgorithmTestMigration : public CScheduleAlgorithm {
private:
CEstimation* mpEstimation;
std::unordered_map<int,int> mTaskMap;
CSchedule* mpPreviousSchedule = 0;
public:
CScheduleAlgorithmTestMigration(std::vector<CResource*>& rResources);
~CScheduleAlgorithmTestMigration();
int init();
void fini();
CSchedule* compute(std::vector<CTaskCopy>* pTasks, std::vector<CTaskCopy*>* runningTasks, volatile int* interrupt, int updated);
};
} }
#endif
| [
"awiens@mail.upb.de"
] | awiens@mail.upb.de |
a10eed70d9aa5958854f885527421f92de2b4420 | e89c3fdb417976fc813da96510bba8da42235c71 | /editor/paintItems/shapes/parallelogramitem.cpp | ea87bc701fdb6ab9c5999f3e41ae355e64f8da94 | [] | no_license | sm-jalali-f/jetprint | ec02f796d9445b497b424f01af739438146005eb | fb8c5fc669ae3ab5b6b787207ebcdf2a7567a7f4 | refs/heads/master | 2021-01-09T05:28:54.478245 | 2017-03-18T08:11:51 | 2017-03-18T08:11:51 | 80,773,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,283 | cpp | #include "parallelogramitem.h"
ParallelogramItem::ParallelogramItem(QWidget *parent, QPointF position, int width, int height, float leftBottomVertexAngle)
:DrawItem()
{
this->parent = parent;
this->position = position;
this->width = width;
this->height= height;
this->leftBottomVertexAngle = leftBottomVertexAngle;
this->itemType = SHAPE_PARALLELOGRAM;
}
QPoint ParallelogramItem::getPosition()
{
return QPoint(position.x(),position.y());
}
int ParallelogramItem::getWidth() const
{
return width;
}
int ParallelogramItem::getHeight() const
{
return height;
}
QPixmap ParallelogramItem::toPixmap()
{
if (!scene()) {
qWarning() << "[ControlItem::toPixmap] scene is null.";
return QPixmap();
}
QRectF r = boundingRect();
QPixmap pixmap(r.width(), r.height());
pixmap.fill(Qt::transparent);
QPainter painter(&pixmap);
painter.drawRect(r);
scene()->render(&painter, QRectF(), sceneBoundingRect());
painter.end();
return pixmap;
}
void ParallelogramItem::setPosition(int x, int y)
{
this->position.setX(x);
this->position.setY(y);
}
void ParallelogramItem::hideItem()
{
this->hide();
}
void ParallelogramItem::showItem()
{
this->show();
}
bool ParallelogramItem::isInside(QPoint point)
{
if( point.x()< this->getPosition().x()+this->getWidth()
&& point.x() > this->getPosition().x()
&& point.y() > this->getPosition().y()
&& point.y() < this->getPosition().y()+this->getHeight()){
return true;
}
return false;
}
void ParallelogramItem::changeFontSize(int fontSize)
{
}
void ParallelogramItem::itemDropEvent(QDropEvent *event)
{
if(!isDragingItem())
return;
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
itemState = NOTHING_STATE;
// isDraging = false;
// isPressed = false;
QByteArray itemData = event->mimeData()->data("application/x-dnditemdata");
QDataStream dataStream(&itemData, QIODevice::ReadOnly);
QPixmap pixmap;
QPoint offset;
dataStream >> pixmap >> offset;
this->setPosition(event->pos().x()-insideX,event->pos().y()-insideY);
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void ParallelogramItem::itemDragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void ParallelogramItem::itemDragMoveEvent(QDragMoveEvent *event)
{
if (event->mimeData()->hasFormat("application/x-dnditemdata")) {
if (event->source() == parent) {
event->setDropAction(Qt::MoveAction);
event->accept();
} else {
event->acceptProposedAction();
}
} else {
event->ignore();
}
}
void ParallelogramItem::keyboardPressed(QKeyEvent *event)
{
}
MouseMoveResult ParallelogramItem::onMouseMove(QMouseEvent *event)
{
if(!isPressedItem()){
return whereIsPoint(QPoint(event->x(),event->y()));
}
int lastWidth;
int lastHeight;
switch (itemState) {
case BOTTOM_RESIZING:
lastHeight = height;
height = height + ((-middleBottom.y() +event->pos().y()))/2;
this->update();
return TOP_RESIZE_PRESSED;
case TOP_RESIZING:
lastHeight = height;
height = height + ((middleTop.y() -event->pos().y()))/2;
setPosition(getPosition().x(),getPosition().y()+lastHeight-height);
this->update();
return TOP_RESIZE_PRESSED;
case LEFT_RESIZING:
lastWidth = width;
width = width + ((middleLeft.x() -event->pos().x()))/2;
setPosition(getPosition().x()+lastWidth-width,getPosition().y());
this->update();
return LEFT_RESIZE_PRESSED;
case RIGHT_RESIZING:
lastWidth = width;
width = width + ((-middleRight.x() +event->pos().x()))/2;
this->update();
return RIGHT_RESIZE_PRESSED;
case LEFT_TOP_RESIZING:
lastHeight = height;
height = height + ((middleTop.y() -event->pos().y()))/2;
lastWidth = width;
width = width + ((middleLeft.x() -event->pos().x()))/2;
setPosition(getPosition().x()+lastWidth-width,getPosition().y()+lastHeight-height);
this->update();
return LEFT_TOP_RESIZE_PRESSED;
case LEFT_BOTTOM_RESIZING:
lastHeight = height;
height = height + ((-middleBottom.y() +event->pos().y()))/2;
lastWidth = width;
width = width + ((middleLeft.x() -event->pos().x()))/2;
setPosition(getPosition().x()+lastWidth-width,getPosition().y());
this->update();
return LEFT_BOTTOM_RESIZE_PRESSED;
case RIGHT_TOP_RESIZING:
lastWidth = width;
width = width + ((-middleRight.x() +event->pos().x()))/2;
lastHeight = height;
height = height + ((middleTop.y() -event->pos().y()))/2;
setPosition(getPosition().x(),getPosition().y()+lastHeight-height);
this->update();
return RIGHT_TOP_RESIZE_PRESSED;
case RIGHT_BOTTOM_RESIZING:
lastHeight = height;
height = height + ((-middleBottom.y() +event->pos().y()))/2;
lastWidth = width;
width = width + ((-middleRight.x() +event->pos().x()))/2;
this->update();
return RIGHT_BOTTOM_RESIZE_PRESSED;
case PREPARE_FOR_DRAGING :
itemState = DRAGING;
qDebug()<<"CircleItem: onMouseMove() prepare for draging";
QByteArray itemData;
QDataStream dataStream(&itemData, QIODevice::WriteOnly);
QPoint circleCenter(this->getPosition().x(),this->getPosition().y());
dataStream << this->toPixmap() << QPoint(event->pos() - circleCenter);
QMimeData *mimeData = new QMimeData;
mimeData->setData("application/x-dnditemdata", itemData);
QDrag *drag = new QDrag(parent);
drag->setMimeData(mimeData);
drag->setPixmap(this->toPixmap());
drag->setHotSpot(event->pos() - circleCenter);
drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction);
return IN_DRAGING_MODE;
// default:
// break;
}
// if(!isPressedItem()){
// return whereIsPoint(QPoint(event->x(),event->y()));
// }
// isDraging =true;
// QByteArray itemData;
// QDataStream dataStream(&itemData, QIODevice::WriteOnly);
// QPoint circleCenter(this->getPosition().x(),this->getPosition().y());
// dataStream << this->toPixmap() << QPoint(event->pos() - circleCenter);
// QMimeData *mimeData = new QMimeData;
// mimeData->setData("application/x-dnditemdata", itemData);
// QDrag *drag = new QDrag(parent);
// drag->setMimeData(mimeData);
// drag->setPixmap(this->toPixmap());
// drag->setHotSpot(event->pos() - circleCenter);
// drag->exec(Qt::CopyAction | Qt::MoveAction, Qt::CopyAction);
// return IN_DRAGING_MODE;
}
void ParallelogramItem::onMouseReleased(QMouseEvent *event)
{
mouseReleaseUpdateState(QPoint(event->pos().x(),event->pos().y()));
this->update();
// if(!isDraging && isPressed){
// this->isSelect =true;
// this->isPressed= false;
// }
}
bool ParallelogramItem::onMousePressed(QMouseEvent *event)
{
mousePressUpdateState(QPoint(event->pos().x(),event->pos().y()));
this->update();
if(this->itemState == PREPARE_FOR_DRAGING){
insideX = event->pos().x()-this->getPosition().x();
insideY = event->pos().y()-this->getPosition().y();
return true;
}
return false;
// if(isInside(QPoint(event->pos().x(),event->pos().y()))){
// insideX = event->pos().x()-this->getPosition().x();
// insideY = event->pos().y()-this->getPosition().y();
//// isPressed = true;
// return true;
// }
// this->isSelect =false;
// return false;
}
QRectF ParallelogramItem::boundingRect() const
{
return QRect(position.x(),position.y(),width,height);
}
void ParallelogramItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
Q_UNUSED(option);
Q_UNUSED(widget);
if(isRemoved())
return;
scene()->setBackgroundBrush(shapeBgBrush);
painter->setOpacity(Qt::transparent);
QPoint v1,v2,v3,v4;
if(leftBottomVertexAngle <=90 ){
v1 = QPoint(position.x()+height/(qTan(qDegreesToRadians(leftBottomVertexAngle))),position.y());
v2 = QPoint(position.x()+width,position.y());
v3 = QPoint(position.x()+width -(height/qTan(qDegreesToRadians(leftBottomVertexAngle))),position.y()+height);
v4 = QPoint(position.x(),position.y()+height);
}else if(leftBottomVertexAngle > 90 && leftBottomVertexAngle <180){
v1 = QPoint(position.x(),position.y());
v2 = QPoint( position.x() + width-height/qTan(qDegreesToRadians(180-leftBottomVertexAngle)) , position.y());
v3 = QPoint(position.x()+width , position.y()+height);
v4 = QPoint(position.x()+(height/(qTan(qDegreesToRadians(180-leftBottomVertexAngle)))) , position.y()+height);
}else if(leftBottomVertexAngle > 180 && leftBottomVertexAngle <270){
leftBottomVertexAngle =180-(360- leftBottomVertexAngle);
v1 = QPoint(position.x()+height/(qTan(qDegreesToRadians(leftBottomVertexAngle))),position.y());
v2 = QPoint(position.x()+width,position.y());
v3 = QPoint(position.x()+width -(height/qTan(qDegreesToRadians(leftBottomVertexAngle))),position.y()+height);
v4 = QPoint(position.x(),position.y()+height);
}else if(leftBottomVertexAngle > 270 && leftBottomVertexAngle <360){
leftBottomVertexAngle =180-(360- leftBottomVertexAngle);
v1 = QPoint(position.x(),position.y());
v2 = QPoint(position.x()+width-(height/(qTan(qDegreesToRadians(180-leftBottomVertexAngle)))) , position.y());
v3 = QPoint(position.x()+width , position.y()+height);
v4 = QPoint(position.x()+(height/(qTan(qDegreesToRadians(180-leftBottomVertexAngle)))) , position.y()+height);
}
if(!isDragingItem())
painter->setPen(shapePen);
else
painter->setPen(dragPen);
painter->drawLine(QPointF(v1.x(),v1.y()),QPointF(v2.x(),v2.y()));
painter->drawLine(QPointF(v2.x(),v2.y()),QPointF(v3.x(),v3.y()));
painter->drawLine(QPointF(v3.x(),v3.y()),QPointF(v4.x(),v4.y()));
painter->drawLine(QPointF(v4.x(),v4.y()),QPointF(v1.x(),v1.y()));
updateCornerPoint();
if(isDrawBorder()){
this->paintSelectBorder(painter,leftTop,rightTop,leftBottom,rightBottom);
}
}
| [
"sm.jalali.f@gmail.com"
] | sm.jalali.f@gmail.com |
3090fdefc435d649a23a0ac3e0268b75df1f8b64 | 0b17877ae6b10f45cf10c96f12828aed455ae1f9 | /src/interpreter/bytecode-generator.cc | fc90ae051d3b0116c36cb9df373a359d17f89272 | [
"BSD-3-Clause",
"bzip2-1.0.6",
"SunPro"
] | permissive | hmbeconfidenct/v8 | 0e49c88ec8b2649cec63dffd5b9ad739f1fbaa67 | 27fd52abad7d6959f71c8510c4af9f7b4a6d6431 | refs/heads/master | 2020-03-26T14:03:02.331555 | 2017-08-23T08:00:32 | 2017-08-23T09:55:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 167,459 | cc | // Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/interpreter/bytecode-generator.h"
#include "src/ast/ast-source-ranges.h"
#include "src/ast/compile-time-value.h"
#include "src/ast/scopes.h"
#include "src/builtins/builtins-constructor.h"
#include "src/code-stubs.h"
#include "src/compilation-info.h"
#include "src/compiler.h"
#include "src/interpreter/bytecode-flags.h"
#include "src/interpreter/bytecode-jump-table.h"
#include "src/interpreter/bytecode-label.h"
#include "src/interpreter/bytecode-register-allocator.h"
#include "src/interpreter/control-flow-builders.h"
#include "src/objects-inl.h"
#include "src/parsing/parse-info.h"
#include "src/parsing/token.h"
namespace v8 {
namespace internal {
namespace interpreter {
// Scoped class tracking context objects created by the visitor. Represents
// mutations of the context chain within the function body, allowing pushing and
// popping of the current {context_register} during visitation.
class BytecodeGenerator::ContextScope BASE_EMBEDDED {
public:
ContextScope(BytecodeGenerator* generator, Scope* scope)
: generator_(generator),
scope_(scope),
outer_(generator_->execution_context()),
register_(Register::current_context()),
depth_(0) {
DCHECK(scope->NeedsContext() || outer_ == nullptr);
if (outer_) {
depth_ = outer_->depth_ + 1;
// Push the outer context into a new context register.
Register outer_context_reg =
generator_->register_allocator()->NewRegister();
outer_->set_register(outer_context_reg);
generator_->builder()->PushContext(outer_context_reg);
}
generator_->set_execution_context(this);
}
~ContextScope() {
if (outer_) {
DCHECK_EQ(register_.index(), Register::current_context().index());
generator_->builder()->PopContext(outer_->reg());
outer_->set_register(register_);
}
generator_->set_execution_context(outer_);
}
// Returns the depth of the given |scope| for the current execution context.
int ContextChainDepth(Scope* scope) {
return scope_->ContextChainLength(scope);
}
// Returns the execution context at |depth| in the current context chain if it
// is a function local execution context, otherwise returns nullptr.
ContextScope* Previous(int depth) {
if (depth > depth_) {
return nullptr;
}
ContextScope* previous = this;
for (int i = depth; i > 0; --i) {
previous = previous->outer_;
}
return previous;
}
Register reg() const { return register_; }
private:
const BytecodeArrayBuilder* builder() const { return generator_->builder(); }
void set_register(Register reg) { register_ = reg; }
BytecodeGenerator* generator_;
Scope* scope_;
ContextScope* outer_;
Register register_;
int depth_;
};
// Scoped class for tracking control statements entered by the
// visitor. The pattern derives AstGraphBuilder::ControlScope.
class BytecodeGenerator::ControlScope BASE_EMBEDDED {
public:
explicit ControlScope(BytecodeGenerator* generator)
: generator_(generator), outer_(generator->execution_control()),
context_(generator->execution_context()) {
generator_->set_execution_control(this);
}
virtual ~ControlScope() { generator_->set_execution_control(outer()); }
void Break(Statement* stmt) {
PerformCommand(CMD_BREAK, stmt, kNoSourcePosition);
}
void Continue(Statement* stmt) {
PerformCommand(CMD_CONTINUE, stmt, kNoSourcePosition);
}
void ReturnAccumulator(int source_position = kNoSourcePosition) {
PerformCommand(CMD_RETURN, nullptr, source_position);
}
void AsyncReturnAccumulator(int source_position = kNoSourcePosition) {
PerformCommand(CMD_ASYNC_RETURN, nullptr, source_position);
}
class DeferredCommands;
protected:
enum Command {
CMD_BREAK,
CMD_CONTINUE,
CMD_RETURN,
CMD_ASYNC_RETURN,
CMD_RETHROW
};
static constexpr bool CommandUsesAccumulator(Command command) {
return command != CMD_BREAK && command != CMD_CONTINUE;
}
void PerformCommand(Command command, Statement* statement,
int source_position);
virtual bool Execute(Command command, Statement* statement,
int source_position) = 0;
// Helper to pop the context chain to a depth expected by this control scope.
// Note that it is the responsibility of each individual {Execute} method to
// trigger this when commands are handled and control-flow continues locally.
void PopContextToExpectedDepth();
BytecodeGenerator* generator() const { return generator_; }
ControlScope* outer() const { return outer_; }
ContextScope* context() const { return context_; }
private:
BytecodeGenerator* generator_;
ControlScope* outer_;
ContextScope* context_;
DISALLOW_COPY_AND_ASSIGN(ControlScope);
};
// Helper class for a try-finally control scope. It can record intercepted
// control-flow commands that cause entry into a finally-block, and re-apply
// them after again leaving that block. Special tokens are used to identify
// paths going through the finally-block to dispatch after leaving the block.
class BytecodeGenerator::ControlScope::DeferredCommands final {
public:
DeferredCommands(BytecodeGenerator* generator, Register token_register,
Register result_register)
: generator_(generator),
deferred_(generator->zone()),
token_register_(token_register),
result_register_(result_register),
return_token_(-1),
async_return_token_(-1),
rethrow_token_(-1) {}
// One recorded control-flow command.
struct Entry {
Command command; // The command type being applied on this path.
Statement* statement; // The target statement for the command or {nullptr}.
int token; // A token identifying this particular path.
};
// Records a control-flow command while entering the finally-block. This also
// generates a new dispatch token that identifies one particular path. This
// expects the result to be in the accumulator.
void RecordCommand(Command command, Statement* statement) {
int token = GetTokenForCommand(command, statement);
DCHECK_LT(token, deferred_.size());
DCHECK_EQ(deferred_[token].command, command);
DCHECK_EQ(deferred_[token].statement, statement);
DCHECK_EQ(deferred_[token].token, token);
if (CommandUsesAccumulator(command)) {
builder()->StoreAccumulatorInRegister(result_register_);
}
builder()->LoadLiteral(Smi::FromInt(token));
builder()->StoreAccumulatorInRegister(token_register_);
}
// Records the dispatch token to be used to identify the re-throw path when
// the finally-block has been entered through the exception handler. This
// expects the exception to be in the accumulator.
void RecordHandlerReThrowPath() {
// The accumulator contains the exception object.
RecordCommand(CMD_RETHROW, nullptr);
}
// Records the dispatch token to be used to identify the implicit fall-through
// path at the end of a try-block into the corresponding finally-block.
void RecordFallThroughPath() {
builder()->LoadLiteral(Smi::FromInt(-1));
builder()->StoreAccumulatorInRegister(token_register_);
}
// Applies all recorded control-flow commands after the finally-block again.
// This generates a dynamic dispatch on the token from the entry point.
void ApplyDeferredCommands() {
if (deferred_.size() == 0) return;
BytecodeLabel fall_through;
if (deferred_.size() == 1) {
// For a single entry, just jump to the fallthrough if we don't match the
// entry token.
const Entry& entry = deferred_[0];
builder()
->LoadLiteral(Smi::FromInt(entry.token))
.CompareOperation(Token::EQ_STRICT, token_register_)
.JumpIfFalse(ToBooleanMode::kAlreadyBoolean, &fall_through);
if (CommandUsesAccumulator(entry.command)) {
builder()->LoadAccumulatorWithRegister(result_register_);
}
execution_control()->PerformCommand(entry.command, entry.statement,
kNoSourcePosition);
} else {
// For multiple entries, build a jump table and switch on the token,
// jumping to the fallthrough if none of them match.
BytecodeJumpTable* jump_table =
builder()->AllocateJumpTable(static_cast<int>(deferred_.size()), 0);
builder()
->LoadAccumulatorWithRegister(token_register_)
.SwitchOnSmiNoFeedback(jump_table)
.Jump(&fall_through);
for (const Entry& entry : deferred_) {
builder()->Bind(jump_table, entry.token);
if (CommandUsesAccumulator(entry.command)) {
builder()->LoadAccumulatorWithRegister(result_register_);
}
execution_control()->PerformCommand(entry.command, entry.statement,
kNoSourcePosition);
}
}
builder()->Bind(&fall_through);
}
BytecodeArrayBuilder* builder() { return generator_->builder(); }
ControlScope* execution_control() { return generator_->execution_control(); }
private:
int GetTokenForCommand(Command command, Statement* statement) {
switch (command) {
case CMD_RETURN:
return GetReturnToken();
case CMD_ASYNC_RETURN:
return GetAsyncReturnToken();
case CMD_RETHROW:
return GetRethrowToken();
default:
// TODO(leszeks): We could also search for entries with the same
// command and statement.
return GetNewTokenForCommand(command, statement);
}
}
int GetReturnToken() {
if (return_token_ == -1) {
return_token_ = GetNewTokenForCommand(CMD_RETURN, nullptr);
}
return return_token_;
}
int GetAsyncReturnToken() {
if (async_return_token_ == -1) {
async_return_token_ = GetNewTokenForCommand(CMD_ASYNC_RETURN, nullptr);
}
return async_return_token_;
}
int GetRethrowToken() {
if (rethrow_token_ == -1) {
rethrow_token_ = GetNewTokenForCommand(CMD_RETHROW, nullptr);
}
return rethrow_token_;
}
int GetNewTokenForCommand(Command command, Statement* statement) {
int token = static_cast<int>(deferred_.size());
deferred_.push_back({command, statement, token});
return token;
}
BytecodeGenerator* generator_;
ZoneVector<Entry> deferred_;
Register token_register_;
Register result_register_;
// Tokens for commands that don't need a statement.
int return_token_;
int async_return_token_;
int rethrow_token_;
};
// Scoped class for dealing with control flow reaching the function level.
class BytecodeGenerator::ControlScopeForTopLevel final
: public BytecodeGenerator::ControlScope {
public:
explicit ControlScopeForTopLevel(BytecodeGenerator* generator)
: ControlScope(generator) {}
protected:
bool Execute(Command command, Statement* statement,
int source_position) override {
switch (command) {
case CMD_BREAK: // We should never see break/continue in top-level.
case CMD_CONTINUE:
UNREACHABLE();
case CMD_RETURN:
// No need to pop contexts, execution leaves the method body.
generator()->BuildReturn(source_position);
return true;
case CMD_ASYNC_RETURN:
// No need to pop contexts, execution leaves the method body.
generator()->BuildAsyncReturn(source_position);
return true;
case CMD_RETHROW:
// No need to pop contexts, execution leaves the method body.
generator()->BuildReThrow();
return true;
}
return false;
}
};
// Scoped class for enabling break inside blocks and switch blocks.
class BytecodeGenerator::ControlScopeForBreakable final
: public BytecodeGenerator::ControlScope {
public:
ControlScopeForBreakable(BytecodeGenerator* generator,
BreakableStatement* statement,
BreakableControlFlowBuilder* control_builder)
: ControlScope(generator),
statement_(statement),
control_builder_(control_builder) {}
protected:
bool Execute(Command command, Statement* statement,
int source_position) override {
control_builder_->set_needs_continuation_counter();
if (statement != statement_) return false;
switch (command) {
case CMD_BREAK:
PopContextToExpectedDepth();
control_builder_->Break();
return true;
case CMD_CONTINUE:
case CMD_RETURN:
case CMD_ASYNC_RETURN:
case CMD_RETHROW:
break;
}
return false;
}
private:
Statement* statement_;
BreakableControlFlowBuilder* control_builder_;
};
// Scoped class for enabling 'break' and 'continue' in iteration
// constructs, e.g. do...while, while..., for...
class BytecodeGenerator::ControlScopeForIteration final
: public BytecodeGenerator::ControlScope {
public:
ControlScopeForIteration(BytecodeGenerator* generator,
IterationStatement* statement,
LoopBuilder* loop_builder)
: ControlScope(generator),
statement_(statement),
loop_builder_(loop_builder) {
generator->loop_depth_++;
}
~ControlScopeForIteration() { generator()->loop_depth_--; }
protected:
bool Execute(Command command, Statement* statement,
int source_position) override {
if (statement != statement_) return false;
switch (command) {
case CMD_BREAK:
PopContextToExpectedDepth();
loop_builder_->Break();
return true;
case CMD_CONTINUE:
PopContextToExpectedDepth();
loop_builder_->Continue();
return true;
case CMD_RETURN:
case CMD_ASYNC_RETURN:
case CMD_RETHROW:
break;
}
return false;
}
private:
Statement* statement_;
LoopBuilder* loop_builder_;
};
// Scoped class for enabling 'throw' in try-catch constructs.
class BytecodeGenerator::ControlScopeForTryCatch final
: public BytecodeGenerator::ControlScope {
public:
ControlScopeForTryCatch(BytecodeGenerator* generator,
TryCatchBuilder* try_catch_builder)
: ControlScope(generator) {}
protected:
bool Execute(Command command, Statement* statement,
int source_position) override {
switch (command) {
case CMD_BREAK:
case CMD_CONTINUE:
case CMD_RETURN:
case CMD_ASYNC_RETURN:
break;
case CMD_RETHROW:
// No need to pop contexts, execution re-enters the method body via the
// stack unwinding mechanism which itself restores contexts correctly.
generator()->BuildReThrow();
return true;
}
return false;
}
};
// Scoped class for enabling control flow through try-finally constructs.
class BytecodeGenerator::ControlScopeForTryFinally final
: public BytecodeGenerator::ControlScope {
public:
ControlScopeForTryFinally(BytecodeGenerator* generator,
TryFinallyBuilder* try_finally_builder,
DeferredCommands* commands)
: ControlScope(generator),
try_finally_builder_(try_finally_builder),
commands_(commands) {}
protected:
bool Execute(Command command, Statement* statement,
int source_position) override {
switch (command) {
case CMD_BREAK:
case CMD_CONTINUE:
case CMD_RETURN:
case CMD_ASYNC_RETURN:
case CMD_RETHROW:
PopContextToExpectedDepth();
// We don't record source_position here since we don't generate return
// bytecode right here and will generate it later as part of finally
// block. Each return bytecode generated in finally block will get own
// return source position from corresponded return statement or we'll
// use end of function if no return statement is presented.
commands_->RecordCommand(command, statement);
try_finally_builder_->LeaveTry();
return true;
}
return false;
}
private:
TryFinallyBuilder* try_finally_builder_;
DeferredCommands* commands_;
};
void BytecodeGenerator::ControlScope::PerformCommand(Command command,
Statement* statement,
int source_position) {
ControlScope* current = this;
do {
if (current->Execute(command, statement, source_position)) {
return;
}
current = current->outer();
} while (current != nullptr);
UNREACHABLE();
}
void BytecodeGenerator::ControlScope::PopContextToExpectedDepth() {
// Pop context to the expected depth. Note that this can in fact pop multiple
// contexts at once because the {PopContext} bytecode takes a saved register.
if (generator()->execution_context() != context()) {
generator()->builder()->PopContext(context()->reg());
}
}
class BytecodeGenerator::RegisterAllocationScope final {
public:
explicit RegisterAllocationScope(BytecodeGenerator* generator)
: generator_(generator),
outer_next_register_index_(
generator->register_allocator()->next_register_index()) {}
~RegisterAllocationScope() {
generator_->register_allocator()->ReleaseRegisters(
outer_next_register_index_);
}
private:
BytecodeGenerator* generator_;
int outer_next_register_index_;
DISALLOW_COPY_AND_ASSIGN(RegisterAllocationScope);
};
// Scoped base class for determining how the result of an expression will be
// used.
class BytecodeGenerator::ExpressionResultScope {
public:
ExpressionResultScope(BytecodeGenerator* generator, Expression::Context kind)
: generator_(generator),
outer_(generator->execution_result()),
allocator_(generator),
kind_(kind),
type_hint_(TypeHint::kAny) {
generator_->set_execution_result(this);
}
virtual ~ExpressionResultScope() {
generator_->set_execution_result(outer_);
}
bool IsEffect() const { return kind_ == Expression::kEffect; }
bool IsValue() const { return kind_ == Expression::kValue; }
bool IsTest() const { return kind_ == Expression::kTest; }
TestResultScope* AsTest() {
DCHECK(IsTest());
return reinterpret_cast<TestResultScope*>(this);
}
// Specify expression always returns a Boolean result value.
void SetResultIsBoolean() {
DCHECK(type_hint_ == TypeHint::kAny);
type_hint_ = TypeHint::kBoolean;
}
TypeHint type_hint() const { return type_hint_; }
private:
BytecodeGenerator* generator_;
ExpressionResultScope* outer_;
RegisterAllocationScope allocator_;
Expression::Context kind_;
TypeHint type_hint_;
DISALLOW_COPY_AND_ASSIGN(ExpressionResultScope);
};
// Scoped class used when the result of the current expression is not
// expected to produce a result.
class BytecodeGenerator::EffectResultScope final
: public ExpressionResultScope {
public:
explicit EffectResultScope(BytecodeGenerator* generator)
: ExpressionResultScope(generator, Expression::kEffect) {}
};
// Scoped class used when the result of the current expression to be
// evaluated should go into the interpreter's accumulator.
class BytecodeGenerator::ValueResultScope final : public ExpressionResultScope {
public:
explicit ValueResultScope(BytecodeGenerator* generator)
: ExpressionResultScope(generator, Expression::kValue) {}
};
// Scoped class used when the result of the current expression to be
// evaluated is only tested with jumps to two branches.
class BytecodeGenerator::TestResultScope final : public ExpressionResultScope {
public:
TestResultScope(BytecodeGenerator* generator, BytecodeLabels* then_labels,
BytecodeLabels* else_labels, TestFallthrough fallthrough)
: ExpressionResultScope(generator, Expression::kTest),
result_consumed_by_test_(false),
fallthrough_(fallthrough),
then_labels_(then_labels),
else_labels_(else_labels) {}
// Used when code special cases for TestResultScope and consumes any
// possible value by testing and jumping to a then/else label.
void SetResultConsumedByTest() {
result_consumed_by_test_ = true;
}
bool result_consumed_by_test() { return result_consumed_by_test_; }
// Inverts the control flow of the operation, swapping the then and else
// labels and the fallthrough.
void InvertControlFlow() {
std::swap(then_labels_, else_labels_);
fallthrough_ = inverted_fallthrough();
}
BytecodeLabel* NewThenLabel() { return then_labels_->New(); }
BytecodeLabel* NewElseLabel() { return else_labels_->New(); }
BytecodeLabels* then_labels() const { return then_labels_; }
BytecodeLabels* else_labels() const { return else_labels_; }
void set_then_labels(BytecodeLabels* then_labels) {
then_labels_ = then_labels;
}
void set_else_labels(BytecodeLabels* else_labels) {
else_labels_ = else_labels;
}
TestFallthrough fallthrough() const { return fallthrough_; }
TestFallthrough inverted_fallthrough() const {
switch (fallthrough_) {
case TestFallthrough::kThen:
return TestFallthrough::kElse;
case TestFallthrough::kElse:
return TestFallthrough::kThen;
default:
return TestFallthrough::kNone;
}
}
void set_fallthrough(TestFallthrough fallthrough) {
fallthrough_ = fallthrough;
}
private:
bool result_consumed_by_test_;
TestFallthrough fallthrough_;
BytecodeLabels* then_labels_;
BytecodeLabels* else_labels_;
DISALLOW_COPY_AND_ASSIGN(TestResultScope);
};
// Used to build a list of global declaration initial value pairs.
class BytecodeGenerator::GlobalDeclarationsBuilder final : public ZoneObject {
public:
explicit GlobalDeclarationsBuilder(Zone* zone)
: declarations_(0, zone),
constant_pool_entry_(0),
has_constant_pool_entry_(false) {}
void AddFunctionDeclaration(const AstRawString* name, FeedbackSlot slot,
FeedbackSlot literal_slot,
FunctionLiteral* func) {
DCHECK(!slot.IsInvalid());
declarations_.push_back(Declaration(name, slot, literal_slot, func));
}
void AddUndefinedDeclaration(const AstRawString* name, FeedbackSlot slot) {
DCHECK(!slot.IsInvalid());
declarations_.push_back(Declaration(name, slot, nullptr));
}
Handle<FixedArray> AllocateDeclarations(CompilationInfo* info) {
DCHECK(has_constant_pool_entry_);
int array_index = 0;
Handle<FixedArray> data = info->isolate()->factory()->NewFixedArray(
static_cast<int>(declarations_.size() * 4), TENURED);
for (const Declaration& declaration : declarations_) {
FunctionLiteral* func = declaration.func;
Handle<Object> initial_value;
if (func == nullptr) {
initial_value = info->isolate()->factory()->undefined_value();
} else {
initial_value = Compiler::GetSharedFunctionInfo(func, info->script(),
info->isolate());
}
// Return a null handle if any initial values can't be created. Caller
// will set stack overflow.
if (initial_value.is_null()) return Handle<FixedArray>();
data->set(array_index++, *declaration.name->string());
data->set(array_index++, Smi::FromInt(declaration.slot.ToInt()));
Object* undefined_or_literal_slot;
if (declaration.literal_slot.IsInvalid()) {
undefined_or_literal_slot = info->isolate()->heap()->undefined_value();
} else {
undefined_or_literal_slot =
Smi::FromInt(declaration.literal_slot.ToInt());
}
data->set(array_index++, undefined_or_literal_slot);
data->set(array_index++, *initial_value);
}
return data;
}
size_t constant_pool_entry() {
DCHECK(has_constant_pool_entry_);
return constant_pool_entry_;
}
void set_constant_pool_entry(size_t constant_pool_entry) {
DCHECK(!empty());
DCHECK(!has_constant_pool_entry_);
constant_pool_entry_ = constant_pool_entry;
has_constant_pool_entry_ = true;
}
bool empty() { return declarations_.empty(); }
private:
struct Declaration {
Declaration() : slot(FeedbackSlot::Invalid()), func(nullptr) {}
Declaration(const AstRawString* name, FeedbackSlot slot,
FeedbackSlot literal_slot, FunctionLiteral* func)
: name(name), slot(slot), literal_slot(literal_slot), func(func) {}
Declaration(const AstRawString* name, FeedbackSlot slot,
FunctionLiteral* func)
: name(name),
slot(slot),
literal_slot(FeedbackSlot::Invalid()),
func(func) {}
const AstRawString* name;
FeedbackSlot slot;
FeedbackSlot literal_slot;
FunctionLiteral* func;
};
ZoneVector<Declaration> declarations_;
size_t constant_pool_entry_;
bool has_constant_pool_entry_;
};
class BytecodeGenerator::CurrentScope final {
public:
CurrentScope(BytecodeGenerator* generator, Scope* scope)
: generator_(generator), outer_scope_(generator->current_scope()) {
if (scope != nullptr) {
DCHECK_EQ(outer_scope_, scope->outer_scope());
generator_->set_current_scope(scope);
}
}
~CurrentScope() {
if (outer_scope_ != generator_->current_scope()) {
generator_->set_current_scope(outer_scope_);
}
}
private:
BytecodeGenerator* generator_;
Scope* outer_scope_;
};
BytecodeGenerator::BytecodeGenerator(CompilationInfo* info)
: zone_(info->zone()),
builder_(new (zone()) BytecodeArrayBuilder(
info->isolate(), info->zone(), info->num_parameters_including_this(),
info->scope()->num_stack_slots(), info->literal(),
info->SourcePositionRecordingMode())),
info_(info),
ast_string_constants_(info->isolate()->ast_string_constants()),
closure_scope_(info->scope()),
current_scope_(info->scope()),
globals_builder_(new (zone()) GlobalDeclarationsBuilder(info->zone())),
block_coverage_builder_(nullptr),
global_declarations_(0, info->zone()),
function_literals_(0, info->zone()),
native_function_literals_(0, info->zone()),
object_literals_(0, info->zone()),
array_literals_(0, info->zone()),
execution_control_(nullptr),
execution_context_(nullptr),
execution_result_(nullptr),
incoming_new_target_or_generator_(),
generator_jump_table_(nullptr),
generator_state_(),
loop_depth_(0),
catch_prediction_(HandlerTable::UNCAUGHT) {
DCHECK_EQ(closure_scope(), closure_scope()->GetClosureScope());
if (info->has_source_range_map()) {
DCHECK(FLAG_block_coverage);
block_coverage_builder_ = new (zone())
BlockCoverageBuilder(zone(), builder(), info->source_range_map());
}
}
Handle<BytecodeArray> BytecodeGenerator::FinalizeBytecode(Isolate* isolate) {
DCHECK(ThreadId::Current().Equals(isolate->thread_id()));
AllocateDeferredConstants(isolate);
if (block_coverage_builder_) {
info()->set_coverage_info(
isolate->factory()->NewCoverageInfo(block_coverage_builder_->slots()));
if (FLAG_trace_block_coverage) {
info()->coverage_info()->Print(info()->shared_info()->name());
}
}
if (HasStackOverflow()) return Handle<BytecodeArray>();
Handle<BytecodeArray> bytecode_array = builder()->ToBytecodeArray(isolate);
if (incoming_new_target_or_generator_.is_valid()) {
bytecode_array->set_incoming_new_target_or_generator_register(
incoming_new_target_or_generator_);
}
return bytecode_array;
}
void BytecodeGenerator::AllocateDeferredConstants(Isolate* isolate) {
// Build global declaration pair arrays.
for (GlobalDeclarationsBuilder* globals_builder : global_declarations_) {
Handle<FixedArray> declarations =
globals_builder->AllocateDeclarations(info());
if (declarations.is_null()) return SetStackOverflow();
builder()->SetDeferredConstantPoolEntry(
globals_builder->constant_pool_entry(), declarations);
}
// Find or build shared function infos.
for (std::pair<FunctionLiteral*, size_t> literal : function_literals_) {
FunctionLiteral* expr = literal.first;
Handle<SharedFunctionInfo> shared_info =
Compiler::GetSharedFunctionInfo(expr, info()->script(), isolate);
if (shared_info.is_null()) return SetStackOverflow();
builder()->SetDeferredConstantPoolEntry(literal.second, shared_info);
}
// Find or build shared function infos for the native function templates.
for (std::pair<NativeFunctionLiteral*, size_t> literal :
native_function_literals_) {
NativeFunctionLiteral* expr = literal.first;
Handle<SharedFunctionInfo> shared_info =
Compiler::GetSharedFunctionInfoForNative(expr->extension(),
expr->name());
if (shared_info.is_null()) return SetStackOverflow();
builder()->SetDeferredConstantPoolEntry(literal.second, shared_info);
}
// Build object literal constant properties
for (std::pair<ObjectLiteral*, size_t> literal : object_literals_) {
ObjectLiteral* object_literal = literal.first;
if (object_literal->properties_count() > 0) {
// If constant properties is an empty fixed array, we've already added it
// to the constant pool when visiting the object literal.
Handle<BoilerplateDescription> constant_properties =
object_literal->GetOrBuildConstantProperties(isolate);
builder()->SetDeferredConstantPoolEntry(literal.second,
constant_properties);
}
}
// Build array literal constant elements
for (std::pair<ArrayLiteral*, size_t> literal : array_literals_) {
ArrayLiteral* array_literal = literal.first;
Handle<ConstantElementsPair> constant_elements =
array_literal->GetOrBuildConstantElements(isolate);
builder()->SetDeferredConstantPoolEntry(literal.second, constant_elements);
}
}
void BytecodeGenerator::GenerateBytecode(uintptr_t stack_limit) {
DisallowHeapAllocation no_allocation;
DisallowHandleAllocation no_handles;
DisallowHandleDereference no_deref;
InitializeAstVisitor(stack_limit);
// Initialize the incoming context.
ContextScope incoming_context(this, closure_scope());
// Initialize control scope.
ControlScopeForTopLevel control(this);
RegisterAllocationScope register_scope(this);
AllocateTopLevelRegisters();
if (info()->literal()->CanSuspend()) {
BuildGeneratorPrologue();
}
if (closure_scope()->NeedsContext()) {
// Push a new inner context scope for the function.
BuildNewLocalActivationContext();
ContextScope local_function_context(this, closure_scope());
BuildLocalActivationContextInitialization();
GenerateBytecodeBody();
} else {
GenerateBytecodeBody();
}
// Check that we are not falling off the end.
DCHECK(!builder()->RequiresImplicitReturn());
}
void BytecodeGenerator::GenerateBytecodeBody() {
// Build the arguments object if it is used.
VisitArgumentsObject(closure_scope()->arguments());
// Build rest arguments array if it is used.
Variable* rest_parameter = closure_scope()->rest_parameter();
VisitRestArgumentsArray(rest_parameter);
// Build assignment to {.this_function} variable if it is used.
VisitThisFunctionVariable(closure_scope()->this_function_var());
// Build assignment to {new.target} variable if it is used.
VisitNewTargetVariable(closure_scope()->new_target_var());
// Create a generator object if necessary and initialize the
// {.generator_object} variable.
if (info()->literal()->CanSuspend()) {
BuildGeneratorObjectVariableInitialization();
}
// Emit tracing call if requested to do so.
if (FLAG_trace) builder()->CallRuntime(Runtime::kTraceEnter);
// Emit type profile call.
if (info()->literal()->feedback_vector_spec()->HasTypeProfileSlot()) {
int num_parameters = closure_scope()->num_parameters();
for (int i = 0; i < num_parameters; i++) {
Register parameter(builder()->Parameter(i));
builder()->LoadAccumulatorWithRegister(parameter).CollectTypeProfile(
closure_scope()->parameter(i)->initializer_position());
}
}
// Visit declarations within the function scope.
VisitDeclarations(closure_scope()->declarations());
// Emit initializing assignments for module namespace imports (if any).
VisitModuleNamespaceImports();
// Perform a stack-check before the body.
builder()->StackCheck(info()->literal()->start_position());
// Visit statements in the function body.
VisitStatements(info()->literal()->body());
// Emit an implicit return instruction in case control flow can fall off the
// end of the function without an explicit return being present on all paths.
if (builder()->RequiresImplicitReturn()) {
builder()->LoadUndefined();
BuildReturn();
}
}
void BytecodeGenerator::AllocateTopLevelRegisters() {
if (info()->literal()->CanSuspend()) {
// Allocate a register for generator_state_.
generator_state_ = register_allocator()->NewRegister();
// Either directly use generator_object_var or allocate a new register for
// the incoming generator object.
Variable* generator_object_var = closure_scope()->generator_object_var();
if (generator_object_var->location() == VariableLocation::LOCAL) {
incoming_new_target_or_generator_ =
GetRegisterForLocalVariable(generator_object_var);
} else {
incoming_new_target_or_generator_ = register_allocator()->NewRegister();
}
} else if (closure_scope()->new_target_var()) {
// Either directly use new_target_var or allocate a new register for
// the incoming new target object.
Variable* new_target_var = closure_scope()->new_target_var();
if (new_target_var->location() == VariableLocation::LOCAL) {
incoming_new_target_or_generator_ =
GetRegisterForLocalVariable(new_target_var);
} else {
incoming_new_target_or_generator_ = register_allocator()->NewRegister();
}
}
}
void BytecodeGenerator::VisitIterationHeader(IterationStatement* stmt,
LoopBuilder* loop_builder) {
VisitIterationHeader(stmt->first_suspend_id(), stmt->suspend_count(),
loop_builder);
}
void BytecodeGenerator::VisitIterationHeader(int first_suspend_id,
int suspend_count,
LoopBuilder* loop_builder) {
// Recall that suspend_count is always zero inside ordinary (i.e.
// non-generator) functions.
if (suspend_count == 0) {
loop_builder->LoopHeader();
} else {
loop_builder->LoopHeaderInGenerator(&generator_jump_table_,
first_suspend_id, suspend_count);
// Perform state dispatch on the generator state, assuming this is a resume.
builder()
->LoadAccumulatorWithRegister(generator_state_)
.SwitchOnSmiNoFeedback(generator_jump_table_);
// We fall through when the generator state is not in the jump table. If we
// are not resuming, we want to fall through to the loop body.
// TODO(leszeks): Only generate this test for debug builds, we can skip it
// entirely in release assuming that the generator states is always valid.
BytecodeLabel not_resuming;
builder()
->LoadLiteral(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting))
.CompareOperation(Token::Value::EQ_STRICT, generator_state_)
.JumpIfTrue(ToBooleanMode::kAlreadyBoolean, ¬_resuming);
// Otherwise this is an error.
BuildAbort(BailoutReason::kInvalidJumpTableIndex);
builder()->Bind(¬_resuming);
}
}
void BytecodeGenerator::BuildGeneratorPrologue() {
DCHECK_GT(info()->literal()->suspend_count(), 0);
DCHECK(generator_state_.is_valid());
DCHECK(generator_object().is_valid());
generator_jump_table_ =
builder()->AllocateJumpTable(info()->literal()->suspend_count(), 0);
BytecodeLabel regular_call;
builder()
->LoadAccumulatorWithRegister(generator_object())
.JumpIfUndefined(®ular_call);
// This is a resume call. Restore the current context and the registers,
// then perform state dispatch.
{
RegisterAllocationScope register_scope(this);
Register generator_context = register_allocator()->NewRegister();
builder()
->CallRuntime(Runtime::kInlineGeneratorGetContext, generator_object())
.PushContext(generator_context)
.RestoreGeneratorState(generator_object())
.StoreAccumulatorInRegister(generator_state_)
.SwitchOnSmiNoFeedback(generator_jump_table_);
}
// We fall through when the generator state is not in the jump table.
// TODO(leszeks): Only generate this for debug builds.
BuildAbort(BailoutReason::kInvalidJumpTableIndex);
// This is a regular call.
builder()
->Bind(®ular_call)
.LoadLiteral(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting))
.StoreAccumulatorInRegister(generator_state_);
// Now fall through to the ordinary function prologue, after which we will run
// into the generator object creation and other extra code inserted by the
// parser.
}
void BytecodeGenerator::VisitBlock(Block* stmt) {
// Visit declarations and statements.
CurrentScope current_scope(this, stmt->scope());
if (stmt->scope() != nullptr && stmt->scope()->NeedsContext()) {
BuildNewLocalBlockContext(stmt->scope());
ContextScope scope(this, stmt->scope());
VisitBlockDeclarationsAndStatements(stmt);
} else {
VisitBlockDeclarationsAndStatements(stmt);
}
}
void BytecodeGenerator::VisitBlockDeclarationsAndStatements(Block* stmt) {
BlockBuilder block_builder(builder(), block_coverage_builder_, stmt);
ControlScopeForBreakable execution_control(this, stmt, &block_builder);
if (stmt->scope() != nullptr) {
VisitDeclarations(stmt->scope()->declarations());
}
VisitStatements(stmt->statements());
}
void BytecodeGenerator::VisitVariableDeclaration(VariableDeclaration* decl) {
Variable* variable = decl->proxy()->var();
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
DCHECK(!variable->binding_needs_init());
FeedbackSlot slot = decl->proxy()->VariableFeedbackSlot();
globals_builder()->AddUndefinedDeclaration(variable->raw_name(), slot);
break;
}
case VariableLocation::LOCAL:
if (variable->binding_needs_init()) {
Register destination(builder()->Local(variable->index()));
builder()->LoadTheHole().StoreAccumulatorInRegister(destination);
}
break;
case VariableLocation::PARAMETER:
if (variable->binding_needs_init()) {
Register destination(builder()->Parameter(variable->index()));
builder()->LoadTheHole().StoreAccumulatorInRegister(destination);
}
break;
case VariableLocation::CONTEXT:
if (variable->binding_needs_init()) {
DCHECK_EQ(0, execution_context()->ContextChainDepth(variable->scope()));
builder()->LoadTheHole().StoreContextSlot(execution_context()->reg(),
variable->index(), 0);
}
break;
case VariableLocation::LOOKUP: {
DCHECK_EQ(VAR, variable->mode());
DCHECK(!variable->binding_needs_init());
Register name = register_allocator()->NewRegister();
builder()
->LoadLiteral(variable->raw_name())
.StoreAccumulatorInRegister(name)
.CallRuntime(Runtime::kDeclareEvalVar, name);
break;
}
case VariableLocation::MODULE:
if (variable->IsExport() && variable->binding_needs_init()) {
builder()->LoadTheHole();
BuildVariableAssignment(variable, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
// Nothing to do for imports.
break;
}
}
void BytecodeGenerator::VisitFunctionDeclaration(FunctionDeclaration* decl) {
Variable* variable = decl->proxy()->var();
DCHECK(variable->mode() == LET || variable->mode() == VAR);
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
FeedbackSlot slot = decl->proxy()->VariableFeedbackSlot();
globals_builder()->AddFunctionDeclaration(
variable->raw_name(), slot, decl->fun()->LiteralFeedbackSlot(),
decl->fun());
break;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL: {
VisitForAccumulatorValue(decl->fun());
BuildVariableAssignment(variable, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
break;
}
case VariableLocation::CONTEXT: {
DCHECK_EQ(0, execution_context()->ContextChainDepth(variable->scope()));
VisitForAccumulatorValue(decl->fun());
builder()->StoreContextSlot(execution_context()->reg(), variable->index(),
0);
break;
}
case VariableLocation::LOOKUP: {
RegisterList args = register_allocator()->NewRegisterList(2);
builder()
->LoadLiteral(variable->raw_name())
.StoreAccumulatorInRegister(args[0]);
VisitForAccumulatorValue(decl->fun());
builder()->StoreAccumulatorInRegister(args[1]).CallRuntime(
Runtime::kDeclareEvalFunction, args);
break;
}
case VariableLocation::MODULE:
DCHECK_EQ(variable->mode(), LET);
DCHECK(variable->IsExport());
VisitForAccumulatorValue(decl->fun());
BuildVariableAssignment(variable, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
break;
}
}
void BytecodeGenerator::VisitModuleNamespaceImports() {
if (!closure_scope()->is_module_scope()) return;
RegisterAllocationScope register_scope(this);
Register module_request = register_allocator()->NewRegister();
ModuleDescriptor* descriptor = closure_scope()->AsModuleScope()->module();
for (auto entry : descriptor->namespace_imports()) {
builder()
->LoadLiteral(Smi::FromInt(entry->module_request))
.StoreAccumulatorInRegister(module_request)
.CallRuntime(Runtime::kGetModuleNamespace, module_request);
Variable* var = closure_scope()->LookupLocal(entry->local_name);
DCHECK_NOT_NULL(var);
BuildVariableAssignment(var, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
}
void BytecodeGenerator::VisitDeclarations(Declaration::List* declarations) {
RegisterAllocationScope register_scope(this);
DCHECK(globals_builder()->empty());
for (Declaration* decl : *declarations) {
RegisterAllocationScope register_scope(this);
Visit(decl);
}
if (globals_builder()->empty()) return;
globals_builder()->set_constant_pool_entry(
builder()->AllocateDeferredConstantPoolEntry());
int encoded_flags = info()->GetDeclareGlobalsFlags();
// Emit code to declare globals.
RegisterList args = register_allocator()->NewRegisterList(3);
builder()
->LoadConstantPoolEntry(globals_builder()->constant_pool_entry())
.StoreAccumulatorInRegister(args[0])
.LoadLiteral(Smi::FromInt(encoded_flags))
.StoreAccumulatorInRegister(args[1])
.MoveRegister(Register::function_closure(), args[2])
.CallRuntime(Runtime::kDeclareGlobalsForInterpreter, args);
// Push and reset globals builder.
global_declarations_.push_back(globals_builder());
globals_builder_ = new (zone()) GlobalDeclarationsBuilder(zone());
}
void BytecodeGenerator::VisitStatements(ZoneList<Statement*>* statements) {
for (int i = 0; i < statements->length(); i++) {
// Allocate an outer register allocations scope for the statement.
RegisterAllocationScope allocation_scope(this);
Statement* stmt = statements->at(i);
Visit(stmt);
if (stmt->IsJump()) break;
}
}
void BytecodeGenerator::VisitExpressionStatement(ExpressionStatement* stmt) {
builder()->SetStatementPosition(stmt);
VisitForEffect(stmt->expression());
}
void BytecodeGenerator::VisitEmptyStatement(EmptyStatement* stmt) {
}
void BytecodeGenerator::VisitIfStatement(IfStatement* stmt) {
ConditionalControlFlowBuilder conditional_builder(
builder(), block_coverage_builder_, stmt);
builder()->SetStatementPosition(stmt);
if (stmt->condition()->ToBooleanIsTrue()) {
// Generate then block unconditionally as always true.
conditional_builder.Then();
Visit(stmt->then_statement());
} else if (stmt->condition()->ToBooleanIsFalse()) {
// Generate else block unconditionally if it exists.
if (stmt->HasElseStatement()) {
conditional_builder.Else();
Visit(stmt->else_statement());
}
} else {
// TODO(oth): If then statement is BreakStatement or
// ContinueStatement we can reduce number of generated
// jump/jump_ifs here. See BasicLoops test.
VisitForTest(stmt->condition(), conditional_builder.then_labels(),
conditional_builder.else_labels(), TestFallthrough::kThen);
conditional_builder.Then();
Visit(stmt->then_statement());
if (stmt->HasElseStatement()) {
conditional_builder.JumpToEnd();
conditional_builder.Else();
Visit(stmt->else_statement());
}
}
}
void BytecodeGenerator::VisitSloppyBlockFunctionStatement(
SloppyBlockFunctionStatement* stmt) {
Visit(stmt->statement());
}
void BytecodeGenerator::VisitContinueStatement(ContinueStatement* stmt) {
AllocateBlockCoverageSlotIfEnabled(stmt, SourceRangeKind::kContinuation);
builder()->SetStatementPosition(stmt);
execution_control()->Continue(stmt->target());
}
void BytecodeGenerator::VisitBreakStatement(BreakStatement* stmt) {
AllocateBlockCoverageSlotIfEnabled(stmt, SourceRangeKind::kContinuation);
builder()->SetStatementPosition(stmt);
execution_control()->Break(stmt->target());
}
void BytecodeGenerator::VisitReturnStatement(ReturnStatement* stmt) {
AllocateBlockCoverageSlotIfEnabled(stmt, SourceRangeKind::kContinuation);
builder()->SetStatementPosition(stmt);
VisitForAccumulatorValue(stmt->expression());
if (stmt->is_async_return()) {
execution_control()->AsyncReturnAccumulator(stmt->end_position());
} else {
execution_control()->ReturnAccumulator(stmt->end_position());
}
}
void BytecodeGenerator::VisitWithStatement(WithStatement* stmt) {
builder()->SetStatementPosition(stmt);
VisitForAccumulatorValue(stmt->expression());
BuildNewLocalWithContext(stmt->scope());
VisitInScope(stmt->statement(), stmt->scope());
}
void BytecodeGenerator::VisitSwitchStatement(SwitchStatement* stmt) {
// We need this scope because we visit for register values. We have to
// maintain a execution result scope where registers can be allocated.
ZoneList<CaseClause*>* clauses = stmt->cases();
SwitchBuilder switch_builder(builder(), block_coverage_builder_, stmt,
clauses->length());
ControlScopeForBreakable scope(this, stmt, &switch_builder);
int default_index = -1;
builder()->SetStatementPosition(stmt);
// Keep the switch value in a register until a case matches.
Register tag = VisitForRegisterValue(stmt->tag());
// Iterate over all cases and create nodes for label comparison.
for (int i = 0; i < clauses->length(); i++) {
CaseClause* clause = clauses->at(i);
// The default is not a test, remember index.
if (clause->is_default()) {
default_index = i;
continue;
}
// Perform label comparison as if via '===' with tag.
VisitForAccumulatorValue(clause->label());
builder()->CompareOperation(
Token::Value::EQ_STRICT, tag,
feedback_index(clause->CompareOperationFeedbackSlot()));
switch_builder.Case(ToBooleanMode::kAlreadyBoolean, i);
}
if (default_index >= 0) {
// Emit default jump if there is a default case.
switch_builder.DefaultAt(default_index);
} else {
// Otherwise if we have reached here none of the cases matched, so jump to
// the end.
switch_builder.Break();
}
// Iterate over all cases and create the case bodies.
for (int i = 0; i < clauses->length(); i++) {
CaseClause* clause = clauses->at(i);
switch_builder.SetCaseTarget(i, clause);
VisitStatements(clause->statements());
}
}
void BytecodeGenerator::VisitCaseClause(CaseClause* clause) {
// Handled entirely in VisitSwitchStatement.
UNREACHABLE();
}
void BytecodeGenerator::VisitIterationBody(IterationStatement* stmt,
LoopBuilder* loop_builder) {
loop_builder->LoopBody();
ControlScopeForIteration execution_control(this, stmt, loop_builder);
builder()->StackCheck(stmt->position());
Visit(stmt->body());
loop_builder->BindContinueTarget();
}
void BytecodeGenerator::VisitDoWhileStatement(DoWhileStatement* stmt) {
LoopBuilder loop_builder(builder(), block_coverage_builder_, stmt);
if (stmt->cond()->ToBooleanIsFalse()) {
VisitIterationBody(stmt, &loop_builder);
} else if (stmt->cond()->ToBooleanIsTrue()) {
VisitIterationHeader(stmt, &loop_builder);
VisitIterationBody(stmt, &loop_builder);
loop_builder.JumpToHeader(loop_depth_);
} else {
VisitIterationHeader(stmt, &loop_builder);
VisitIterationBody(stmt, &loop_builder);
builder()->SetExpressionAsStatementPosition(stmt->cond());
BytecodeLabels loop_backbranch(zone());
VisitForTest(stmt->cond(), &loop_backbranch, loop_builder.break_labels(),
TestFallthrough::kThen);
loop_backbranch.Bind(builder());
loop_builder.JumpToHeader(loop_depth_);
}
}
void BytecodeGenerator::VisitWhileStatement(WhileStatement* stmt) {
LoopBuilder loop_builder(builder(), block_coverage_builder_, stmt);
if (stmt->cond()->ToBooleanIsFalse()) {
// If the condition is false there is no need to generate the loop.
return;
}
VisitIterationHeader(stmt, &loop_builder);
if (!stmt->cond()->ToBooleanIsTrue()) {
builder()->SetExpressionAsStatementPosition(stmt->cond());
BytecodeLabels loop_body(zone());
VisitForTest(stmt->cond(), &loop_body, loop_builder.break_labels(),
TestFallthrough::kThen);
loop_body.Bind(builder());
}
VisitIterationBody(stmt, &loop_builder);
loop_builder.JumpToHeader(loop_depth_);
}
void BytecodeGenerator::VisitForStatement(ForStatement* stmt) {
LoopBuilder loop_builder(builder(), block_coverage_builder_, stmt);
if (stmt->init() != nullptr) {
Visit(stmt->init());
}
if (stmt->cond() && stmt->cond()->ToBooleanIsFalse()) {
// If the condition is known to be false there is no need to generate
// body, next or condition blocks. Init block should be generated.
return;
}
VisitIterationHeader(stmt, &loop_builder);
if (stmt->cond() && !stmt->cond()->ToBooleanIsTrue()) {
builder()->SetExpressionAsStatementPosition(stmt->cond());
BytecodeLabels loop_body(zone());
VisitForTest(stmt->cond(), &loop_body, loop_builder.break_labels(),
TestFallthrough::kThen);
loop_body.Bind(builder());
}
VisitIterationBody(stmt, &loop_builder);
if (stmt->next() != nullptr) {
builder()->SetStatementPosition(stmt->next());
Visit(stmt->next());
}
loop_builder.JumpToHeader(loop_depth_);
}
void BytecodeGenerator::VisitForInAssignment(Expression* expr,
FeedbackSlot slot) {
DCHECK(expr->IsValidReferenceExpression());
// Evaluate assignment starting with the value to be stored in the
// accumulator.
Property* property = expr->AsProperty();
LhsKind assign_type = Property::GetAssignType(property);
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->AsVariableProxy();
BuildVariableAssignment(proxy->var(), Token::ASSIGN, slot,
proxy->hole_check_mode());
break;
}
case NAMED_PROPERTY: {
RegisterAllocationScope register_scope(this);
Register value = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(value);
Register object = VisitForRegisterValue(property->obj());
const AstRawString* name =
property->key()->AsLiteral()->AsRawPropertyName();
builder()->LoadAccumulatorWithRegister(value);
builder()->StoreNamedProperty(object, name, feedback_index(slot),
language_mode());
break;
}
case KEYED_PROPERTY: {
RegisterAllocationScope register_scope(this);
Register value = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(value);
Register object = VisitForRegisterValue(property->obj());
Register key = VisitForRegisterValue(property->key());
builder()->LoadAccumulatorWithRegister(value);
builder()->StoreKeyedProperty(object, key, feedback_index(slot),
language_mode());
break;
}
case NAMED_SUPER_PROPERTY: {
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(4);
builder()->StoreAccumulatorInRegister(args[3]);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), args[0]);
VisitForRegisterValue(super_property->home_object(), args[1]);
builder()
->LoadLiteral(property->key()->AsLiteral()->AsRawPropertyName())
.StoreAccumulatorInRegister(args[2])
.CallRuntime(StoreToSuperRuntimeId(), args);
break;
}
case KEYED_SUPER_PROPERTY: {
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(4);
builder()->StoreAccumulatorInRegister(args[3]);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), args[0]);
VisitForRegisterValue(super_property->home_object(), args[1]);
VisitForRegisterValue(property->key(), args[2]);
builder()->CallRuntime(StoreKeyedToSuperRuntimeId(), args);
break;
}
}
}
void BytecodeGenerator::VisitForInStatement(ForInStatement* stmt) {
if (stmt->subject()->IsNullLiteral() ||
stmt->subject()->IsUndefinedLiteral()) {
// ForIn generates lots of code, skip if it wouldn't produce any effects.
return;
}
BytecodeLabel subject_null_label, subject_undefined_label;
// Prepare the state for executing ForIn.
builder()->SetExpressionAsStatementPosition(stmt->subject());
VisitForAccumulatorValue(stmt->subject());
builder()->JumpIfUndefined(&subject_undefined_label);
builder()->JumpIfNull(&subject_null_label);
Register receiver = register_allocator()->NewRegister();
builder()->ToObject(receiver);
// Used as kRegTriple and kRegPair in ForInPrepare and ForInNext.
RegisterList triple = register_allocator()->NewRegisterList(3);
Register cache_length = triple[2];
builder()->ForInPrepare(receiver, triple);
// Set up loop counter
Register index = register_allocator()->NewRegister();
builder()->LoadLiteral(Smi::kZero);
builder()->StoreAccumulatorInRegister(index);
// The loop
{
LoopBuilder loop_builder(builder(), block_coverage_builder_, stmt);
VisitIterationHeader(stmt, &loop_builder);
builder()->SetExpressionAsStatementPosition(stmt->each());
builder()->ForInContinue(index, cache_length);
loop_builder.BreakIfFalse(ToBooleanMode::kAlreadyBoolean);
FeedbackSlot slot = stmt->ForInFeedbackSlot();
builder()->ForInNext(receiver, index, triple.Truncate(2),
feedback_index(slot));
loop_builder.ContinueIfUndefined();
VisitForInAssignment(stmt->each(), stmt->EachFeedbackSlot());
VisitIterationBody(stmt, &loop_builder);
builder()->ForInStep(index);
builder()->StoreAccumulatorInRegister(index);
loop_builder.JumpToHeader(loop_depth_);
}
builder()->Bind(&subject_null_label);
builder()->Bind(&subject_undefined_label);
}
void BytecodeGenerator::VisitForOfStatement(ForOfStatement* stmt) {
LoopBuilder loop_builder(builder(), block_coverage_builder_, stmt);
builder()->SetExpressionAsStatementPosition(stmt->assign_iterator());
VisitForEffect(stmt->assign_iterator());
VisitIterationHeader(stmt, &loop_builder);
builder()->SetExpressionAsStatementPosition(stmt->next_result());
VisitForEffect(stmt->next_result());
TypeHint type_hint = VisitForAccumulatorValue(stmt->result_done());
loop_builder.BreakIfTrue(ToBooleanModeFromTypeHint(type_hint));
VisitForEffect(stmt->assign_each());
VisitIterationBody(stmt, &loop_builder);
loop_builder.JumpToHeader(loop_depth_);
}
void BytecodeGenerator::VisitTryCatchStatement(TryCatchStatement* stmt) {
// Update catch prediction tracking. The updated catch_prediction value lasts
// until the end of the try_block in the AST node, and does not apply to the
// catch_block.
HandlerTable::CatchPrediction outer_catch_prediction = catch_prediction();
set_catch_prediction(stmt->GetCatchPrediction(outer_catch_prediction));
TryCatchBuilder try_control_builder(builder(), catch_prediction());
// Preserve the context in a dedicated register, so that it can be restored
// when the handler is entered by the stack-unwinding machinery.
// TODO(mstarzinger): Be smarter about register allocation.
Register context = register_allocator()->NewRegister();
builder()->MoveRegister(Register::current_context(), context);
// Evaluate the try-block inside a control scope. This simulates a handler
// that is intercepting 'throw' control commands.
try_control_builder.BeginTry(context);
{
ControlScopeForTryCatch scope(this, &try_control_builder);
Visit(stmt->try_block());
set_catch_prediction(outer_catch_prediction);
}
try_control_builder.EndTry();
// Create a catch scope that binds the exception.
BuildNewLocalCatchContext(stmt->scope());
builder()->StoreAccumulatorInRegister(context);
// If requested, clear message object as we enter the catch block.
if (stmt->ShouldClearPendingException(outer_catch_prediction)) {
builder()->LoadTheHole().SetPendingMessage();
}
// Load the catch context into the accumulator.
builder()->LoadAccumulatorWithRegister(context);
// Evaluate the catch-block.
BuildIncrementBlockCoverageCounterIfEnabled(stmt, SourceRangeKind::kCatch);
VisitInScope(stmt->catch_block(), stmt->scope());
try_control_builder.EndCatch();
BuildIncrementBlockCoverageCounterIfEnabled(stmt,
SourceRangeKind::kContinuation);
}
void BytecodeGenerator::VisitTryFinallyStatement(TryFinallyStatement* stmt) {
// We can't know whether the finally block will override ("catch") an
// exception thrown in the try block, so we just adopt the outer prediction.
TryFinallyBuilder try_control_builder(builder(), catch_prediction());
// We keep a record of all paths that enter the finally-block to be able to
// dispatch to the correct continuation point after the statements in the
// finally-block have been evaluated.
//
// The try-finally construct can enter the finally-block in three ways:
// 1. By exiting the try-block normally, falling through at the end.
// 2. By exiting the try-block with a function-local control flow transfer
// (i.e. through break/continue/return statements).
// 3. By exiting the try-block with a thrown exception.
//
// The result register semantics depend on how the block was entered:
// - ReturnStatement: It represents the return value being returned.
// - ThrowStatement: It represents the exception being thrown.
// - BreakStatement/ContinueStatement: Undefined and not used.
// - Falling through into finally-block: Undefined and not used.
Register token = register_allocator()->NewRegister();
Register result = register_allocator()->NewRegister();
ControlScope::DeferredCommands commands(this, token, result);
// Preserve the context in a dedicated register, so that it can be restored
// when the handler is entered by the stack-unwinding machinery.
// TODO(mstarzinger): Be smarter about register allocation.
Register context = register_allocator()->NewRegister();
builder()->MoveRegister(Register::current_context(), context);
// Evaluate the try-block inside a control scope. This simulates a handler
// that is intercepting all control commands.
try_control_builder.BeginTry(context);
{
ControlScopeForTryFinally scope(this, &try_control_builder, &commands);
Visit(stmt->try_block());
}
try_control_builder.EndTry();
// Record fall-through and exception cases.
commands.RecordFallThroughPath();
try_control_builder.LeaveTry();
try_control_builder.BeginHandler();
commands.RecordHandlerReThrowPath();
// Pending message object is saved on entry.
try_control_builder.BeginFinally();
Register message = context; // Reuse register.
// Clear message object as we enter the finally block.
builder()->LoadTheHole().SetPendingMessage().StoreAccumulatorInRegister(
message);
// Evaluate the finally-block.
BuildIncrementBlockCoverageCounterIfEnabled(stmt, SourceRangeKind::kFinally);
Visit(stmt->finally_block());
try_control_builder.EndFinally();
// Pending message object is restored on exit.
builder()->LoadAccumulatorWithRegister(message).SetPendingMessage();
// Dynamic dispatch after the finally-block.
commands.ApplyDeferredCommands();
BuildIncrementBlockCoverageCounterIfEnabled(stmt,
SourceRangeKind::kContinuation);
}
void BytecodeGenerator::VisitDebuggerStatement(DebuggerStatement* stmt) {
builder()->SetStatementPosition(stmt);
builder()->Debugger();
}
void BytecodeGenerator::VisitFunctionLiteral(FunctionLiteral* expr) {
DCHECK_EQ(expr->scope()->outer_scope(), current_scope());
uint8_t flags = CreateClosureFlags::Encode(
expr->pretenure(), closure_scope()->is_function_scope());
size_t entry = builder()->AllocateDeferredConstantPoolEntry();
int slot_index = feedback_index(expr->LiteralFeedbackSlot());
builder()->CreateClosure(entry, slot_index, flags);
function_literals_.push_back(std::make_pair(expr, entry));
}
void BytecodeGenerator::BuildClassLiteral(ClassLiteral* expr) {
VisitDeclarations(expr->scope()->declarations());
Register constructor = VisitForRegisterValue(expr->constructor());
{
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(4);
VisitForAccumulatorValueOrTheHole(expr->extends());
builder()
->StoreAccumulatorInRegister(args[0])
.MoveRegister(constructor, args[1])
.LoadLiteral(Smi::FromInt(expr->start_position()))
.StoreAccumulatorInRegister(args[2])
.LoadLiteral(Smi::FromInt(expr->end_position()))
.StoreAccumulatorInRegister(args[3])
.CallRuntime(Runtime::kDefineClass, args);
}
Register prototype = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(prototype);
if (FunctionLiteral::NeedsHomeObject(expr->constructor())) {
// Prototype is already in the accumulator.
builder()->StoreHomeObjectProperty(
constructor, feedback_index(expr->HomeObjectSlot()), language_mode());
}
VisitClassLiteralProperties(expr, constructor, prototype);
BuildClassLiteralNameProperty(expr, constructor);
builder()->CallRuntime(Runtime::kToFastProperties, constructor);
// Assign to class variable.
if (expr->class_variable_proxy() != nullptr) {
VariableProxy* proxy = expr->class_variable_proxy();
FeedbackSlot slot =
expr->NeedsProxySlot() ? expr->ProxySlot() : FeedbackSlot::Invalid();
BuildVariableAssignment(proxy->var(), Token::INIT, slot,
HoleCheckMode::kElided);
}
}
void BytecodeGenerator::VisitClassLiteral(ClassLiteral* expr) {
CurrentScope current_scope(this, expr->scope());
DCHECK_NOT_NULL(expr->scope());
if (expr->scope()->NeedsContext()) {
BuildNewLocalBlockContext(expr->scope());
ContextScope scope(this, expr->scope());
BuildClassLiteral(expr);
} else {
BuildClassLiteral(expr);
}
}
void BytecodeGenerator::VisitClassLiteralProperties(ClassLiteral* expr,
Register constructor,
Register prototype) {
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(4);
Register receiver = args[0], key = args[1], value = args[2], attr = args[3];
bool attr_assigned = false;
Register old_receiver = Register::invalid_value();
// Create nodes to store method values into the literal.
for (int i = 0; i < expr->properties()->length(); i++) {
ClassLiteral::Property* property = expr->properties()->at(i);
// Set-up receiver.
Register new_receiver = property->is_static() ? constructor : prototype;
if (new_receiver != old_receiver) {
builder()->MoveRegister(new_receiver, receiver);
old_receiver = new_receiver;
}
BuildLoadPropertyKey(property, key);
if (property->is_static() && property->is_computed_name()) {
// The static prototype property is read only. We handle the non computed
// property name case in the parser. Since this is the only case where we
// need to check for an own read only property we special case this so we
// do not need to do this for every property.
BytecodeLabel done;
builder()
->LoadLiteral(ast_string_constants()->prototype_string())
.CompareOperation(Token::Value::EQ_STRICT, key)
.JumpIfFalse(ToBooleanMode::kAlreadyBoolean, &done)
.CallRuntime(Runtime::kThrowStaticPrototypeError)
.Bind(&done);
}
VisitForRegisterValue(property->value(), value);
VisitSetHomeObject(value, receiver, property);
if (!attr_assigned) {
builder()
->LoadLiteral(Smi::FromInt(DONT_ENUM))
.StoreAccumulatorInRegister(attr);
attr_assigned = true;
}
switch (property->kind()) {
case ClassLiteral::Property::METHOD: {
DataPropertyInLiteralFlags flags = DataPropertyInLiteralFlag::kDontEnum;
if (property->NeedsSetFunctionName()) {
flags |= DataPropertyInLiteralFlag::kSetFunctionName;
}
FeedbackSlot slot = property->GetStoreDataPropertySlot();
DCHECK(!slot.IsInvalid());
builder()
->LoadAccumulatorWithRegister(value)
.StoreDataPropertyInLiteral(receiver, key, flags,
feedback_index(slot));
break;
}
case ClassLiteral::Property::GETTER: {
builder()->CallRuntime(Runtime::kDefineGetterPropertyUnchecked, args);
break;
}
case ClassLiteral::Property::SETTER: {
builder()->CallRuntime(Runtime::kDefineSetterPropertyUnchecked, args);
break;
}
case ClassLiteral::Property::FIELD: {
UNREACHABLE();
break;
}
}
}
}
void BytecodeGenerator::BuildClassLiteralNameProperty(ClassLiteral* expr,
Register literal) {
if (!expr->has_name_static_property() &&
expr->constructor()->has_shared_name()) {
Runtime::FunctionId runtime_id =
expr->has_static_computed_names()
? Runtime::kInstallClassNameAccessorWithCheck
: Runtime::kInstallClassNameAccessor;
builder()->CallRuntime(runtime_id, literal);
}
}
void BytecodeGenerator::VisitNativeFunctionLiteral(
NativeFunctionLiteral* expr) {
size_t entry = builder()->AllocateDeferredConstantPoolEntry();
int slot_index = feedback_index(expr->LiteralFeedbackSlot());
builder()->CreateClosure(entry, slot_index, NOT_TENURED);
native_function_literals_.push_back(std::make_pair(expr, entry));
}
void BytecodeGenerator::VisitDoExpression(DoExpression* expr) {
VisitBlock(expr->block());
VisitVariableProxy(expr->result());
}
void BytecodeGenerator::VisitConditional(Conditional* expr) {
ConditionalControlFlowBuilder conditional_builder(
builder(), block_coverage_builder_, expr);
if (expr->condition()->ToBooleanIsTrue()) {
// Generate then block unconditionally as always true.
conditional_builder.Then();
VisitForAccumulatorValue(expr->then_expression());
} else if (expr->condition()->ToBooleanIsFalse()) {
// Generate else block unconditionally if it exists.
conditional_builder.Else();
VisitForAccumulatorValue(expr->else_expression());
} else {
VisitForTest(expr->condition(), conditional_builder.then_labels(),
conditional_builder.else_labels(), TestFallthrough::kThen);
conditional_builder.Then();
VisitForAccumulatorValue(expr->then_expression());
conditional_builder.JumpToEnd();
conditional_builder.Else();
VisitForAccumulatorValue(expr->else_expression());
}
}
void BytecodeGenerator::VisitLiteral(Literal* expr) {
if (!execution_result()->IsEffect()) {
const AstValue* raw_value = expr->raw_value();
builder()->LoadLiteral(raw_value);
if (raw_value->IsTrue() || raw_value->IsFalse()) {
execution_result()->SetResultIsBoolean();
}
}
}
void BytecodeGenerator::VisitRegExpLiteral(RegExpLiteral* expr) {
// Materialize a regular expression literal.
builder()->CreateRegExpLiteral(
expr->raw_pattern(), feedback_index(expr->literal_slot()), expr->flags());
}
void BytecodeGenerator::VisitObjectLiteral(ObjectLiteral* expr) {
int literal_index = feedback_index(expr->literal_slot());
// Fast path for the empty object literal which doesn't need an
// AllocationSite.
if (expr->IsEmptyObjectLiteral()) {
DCHECK(expr->IsFastCloningSupported());
builder()->CreateEmptyObjectLiteral(literal_index);
return;
}
// Deep-copy the literal boilerplate.
uint8_t flags = CreateObjectLiteralFlags::Encode(
expr->ComputeFlags(), expr->IsFastCloningSupported());
Register literal = register_allocator()->NewRegister();
size_t entry;
// If constant properties is an empty fixed array, use a cached empty fixed
// array to ensure it's only added to the constant pool once.
if (expr->properties_count() == 0) {
entry = builder()->EmptyFixedArrayConstantPoolEntry();
} else {
entry = builder()->AllocateDeferredConstantPoolEntry();
object_literals_.push_back(std::make_pair(expr, entry));
}
// TODO(cbruni): Directly generate runtime call for literals we cannot
// optimize once the FastCloneShallowObject stub is in sync with the TF
// optimizations.
builder()->CreateObjectLiteral(entry, literal_index, flags, literal);
// Store computed values into the literal.
int property_index = 0;
AccessorTable accessor_table(zone());
for (; property_index < expr->properties()->length(); property_index++) {
ObjectLiteral::Property* property = expr->properties()->at(property_index);
if (property->is_computed_name()) break;
if (property->IsCompileTimeValue()) continue;
RegisterAllocationScope inner_register_scope(this);
Literal* key = property->key()->AsLiteral();
switch (property->kind()) {
case ObjectLiteral::Property::SPREAD:
case ObjectLiteral::Property::CONSTANT:
UNREACHABLE();
case ObjectLiteral::Property::MATERIALIZED_LITERAL:
DCHECK(!CompileTimeValue::IsCompileTimeValue(property->value()));
// Fall through.
case ObjectLiteral::Property::COMPUTED: {
// It is safe to use [[Put]] here because the boilerplate already
// contains computed properties with an uninitialized value.
if (key->IsStringLiteral()) {
DCHECK(key->IsPropertyName());
if (property->emit_store()) {
VisitForAccumulatorValue(property->value());
if (FunctionLiteral::NeedsHomeObject(property->value())) {
RegisterAllocationScope register_scope(this);
Register value = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(value);
builder()->StoreNamedOwnProperty(
literal, key->AsRawPropertyName(),
feedback_index(property->GetSlot(0)));
VisitSetHomeObject(value, literal, property, 1);
} else {
builder()->StoreNamedOwnProperty(
literal, key->AsRawPropertyName(),
feedback_index(property->GetSlot(0)));
}
} else {
VisitForEffect(property->value());
}
} else {
RegisterList args = register_allocator()->NewRegisterList(4);
builder()->MoveRegister(literal, args[0]);
VisitForRegisterValue(property->key(), args[1]);
VisitForRegisterValue(property->value(), args[2]);
if (property->emit_store()) {
builder()
->LoadLiteral(Smi::FromInt(SLOPPY))
.StoreAccumulatorInRegister(args[3])
.CallRuntime(Runtime::kSetProperty, args);
Register value = args[2];
VisitSetHomeObject(value, literal, property);
}
}
break;
}
case ObjectLiteral::Property::PROTOTYPE: {
// __proto__:null is handled by CreateObjectLiteral.
if (property->IsNullPrototype()) break;
DCHECK(property->emit_store());
DCHECK(!property->NeedsSetFunctionName());
RegisterList args = register_allocator()->NewRegisterList(2);
builder()->MoveRegister(literal, args[0]);
VisitForRegisterValue(property->value(), args[1]);
builder()->CallRuntime(Runtime::kInternalSetPrototype, args);
break;
}
case ObjectLiteral::Property::GETTER:
if (property->emit_store()) {
accessor_table.lookup(key)->second->getter = property;
}
break;
case ObjectLiteral::Property::SETTER:
if (property->emit_store()) {
accessor_table.lookup(key)->second->setter = property;
}
break;
}
}
// Define accessors, using only a single call to the runtime for each pair of
// corresponding getters and setters.
for (AccessorTable::Iterator it = accessor_table.begin();
it != accessor_table.end(); ++it) {
RegisterAllocationScope inner_register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(5);
builder()->MoveRegister(literal, args[0]);
VisitForRegisterValue(it->first, args[1]);
VisitObjectLiteralAccessor(literal, it->second->getter, args[2]);
VisitObjectLiteralAccessor(literal, it->second->setter, args[3]);
builder()
->LoadLiteral(Smi::FromInt(NONE))
.StoreAccumulatorInRegister(args[4])
.CallRuntime(Runtime::kDefineAccessorPropertyUnchecked, args);
}
// Object literals have two parts. The "static" part on the left contains no
// computed property names, and so we can compute its map ahead of time; see
// Runtime_CreateObjectLiteralBoilerplate. The second "dynamic" part starts
// with the first computed property name and continues with all properties to
// its right. All the code from above initializes the static component of the
// object literal, and arranges for the map of the result to reflect the
// static order in which the keys appear. For the dynamic properties, we
// compile them into a series of "SetOwnProperty" runtime calls. This will
// preserve insertion order.
for (; property_index < expr->properties()->length(); property_index++) {
ObjectLiteral::Property* property = expr->properties()->at(property_index);
RegisterAllocationScope inner_register_scope(this);
if (property->IsPrototype()) {
// __proto__:null is handled by CreateObjectLiteral.
if (property->IsNullPrototype()) continue;
DCHECK(property->emit_store());
DCHECK(!property->NeedsSetFunctionName());
RegisterList args = register_allocator()->NewRegisterList(2);
builder()->MoveRegister(literal, args[0]);
VisitForRegisterValue(property->value(), args[1]);
builder()->CallRuntime(Runtime::kInternalSetPrototype, args);
continue;
}
switch (property->kind()) {
case ObjectLiteral::Property::CONSTANT:
case ObjectLiteral::Property::COMPUTED:
case ObjectLiteral::Property::MATERIALIZED_LITERAL: {
Register key = register_allocator()->NewRegister();
BuildLoadPropertyKey(property, key);
Register value = VisitForRegisterValue(property->value());
VisitSetHomeObject(value, literal, property);
DataPropertyInLiteralFlags data_property_flags =
DataPropertyInLiteralFlag::kNoFlags;
if (property->NeedsSetFunctionName()) {
data_property_flags |= DataPropertyInLiteralFlag::kSetFunctionName;
}
FeedbackSlot slot = property->GetStoreDataPropertySlot();
DCHECK(!slot.IsInvalid());
builder()
->LoadAccumulatorWithRegister(value)
.StoreDataPropertyInLiteral(literal, key, data_property_flags,
feedback_index(slot));
break;
}
case ObjectLiteral::Property::GETTER:
case ObjectLiteral::Property::SETTER: {
RegisterList args = register_allocator()->NewRegisterList(4);
builder()->MoveRegister(literal, args[0]);
BuildLoadPropertyKey(property, args[1]);
VisitForRegisterValue(property->value(), args[2]);
VisitSetHomeObject(args[2], literal, property);
builder()
->LoadLiteral(Smi::FromInt(NONE))
.StoreAccumulatorInRegister(args[3]);
Runtime::FunctionId function_id =
property->kind() == ObjectLiteral::Property::GETTER
? Runtime::kDefineGetterPropertyUnchecked
: Runtime::kDefineSetterPropertyUnchecked;
builder()->CallRuntime(function_id, args);
break;
}
case ObjectLiteral::Property::SPREAD: {
RegisterList args = register_allocator()->NewRegisterList(2);
builder()->MoveRegister(literal, args[0]);
VisitForRegisterValue(property->value(), args[1]);
builder()->CallRuntime(Runtime::kCopyDataProperties, args);
break;
}
case ObjectLiteral::Property::PROTOTYPE:
UNREACHABLE(); // Handled specially above.
break;
}
}
builder()->LoadAccumulatorWithRegister(literal);
}
void BytecodeGenerator::VisitArrayLiteral(ArrayLiteral* expr) {
// Deep-copy the literal boilerplate.
int literal_index = feedback_index(expr->literal_slot());
if (expr->is_empty()) {
// Empty array literal fast-path.
DCHECK(expr->IsFastCloningSupported());
builder()->CreateEmptyArrayLiteral(literal_index);
return;
}
uint8_t flags = CreateArrayLiteralFlags::Encode(
expr->IsFastCloningSupported(), expr->ComputeFlags());
size_t entry = builder()->AllocateDeferredConstantPoolEntry();
builder()->CreateArrayLiteral(entry, literal_index, flags);
array_literals_.push_back(std::make_pair(expr, entry));
Register index, literal;
// Evaluate all the non-constant subexpressions and store them into the
// newly cloned array.
bool literal_in_accumulator = true;
for (int array_index = 0; array_index < expr->values()->length();
array_index++) {
Expression* subexpr = expr->values()->at(array_index);
if (CompileTimeValue::IsCompileTimeValue(subexpr)) continue;
DCHECK(!subexpr->IsSpread());
if (literal_in_accumulator) {
index = register_allocator()->NewRegister();
literal = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(literal);
literal_in_accumulator = false;
}
FeedbackSlot slot = expr->LiteralFeedbackSlot();
builder()
->LoadLiteral(Smi::FromInt(array_index))
.StoreAccumulatorInRegister(index);
VisitForAccumulatorValue(subexpr);
builder()->StoreKeyedProperty(literal, index, feedback_index(slot),
language_mode());
}
if (!literal_in_accumulator) {
// Restore literal array into accumulator.
builder()->LoadAccumulatorWithRegister(literal);
}
}
void BytecodeGenerator::VisitVariableProxy(VariableProxy* proxy) {
builder()->SetExpressionPosition(proxy);
BuildVariableLoad(proxy->var(), proxy->VariableFeedbackSlot(),
proxy->hole_check_mode());
}
void BytecodeGenerator::BuildVariableLoad(Variable* variable, FeedbackSlot slot,
HoleCheckMode hole_check_mode,
TypeofMode typeof_mode) {
switch (variable->location()) {
case VariableLocation::LOCAL: {
Register source(builder()->Local(variable->index()));
// We need to load the variable into the accumulator, even when in a
// VisitForRegisterScope, in order to avoid register aliasing if
// subsequent expressions assign to the same variable.
builder()->LoadAccumulatorWithRegister(source);
if (hole_check_mode == HoleCheckMode::kRequired) {
BuildThrowIfHole(variable);
}
break;
}
case VariableLocation::PARAMETER: {
Register source;
if (variable->IsReceiver()) {
source = builder()->Receiver();
} else {
source = builder()->Parameter(variable->index());
}
// We need to load the variable into the accumulator, even when in a
// VisitForRegisterScope, in order to avoid register aliasing if
// subsequent expressions assign to the same variable.
builder()->LoadAccumulatorWithRegister(source);
if (hole_check_mode == HoleCheckMode::kRequired) {
BuildThrowIfHole(variable);
}
break;
}
case VariableLocation::UNALLOCATED: {
// The global identifier "undefined" is immutable. Everything
// else could be reassigned. For performance, we do a pointer comparison
// rather than checking if the raw_name is really "undefined".
if (variable->raw_name() == ast_string_constants()->undefined_string()) {
builder()->LoadUndefined();
} else {
builder()->LoadGlobal(variable->raw_name(), feedback_index(slot),
typeof_mode);
}
break;
}
case VariableLocation::CONTEXT: {
int depth = execution_context()->ContextChainDepth(variable->scope());
ContextScope* context = execution_context()->Previous(depth);
Register context_reg;
if (context) {
context_reg = context->reg();
depth = 0;
} else {
context_reg = execution_context()->reg();
}
BytecodeArrayBuilder::ContextSlotMutability immutable =
(variable->maybe_assigned() == kNotAssigned)
? BytecodeArrayBuilder::kImmutableSlot
: BytecodeArrayBuilder::kMutableSlot;
builder()->LoadContextSlot(context_reg, variable->index(), depth,
immutable);
if (hole_check_mode == HoleCheckMode::kRequired) {
BuildThrowIfHole(variable);
}
break;
}
case VariableLocation::LOOKUP: {
switch (variable->mode()) {
case DYNAMIC_LOCAL: {
Variable* local_variable = variable->local_if_not_shadowed();
int depth =
execution_context()->ContextChainDepth(local_variable->scope());
builder()->LoadLookupContextSlot(variable->raw_name(), typeof_mode,
local_variable->index(), depth);
if (hole_check_mode == HoleCheckMode::kRequired) {
BuildThrowIfHole(variable);
}
break;
}
case DYNAMIC_GLOBAL: {
int depth =
closure_scope()->ContextChainLengthUntilOutermostSloppyEval();
builder()->LoadLookupGlobalSlot(variable->raw_name(), typeof_mode,
feedback_index(slot), depth);
break;
}
default:
builder()->LoadLookupSlot(variable->raw_name(), typeof_mode);
}
break;
}
case VariableLocation::MODULE: {
int depth = execution_context()->ContextChainDepth(variable->scope());
builder()->LoadModuleVariable(variable->index(), depth);
if (hole_check_mode == HoleCheckMode::kRequired) {
BuildThrowIfHole(variable);
}
break;
}
}
}
void BytecodeGenerator::BuildVariableLoadForAccumulatorValue(
Variable* variable, FeedbackSlot slot, HoleCheckMode hole_check_mode,
TypeofMode typeof_mode) {
ValueResultScope accumulator_result(this);
BuildVariableLoad(variable, slot, hole_check_mode, typeof_mode);
}
void BytecodeGenerator::BuildReturn(int source_position) {
if (FLAG_trace) {
RegisterAllocationScope register_scope(this);
Register result = register_allocator()->NewRegister();
// Runtime returns {result} value, preserving accumulator.
builder()->StoreAccumulatorInRegister(result).CallRuntime(
Runtime::kTraceExit, result);
}
if (info()->literal()->feedback_vector_spec()->HasTypeProfileSlot()) {
builder()->CollectTypeProfile(info()->literal()->return_position());
}
builder()->SetReturnPosition(source_position, info()->literal());
builder()->Return();
}
void BytecodeGenerator::BuildAsyncReturn(int source_position) {
RegisterAllocationScope register_scope(this);
if (IsAsyncGeneratorFunction(info()->literal()->kind())) {
RegisterList args = register_allocator()->NewRegisterList(3);
builder()
->MoveRegister(generator_object(), args[0]) // generator
.StoreAccumulatorInRegister(args[1]) // value
.LoadTrue()
.StoreAccumulatorInRegister(args[2]) // done
.CallRuntime(Runtime::kInlineAsyncGeneratorResolve, args);
} else {
DCHECK(IsAsyncFunction(info()->literal()->kind()));
RegisterList args = register_allocator()->NewRegisterList(3);
Register receiver = args[0];
Register promise = args[1];
Register return_value = args[2];
builder()->StoreAccumulatorInRegister(return_value);
Variable* var_promise = closure_scope()->promise_var();
DCHECK_NOT_NULL(var_promise);
BuildVariableLoad(var_promise, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
builder()
->StoreAccumulatorInRegister(promise)
.LoadUndefined()
.StoreAccumulatorInRegister(receiver)
.CallJSRuntime(Context::PROMISE_RESOLVE_INDEX, args)
.LoadAccumulatorWithRegister(promise);
}
BuildReturn(source_position);
}
void BytecodeGenerator::BuildReThrow() { builder()->ReThrow(); }
void BytecodeGenerator::BuildAbort(BailoutReason bailout_reason) {
RegisterAllocationScope register_scope(this);
Register reason = register_allocator()->NewRegister();
builder()
->LoadLiteral(Smi::FromInt(static_cast<int>(bailout_reason)))
.StoreAccumulatorInRegister(reason)
.CallRuntime(Runtime::kAbort, reason);
}
void BytecodeGenerator::BuildThrowIfHole(Variable* variable) {
if (variable->is_this()) {
DCHECK(variable->mode() == CONST);
builder()->ThrowSuperNotCalledIfHole();
} else {
builder()->ThrowReferenceErrorIfHole(variable->raw_name());
}
}
void BytecodeGenerator::BuildHoleCheckForVariableAssignment(Variable* variable,
Token::Value op) {
if (variable->is_this() && variable->mode() == CONST && op == Token::INIT) {
// Perform an initialization check for 'this'. 'this' variable is the
// only variable able to trigger bind operations outside the TDZ
// via 'super' calls.
builder()->ThrowSuperAlreadyCalledIfNotHole();
} else {
// Perform an initialization check for let/const declared variables.
// E.g. let x = (x = 20); is not allowed.
DCHECK(IsLexicalVariableMode(variable->mode()));
BuildThrowIfHole(variable);
}
}
void BytecodeGenerator::BuildVariableAssignment(
Variable* variable, Token::Value op, FeedbackSlot slot,
HoleCheckMode hole_check_mode, LookupHoistingMode lookup_hoisting_mode) {
VariableMode mode = variable->mode();
RegisterAllocationScope assignment_register_scope(this);
BytecodeLabel end_label;
switch (variable->location()) {
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL: {
Register destination;
if (VariableLocation::PARAMETER == variable->location()) {
if (variable->IsReceiver()) {
destination = builder()->Receiver();
} else {
destination = builder()->Parameter(variable->index());
}
} else {
destination = builder()->Local(variable->index());
}
if (hole_check_mode == HoleCheckMode::kRequired) {
// Load destination to check for hole.
Register value_temp = register_allocator()->NewRegister();
builder()
->StoreAccumulatorInRegister(value_temp)
.LoadAccumulatorWithRegister(destination);
BuildHoleCheckForVariableAssignment(variable, op);
builder()->LoadAccumulatorWithRegister(value_temp);
}
if (mode != CONST || op == Token::INIT) {
builder()->StoreAccumulatorInRegister(destination);
} else if (variable->throw_on_const_assignment(language_mode())) {
builder()->CallRuntime(Runtime::kThrowConstAssignError);
}
break;
}
case VariableLocation::UNALLOCATED: {
builder()->StoreGlobal(variable->raw_name(), feedback_index(slot),
language_mode());
break;
}
case VariableLocation::CONTEXT: {
int depth = execution_context()->ContextChainDepth(variable->scope());
ContextScope* context = execution_context()->Previous(depth);
Register context_reg;
if (context) {
context_reg = context->reg();
depth = 0;
} else {
context_reg = execution_context()->reg();
}
if (hole_check_mode == HoleCheckMode::kRequired) {
// Load destination to check for hole.
Register value_temp = register_allocator()->NewRegister();
builder()
->StoreAccumulatorInRegister(value_temp)
.LoadContextSlot(context_reg, variable->index(), depth,
BytecodeArrayBuilder::kMutableSlot);
BuildHoleCheckForVariableAssignment(variable, op);
builder()->LoadAccumulatorWithRegister(value_temp);
}
if (mode != CONST || op == Token::INIT) {
builder()->StoreContextSlot(context_reg, variable->index(), depth);
} else if (variable->throw_on_const_assignment(language_mode())) {
builder()->CallRuntime(Runtime::kThrowConstAssignError);
}
break;
}
case VariableLocation::LOOKUP: {
builder()->StoreLookupSlot(variable->raw_name(), language_mode(),
lookup_hoisting_mode);
break;
}
case VariableLocation::MODULE: {
DCHECK(IsDeclaredVariableMode(mode));
if (mode == CONST && op != Token::INIT) {
builder()->CallRuntime(Runtime::kThrowConstAssignError);
break;
}
// If we don't throw above, we know that we're dealing with an
// export because imports are const and we do not generate initializing
// assignments for them.
DCHECK(variable->IsExport());
int depth = execution_context()->ContextChainDepth(variable->scope());
if (hole_check_mode == HoleCheckMode::kRequired) {
Register value_temp = register_allocator()->NewRegister();
builder()
->StoreAccumulatorInRegister(value_temp)
.LoadModuleVariable(variable->index(), depth);
BuildHoleCheckForVariableAssignment(variable, op);
builder()->LoadAccumulatorWithRegister(value_temp);
}
builder()->StoreModuleVariable(variable->index(), depth);
break;
}
}
}
void BytecodeGenerator::VisitAssignment(Assignment* expr) {
DCHECK(expr->target()->IsValidReferenceExpressionOrThis());
Register object, key;
RegisterList super_property_args;
const AstRawString* name;
// Left-hand side can only be a property, a global or a variable slot.
Property* property = expr->target()->AsProperty();
LhsKind assign_type = Property::GetAssignType(property);
// Evaluate LHS expression.
switch (assign_type) {
case VARIABLE:
// Nothing to do to evaluate variable assignment LHS.
break;
case NAMED_PROPERTY: {
object = VisitForRegisterValue(property->obj());
name = property->key()->AsLiteral()->AsRawPropertyName();
break;
}
case KEYED_PROPERTY: {
object = VisitForRegisterValue(property->obj());
key = VisitForRegisterValue(property->key());
break;
}
case NAMED_SUPER_PROPERTY: {
super_property_args = register_allocator()->NewRegisterList(4);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), super_property_args[0]);
VisitForRegisterValue(super_property->home_object(),
super_property_args[1]);
builder()
->LoadLiteral(property->key()->AsLiteral()->AsRawPropertyName())
.StoreAccumulatorInRegister(super_property_args[2]);
break;
}
case KEYED_SUPER_PROPERTY: {
super_property_args = register_allocator()->NewRegisterList(4);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), super_property_args[0]);
VisitForRegisterValue(super_property->home_object(),
super_property_args[1]);
VisitForRegisterValue(property->key(), super_property_args[2]);
break;
}
}
// Evaluate the value and potentially handle compound assignments by loading
// the left-hand side value and performing a binary operation.
if (expr->IsCompoundAssignment()) {
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->target()->AsVariableProxy();
BuildVariableLoad(proxy->var(), proxy->VariableFeedbackSlot(),
proxy->hole_check_mode());
break;
}
case NAMED_PROPERTY: {
FeedbackSlot slot = property->PropertyFeedbackSlot();
builder()->LoadNamedProperty(object, name, feedback_index(slot));
break;
}
case KEYED_PROPERTY: {
// Key is already in accumulator at this point due to evaluating the
// LHS above.
FeedbackSlot slot = property->PropertyFeedbackSlot();
builder()->LoadKeyedProperty(object, feedback_index(slot));
break;
}
case NAMED_SUPER_PROPERTY: {
builder()->CallRuntime(Runtime::kLoadFromSuper,
super_property_args.Truncate(3));
break;
}
case KEYED_SUPER_PROPERTY: {
builder()->CallRuntime(Runtime::kLoadKeyedFromSuper,
super_property_args.Truncate(3));
break;
}
}
BinaryOperation* binop = expr->AsCompoundAssignment()->binary_operation();
FeedbackSlot slot = binop->BinaryOperationFeedbackSlot();
if (expr->value()->IsSmiLiteral()) {
builder()->BinaryOperationSmiLiteral(
binop->op(), expr->value()->AsLiteral()->AsSmiLiteral(),
feedback_index(slot));
} else {
Register old_value = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(old_value);
VisitForAccumulatorValue(expr->value());
builder()->BinaryOperation(binop->op(), old_value, feedback_index(slot));
}
} else {
VisitForAccumulatorValue(expr->value());
}
// Store the value.
builder()->SetExpressionPosition(expr);
FeedbackSlot slot = expr->AssignmentSlot();
switch (assign_type) {
case VARIABLE: {
// TODO(oth): The BuildVariableAssignment() call is hard to reason about.
// Is the value in the accumulator safe? Yes, but scary.
VariableProxy* proxy = expr->target()->AsVariableProxy();
BuildVariableAssignment(proxy->var(), expr->op(), slot,
proxy->hole_check_mode(),
expr->lookup_hoisting_mode());
break;
}
case NAMED_PROPERTY:
builder()->StoreNamedProperty(object, name, feedback_index(slot),
language_mode());
break;
case KEYED_PROPERTY:
builder()->StoreKeyedProperty(object, key, feedback_index(slot),
language_mode());
break;
case NAMED_SUPER_PROPERTY: {
builder()
->StoreAccumulatorInRegister(super_property_args[3])
.CallRuntime(StoreToSuperRuntimeId(), super_property_args);
break;
}
case KEYED_SUPER_PROPERTY: {
builder()
->StoreAccumulatorInRegister(super_property_args[3])
.CallRuntime(StoreKeyedToSuperRuntimeId(), super_property_args);
break;
}
}
}
void BytecodeGenerator::VisitCompoundAssignment(CompoundAssignment* expr) {
VisitAssignment(expr);
}
// Suspends the generator to resume at |suspend_id|, with output stored in the
// accumulator. When the generator is resumed, the sent value is loaded in the
// accumulator.
void BytecodeGenerator::BuildSuspendPoint(int suspend_id) {
RegisterList registers(0, register_allocator()->next_register_index());
// Save context, registers, and state. Then return.
builder()->SuspendGenerator(generator_object(), registers, suspend_id);
builder()->SetReturnPosition(kNoSourcePosition, info()->literal());
builder()->Return(); // Hard return (ignore any finally blocks).
// Upon resume, we continue here.
builder()->Bind(generator_jump_table_, suspend_id);
// Clobbers all registers.
builder()->RestoreGeneratorRegisters(generator_object(), registers);
// Update state to indicate that we have finished resuming. Loop headers
// rely on this.
builder()
->LoadLiteral(Smi::FromInt(JSGeneratorObject::kGeneratorExecuting))
.StoreAccumulatorInRegister(generator_state_);
// When resuming execution of a generator, module or async function, the sent
// value is in the [[input_or_debug_pos]] slot.
builder()->CallRuntime(Runtime::kInlineGeneratorGetInputOrDebugPos,
generator_object());
}
void BytecodeGenerator::VisitYield(Yield* expr) {
builder()->SetExpressionPosition(expr);
VisitForAccumulatorValue(expr->expression());
if (!expr->IsInitialYield()) {
if (IsAsyncGeneratorFunction(function_kind())) {
// AsyncGenerator yields (with the exception of the initial yield)
// delegate work to the AsyncGeneratorYield stub, which Awaits the operand
// and on success, wraps the value in an IteratorResult.
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(3);
builder()
->MoveRegister(generator_object(), args[0]) // generator
.StoreAccumulatorInRegister(args[1]) // value
.LoadBoolean(catch_prediction() != HandlerTable::ASYNC_AWAIT)
.StoreAccumulatorInRegister(args[2]) // is_caught
.CallRuntime(Runtime::kInlineAsyncGeneratorYield, args);
} else {
// Generator yields (with the exception of the initial yield) wrap the
// value into IteratorResult.
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(2);
builder()
->StoreAccumulatorInRegister(args[0]) // value
.LoadFalse()
.StoreAccumulatorInRegister(args[1]) // done
.CallRuntime(Runtime::kInlineCreateIterResultObject, args);
}
}
BuildSuspendPoint(expr->suspend_id());
// At this point, the generator has been resumed, with the received value in
// the accumulator.
// TODO(caitp): remove once yield* desugaring for async generators is handled
// in BytecodeGenerator.
if (expr->on_abrupt_resume() == Yield::kNoControl) {
DCHECK(IsAsyncGeneratorFunction(function_kind()));
return;
}
Register input = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(input).CallRuntime(
Runtime::kInlineGeneratorGetResumeMode, generator_object());
// Now dispatch on resume mode.
STATIC_ASSERT(JSGeneratorObject::kNext + 1 == JSGeneratorObject::kReturn);
BytecodeJumpTable* jump_table =
builder()->AllocateJumpTable(2, JSGeneratorObject::kNext);
builder()->SwitchOnSmiNoFeedback(jump_table);
{
// Resume with throw (switch fallthrough).
// TODO(leszeks): Add a debug-only check that the accumulator is
// JSGeneratorObject::kThrow.
builder()->SetExpressionPosition(expr);
builder()->LoadAccumulatorWithRegister(input);
builder()->Throw();
}
{
// Resume with return.
builder()->Bind(jump_table, JSGeneratorObject::kReturn);
builder()->LoadAccumulatorWithRegister(input);
if (IsAsyncGeneratorFunction(function_kind())) {
execution_control()->AsyncReturnAccumulator();
} else {
execution_control()->ReturnAccumulator();
}
}
{
// Resume with next.
builder()->Bind(jump_table, JSGeneratorObject::kNext);
BuildIncrementBlockCoverageCounterIfEnabled(expr,
SourceRangeKind::kContinuation);
builder()->LoadAccumulatorWithRegister(input);
}
}
// Desugaring of (yield* iterable)
//
// do {
// const kNext = 0;
// const kReturn = 1;
// const kThrow = 2;
//
// let output; // uninitialized
//
// let iterator = GetIterator(iterable);
// let input = undefined;
// let resumeMode = kNext;
//
// while (true) {
// // From the generator to the iterator:
// // Forward input according to resumeMode and obtain output.
// switch (resumeMode) {
// case kNext:
// output = iterator.next(input);
// break;
// case kReturn:
// let iteratorReturn = iterator.return;
// if (IS_NULL_OR_UNDEFINED(iteratorReturn)) return input;
// output = %_Call(iteratorReturn, iterator, input);
// break;
// case kThrow:
// let iteratorThrow = iterator.throw;
// if (IS_NULL_OR_UNDEFINED(iteratorThrow)) {
// let iteratorReturn = iterator.return;
// if (!IS_NULL_OR_UNDEFINED(iteratorReturn)) {
// output = %_Call(iteratorReturn, iterator);
// if (IS_ASYNC_GENERATOR) output = await output;
// if (!IS_RECEIVER(output)) %ThrowIterResultNotAnObject(output);
// }
// throw MakeTypeError(kThrowMethodMissing);
// }
// output = %_Call(iteratorThrow, iterator, input);
// break;
// }
//
// if (IS_ASYNC_GENERATOR) output = await output;
// if (!IS_RECEIVER(output)) %ThrowIterResultNotAnObject(output);
// if (output.done) break;
//
// // From the generator to its user:
// // Forward output, receive new input, and determine resume mode.
// if (IS_ASYNC_GENERATOR) {
// // AsyncGeneratorYield abstract operation awaits the operand before
// // resolving the promise for the current AsyncGeneratorRequest.
// %_AsyncGeneratorYield(output.value)
// }
// input = Suspend(output);
// resumeMode = %GeneratorGetResumeMode();
// }
//
// if (resumeMode === kReturn) {
// return output.value;
// }
// output.value
// }
void BytecodeGenerator::VisitYieldStar(YieldStar* expr) {
Register output = register_allocator()->NewRegister();
Register resume_mode = register_allocator()->NewRegister();
IteratorType iterator_type = IsAsyncGeneratorFunction(function_kind())
? IteratorType::kAsync
: IteratorType::kNormal;
{
RegisterAllocationScope register_scope(this);
RegisterList iterator_and_input = register_allocator()->NewRegisterList(2);
Register iterator = iterator_and_input[0];
BuildGetIterator(expr->expression(), iterator_type,
expr->load_iterable_iterator_slot(),
expr->call_iterable_iterator_slot(),
expr->load_iterable_async_iterator_slot(),
expr->call_iterable_async_iterator_slot());
builder()->StoreAccumulatorInRegister(iterator);
Register input = iterator_and_input[1];
builder()->LoadUndefined().StoreAccumulatorInRegister(input);
builder()
->LoadLiteral(Smi::FromInt(JSGeneratorObject::kNext))
.StoreAccumulatorInRegister(resume_mode);
{
// This loop builder does not construct counters as the loop is not
// visible to the user, and we therefore neither pass the block coverage
// builder nor the expression.
//
// YieldStar in AsyncGenerator functions includes 3 suspend points, rather
// than 1. These are documented in the YieldStar AST node.
LoopBuilder loop(builder(), nullptr, nullptr);
VisitIterationHeader(expr->suspend_id(), expr->suspend_count(), &loop);
{
BytecodeLabels after_switch(zone());
BytecodeJumpTable* switch_jump_table =
builder()->AllocateJumpTable(2, 1);
builder()
->LoadAccumulatorWithRegister(resume_mode)
.SwitchOnSmiNoFeedback(switch_jump_table);
// Fallthrough to default case.
// TODO(tebbi): Add debug code to check that {resume_mode} really is
// {JSGeneratorObject::kNext} in this case.
STATIC_ASSERT(JSGeneratorObject::kNext == 0);
{
RegisterAllocationScope register_scope(this);
// output = iterator.next(input);
Register iterator_next = register_allocator()->NewRegister();
builder()
->LoadNamedProperty(
iterator, ast_string_constants()->next_string(),
feedback_index(expr->load_iterator_next_slot()))
.StoreAccumulatorInRegister(iterator_next)
.CallProperty(iterator_next, iterator_and_input,
feedback_index(expr->call_iterator_next_slot()))
.Jump(after_switch.New());
}
STATIC_ASSERT(JSGeneratorObject::kReturn == 1);
builder()->Bind(switch_jump_table, JSGeneratorObject::kReturn);
{
RegisterAllocationScope register_scope(this);
BytecodeLabels return_input(zone());
// Trigger return from within the inner iterator.
Register iterator_return = register_allocator()->NewRegister();
builder()
->LoadNamedProperty(
iterator, ast_string_constants()->return_string(),
feedback_index(expr->load_iterator_return_slot()))
.JumpIfUndefined(return_input.New())
.JumpIfNull(return_input.New())
.StoreAccumulatorInRegister(iterator_return)
.CallProperty(iterator_return, iterator_and_input,
feedback_index(expr->call_iterator_return_slot1()))
.Jump(after_switch.New());
return_input.Bind(builder());
{
builder()->LoadAccumulatorWithRegister(input);
if (iterator_type == IteratorType::kAsync) {
execution_control()->AsyncReturnAccumulator();
} else {
execution_control()->ReturnAccumulator();
}
}
}
STATIC_ASSERT(JSGeneratorObject::kThrow == 2);
builder()->Bind(switch_jump_table, JSGeneratorObject::kThrow);
{
BytecodeLabels iterator_throw_is_undefined(zone());
{
RegisterAllocationScope register_scope(this);
// If the inner iterator has a throw method, use it to trigger an
// exception inside.
Register iterator_throw = register_allocator()->NewRegister();
builder()
->LoadNamedProperty(
iterator, ast_string_constants()->throw_string(),
feedback_index(expr->load_iterator_throw_slot()))
.JumpIfUndefined(iterator_throw_is_undefined.New())
.JumpIfNull(iterator_throw_is_undefined.New())
.StoreAccumulatorInRegister(iterator_throw);
builder()
->CallProperty(iterator_throw, iterator_and_input,
feedback_index(expr->call_iterator_throw_slot()))
.Jump(after_switch.New());
}
iterator_throw_is_undefined.Bind(builder());
{
RegisterAllocationScope register_scope(this);
BytecodeLabels throw_throw_method_missing(zone());
Register iterator_return = register_allocator()->NewRegister();
// If iterator.throw does not exist, try to use iterator.return to
// inform the iterator that it should stop.
builder()
->LoadNamedProperty(
iterator, ast_string_constants()->return_string(),
feedback_index(expr->load_iterator_return_slot()))
.StoreAccumulatorInRegister(iterator_return);
builder()
->JumpIfUndefined(throw_throw_method_missing.New())
.JumpIfNull(throw_throw_method_missing.New())
.CallProperty(
iterator_return, RegisterList(iterator),
feedback_index(expr->call_iterator_return_slot2()));
if (iterator_type == IteratorType::kAsync) {
// For async generators, await the result of the .return() call.
BuildAwait(expr->await_iterator_close_suspend_id());
builder()->StoreAccumulatorInRegister(output);
}
builder()
->JumpIfJSReceiver(throw_throw_method_missing.New())
.CallRuntime(Runtime::kThrowIteratorResultNotAnObject, output);
throw_throw_method_missing.Bind(builder());
builder()->CallRuntime(Runtime::kThrowThrowMethodMissing);
}
}
after_switch.Bind(builder());
}
if (iterator_type == IteratorType::kAsync) {
// Await the result of the method invocation.
BuildAwait(expr->await_delegated_iterator_output_suspend_id());
}
// Check that output is an object.
BytecodeLabel check_if_done;
builder()
->StoreAccumulatorInRegister(output)
.JumpIfJSReceiver(&check_if_done)
.CallRuntime(Runtime::kThrowIteratorResultNotAnObject, output);
builder()->Bind(&check_if_done);
// Break once output.done is true.
builder()->LoadNamedProperty(
output, ast_string_constants()->done_string(),
feedback_index(expr->load_output_done_slot()));
loop.BreakIfTrue(ToBooleanMode::kConvertToBoolean);
// Suspend the current generator.
if (iterator_type == IteratorType::kNormal) {
builder()->LoadAccumulatorWithRegister(output);
} else {
RegisterAllocationScope register_scope(this);
DCHECK(iterator_type == IteratorType::kAsync);
// If generatorKind is async, perform AsyncGeneratorYield(output.value),
// which will await `output.value` before resolving the current
// AsyncGeneratorRequest's promise.
builder()->LoadNamedProperty(
output, ast_string_constants()->value_string(),
feedback_index(expr->load_output_value_slot()));
RegisterList args = register_allocator()->NewRegisterList(3);
builder()
->MoveRegister(generator_object(), args[0]) // generator
.StoreAccumulatorInRegister(args[1]) // value
.LoadBoolean(catch_prediction() != HandlerTable::ASYNC_AWAIT)
.StoreAccumulatorInRegister(args[2]) // is_caught
.CallRuntime(Runtime::kInlineAsyncGeneratorYield, args);
}
BuildSuspendPoint(expr->suspend_id());
builder()->StoreAccumulatorInRegister(input);
builder()
->CallRuntime(Runtime::kInlineGeneratorGetResumeMode,
generator_object())
.StoreAccumulatorInRegister(resume_mode);
loop.BindContinueTarget();
loop.JumpToHeader(loop_depth_);
}
}
// Decide if we trigger a return or if the yield* expression should just
// produce a value.
BytecodeLabel completion_is_output_value;
Register output_value = register_allocator()->NewRegister();
builder()
->LoadNamedProperty(output, ast_string_constants()->value_string(),
feedback_index(expr->load_output_value_slot()))
.StoreAccumulatorInRegister(output_value)
.LoadLiteral(Smi::FromInt(JSGeneratorObject::kReturn))
.CompareOperation(Token::EQ_STRICT, resume_mode)
.JumpIfFalse(ToBooleanMode::kAlreadyBoolean, &completion_is_output_value)
.LoadAccumulatorWithRegister(output_value);
if (iterator_type == IteratorType::kAsync) {
execution_control()->AsyncReturnAccumulator();
} else {
execution_control()->ReturnAccumulator();
}
builder()->Bind(&completion_is_output_value);
BuildIncrementBlockCoverageCounterIfEnabled(expr,
SourceRangeKind::kContinuation);
builder()->LoadAccumulatorWithRegister(output_value);
}
void BytecodeGenerator::BuildAwait(int suspend_id) {
// Rather than HandlerTable::UNCAUGHT, async functions use
// HandlerTable::ASYNC_AWAIT to communicate that top-level exceptions are
// transformed into promise rejections. This is necessary to prevent emitting
// multiple debug events for the same uncaught exception. There is no point
// in the body of an async function where catch prediction is
// HandlerTable::UNCAUGHT.
DCHECK(catch_prediction() != HandlerTable::UNCAUGHT);
{
// Await(operand) and suspend.
RegisterAllocationScope register_scope(this);
int await_builtin_context_index;
RegisterList args;
if (IsAsyncGeneratorFunction(function_kind())) {
await_builtin_context_index =
catch_prediction() == HandlerTable::ASYNC_AWAIT
? Context::ASYNC_GENERATOR_AWAIT_UNCAUGHT
: Context::ASYNC_GENERATOR_AWAIT_CAUGHT;
args = register_allocator()->NewRegisterList(2);
builder()
->MoveRegister(generator_object(), args[0])
.StoreAccumulatorInRegister(args[1]);
} else {
await_builtin_context_index =
catch_prediction() == HandlerTable::ASYNC_AWAIT
? Context::ASYNC_FUNCTION_AWAIT_UNCAUGHT_INDEX
: Context::ASYNC_FUNCTION_AWAIT_CAUGHT_INDEX;
args = register_allocator()->NewRegisterList(3);
builder()
->MoveRegister(generator_object(), args[0])
.StoreAccumulatorInRegister(args[1]);
// AsyncFunction Await builtins require a 3rd parameter to hold the outer
// promise.
Variable* var_promise = closure_scope()->promise_var();
BuildVariableLoadForAccumulatorValue(var_promise, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
builder()->StoreAccumulatorInRegister(args[2]);
}
builder()->CallJSRuntime(await_builtin_context_index, args);
}
BuildSuspendPoint(suspend_id);
Register input = register_allocator()->NewRegister();
Register resume_mode = register_allocator()->NewRegister();
// Now dispatch on resume mode.
BytecodeLabel resume_next;
builder()
->StoreAccumulatorInRegister(input)
.CallRuntime(Runtime::kInlineGeneratorGetResumeMode, generator_object())
.StoreAccumulatorInRegister(resume_mode)
.LoadLiteral(Smi::FromInt(JSGeneratorObject::kNext))
.CompareOperation(Token::EQ_STRICT, resume_mode)
.JumpIfTrue(ToBooleanMode::kAlreadyBoolean, &resume_next);
// Resume with "throw" completion (rethrow the received value).
// TODO(leszeks): Add a debug-only check that the accumulator is
// JSGeneratorObject::kThrow.
builder()->LoadAccumulatorWithRegister(input).ReThrow();
// Resume with next.
builder()->Bind(&resume_next);
builder()->LoadAccumulatorWithRegister(input);
}
void BytecodeGenerator::VisitAwait(Await* expr) {
builder()->SetExpressionPosition(expr);
VisitForAccumulatorValue(expr->expression());
BuildAwait(expr->suspend_id());
BuildIncrementBlockCoverageCounterIfEnabled(expr,
SourceRangeKind::kContinuation);
}
void BytecodeGenerator::VisitThrow(Throw* expr) {
AllocateBlockCoverageSlotIfEnabled(expr, SourceRangeKind::kContinuation);
VisitForAccumulatorValue(expr->exception());
builder()->SetExpressionPosition(expr);
builder()->Throw();
}
void BytecodeGenerator::VisitPropertyLoad(Register obj, Property* property) {
LhsKind property_kind = Property::GetAssignType(property);
FeedbackSlot slot = property->PropertyFeedbackSlot();
switch (property_kind) {
case VARIABLE:
UNREACHABLE();
case NAMED_PROPERTY: {
builder()->SetExpressionPosition(property);
builder()->LoadNamedProperty(
obj, property->key()->AsLiteral()->AsRawPropertyName(),
feedback_index(slot));
break;
}
case KEYED_PROPERTY: {
VisitForAccumulatorValue(property->key());
builder()->SetExpressionPosition(property);
builder()->LoadKeyedProperty(obj, feedback_index(slot));
break;
}
case NAMED_SUPER_PROPERTY:
VisitNamedSuperPropertyLoad(property, Register::invalid_value());
break;
case KEYED_SUPER_PROPERTY:
VisitKeyedSuperPropertyLoad(property, Register::invalid_value());
break;
}
}
void BytecodeGenerator::VisitPropertyLoadForRegister(Register obj,
Property* expr,
Register destination) {
ValueResultScope result_scope(this);
VisitPropertyLoad(obj, expr);
builder()->StoreAccumulatorInRegister(destination);
}
void BytecodeGenerator::VisitNamedSuperPropertyLoad(Property* property,
Register opt_receiver_out) {
RegisterAllocationScope register_scope(this);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
RegisterList args = register_allocator()->NewRegisterList(3);
VisitForRegisterValue(super_property->this_var(), args[0]);
VisitForRegisterValue(super_property->home_object(), args[1]);
builder()->SetExpressionPosition(property);
builder()
->LoadLiteral(property->key()->AsLiteral()->AsRawPropertyName())
.StoreAccumulatorInRegister(args[2])
.CallRuntime(Runtime::kLoadFromSuper, args);
if (opt_receiver_out.is_valid()) {
builder()->MoveRegister(args[0], opt_receiver_out);
}
}
void BytecodeGenerator::VisitKeyedSuperPropertyLoad(Property* property,
Register opt_receiver_out) {
RegisterAllocationScope register_scope(this);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
RegisterList args = register_allocator()->NewRegisterList(3);
VisitForRegisterValue(super_property->this_var(), args[0]);
VisitForRegisterValue(super_property->home_object(), args[1]);
VisitForRegisterValue(property->key(), args[2]);
builder()->SetExpressionPosition(property);
builder()->CallRuntime(Runtime::kLoadKeyedFromSuper, args);
if (opt_receiver_out.is_valid()) {
builder()->MoveRegister(args[0], opt_receiver_out);
}
}
void BytecodeGenerator::VisitProperty(Property* expr) {
LhsKind property_kind = Property::GetAssignType(expr);
if (property_kind != NAMED_SUPER_PROPERTY &&
property_kind != KEYED_SUPER_PROPERTY) {
Register obj = VisitForRegisterValue(expr->obj());
VisitPropertyLoad(obj, expr);
} else {
VisitPropertyLoad(Register::invalid_value(), expr);
}
}
void BytecodeGenerator::VisitArguments(ZoneList<Expression*>* args,
RegisterList* arg_regs) {
// Visit arguments.
for (int i = 0; i < static_cast<int>(args->length()); i++) {
VisitAndPushIntoRegisterList(args->at(i), arg_regs);
}
}
void BytecodeGenerator::VisitCall(Call* expr) {
Expression* callee_expr = expr->expression();
Call::CallType call_type = expr->GetCallType();
if (call_type == Call::SUPER_CALL) {
return VisitCallSuper(expr);
}
// Grow the args list as we visit receiver / arguments to avoid allocating all
// the registers up-front. Otherwise these registers are unavailable during
// receiver / argument visiting and we can end up with memory leaks due to
// registers keeping objects alive.
Register callee = register_allocator()->NewRegister();
RegisterList args = register_allocator()->NewGrowableRegisterList();
bool implicit_undefined_receiver = false;
// When a call contains a spread, a Call AST node is only created if there is
// exactly one spread, and it is the last argument.
bool is_spread_call = expr->only_last_arg_is_spread();
// TODO(petermarshall): We have a lot of call bytecodes that are very similar,
// see if we can reduce the number by adding a separate argument which
// specifies the call type (e.g., property, spread, tailcall, etc.).
// Prepare the callee and the receiver to the function call. This depends on
// the semantics of the underlying call type.
switch (call_type) {
case Call::NAMED_PROPERTY_CALL:
case Call::KEYED_PROPERTY_CALL: {
Property* property = callee_expr->AsProperty();
VisitAndPushIntoRegisterList(property->obj(), &args);
VisitPropertyLoadForRegister(args.last_register(), property, callee);
break;
}
case Call::GLOBAL_CALL: {
// Receiver is undefined for global calls.
if (!is_spread_call) {
implicit_undefined_receiver = true;
} else {
// TODO(leszeks): There's no special bytecode for tail calls or spread
// calls with an undefined receiver, so just push undefined ourselves.
BuildPushUndefinedIntoRegisterList(&args);
}
// Load callee as a global variable.
VariableProxy* proxy = callee_expr->AsVariableProxy();
BuildVariableLoadForAccumulatorValue(proxy->var(),
proxy->VariableFeedbackSlot(),
proxy->hole_check_mode());
builder()->StoreAccumulatorInRegister(callee);
break;
}
case Call::WITH_CALL: {
Register receiver = register_allocator()->GrowRegisterList(&args);
DCHECK(callee_expr->AsVariableProxy()->var()->IsLookupSlot());
{
RegisterAllocationScope inner_register_scope(this);
Register name = register_allocator()->NewRegister();
// Call %LoadLookupSlotForCall to get the callee and receiver.
DCHECK(Register::AreContiguous(callee, receiver));
RegisterList result_pair(callee.index(), 2);
USE(receiver);
Variable* variable = callee_expr->AsVariableProxy()->var();
builder()
->LoadLiteral(variable->raw_name())
.StoreAccumulatorInRegister(name)
.CallRuntimeForPair(Runtime::kLoadLookupSlotForCall, name,
result_pair);
}
break;
}
case Call::OTHER_CALL: {
// Receiver is undefined for other calls.
if (!is_spread_call) {
implicit_undefined_receiver = true;
} else {
// TODO(leszeks): There's no special bytecode for tail calls or spread
// calls with an undefined receiver, so just push undefined ourselves.
BuildPushUndefinedIntoRegisterList(&args);
}
VisitForRegisterValue(callee_expr, callee);
break;
}
case Call::NAMED_SUPER_PROPERTY_CALL: {
Register receiver = register_allocator()->GrowRegisterList(&args);
Property* property = callee_expr->AsProperty();
VisitNamedSuperPropertyLoad(property, receiver);
builder()->StoreAccumulatorInRegister(callee);
break;
}
case Call::KEYED_SUPER_PROPERTY_CALL: {
Register receiver = register_allocator()->GrowRegisterList(&args);
Property* property = callee_expr->AsProperty();
VisitKeyedSuperPropertyLoad(property, receiver);
builder()->StoreAccumulatorInRegister(callee);
break;
}
case Call::SUPER_CALL:
UNREACHABLE();
break;
}
// Evaluate all arguments to the function call and store in sequential args
// registers.
VisitArguments(expr->arguments(), &args);
int reciever_arg_count = implicit_undefined_receiver ? 0 : 1;
CHECK_EQ(reciever_arg_count + expr->arguments()->length(),
args.register_count());
// Resolve callee for a potential direct eval call. This block will mutate the
// callee value.
if (expr->is_possibly_eval() && expr->arguments()->length() > 0) {
RegisterAllocationScope inner_register_scope(this);
// Set up arguments for ResolvePossiblyDirectEval by copying callee, source
// strings and function closure, and loading language and
// position.
Register first_arg = args[reciever_arg_count];
RegisterList runtime_call_args = register_allocator()->NewRegisterList(6);
builder()
->MoveRegister(callee, runtime_call_args[0])
.MoveRegister(first_arg, runtime_call_args[1])
.MoveRegister(Register::function_closure(), runtime_call_args[2])
.LoadLiteral(Smi::FromInt(language_mode()))
.StoreAccumulatorInRegister(runtime_call_args[3])
.LoadLiteral(Smi::FromInt(current_scope()->start_position()))
.StoreAccumulatorInRegister(runtime_call_args[4])
.LoadLiteral(Smi::FromInt(expr->position()))
.StoreAccumulatorInRegister(runtime_call_args[5]);
// Call ResolvePossiblyDirectEval and modify the callee.
builder()
->CallRuntime(Runtime::kResolvePossiblyDirectEval, runtime_call_args)
.StoreAccumulatorInRegister(callee);
}
builder()->SetExpressionPosition(expr);
int const feedback_slot_index = feedback_index(expr->CallFeedbackICSlot());
if (is_spread_call) {
DCHECK(!implicit_undefined_receiver);
builder()->CallWithSpread(callee, args, feedback_slot_index);
} else if (call_type == Call::NAMED_PROPERTY_CALL ||
call_type == Call::KEYED_PROPERTY_CALL) {
DCHECK(!implicit_undefined_receiver);
builder()->CallProperty(callee, args, feedback_slot_index);
} else if (implicit_undefined_receiver) {
builder()->CallUndefinedReceiver(callee, args, feedback_slot_index);
} else {
builder()->CallAnyReceiver(callee, args, feedback_slot_index);
}
}
void BytecodeGenerator::VisitCallSuper(Call* expr) {
RegisterAllocationScope register_scope(this);
SuperCallReference* super = expr->expression()->AsSuperCallReference();
// Prepare the constructor to the super call.
VisitForAccumulatorValue(super->this_function_var());
Register constructor = register_allocator()->NewRegister();
builder()->GetSuperConstructor(constructor);
ZoneList<Expression*>* args = expr->arguments();
RegisterList args_regs = register_allocator()->NewGrowableRegisterList();
VisitArguments(args, &args_regs);
// The new target is loaded into the accumulator from the
// {new.target} variable.
VisitForAccumulatorValue(super->new_target_var());
builder()->SetExpressionPosition(expr);
// When a super call contains a spread, a CallSuper AST node is only created
// if there is exactly one spread, and it is the last argument.
int const feedback_slot_index = feedback_index(expr->CallFeedbackICSlot());
if (expr->only_last_arg_is_spread()) {
builder()->ConstructWithSpread(constructor, args_regs, feedback_slot_index);
} else {
// Call construct.
// TODO(turbofan): For now we do gather feedback on super constructor
// calls, utilizing the existing machinery to inline the actual call
// target and the JSCreate for the implicit receiver allocation. This
// is not an ideal solution for super constructor calls, but it gets
// the job done for now. In the long run we might want to revisit this
// and come up with a better way.
builder()->Construct(constructor, args_regs, feedback_slot_index);
}
}
void BytecodeGenerator::VisitCallNew(CallNew* expr) {
Register constructor = VisitForRegisterValue(expr->expression());
RegisterList args = register_allocator()->NewGrowableRegisterList();
VisitArguments(expr->arguments(), &args);
// The accumulator holds new target which is the same as the
// constructor for CallNew.
builder()->SetExpressionPosition(expr);
builder()->LoadAccumulatorWithRegister(constructor);
int const feedback_slot_index = feedback_index(expr->CallNewFeedbackSlot());
if (expr->only_last_arg_is_spread()) {
builder()->ConstructWithSpread(constructor, args, feedback_slot_index);
} else {
builder()->Construct(constructor, args, feedback_slot_index);
}
}
void BytecodeGenerator::VisitCallRuntime(CallRuntime* expr) {
if (expr->is_jsruntime()) {
RegisterList args = register_allocator()->NewGrowableRegisterList();
// Allocate a register for the receiver and load it with undefined.
// TODO(leszeks): If CallJSRuntime always has an undefined receiver, use the
// same mechanism as CallUndefinedReceiver.
BuildPushUndefinedIntoRegisterList(&args);
VisitArguments(expr->arguments(), &args);
builder()->CallJSRuntime(expr->context_index(), args);
} else {
// Evaluate all arguments to the runtime call.
RegisterList args = register_allocator()->NewGrowableRegisterList();
VisitArguments(expr->arguments(), &args);
Runtime::FunctionId function_id = expr->function()->function_id;
builder()->CallRuntime(function_id, args);
}
}
void BytecodeGenerator::VisitVoid(UnaryOperation* expr) {
VisitForEffect(expr->expression());
builder()->LoadUndefined();
}
void BytecodeGenerator::VisitForTypeOfValue(Expression* expr) {
if (expr->IsVariableProxy()) {
// Typeof does not throw a reference error on global variables, hence we
// perform a non-contextual load in case the operand is a variable proxy.
VariableProxy* proxy = expr->AsVariableProxy();
BuildVariableLoadForAccumulatorValue(
proxy->var(), proxy->VariableFeedbackSlot(), proxy->hole_check_mode(),
INSIDE_TYPEOF);
} else {
VisitForAccumulatorValue(expr);
}
}
void BytecodeGenerator::VisitTypeOf(UnaryOperation* expr) {
VisitForTypeOfValue(expr->expression());
builder()->TypeOf();
}
void BytecodeGenerator::VisitNot(UnaryOperation* expr) {
if (execution_result()->IsEffect()) {
VisitForEffect(expr->expression());
} else if (execution_result()->IsTest()) {
// No actual logical negation happening, we just swap the control flow, by
// swapping the target labels and the fallthrough branch, and visit in the
// same test result context.
TestResultScope* test_result = execution_result()->AsTest();
test_result->InvertControlFlow();
VisitInSameTestExecutionScope(expr->expression());
} else {
TypeHint type_hint = VisitForAccumulatorValue(expr->expression());
builder()->LogicalNot(ToBooleanModeFromTypeHint(type_hint));
// Always returns a boolean value.
execution_result()->SetResultIsBoolean();
}
}
void BytecodeGenerator::VisitUnaryOperation(UnaryOperation* expr) {
switch (expr->op()) {
case Token::Value::NOT:
VisitNot(expr);
break;
case Token::Value::TYPEOF:
VisitTypeOf(expr);
break;
case Token::Value::VOID:
VisitVoid(expr);
break;
case Token::Value::DELETE:
VisitDelete(expr);
break;
case Token::Value::BIT_NOT:
case Token::Value::ADD:
case Token::Value::SUB:
// These operators are converted to an equivalent binary operators in
// the parser. These operators are not expected to be visited here.
UNREACHABLE();
default:
UNREACHABLE();
}
}
void BytecodeGenerator::VisitDelete(UnaryOperation* expr) {
if (expr->expression()->IsProperty()) {
// Delete of an object property is allowed both in sloppy
// and strict modes.
Property* property = expr->expression()->AsProperty();
Register object = VisitForRegisterValue(property->obj());
VisitForAccumulatorValue(property->key());
builder()->Delete(object, language_mode());
} else if (expr->expression()->IsVariableProxy()) {
// Delete of an unqualified identifier is allowed in sloppy mode but is
// not allowed in strict mode. Deleting 'this' is allowed in both modes.
VariableProxy* proxy = expr->expression()->AsVariableProxy();
Variable* variable = proxy->var();
DCHECK(is_sloppy(language_mode()) || variable->is_this());
switch (variable->location()) {
case VariableLocation::UNALLOCATED: {
// Global var, let, const or variables not explicitly declared.
Register native_context = register_allocator()->NewRegister();
Register global_object = register_allocator()->NewRegister();
builder()
->LoadContextSlot(execution_context()->reg(),
Context::NATIVE_CONTEXT_INDEX, 0,
BytecodeArrayBuilder::kImmutableSlot)
.StoreAccumulatorInRegister(native_context)
.LoadContextSlot(native_context, Context::EXTENSION_INDEX, 0,
BytecodeArrayBuilder::kImmutableSlot)
.StoreAccumulatorInRegister(global_object)
.LoadLiteral(variable->raw_name())
.Delete(global_object, language_mode());
break;
}
case VariableLocation::PARAMETER:
case VariableLocation::LOCAL:
case VariableLocation::CONTEXT: {
// Deleting local var/let/const, context variables, and arguments
// does not have any effect.
if (variable->is_this()) {
builder()->LoadTrue();
} else {
builder()->LoadFalse();
}
break;
}
case VariableLocation::LOOKUP: {
Register name_reg = register_allocator()->NewRegister();
builder()
->LoadLiteral(variable->raw_name())
.StoreAccumulatorInRegister(name_reg)
.CallRuntime(Runtime::kDeleteLookupSlot, name_reg);
break;
}
default:
UNREACHABLE();
}
} else {
// Delete of an unresolvable reference returns true.
VisitForEffect(expr->expression());
builder()->LoadTrue();
}
}
void BytecodeGenerator::VisitCountOperation(CountOperation* expr) {
DCHECK(expr->expression()->IsValidReferenceExpressionOrThis());
// Left-hand side can only be a property, a global or a variable slot.
Property* property = expr->expression()->AsProperty();
LhsKind assign_type = Property::GetAssignType(property);
bool is_postfix = expr->is_postfix() && !execution_result()->IsEffect();
// Evaluate LHS expression and get old value.
Register object, key, old_value;
RegisterList super_property_args;
const AstRawString* name;
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->expression()->AsVariableProxy();
BuildVariableLoadForAccumulatorValue(proxy->var(),
proxy->VariableFeedbackSlot(),
proxy->hole_check_mode());
break;
}
case NAMED_PROPERTY: {
FeedbackSlot slot = property->PropertyFeedbackSlot();
object = VisitForRegisterValue(property->obj());
name = property->key()->AsLiteral()->AsRawPropertyName();
builder()->LoadNamedProperty(object, name, feedback_index(slot));
break;
}
case KEYED_PROPERTY: {
FeedbackSlot slot = property->PropertyFeedbackSlot();
object = VisitForRegisterValue(property->obj());
// Use visit for accumulator here since we need the key in the accumulator
// for the LoadKeyedProperty.
key = register_allocator()->NewRegister();
VisitForAccumulatorValue(property->key());
builder()->StoreAccumulatorInRegister(key).LoadKeyedProperty(
object, feedback_index(slot));
break;
}
case NAMED_SUPER_PROPERTY: {
super_property_args = register_allocator()->NewRegisterList(4);
RegisterList load_super_args = super_property_args.Truncate(3);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), load_super_args[0]);
VisitForRegisterValue(super_property->home_object(), load_super_args[1]);
builder()
->LoadLiteral(property->key()->AsLiteral()->AsRawPropertyName())
.StoreAccumulatorInRegister(load_super_args[2])
.CallRuntime(Runtime::kLoadFromSuper, load_super_args);
break;
}
case KEYED_SUPER_PROPERTY: {
super_property_args = register_allocator()->NewRegisterList(4);
RegisterList load_super_args = super_property_args.Truncate(3);
SuperPropertyReference* super_property =
property->obj()->AsSuperPropertyReference();
VisitForRegisterValue(super_property->this_var(), load_super_args[0]);
VisitForRegisterValue(super_property->home_object(), load_super_args[1]);
VisitForRegisterValue(property->key(), load_super_args[2]);
builder()->CallRuntime(Runtime::kLoadKeyedFromSuper, load_super_args);
break;
}
}
// Save result for postfix expressions.
FeedbackSlot count_slot = expr->CountBinaryOpFeedbackSlot();
if (is_postfix) {
// Convert old value into a number before saving it.
old_value = register_allocator()->NewRegister();
// TODO(ignition): Think about adding proper PostInc/PostDec bytecodes
// instead of this ToNumber + Inc/Dec dance.
builder()
->ToNumber(old_value, feedback_index(count_slot))
.LoadAccumulatorWithRegister(old_value);
}
// Perform +1/-1 operation.
builder()->CountOperation(expr->binary_op(), feedback_index(count_slot));
// Store the value.
builder()->SetExpressionPosition(expr);
FeedbackSlot feedback_slot = expr->CountSlot();
switch (assign_type) {
case VARIABLE: {
VariableProxy* proxy = expr->expression()->AsVariableProxy();
BuildVariableAssignment(proxy->var(), expr->op(), feedback_slot,
proxy->hole_check_mode());
break;
}
case NAMED_PROPERTY: {
builder()->StoreNamedProperty(object, name, feedback_index(feedback_slot),
language_mode());
break;
}
case KEYED_PROPERTY: {
builder()->StoreKeyedProperty(object, key, feedback_index(feedback_slot),
language_mode());
break;
}
case NAMED_SUPER_PROPERTY: {
builder()
->StoreAccumulatorInRegister(super_property_args[3])
.CallRuntime(StoreToSuperRuntimeId(), super_property_args);
break;
}
case KEYED_SUPER_PROPERTY: {
builder()
->StoreAccumulatorInRegister(super_property_args[3])
.CallRuntime(StoreKeyedToSuperRuntimeId(), super_property_args);
break;
}
}
// Restore old value for postfix expressions.
if (is_postfix) {
builder()->LoadAccumulatorWithRegister(old_value);
}
}
void BytecodeGenerator::VisitBinaryOperation(BinaryOperation* binop) {
switch (binop->op()) {
case Token::COMMA:
VisitCommaExpression(binop);
break;
case Token::OR:
VisitLogicalOrExpression(binop);
break;
case Token::AND:
VisitLogicalAndExpression(binop);
break;
default:
VisitArithmeticExpression(binop);
break;
}
}
void BytecodeGenerator::BuildLiteralCompareNil(Token::Value op, NilValue nil) {
if (execution_result()->IsTest()) {
TestResultScope* test_result = execution_result()->AsTest();
switch (test_result->fallthrough()) {
case TestFallthrough::kThen:
builder()->JumpIfNotNil(test_result->NewElseLabel(), op, nil);
break;
case TestFallthrough::kElse:
builder()->JumpIfNil(test_result->NewThenLabel(), op, nil);
break;
case TestFallthrough::kNone:
builder()
->JumpIfNil(test_result->NewThenLabel(), op, nil)
.Jump(test_result->NewElseLabel());
}
test_result->SetResultConsumedByTest();
} else {
builder()->CompareNil(op, nil);
}
}
void BytecodeGenerator::VisitCompareOperation(CompareOperation* expr) {
Expression* sub_expr;
Literal* literal;
if (expr->IsLiteralCompareTypeof(&sub_expr, &literal)) {
// Emit a fast literal comparion for expressions of the form:
// typeof(x) === 'string'.
VisitForTypeOfValue(sub_expr);
builder()->SetExpressionPosition(expr);
TestTypeOfFlags::LiteralFlag literal_flag =
TestTypeOfFlags::GetFlagForLiteral(ast_string_constants(), literal);
if (literal_flag == TestTypeOfFlags::LiteralFlag::kOther) {
builder()->LoadFalse();
} else {
builder()->CompareTypeOf(literal_flag);
}
} else if (expr->IsLiteralCompareUndefined(&sub_expr)) {
VisitForAccumulatorValue(sub_expr);
builder()->SetExpressionPosition(expr);
BuildLiteralCompareNil(expr->op(), kUndefinedValue);
} else if (expr->IsLiteralCompareNull(&sub_expr)) {
VisitForAccumulatorValue(sub_expr);
builder()->SetExpressionPosition(expr);
BuildLiteralCompareNil(expr->op(), kNullValue);
} else {
Register lhs = VisitForRegisterValue(expr->left());
VisitForAccumulatorValue(expr->right());
builder()->SetExpressionPosition(expr);
FeedbackSlot slot = expr->CompareOperationFeedbackSlot();
if (slot.IsInvalid()) {
builder()->CompareOperation(expr->op(), lhs);
} else {
builder()->CompareOperation(expr->op(), lhs, feedback_index(slot));
}
}
// Always returns a boolean value.
execution_result()->SetResultIsBoolean();
}
void BytecodeGenerator::VisitArithmeticExpression(BinaryOperation* expr) {
// TODO(rmcilroy): Special case "x * 1.0" and "x * -1" which are generated for
// +x and -x by the parser.
FeedbackSlot slot = expr->BinaryOperationFeedbackSlot();
Expression* subexpr;
Smi* literal;
if (expr->IsSmiLiteralOperation(&subexpr, &literal)) {
VisitForAccumulatorValue(subexpr);
builder()->SetExpressionPosition(expr);
builder()->BinaryOperationSmiLiteral(expr->op(), literal,
feedback_index(slot));
} else {
Register lhs = VisitForRegisterValue(expr->left());
VisitForAccumulatorValue(expr->right());
builder()->SetExpressionPosition(expr);
builder()->BinaryOperation(expr->op(), lhs, feedback_index(slot));
}
}
void BytecodeGenerator::VisitSpread(Spread* expr) { Visit(expr->expression()); }
void BytecodeGenerator::VisitEmptyParentheses(EmptyParentheses* expr) {
UNREACHABLE();
}
void BytecodeGenerator::VisitImportCallExpression(ImportCallExpression* expr) {
RegisterList args = register_allocator()->NewRegisterList(2);
VisitForRegisterValue(expr->argument(), args[1]);
builder()
->MoveRegister(Register::function_closure(), args[0])
.CallRuntime(Runtime::kDynamicImportCall, args);
}
void BytecodeGenerator::BuildGetIterator(Expression* iterable,
IteratorType hint,
FeedbackSlot load_slot,
FeedbackSlot call_slot,
FeedbackSlot async_load_slot,
FeedbackSlot async_call_slot) {
RegisterList args = register_allocator()->NewRegisterList(1);
Register method = register_allocator()->NewRegister();
Register obj = args[0];
VisitForAccumulatorValue(iterable);
if (hint == IteratorType::kAsync) {
// Set method to GetMethod(obj, @@asyncIterator)
builder()->StoreAccumulatorInRegister(obj).LoadAsyncIteratorProperty(
obj, feedback_index(async_load_slot));
BytecodeLabel async_iterator_undefined, async_iterator_null, done;
// TODO(ignition): Add a single opcode for JumpIfNullOrUndefined
builder()->JumpIfUndefined(&async_iterator_undefined);
builder()->JumpIfNull(&async_iterator_null);
// Let iterator be Call(method, obj)
builder()->StoreAccumulatorInRegister(method).CallProperty(
method, args, feedback_index(async_call_slot));
// If Type(iterator) is not Object, throw a TypeError exception.
builder()->JumpIfJSReceiver(&done);
builder()->CallRuntime(Runtime::kThrowSymbolAsyncIteratorInvalid);
builder()->Bind(&async_iterator_undefined);
builder()->Bind(&async_iterator_null);
// If method is undefined,
// Let syncMethod be GetMethod(obj, @@iterator)
builder()
->LoadIteratorProperty(obj, feedback_index(load_slot))
.StoreAccumulatorInRegister(method);
// Let syncIterator be Call(syncMethod, obj)
builder()->CallProperty(method, args, feedback_index(call_slot));
// Return CreateAsyncFromSyncIterator(syncIterator)
// alias `method` register as it's no longer used
Register sync_iter = method;
builder()->StoreAccumulatorInRegister(sync_iter).CallRuntime(
Runtime::kInlineCreateAsyncFromSyncIterator, sync_iter);
builder()->Bind(&done);
} else {
// Let method be GetMethod(obj, @@iterator).
builder()
->StoreAccumulatorInRegister(obj)
.LoadIteratorProperty(obj, feedback_index(load_slot))
.StoreAccumulatorInRegister(method);
// Let iterator be Call(method, obj).
builder()->CallProperty(method, args, feedback_index(call_slot));
// If Type(iterator) is not Object, throw a TypeError exception.
BytecodeLabel no_type_error;
builder()->JumpIfJSReceiver(&no_type_error);
builder()->CallRuntime(Runtime::kThrowSymbolIteratorInvalid);
builder()->Bind(&no_type_error);
}
}
void BytecodeGenerator::VisitGetIterator(GetIterator* expr) {
builder()->SetExpressionPosition(expr);
BuildGetIterator(expr->iterable(), expr->hint(),
expr->IteratorPropertyFeedbackSlot(),
expr->IteratorCallFeedbackSlot(),
expr->AsyncIteratorPropertyFeedbackSlot(),
expr->AsyncIteratorCallFeedbackSlot());
}
void BytecodeGenerator::VisitThisFunction(ThisFunction* expr) {
builder()->LoadAccumulatorWithRegister(Register::function_closure());
}
void BytecodeGenerator::VisitSuperCallReference(SuperCallReference* expr) {
// Handled by VisitCall().
UNREACHABLE();
}
void BytecodeGenerator::VisitSuperPropertyReference(
SuperPropertyReference* expr) {
builder()->CallRuntime(Runtime::kThrowUnsupportedSuperError);
}
void BytecodeGenerator::VisitCommaExpression(BinaryOperation* binop) {
VisitForEffect(binop->left());
Visit(binop->right());
}
void BytecodeGenerator::BuildLogicalTest(Token::Value token, Expression* left,
Expression* right) {
DCHECK(token == Token::OR || token == Token::AND);
TestResultScope* test_result = execution_result()->AsTest();
BytecodeLabels* then_labels = test_result->then_labels();
BytecodeLabels* else_labels = test_result->else_labels();
TestFallthrough fallthrough = test_result->fallthrough();
{
// Visit the left side using current TestResultScope.
BytecodeLabels test_right(zone());
if (token == Token::OR) {
test_result->set_fallthrough(TestFallthrough::kElse);
test_result->set_else_labels(&test_right);
} else {
DCHECK_EQ(Token::AND, token);
test_result->set_fallthrough(TestFallthrough::kThen);
test_result->set_then_labels(&test_right);
}
VisitInSameTestExecutionScope(left);
test_right.Bind(builder());
}
// Visit the right side in a new TestResultScope.
VisitForTest(right, then_labels, else_labels, fallthrough);
}
void BytecodeGenerator::VisitLogicalOrExpression(BinaryOperation* binop) {
Expression* left = binop->left();
Expression* right = binop->right();
if (execution_result()->IsTest()) {
TestResultScope* test_result = execution_result()->AsTest();
if (left->ToBooleanIsTrue()) {
builder()->Jump(test_result->NewThenLabel());
} else if (left->ToBooleanIsFalse() && right->ToBooleanIsFalse()) {
builder()->Jump(test_result->NewElseLabel());
} else {
BuildLogicalTest(Token::OR, left, right);
}
test_result->SetResultConsumedByTest();
} else {
if (left->ToBooleanIsTrue()) {
VisitForAccumulatorValue(left);
} else if (left->ToBooleanIsFalse()) {
VisitForAccumulatorValue(right);
} else {
BytecodeLabel end_label;
TypeHint type_hint = VisitForAccumulatorValue(left);
builder()->JumpIfTrue(ToBooleanModeFromTypeHint(type_hint), &end_label);
VisitForAccumulatorValue(right);
builder()->Bind(&end_label);
}
}
}
void BytecodeGenerator::VisitLogicalAndExpression(BinaryOperation* binop) {
Expression* left = binop->left();
Expression* right = binop->right();
if (execution_result()->IsTest()) {
TestResultScope* test_result = execution_result()->AsTest();
if (left->ToBooleanIsFalse()) {
builder()->Jump(test_result->NewElseLabel());
} else if (left->ToBooleanIsTrue() && right->ToBooleanIsTrue()) {
builder()->Jump(test_result->NewThenLabel());
} else {
BuildLogicalTest(Token::AND, left, right);
}
test_result->SetResultConsumedByTest();
} else {
if (left->ToBooleanIsFalse()) {
VisitForAccumulatorValue(left);
} else if (left->ToBooleanIsTrue()) {
VisitForAccumulatorValue(right);
} else {
BytecodeLabel end_label;
TypeHint type_hint = VisitForAccumulatorValue(left);
builder()->JumpIfFalse(ToBooleanModeFromTypeHint(type_hint), &end_label);
VisitForAccumulatorValue(right);
builder()->Bind(&end_label);
}
}
}
void BytecodeGenerator::VisitRewritableExpression(RewritableExpression* expr) {
Visit(expr->expression());
}
void BytecodeGenerator::BuildNewLocalActivationContext() {
ValueResultScope value_execution_result(this);
Scope* scope = closure_scope();
// Create the appropriate context.
if (scope->is_script_scope()) {
RegisterList args = register_allocator()->NewRegisterList(2);
builder()
->LoadAccumulatorWithRegister(Register::function_closure())
.StoreAccumulatorInRegister(args[0])
.LoadLiteral(scope)
.StoreAccumulatorInRegister(args[1])
.CallRuntime(Runtime::kNewScriptContext, args);
} else if (scope->is_module_scope()) {
// We don't need to do anything for the outer script scope.
DCHECK(scope->outer_scope()->is_script_scope());
// A JSFunction representing a module is called with the module object as
// its sole argument, which we pass on to PushModuleContext.
RegisterList args = register_allocator()->NewRegisterList(3);
builder()
->MoveRegister(builder()->Parameter(0), args[0])
.LoadAccumulatorWithRegister(Register::function_closure())
.StoreAccumulatorInRegister(args[1])
.LoadLiteral(scope)
.StoreAccumulatorInRegister(args[2])
.CallRuntime(Runtime::kPushModuleContext, args);
} else {
DCHECK(scope->is_function_scope() || scope->is_eval_scope());
int slot_count = scope->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
if (slot_count <= ConstructorBuiltins::MaximumFunctionContextSlots()) {
switch (scope->scope_type()) {
case EVAL_SCOPE:
builder()->CreateEvalContext(slot_count);
break;
case FUNCTION_SCOPE:
builder()->CreateFunctionContext(slot_count);
break;
default:
UNREACHABLE();
}
} else {
RegisterList args = register_allocator()->NewRegisterList(2);
builder()
->MoveRegister(Register::function_closure(), args[0])
.LoadLiteral(Smi::FromInt(scope->scope_type()))
.StoreAccumulatorInRegister(args[1])
.CallRuntime(Runtime::kNewFunctionContext, args);
}
}
}
void BytecodeGenerator::BuildLocalActivationContextInitialization() {
DeclarationScope* scope = closure_scope();
if (scope->has_this_declaration() && scope->receiver()->IsContextSlot()) {
Variable* variable = scope->receiver();
Register receiver(builder()->Receiver());
// Context variable (at bottom of the context chain).
DCHECK_EQ(0, scope->ContextChainLength(variable->scope()));
builder()->LoadAccumulatorWithRegister(receiver).StoreContextSlot(
execution_context()->reg(), variable->index(), 0);
}
// Copy parameters into context if necessary.
int num_parameters = scope->num_parameters();
for (int i = 0; i < num_parameters; i++) {
Variable* variable = scope->parameter(i);
if (!variable->IsContextSlot()) continue;
Register parameter(builder()->Parameter(i));
// Context variable (at bottom of the context chain).
DCHECK_EQ(0, scope->ContextChainLength(variable->scope()));
builder()->LoadAccumulatorWithRegister(parameter).StoreContextSlot(
execution_context()->reg(), variable->index(), 0);
}
}
void BytecodeGenerator::BuildNewLocalBlockContext(Scope* scope) {
ValueResultScope value_execution_result(this);
DCHECK(scope->is_block_scope());
VisitFunctionClosureForContext();
builder()->CreateBlockContext(scope);
}
void BytecodeGenerator::BuildNewLocalWithContext(Scope* scope) {
ValueResultScope value_execution_result(this);
Register extension_object = register_allocator()->NewRegister();
builder()->ToObject(extension_object);
VisitFunctionClosureForContext();
builder()->CreateWithContext(extension_object, scope);
}
void BytecodeGenerator::BuildNewLocalCatchContext(Scope* scope) {
ValueResultScope value_execution_result(this);
DCHECK(scope->catch_variable()->IsContextSlot());
Register exception = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(exception);
VisitFunctionClosureForContext();
builder()->CreateCatchContext(exception, scope->catch_variable()->raw_name(),
scope);
}
void BytecodeGenerator::VisitObjectLiteralAccessor(
Register home_object, ObjectLiteralProperty* property, Register value_out) {
if (property == nullptr) {
builder()->LoadNull().StoreAccumulatorInRegister(value_out);
} else {
VisitForRegisterValue(property->value(), value_out);
VisitSetHomeObject(value_out, home_object, property);
}
}
void BytecodeGenerator::VisitSetHomeObject(Register value, Register home_object,
LiteralProperty* property,
int slot_number) {
Expression* expr = property->value();
if (FunctionLiteral::NeedsHomeObject(expr)) {
FeedbackSlot slot = property->GetSlot(slot_number);
builder()
->LoadAccumulatorWithRegister(home_object)
.StoreHomeObjectProperty(value, feedback_index(slot), language_mode());
}
}
void BytecodeGenerator::VisitArgumentsObject(Variable* variable) {
if (variable == nullptr) return;
DCHECK(variable->IsContextSlot() || variable->IsStackAllocated());
// Allocate and initialize a new arguments object and assign to the
// {arguments} variable.
CreateArgumentsType type =
is_strict(language_mode()) || !info()->has_simple_parameters()
? CreateArgumentsType::kUnmappedArguments
: CreateArgumentsType::kMappedArguments;
builder()->CreateArguments(type);
BuildVariableAssignment(variable, Token::ASSIGN, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
void BytecodeGenerator::VisitRestArgumentsArray(Variable* rest) {
if (rest == nullptr) return;
// Allocate and initialize a new rest parameter and assign to the {rest}
// variable.
builder()->CreateArguments(CreateArgumentsType::kRestParameter);
DCHECK(rest->IsContextSlot() || rest->IsStackAllocated());
BuildVariableAssignment(rest, Token::ASSIGN, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
void BytecodeGenerator::VisitThisFunctionVariable(Variable* variable) {
if (variable == nullptr) return;
// Store the closure we were called with in the given variable.
builder()->LoadAccumulatorWithRegister(Register::function_closure());
BuildVariableAssignment(variable, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
void BytecodeGenerator::VisitNewTargetVariable(Variable* variable) {
if (variable == nullptr) return;
// The generator resume trampoline abuses the new.target register
// to pass in the generator object. In ordinary calls, new.target is always
// undefined because generator functions are non-constructible, so don't
// assign anything to the new.target variable.
if (info()->literal()->CanSuspend()) return;
if (variable->location() == VariableLocation::LOCAL) {
// The new.target register was already assigned by entry trampoline.
DCHECK_EQ(incoming_new_target_or_generator_.index(),
GetRegisterForLocalVariable(variable).index());
return;
}
// Store the new target we were called with in the given variable.
builder()->LoadAccumulatorWithRegister(incoming_new_target_or_generator_);
BuildVariableAssignment(variable, Token::INIT, FeedbackSlot::Invalid(),
HoleCheckMode::kElided);
}
void BytecodeGenerator::BuildGeneratorObjectVariableInitialization() {
DCHECK(IsResumableFunction(info()->literal()->kind()));
Variable* generator_object_var = closure_scope()->generator_object_var();
RegisterAllocationScope register_scope(this);
RegisterList args = register_allocator()->NewRegisterList(2);
builder()
->MoveRegister(Register::function_closure(), args[0])
.MoveRegister(builder()->Receiver(), args[1])
.CallRuntime(Runtime::kInlineCreateJSGeneratorObject, args)
.StoreAccumulatorInRegister(generator_object());
if (generator_object_var->location() == VariableLocation::LOCAL) {
// The generator object register is already set to the variable's local
// register.
DCHECK_EQ(generator_object().index(),
GetRegisterForLocalVariable(generator_object_var).index());
} else {
BuildVariableAssignment(generator_object_var, Token::INIT,
FeedbackSlot::Invalid(), HoleCheckMode::kElided);
}
}
void BytecodeGenerator::VisitFunctionClosureForContext() {
ValueResultScope value_execution_result(this);
if (closure_scope()->is_script_scope()) {
// Contexts nested in the native context have a canonical empty function as
// their closure, not the anonymous closure containing the global code.
Register native_context = register_allocator()->NewRegister();
builder()
->LoadContextSlot(execution_context()->reg(),
Context::NATIVE_CONTEXT_INDEX, 0,
BytecodeArrayBuilder::kImmutableSlot)
.StoreAccumulatorInRegister(native_context)
.LoadContextSlot(native_context, Context::CLOSURE_INDEX, 0,
BytecodeArrayBuilder::kImmutableSlot);
} else if (closure_scope()->is_eval_scope()) {
// Contexts created by a call to eval have the same closure as the
// context calling eval, not the anonymous closure containing the eval
// code. Fetch it from the context.
builder()->LoadContextSlot(execution_context()->reg(),
Context::CLOSURE_INDEX, 0,
BytecodeArrayBuilder::kImmutableSlot);
} else {
DCHECK(closure_scope()->is_function_scope() ||
closure_scope()->is_module_scope());
builder()->LoadAccumulatorWithRegister(Register::function_closure());
}
}
void BytecodeGenerator::BuildPushUndefinedIntoRegisterList(
RegisterList* reg_list) {
Register reg = register_allocator()->GrowRegisterList(reg_list);
builder()->LoadUndefined().StoreAccumulatorInRegister(reg);
}
void BytecodeGenerator::BuildLoadPropertyKey(LiteralProperty* property,
Register out_reg) {
if (property->key()->IsStringLiteral()) {
VisitForRegisterValue(property->key(), out_reg);
} else {
VisitForAccumulatorValue(property->key());
builder()->ToName(out_reg);
}
}
int BytecodeGenerator::AllocateBlockCoverageSlotIfEnabled(
AstNode* node, SourceRangeKind kind) {
return (block_coverage_builder_ == nullptr)
? BlockCoverageBuilder::kNoCoverageArraySlot
: block_coverage_builder_->AllocateBlockCoverageSlot(node, kind);
}
void BytecodeGenerator::BuildIncrementBlockCoverageCounterIfEnabled(
AstNode* node, SourceRangeKind kind) {
if (block_coverage_builder_ == nullptr) return;
block_coverage_builder_->IncrementBlockCounter(node, kind);
}
void BytecodeGenerator::BuildIncrementBlockCoverageCounterIfEnabled(
int coverage_array_slot) {
if (block_coverage_builder_ != nullptr) {
block_coverage_builder_->IncrementBlockCounter(coverage_array_slot);
}
}
// Visits the expression |expr| and places the result in the accumulator.
BytecodeGenerator::TypeHint BytecodeGenerator::VisitForAccumulatorValue(
Expression* expr) {
ValueResultScope accumulator_scope(this);
Visit(expr);
return accumulator_scope.type_hint();
}
void BytecodeGenerator::VisitForAccumulatorValueOrTheHole(Expression* expr) {
if (expr == nullptr) {
builder()->LoadTheHole();
} else {
VisitForAccumulatorValue(expr);
}
}
// Visits the expression |expr| and discards the result.
void BytecodeGenerator::VisitForEffect(Expression* expr) {
EffectResultScope effect_scope(this);
Visit(expr);
}
// Visits the expression |expr| and returns the register containing
// the expression result.
Register BytecodeGenerator::VisitForRegisterValue(Expression* expr) {
VisitForAccumulatorValue(expr);
Register result = register_allocator()->NewRegister();
builder()->StoreAccumulatorInRegister(result);
return result;
}
// Visits the expression |expr| and stores the expression result in
// |destination|.
void BytecodeGenerator::VisitForRegisterValue(Expression* expr,
Register destination) {
ValueResultScope register_scope(this);
Visit(expr);
builder()->StoreAccumulatorInRegister(destination);
}
// Visits the expression |expr| and pushes the result into a new register
// added to the end of |reg_list|.
void BytecodeGenerator::VisitAndPushIntoRegisterList(Expression* expr,
RegisterList* reg_list) {
{
ValueResultScope register_scope(this);
Visit(expr);
}
// Grow the register list after visiting the expression to avoid reserving
// the register across the expression evaluation, which could cause memory
// leaks for deep expressions due to dead objects being kept alive by pointers
// in registers.
Register destination = register_allocator()->GrowRegisterList(reg_list);
builder()->StoreAccumulatorInRegister(destination);
}
void BytecodeGenerator::BuildTest(ToBooleanMode mode,
BytecodeLabels* then_labels,
BytecodeLabels* else_labels,
TestFallthrough fallthrough) {
switch (fallthrough) {
case TestFallthrough::kThen:
builder()->JumpIfFalse(mode, else_labels->New());
break;
case TestFallthrough::kElse:
builder()->JumpIfTrue(mode, then_labels->New());
break;
case TestFallthrough::kNone:
builder()->JumpIfTrue(mode, then_labels->New());
builder()->Jump(else_labels->New());
break;
}
}
// Visits the expression |expr| for testing its boolean value and jumping to the
// |then| or |other| label depending on value and short-circuit semantics
void BytecodeGenerator::VisitForTest(Expression* expr,
BytecodeLabels* then_labels,
BytecodeLabels* else_labels,
TestFallthrough fallthrough) {
bool result_consumed;
TypeHint type_hint;
{
// To make sure that all temporary registers are returned before generating
// jumps below, we ensure that the result scope is deleted before doing so.
// Dead registers might be materialized otherwise.
TestResultScope test_result(this, then_labels, else_labels, fallthrough);
Visit(expr);
result_consumed = test_result.result_consumed_by_test();
type_hint = test_result.type_hint();
// Labels and fallthrough might have been mutated, so update based on
// TestResultScope.
then_labels = test_result.then_labels();
else_labels = test_result.else_labels();
fallthrough = test_result.fallthrough();
}
if (!result_consumed) {
BuildTest(ToBooleanModeFromTypeHint(type_hint), then_labels, else_labels,
fallthrough);
}
}
void BytecodeGenerator::VisitInSameTestExecutionScope(Expression* expr) {
DCHECK(execution_result()->IsTest());
{
RegisterAllocationScope reg_scope(this);
Visit(expr);
}
if (!execution_result()->AsTest()->result_consumed_by_test()) {
TestResultScope* result_scope = execution_result()->AsTest();
BuildTest(ToBooleanModeFromTypeHint(result_scope->type_hint()),
result_scope->then_labels(), result_scope->else_labels(),
result_scope->fallthrough());
result_scope->SetResultConsumedByTest();
}
}
void BytecodeGenerator::VisitInScope(Statement* stmt, Scope* scope) {
DCHECK(scope->declarations()->is_empty());
CurrentScope current_scope(this, scope);
ContextScope context_scope(this, scope);
Visit(stmt);
}
Register BytecodeGenerator::GetRegisterForLocalVariable(Variable* variable) {
DCHECK_EQ(VariableLocation::LOCAL, variable->location());
return builder()->Local(variable->index());
}
FunctionKind BytecodeGenerator::function_kind() const {
return info()->literal()->kind();
}
LanguageMode BytecodeGenerator::language_mode() const {
return current_scope()->language_mode();
}
Register BytecodeGenerator::generator_object() const {
DCHECK(info()->literal()->CanSuspend());
return incoming_new_target_or_generator_;
}
int BytecodeGenerator::feedback_index(FeedbackSlot slot) const {
DCHECK(!slot.IsInvalid());
return FeedbackVector::GetIndex(slot);
}
Runtime::FunctionId BytecodeGenerator::StoreToSuperRuntimeId() {
return is_strict(language_mode()) ? Runtime::kStoreToSuper_Strict
: Runtime::kStoreToSuper_Sloppy;
}
Runtime::FunctionId BytecodeGenerator::StoreKeyedToSuperRuntimeId() {
return is_strict(language_mode()) ? Runtime::kStoreKeyedToSuper_Strict
: Runtime::kStoreKeyedToSuper_Sloppy;
}
} // namespace interpreter
} // namespace internal
} // namespace v8
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
ea513e111215dbdbeb6af616291dd54cb201e585 | 7d3f8e7ba0f1472066228e5ec01e04fe600c146a | /src/tools/BenchMarking.hpp | f48b873d1104bc334f71cc75bd82424cfd059fa3 | [] | no_license | demon90s/CppWorkingTools | 3781449183ed77a0b1e1e50cbad376d2d8ee8225 | 4104f3d3eeff5f1330697aea08aaa4277ca3a3fe | refs/heads/master | 2021-03-11T01:08:47.307788 | 2020-10-15T11:38:10 | 2020-10-15T11:38:10 | 246,500,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | hpp | #pragma once
#include <chrono>
#include <iostream>
#include <functional>
// 基准测试,采用RAII衡量调用栈花费的时间,精度与 std::chrono::duration 一致
// 默认精度: 毫秒
template<typename RATIO = std::chrono::milliseconds>
class BenchMarking
{
public:
BenchMarking(std::function<void(std::size_t)> ouput_func = nullptr)
{
m_start_tp = std::chrono::high_resolution_clock::now();
m_ouput_func = ouput_func;
}
~BenchMarking()
{
auto end_tp = std::chrono::high_resolution_clock::now();
auto start = std::chrono::time_point_cast<RATIO>(m_start_tp);
auto end = std::chrono::time_point_cast<RATIO>(end_tp);
auto diff = end - start;
std::size_t dur = diff.count();
if (m_ouput_func == nullptr)
std::cout << "BenchMarking duration: " << dur << std::endl;
else
m_ouput_func(dur);
}
private:
std::chrono::time_point<std::chrono::high_resolution_clock> m_start_tp;
std::function<void(std::size_t)> m_ouput_func;
}; | [
"demon90s@163.com"
] | demon90s@163.com |
09bd4b4754fd9815650b8ee98c96c6afdacf65fc | 6ffe94c3b84e827449f6a705f0e232399790ce10 | /israel/gorod/gorod.ino | bb34f459c93aad15adca518715983e651bad8f13 | [] | no_license | bart02/traffic2019 | 0942827dd2ab4359ff9d0a4ce0af6b221987ab5c | 08fec04bb7dc66482aa08265e9e1972fc70018e1 | refs/heads/master | 2020-04-23T10:20:49.479212 | 2019-03-14T15:08:21 | 2019-03-14T15:08:21 | 171,101,142 | 0 | 0 | null | 2019-07-29T06:40:25 | 2019-02-17T08:58:10 | C++ | UTF-8 | C++ | false | false | 7,033 | ino | #include <Ultrasonic.h>
#include <Servo.h>
#include "func.h"
#include <Wire.h>
#include <Octoliner.h>
#include <SharpIR.h>
Ultrasonic ultrasonic(48, 49);
Octoliner lineleft(42);
Octoliner lineright(45);
SharpIR sharp(A6, 1080);
#define SPEEDYY 60
#define ENCODER_INT 2 // прерывание энкодера
// текущее значение энкодера в переменной enc
int SPEEDTEK = SPEEDYY - 20;
#define PLEFT 52
#define PRIGHT 53
#define STOPSIG 51
#define RED 40
#define YELLOW 39
#define GREEN 38
// [en, in1, in2]
int motor[3] = { 3, 24, 25 };
float w[16] = { -8, -7, -6, -5, -4, -3, -2, -1, 1, 2, 3, 4, 5, 6, 7, 8 };
bool polin = 1;
int irtek = -1;
bool ultraon = 0;
bool svetofor = 1;
unsigned long mil = 0;
unsigned long vrem = 3000;
bool stopped = 0;
byte blink = 0; //1red 2 y 3g
bool blink_state = 0;
unsigned long blinkmil = 0;
unsigned long irdamil = 0;
unsigned long timerirdamil = 0;
int count = 1;
int speed = SPEEDTEK;
bool wasstopu = 0;
bool infra = 1;
void setup() {
attachInterrupt(ENCODER_INT, encoder, RISING);
myservo.attach(14);
Serial1.begin(115200);
Serial.begin(9600);
Wire.begin();
// начало работы с датчиками линии
lineleft.begin();
// выставляем чувствительность фотоприёмников в диапазоне от 0 до 255
lineleft.setSensitivity(210);
// выставляем яркость свечения ИК-светодиодов в диапазоне от 0 до 255
lineleft.setBrightness(255);
// начало работы с датчиками линии
lineright.begin();
// выставляем чувствительность фотоприёмников в диапазоне от 0 до 255
lineright.setSensitivity(210);
// выставляем яркость свечения ИК-светодиодов в диапазоне от 0 до 255
lineright.setBrightness(255);
pinMode(13, OUTPUT);
pinMode(PLEFT, OUTPUT);
pinMode(PRIGHT, OUTPUT);
pinMode(RED, OUTPUT);
pinMode(YELLOW, OUTPUT);
pinMode(GREEN, OUTPUT);
pinMode(STOPSIG, OUTPUT);
waitGreen();
}
void loop() {
float kp = 26; //40
float kd = 100; //80
int ir = IRread();
int d[16] = { lineleft.analogRead(7), lineleft.analogRead(6), lineleft.analogRead(5), lineleft.analogRead(4), lineleft.analogRead(3), lineleft.analogRead(2), lineleft.analogRead(1), lineleft.analogRead(0), lineright.analogRead(7), lineright.analogRead(6), lineright.analogRead(5), lineright.analogRead(4), lineright.analogRead(3), lineright.analogRead(2), lineright.analogRead(1), lineright.analogRead(0) };
//if (ir == 5) {
if (infra) {
int dist = sharp.distance();
Serial.println(dist);
if (dist < 30 && polin) {
SPEEDTEK = SPEEDYY;
speed = SPEEDTEK;
wasstopu = 1;
digitalWrite(STOPSIG, 1);
polin = 0;
servo(0);
go(motor, -255);
delay(200);
go(motor, 0);
delay(1000);
}
if ((dist >= 60) && !polin && wasstopu) {
wasstopu = 0;
ultraon = 0;
polin = 1;
digitalWrite(STOPSIG, 0);
SPEEDTEK = SPEEDYY;
}
//}
}
if (ir != -1 && ir != 2 && ir != 3 && ir != 5 && ir < 7 && svetofor && polin) {
//speed = SPEEDTEK - 20;
if (lineright.analogRead(0) > 300 && lineright.analogRead(1) > 300 && lineright.analogRead(2) > 300 && lineright.analogRead(3) > 300 && lineright.analogRead(4) > 300 && lineright.analogRead(5) > 300) {
if (ir == 6) {
digitalWrite(STOPSIG, 1);
polin = 0;
servo(0);
go(motor, -255);
delay(200);
go(motor, 0);
delay(5000);
digitalWrite(STOPSIG, 0);
go(motor, 60);
delay(500);
polin = 1;
mil = millis();
svetofor = 0;
}
else {
digitalWrite(STOPSIG, 1);
polin = 0;
servo(0);
go(motor, -255);
delay(200);
go(motor, 0);
delay(500);
mil = millis();
svetofor = 0;
}
}
}
if (ir != -1 && ir == 2 && !polin) {
digitalWrite(STOPSIG, 0);
servo(0);
speed = SPEEDTEK;
//go(motor, speed);
//delay(1000);
polin = 1;
}
if ((ir == 2 || ir == 3) && polin) {
if ( (lineright.analogRead(0) > 300 && lineright.analogRead(1) > 300 && lineright.analogRead(2) > 300 && lineright.analogRead(3) > 300 && lineright.analogRead(4) > 300 && lineright.analogRead(5) > 300) ) {
speed = SPEEDTEK + 5;
svetofor = 0;
mil = millis();
}
}
if (millis() - mil > vrem && !svetofor) {
speed = SPEEDTEK;
svetofor = 1;
}
if (millis() - mil > vrem) {
if (blink == PLEFT || blink == PRIGHT) blink = 0;
digitalWrite(PLEFT, 0);
digitalWrite(PRIGHT, 0);
infra = 1;
}
if (blink && millis() - blinkmil > 500) {
blink_state = !blink_state;
digitalWrite(blink, blink_state);
blinkmil = millis();
}
if (millis() - irdamil > 200) {
if (ir > -1 && ir < 7) {
Serial.println(blink);
if (ir == 0) {
digitalWrite(RED, 1);
digitalWrite(YELLOW, 0);
digitalWrite(GREEN, 0);
blink = 0;
}
else if (ir == 1) {
digitalWrite(RED, 1);
digitalWrite(YELLOW, 1);
digitalWrite(GREEN, 0);
blink = 0;
}
else if (ir == 2) {
digitalWrite(RED, 0);
digitalWrite(YELLOW, 0);
digitalWrite(GREEN, 1);
blink = 0;
}
else if (ir == 3) {
digitalWrite(RED, 0);
digitalWrite(YELLOW, 0);
digitalWrite(GREEN, blink_state);
blink = GREEN;
}
else if (ir == 4) {
digitalWrite(RED, 0);
digitalWrite(YELLOW, 1);
digitalWrite(GREEN, 0);
blink = 0;
}
else if (ir == 5) {
digitalWrite(RED, 0);
digitalWrite(YELLOW, blink_state);
digitalWrite(GREEN, 0);
blink = YELLOW;
}
else if (ir == 6) {
digitalWrite(RED, blink_state);
digitalWrite(YELLOW, 0);
digitalWrite(GREEN, 0);
blink = RED;
}
irdamil = millis();
timerirdamil = millis();
}
else {
if (millis() - timerirdamil > 1000) {
digitalWrite(RED, 0);
digitalWrite(YELLOW, 0);
digitalWrite(GREEN, 0);
}
}
}
if (ir == 7 && senSum(d) > 6500 && senSum(d) < 8000 && millis() - mil > 500) {
infra = 0;
if (count % 2 == 0) {
digitalWrite(PLEFT, 1);
blink = PLEFT;
polin = 0;
servo(0);
delay(500);
polin = 1;
//speed = SPEEDTEK;
} else {
digitalWrite(PRIGHT, 1);
blink = PRIGHT;
polin = 0;
go(motor, SPEEDTEK - 20);
servo(70);
delay(800);
speed = SPEEDTEK;
go(motor, speed);
polin = 1;
}
count++;
mil = millis();
}
//if (count % 2 == 0) {
// digitalWrite(39, 0);
// digitalWrite(40, 1);
//}
//else {
// digitalWrite(39, 1);
// digitalWrite(40, 0);
//}
if (polin) {
float kp = 14; //40
float ki = 0.09; //40
float kd = 50; //80
//Serial.println(count);
//printSensors(d);
float err = senOut(d, w);
float pd = PID(err, kp, ki, kd);
servo(pd);
go(motor, speed);
delay(5);
}
}
| [
"a@batalov.tk"
] | a@batalov.tk |
eece3f6ceef53b2be738d099d8a19158ae639cd7 | 0be68c3f07a9fea1e6e4646f6c489dd18338b516 | /include/GameWindow.h | fce62b0a0290e5610f45587a9461b83431781190 | [] | no_license | brunogouveia/GE-TinyGameEngine | cbdbc2d48db676d372eb817fbdb699f99a886f06 | 4c9e53625811b39638d2f35e3940a67952e82eaf | refs/heads/master | 2021-01-01T06:33:17.130666 | 2015-05-08T21:45:55 | 2015-05-08T21:45:55 | 34,972,592 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 899 | h | /*
* GameWindow.h
*
* Created on: Mar 23, 2015
* Author: Bruno Gouveia
*/
#ifndef GAMEWINDOW_H_
#define GAMEWINDOW_H_
#include <string>
#include <CSCIx239.h>
#include <Renderer.h>
using namespace std;
class GameWindow {
private:
// Renderer
static Renderer * renderer;
static string windowName;
public:
// Windows size
static int width;
static int height;
static float dim;
static void setWindow(string windowName, int width, int height);
static void setRenderer(Renderer * r);
static Renderer * getRenderer();
static bool init(int * argc, char ** argv);
static void mainLoop();
// Callback functions
static void display();
static void reshape(int width, int height);
static void special(int key,int x,int y);
static void key(unsigned char ch,int x,int y);
static void idle();
};
#endif /* GAMEWINDOW_H_ */
| [
"bruno.henrique.gouveia@gmail.com"
] | bruno.henrique.gouveia@gmail.com |
fa486218f89750529529ffe65e29216c50a123a7 | f83ef53177180ebfeb5a3e230aa29794f52ce1fc | /ACE/ACE_wrappers/TAO/tao/LF_Event.cpp | 16139aeb985aeed3d83542601231187845ef0c6a | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-proprietary-license",
"LicenseRef-scancode-sun-iiop"
] | permissive | msrLi/portingSources | fe7528b3fd08eed4a1b41383c88ee5c09c2294ef | 57d561730ab27804a3172b33807f2bffbc9e52ae | refs/heads/master | 2021-07-08T01:22:29.604203 | 2019-07-10T13:07:06 | 2019-07-10T13:07:06 | 196,183,165 | 2 | 1 | Apache-2.0 | 2020-10-13T14:30:53 | 2019-07-10T10:16:46 | null | UTF-8 | C++ | false | false | 1,352 | cpp | // -*- C++ -*-
#include "tao/LF_Event.h"
#include "tao/LF_Follower.h"
#include "tao/Leader_Follower.h"
#include "ace/Guard_T.h"
#if !defined (__ACE_INLINE__)
# include "tao/LF_Event.inl"
#endif /* __ACE_INLINE__ */
TAO_BEGIN_VERSIONED_NAMESPACE_DECL
TAO_LF_Event::TAO_LF_Event (void)
: state_ (TAO_LF_Event::LFS_IDLE)
, follower_ (0)
{
}
TAO_LF_Event::~TAO_LF_Event (void)
{
}
void
TAO_LF_Event::state_changed (LFS_STATE new_state, TAO_Leader_Follower &lf)
{
ACE_GUARD (TAO_SYNCH_MUTEX, ace_mon, lf.lock ());
if (!this->is_state_final ())
{
this->state_changed_i (new_state);
/// Sort of double-checked optimization..
if (this->follower_ != 0)
this->follower_->signal ();
}
}
bool
TAO_LF_Event::keep_waiting (TAO_Leader_Follower &lf) const
{
ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, lf.lock (), false);
return this->keep_waiting_i ();
}
bool
TAO_LF_Event::successful (TAO_Leader_Follower &lf) const
{
ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, lf.lock (), false);
return this->successful_i ();
}
bool
TAO_LF_Event::error_detected (TAO_Leader_Follower &lf) const
{
ACE_GUARD_RETURN (TAO_SYNCH_MUTEX, ace_mon, lf.lock (), true);
return this->error_detected_i ();
}
void
TAO_LF_Event::set_state (LFS_STATE new_state)
{
this->state_ = new_state;
}
TAO_END_VERSIONED_NAMESPACE_DECL
| [
"lihuibin705@163.com"
] | lihuibin705@163.com |
d63cba1f90f5ebf43b2e93df151a217f510cb561 | c6cab233359ba27f6e3bdfdefd262d6925497bd7 | /KnightsAttacks/sample.cpp | dfcbbe5f8e17466894ffc9945f799c590fc0a6c1 | [] | no_license | kurenai3110/MM | cc43ef7b6471fea903d43bd5ce4716b7e4dfa35e | e3d3590655fe410ce54e6255d6436eafc66ea1ca | refs/heads/master | 2021-09-10T08:38:22.852084 | 2018-03-23T02:26:44 | 2018-03-23T02:26:44 | 85,224,593 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 940 | cpp | // C++11
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class KnightsAttacks {
public:
vector<string> placeKnights(vector<string> board) {
int S = board.size();
vector<string> ret(S, string(S, '.'));
srand(123);
for (int i = 0; i < S; ++i)
for (int j = 0; j < S; ++j)
if (rand() % 2)
ret[i][j] = 'K';
return ret;
}
};
// -------8<------- end of solution submitted to the website -------8<-------
template<class T> void getVector(vector<T>& v) {
for (int i = 0; i < v.size(); ++i)
cin >> v[i];
}
int main() {
KnightsAttacks ka;
int S;
cin >> S;
vector<string> board(S);
getVector(board);
vector<string> ret = ka.placeKnights(board);
cout << ret.size() << endl;
for (int i = 0; i < (int)ret.size(); ++i)
cout << ret[i] << endl;
cout.flush();
}
| [
"keke0001@hotmail.co.jp"
] | keke0001@hotmail.co.jp |
fadf6af30908449e9652fd30938dd4b8d4aed870 | 398ea8a311291e0e30c6ad740f4b427b4f8f49ab | /src/shogun/lib/Collection.hpp | 8d5cc7da6439b4e6b2d3de137322091727af5385 | [
"BSD-3-Clause"
] | permissive | lambday/xstream | ee14b51f6c175613d4ff5d8e3cb74afc23ba07cc | 30553fe4af98bae489435098c8dc2892c269f5c9 | refs/heads/master | 2020-12-31T00:10:58.805240 | 2017-03-30T02:52:51 | 2017-03-30T02:52:51 | 86,538,167 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,789 | hpp | /**
* BSD 3-Clause License
*
* Copyright (c) 2017, Soumyajit 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 copyright holder 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.
*/
#ifndef COLLECTION_HPP__
#define COLLECTION_HPP__
#include <map>
#include <iostream>
#include <functional>
#include <tuple>
#include <memory>
#include <initializer_list>
#include <utility>
#include <shogun/lib/Stream.hpp>
namespace shogun
{
template <class T>
struct Collection
{
template <class V>
struct iterator : std::iterator<std::bidirectional_iterator_tag,V>
{
using value_type = V;
explicit iterator(T* _ptr) : ptr(_ptr) {}
iterator& operator++() { ptr++; return *this; }
iterator operator++(int) { auto ret = *this; ++(*this); return ret; }
iterator& operator--() { ptr--; return *this; }
iterator operator--(int) { auto ret = *this; --(*this); return ret; }
friend bool operator==(iterator& first, iterator& second)
{
return first.ptr == second.ptr;
}
friend bool operator!=(iterator& first, iterator& second)
{
return !(first == second);
}
V& operator*() { return *ptr; }
V* ptr;
};
using value_type = T;
using iterator_type = iterator<T>;
Stream<Collection<T>> stream() const
{
return Stream<Collection<T>>(this);
}
virtual iterator<T> begin() const = 0;
virtual iterator<T> end() const = 0;
};
}
#endif // COLLECTION_HPP__
| [
"heavensdevil6909@gmail.com"
] | heavensdevil6909@gmail.com |
383e8a670def200639b9aa8929da53a6cb06bb79 | 24287639a5af25775a34729b5942892271db45b5 | /211INC/AFXOLE.INL | a5090d40c52aa6d3036a7f62bc6373a8eb45a4f1 | [] | no_license | FaucetDC/hldc-sdk | 631c67c29b9a2054b28bf148f2b313cdd078e93b | 1cfeeace3e6caabb567ce989b54dd44caeaf2bf0 | refs/heads/master | 2021-01-12T09:07:37.316770 | 2017-01-15T02:22:40 | 2017-01-15T02:26:33 | 76,768,456 | 8 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 18,066 | inl | // This is a part of the Microsoft Foundation Classes C++ library.
// Copyright (C) 1992-1998 Microsoft Corporation
// All rights reserved.
//
// This source code is only intended as a supplement to the
// Microsoft Foundation Classes Reference and related
// electronic documentation provided with the library.
// See these sources for detailed information regarding the
// Microsoft Foundation Classes product.
// Inlines for AFXOLE.H
/////////////////////////////////////////////////////////////////////////////
// General OLE inlines (CDocItem, COleDocument)
#ifdef _AFXOLE_INLINE
// CDocItem
_AFXOLE_INLINE CDocument* CDocItem::GetDocument() const
{ return m_pDocument; }
// COleDocument
_AFXOLE_INLINE void COleDocument::EnableCompoundFile(BOOL bEnable)
{ m_bCompoundFile = bEnable; }
// COleMessageFilter
_AFXOLE_INLINE void COleMessageFilter::SetBusyReply(SERVERCALL nBusyReply)
{ ASSERT_VALID(this); m_nBusyReply = nBusyReply; }
_AFXOLE_INLINE void COleMessageFilter::SetRetryReply(DWORD nRetryReply)
{ ASSERT_VALID(this); m_nRetryReply = nRetryReply; }
_AFXOLE_INLINE void COleMessageFilter::SetMessagePendingDelay(DWORD nTimeout)
{ ASSERT_VALID(this); m_nTimeout = nTimeout; }
_AFXOLE_INLINE void COleMessageFilter::EnableBusyDialog(BOOL bEnable)
{ ASSERT_VALID(this); m_bEnableBusy = bEnable; }
_AFXOLE_INLINE void COleMessageFilter::EnableNotRespondingDialog(BOOL bEnable)
{ ASSERT_VALID(this); m_bEnableNotResponding = bEnable; }
#endif //_AFXOLE_INLINE
/////////////////////////////////////////////////////////////////////////////
// OLE Moniker inlines
#ifdef _AFXOLEMONIKER_INLINE
// CMonikerFile
_AFXOLEMONIKER_INLINE CMonikerFile::CMonikerFile() { }
_AFXOLEMONIKER_INLINE IMoniker* CMonikerFile::GetMoniker() const
{ ASSERT_VALID(this); return m_Moniker; }
// CAsyncMonikerFile
_AFXOLEMONIKER_INLINE IBinding* CAsyncMonikerFile::GetBinding() const
{ ASSERT_VALID(this); return m_Binding; }
_AFXOLEMONIKER_INLINE void CAsyncMonikerFile::SetBinding(IBinding* pBinding)
{ ASSERT_VALID(this); m_Binding=pBinding; }
_AFXOLEMONIKER_INLINE void CAsyncMonikerFile::SetFormatEtc(FORMATETC* pFormatEtc)
{ ASSERT_VALID(this); m_pFormatEtc=pFormatEtc; }
_AFXOLEMONIKER_INLINE FORMATETC* CAsyncMonikerFile::GetFormatEtc() const
{ ASSERT_VALID(this); return m_pFormatEtc; }
#endif //_AFXOLEMONIKER_INLINE
/////////////////////////////////////////////////////////////////////////////
// OLE automation inlines
#ifdef _AFXDISP_INLINE
// COleException
_AFXDISP_INLINE COleException::COleException()
{ m_sc = S_OK; }
_AFXDISP_INLINE COleException::~COleException()
{ }
// CCmdTarget
_AFXDISP_INLINE DWORD CCmdTarget::InternalAddRef()
{ ASSERT(GetInterfaceMap() != NULL); return InterlockedIncrement(&m_dwRef); }
// CObjectFactory
_AFXDISP_INLINE BOOL COleObjectFactory::IsRegistered() const
{ ASSERT_VALID(this); return m_dwRegister != 0; }
_AFXDISP_INLINE REFCLSID COleObjectFactory::GetClassID() const
{ ASSERT_VALID(this); return m_clsid; }
// COleDispatchDriver
_AFXDISP_INLINE COleDispatchDriver::~COleDispatchDriver()
{ ReleaseDispatch(); }
_AFXDISP_INLINE COleDispatchDriver::operator LPDISPATCH()
{ return m_lpDispatch; }
// COleVariant
_AFXDISP_INLINE COleVariant::COleVariant()
{ AfxVariantInit(this); }
_AFXDISP_INLINE COleVariant::~COleVariant()
{ VERIFY(::VariantClear(this) == NOERROR); }
_AFXDISP_INLINE void COleVariant::Clear()
{ VERIFY(::VariantClear(this) == NOERROR); }
_AFXDISP_INLINE COleVariant::COleVariant(LPCTSTR lpszSrc)
{ vt = VT_EMPTY; *this = lpszSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(CString& strSrc)
{ vt = VT_EMPTY; *this = strSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(BYTE nSrc)
{ vt = VT_UI1; bVal = nSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(const COleCurrency& curSrc)
{ vt = VT_CY; cyVal = curSrc.m_cur; }
_AFXDISP_INLINE COleVariant::COleVariant(float fltSrc)
{ vt = VT_R4; fltVal = fltSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(double dblSrc)
{ vt = VT_R8; dblVal = dblSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(const COleDateTime& dateSrc)
{ vt = VT_DATE; date = dateSrc.m_dt; }
_AFXDISP_INLINE COleVariant::COleVariant(const CByteArray& arrSrc)
{ vt = VT_EMPTY; *this = arrSrc; }
_AFXDISP_INLINE COleVariant::COleVariant(const CLongBinary& lbSrc)
{ vt = VT_EMPTY; *this = lbSrc; }
_AFXDISP_INLINE BOOL COleVariant::operator==(LPCVARIANT pSrc) const
{ return *this == *pSrc; }
_AFXDISP_INLINE COleVariant::operator LPVARIANT()
{ return this; }
_AFXDISP_INLINE COleVariant::operator LPCVARIANT() const
{ return this; }
// COleCurrency
_AFXDISP_INLINE COleCurrency::COleCurrency()
{ m_cur.Hi = 0; m_cur.Lo = 0; SetStatus(valid); }
_AFXDISP_INLINE COleCurrency::COleCurrency(CURRENCY cySrc)
{ m_cur = cySrc; SetStatus(valid); }
_AFXDISP_INLINE COleCurrency::COleCurrency(const COleCurrency& curSrc)
{ m_cur = curSrc.m_cur; m_status = curSrc.m_status; }
_AFXDISP_INLINE COleCurrency::COleCurrency(const VARIANT& varSrc)
{ *this = varSrc; }
_AFXDISP_INLINE COleCurrency::CurrencyStatus COleCurrency::GetStatus() const
{ return m_status; }
_AFXDISP_INLINE void COleCurrency::SetStatus(CurrencyStatus status)
{ m_status = status; }
_AFXDISP_INLINE const COleCurrency& COleCurrency::operator+=(const COleCurrency& cur)
{ *this = *this + cur; return *this; }
_AFXDISP_INLINE const COleCurrency& COleCurrency::operator-=(const COleCurrency& cur)
{ *this = *this - cur; return *this; }
_AFXDISP_INLINE const COleCurrency& COleCurrency::operator*=(long nOperand)
{ *this = *this * nOperand; return *this; }
_AFXDISP_INLINE const COleCurrency& COleCurrency::operator/=(long nOperand)
{ *this = *this / nOperand; return *this; }
_AFXDISP_INLINE BOOL COleCurrency::operator==(const COleCurrency& cur) const
{ return(m_status == cur.m_status && m_cur.Hi == cur.m_cur.Hi &&
m_cur.Lo == cur.m_cur.Lo); }
_AFXDISP_INLINE BOOL COleCurrency::operator!=(const COleCurrency& cur) const
{ return(m_status != cur.m_status || m_cur.Hi != cur.m_cur.Hi ||
m_cur.Lo != cur.m_cur.Lo); }
_AFXDISP_INLINE COleCurrency::operator CURRENCY() const
{ return m_cur; }
// COleDateTime
_AFXDISP_INLINE COleDateTime::COleDateTime()
{ m_dt = 0; SetStatus(valid); }
_AFXDISP_INLINE COleDateTime::COleDateTime(const COleDateTime& dateSrc)
{ m_dt = dateSrc.m_dt; m_status = dateSrc.m_status; }
_AFXDISP_INLINE COleDateTime::COleDateTime(const VARIANT& varSrc)
{ *this = varSrc; }
_AFXDISP_INLINE COleDateTime::COleDateTime(DATE dtSrc)
{ m_dt = dtSrc; SetStatus(valid); }
_AFXDISP_INLINE COleDateTime::COleDateTime(time_t timeSrc)
{ *this = timeSrc; }
_AFXDISP_INLINE COleDateTime::COleDateTime(const SYSTEMTIME& systimeSrc)
{ *this = systimeSrc; }
_AFXDISP_INLINE COleDateTime::COleDateTime(const FILETIME& filetimeSrc)
{ *this = filetimeSrc; }
_AFXDISP_INLINE COleDateTime::COleDateTime(int nYear, int nMonth, int nDay,
int nHour, int nMin, int nSec)
{ SetDateTime(nYear, nMonth, nDay, nHour, nMin, nSec); }
_AFXDISP_INLINE COleDateTime::COleDateTime(WORD wDosDate, WORD wDosTime)
{ m_status = DosDateTimeToVariantTime(wDosDate, wDosTime, &m_dt) ?
valid : invalid; }
_AFXDISP_INLINE const COleDateTime& COleDateTime::operator=(const COleDateTime& dateSrc)
{ m_dt = dateSrc.m_dt; m_status = dateSrc.m_status; return *this; }
_AFXDISP_INLINE COleDateTime::DateTimeStatus COleDateTime::GetStatus() const
{ return m_status; }
_AFXDISP_INLINE void COleDateTime::SetStatus(DateTimeStatus status)
{ m_status = status; }
_AFXDISP_INLINE BOOL COleDateTime::operator==(const COleDateTime& date) const
{ return (m_status == date.m_status && m_dt == date.m_dt); }
_AFXDISP_INLINE BOOL COleDateTime::operator!=(const COleDateTime& date) const
{ return (m_status != date.m_status || m_dt != date.m_dt); }
_AFXDISP_INLINE const COleDateTime& COleDateTime::operator+=(
const COleDateTimeSpan dateSpan)
{ *this = *this + dateSpan; return *this; }
_AFXDISP_INLINE const COleDateTime& COleDateTime::operator-=(
const COleDateTimeSpan dateSpan)
{ *this = *this - dateSpan; return *this; }
_AFXDISP_INLINE COleDateTime::operator DATE() const
{ return m_dt; }
_AFXDISP_INLINE int COleDateTime::SetDate(int nYear, int nMonth, int nDay)
{ return SetDateTime(nYear, nMonth, nDay, 0, 0, 0); }
_AFXDISP_INLINE int COleDateTime::SetTime(int nHour, int nMin, int nSec)
// Set date to zero date - 12/30/1899
{ return SetDateTime(1899, 12, 30, nHour, nMin, nSec); }
// COleDateTimeSpan
_AFXDISP_INLINE COleDateTimeSpan::COleDateTimeSpan()
{ m_span = 0; SetStatus(valid); }
_AFXDISP_INLINE COleDateTimeSpan::COleDateTimeSpan(double dblSpanSrc)
{ m_span = dblSpanSrc; SetStatus(valid); }
_AFXDISP_INLINE COleDateTimeSpan::COleDateTimeSpan(
const COleDateTimeSpan& dateSpanSrc)
{ m_span = dateSpanSrc.m_span; m_status = dateSpanSrc.m_status; }
_AFXDISP_INLINE COleDateTimeSpan::COleDateTimeSpan(
long lDays, int nHours, int nMins, int nSecs)
{ SetDateTimeSpan(lDays, nHours, nMins, nSecs); }
_AFXDISP_INLINE COleDateTimeSpan::DateTimeSpanStatus COleDateTimeSpan::GetStatus() const
{ return m_status; }
_AFXDISP_INLINE void COleDateTimeSpan::SetStatus(DateTimeSpanStatus status)
{ m_status = status; }
_AFXDISP_INLINE double COleDateTimeSpan::GetTotalDays() const
{ ASSERT(GetStatus() == valid); return m_span; }
_AFXDISP_INLINE double COleDateTimeSpan::GetTotalHours() const
{ ASSERT(GetStatus() == valid);
long lReturns = (long)(m_span * 24 + AFX_OLE_DATETIME_HALFSECOND);
return lReturns;
}
_AFXDISP_INLINE double COleDateTimeSpan::GetTotalMinutes() const
{ ASSERT(GetStatus() == valid);
long lReturns = (long)(m_span * 24 * 60 + AFX_OLE_DATETIME_HALFSECOND);
return lReturns;
}
_AFXDISP_INLINE double COleDateTimeSpan::GetTotalSeconds() const
{ ASSERT(GetStatus() == valid);
long lReturns = (long)(m_span * 24 * 60 * 60 + AFX_OLE_DATETIME_HALFSECOND);
return lReturns;
}
_AFXDISP_INLINE long COleDateTimeSpan::GetDays() const
{ ASSERT(GetStatus() == valid); return (long)m_span; }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator==(
const COleDateTimeSpan& dateSpan) const
{ return (m_status == dateSpan.m_status &&
m_span == dateSpan.m_span); }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator!=(
const COleDateTimeSpan& dateSpan) const
{ return (m_status != dateSpan.m_status ||
m_span != dateSpan.m_span); }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator<(
const COleDateTimeSpan& dateSpan) const
{ ASSERT(GetStatus() == valid);
ASSERT(dateSpan.GetStatus() == valid);
return m_span < dateSpan.m_span; }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator>(
const COleDateTimeSpan& dateSpan) const
{ ASSERT(GetStatus() == valid);
ASSERT(dateSpan.GetStatus() == valid);
return m_span > dateSpan.m_span; }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator<=(
const COleDateTimeSpan& dateSpan) const
{ ASSERT(GetStatus() == valid);
ASSERT(dateSpan.GetStatus() == valid);
return m_span <= dateSpan.m_span; }
_AFXDISP_INLINE BOOL COleDateTimeSpan::operator>=(
const COleDateTimeSpan& dateSpan) const
{ ASSERT(GetStatus() == valid);
ASSERT(dateSpan.GetStatus() == valid);
return m_span >= dateSpan.m_span; }
_AFXDISP_INLINE const COleDateTimeSpan& COleDateTimeSpan::operator+=(
const COleDateTimeSpan dateSpan)
{ *this = *this + dateSpan; return *this; }
_AFXDISP_INLINE const COleDateTimeSpan& COleDateTimeSpan::operator-=(
const COleDateTimeSpan dateSpan)
{ *this = *this - dateSpan; return *this; }
_AFXDISP_INLINE COleDateTimeSpan COleDateTimeSpan::operator-() const
{ return -this->m_span; }
_AFXDISP_INLINE COleDateTimeSpan::operator double() const
{ return m_span; }
// COleSafeArray
_AFXDISP_INLINE COleSafeArray::COleSafeArray()
{ AfxSafeArrayInit(this);
vt = VT_EMPTY; }
_AFXDISP_INLINE COleSafeArray::~COleSafeArray()
{ Clear(); }
_AFXDISP_INLINE void COleSafeArray::Clear()
{ VERIFY(::VariantClear(this) == NOERROR); }
_AFXDISP_INLINE COleSafeArray::operator LPVARIANT()
{ return this; }
_AFXDISP_INLINE COleSafeArray::operator LPCVARIANT() const
{ return this; }
_AFXDISP_INLINE DWORD COleSafeArray::GetDim()
{ return ::SafeArrayGetDim(parray); }
_AFXDISP_INLINE DWORD COleSafeArray::GetElemSize()
{ return ::SafeArrayGetElemsize(parray); }
#endif //_AFXDISP_INLINE
/////////////////////////////////////////////////////////////////////////////
// OLE Container inlines
#ifdef _AFXOLECLI_INLINE
// COleClientItem
_AFXOLECLI_INLINE SCODE COleClientItem::GetLastStatus() const
{ ASSERT_VALID(this); return m_scLast; }
_AFXOLECLI_INLINE COleDocument* COleClientItem::GetDocument() const
{ ASSERT_VALID(this); return (COleDocument*)m_pDocument; }
_AFXOLECLI_INLINE OLE_OBJTYPE COleClientItem::GetType() const
{ ASSERT_VALID(this); return m_nItemType; }
_AFXOLECLI_INLINE DVASPECT COleClientItem::GetDrawAspect() const
{ ASSERT_VALID(this); return m_nDrawAspect; }
_AFXOLECLI_INLINE BOOL COleClientItem::IsRunning() const
{ ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
return ::OleIsRunning(m_lpObject); }
_AFXOLECLI_INLINE UINT COleClientItem::GetItemState() const
{ ASSERT_VALID(this); return m_nItemState; }
_AFXOLECLI_INLINE BOOL COleClientItem::IsInPlaceActive() const
{ ASSERT_VALID(this);
return m_nItemState == activeState || m_nItemState == activeUIState; }
_AFXOLECLI_INLINE BOOL COleClientItem::IsOpen() const
{ ASSERT_VALID(this); return m_nItemState == openState; }
_AFXOLECLI_INLINE BOOL COleClientItem::IsLinkUpToDate() const
{ ASSERT_VALID(this);
ASSERT(m_lpObject != NULL);
// TRUE if result is S_OK (aka S_TRUE)
return m_lpObject->IsUpToDate() == NOERROR; }
_AFXOLECLI_INLINE CView* COleClientItem::GetActiveView() const
{ return m_pView; }
// COleLinkingDoc
_AFXOLECLI_INLINE void COleLinkingDoc::BeginDeferErrors()
{ ASSERT(m_pLastException == NULL); ++m_bDeferErrors; }
#endif //_AFXOLECLI_INLINE
#ifdef _AFXOLEDOBJ_INLINE
// COleDataObject
_AFXOLEDOBJ_INLINE COleDataObject::~COleDataObject()
{ Release(); }
#endif //_AFXOLECTL_INLINE
/////////////////////////////////////////////////////////////////////////////
// OLE dialog inlines
#ifdef _AFXODLGS_INLINE
_AFXODLGS_INLINE UINT COleDialog::GetLastError() const
{ return m_nLastError; }
_AFXODLGS_INLINE CString COleInsertDialog::GetPathName() const
{ ASSERT_VALID(this);
ASSERT(GetSelectionType() != createNewItem); return m_szFileName; }
_AFXODLGS_INLINE REFCLSID COleInsertDialog::GetClassID() const
{ ASSERT_VALID(this); return m_io.clsid; }
_AFXODLGS_INLINE HGLOBAL COleInsertDialog::GetIconicMetafile() const
{ ASSERT_VALID(this); return m_io.hMetaPict; }
_AFXODLGS_INLINE DVASPECT COleInsertDialog::GetDrawAspect() const
{ ASSERT_VALID(this); return m_io.dwFlags & IOF_CHECKDISPLAYASICON ?
DVASPECT_ICON : DVASPECT_CONTENT; }
_AFXODLGS_INLINE HGLOBAL COleConvertDialog::GetIconicMetafile() const
{ ASSERT_VALID(this); return m_cv.hMetaPict; }
_AFXODLGS_INLINE DVASPECT COleConvertDialog::GetDrawAspect() const
{ ASSERT_VALID(this); return (DVASPECT)m_cv.dvAspect; }
_AFXODLGS_INLINE REFCLSID COleConvertDialog::GetClassID() const
{ ASSERT_VALID(this); return m_cv.clsidNew; }
_AFXODLGS_INLINE HGLOBAL COleChangeIconDialog::GetIconicMetafile() const
{ ASSERT_VALID(this); return m_ci.hMetaPict; }
_AFXODLGS_INLINE int COlePasteSpecialDialog::GetPasteIndex() const
{ ASSERT_VALID(this); return m_ps.nSelectedIndex; }
_AFXODLGS_INLINE DVASPECT COlePasteSpecialDialog::GetDrawAspect() const
{ ASSERT_VALID(this); return m_ps.dwFlags & PSF_CHECKDISPLAYASICON ?
DVASPECT_ICON : DVASPECT_CONTENT; }
_AFXODLGS_INLINE HGLOBAL COlePasteSpecialDialog::GetIconicMetafile() const
{ ASSERT_VALID(this); return m_ps.hMetaPict; }
_AFXODLGS_INLINE UINT COleBusyDialog::GetSelectionType() const
{ ASSERT_VALID(this); return m_selection; }
_AFXODLGS_INLINE BOOL COleChangeSourceDialog::IsValidSource()
{ return m_cs.dwFlags & CSF_VALIDSOURCE; }
_AFXODLGS_INLINE CString COleChangeSourceDialog::GetDisplayName()
{ return m_cs.lpszDisplayName; }
_AFXODLGS_INLINE CString COleChangeSourceDialog::GetFileName()
{ return CString(m_cs.lpszDisplayName, m_cs.nFileLength); }
_AFXODLGS_INLINE CString COleChangeSourceDialog::GetItemName()
{ return m_cs.lpszDisplayName+m_cs.nFileLength; }
_AFXODLGS_INLINE CString COleChangeSourceDialog::GetFromPrefix()
{ return m_cs.lpszFrom; }
_AFXODLGS_INLINE CString COleChangeSourceDialog::GetToPrefix()
{ return m_cs.lpszTo; }
#endif //_AFXODLGS_INLINE
/////////////////////////////////////////////////////////////////////////////
// OLE Server inlines
#ifdef _AFXOLESVR_INLINE
// COleServerItem
_AFXOLESVR_INLINE COleServerDoc* COleServerItem::GetDocument() const
{ ASSERT_VALID(this); return (COleServerDoc*)m_pDocument; }
_AFXOLESVR_INLINE void COleServerItem::NotifyChanged(DVASPECT nDrawAspect)
{ ASSERT_VALID(this); NotifyClient(OLE_CHANGED, nDrawAspect); }
_AFXOLESVR_INLINE const CString& COleServerItem::GetItemName() const
{ ASSERT_VALID(this); return m_strItemName; }
_AFXOLESVR_INLINE void COleServerItem::SetItemName(LPCTSTR lpszItemName)
{
ASSERT_VALID(this);
ASSERT(lpszItemName != NULL);
ASSERT(AfxIsValidString(lpszItemName));
m_strItemName = lpszItemName;
}
_AFXOLESVR_INLINE BOOL COleServerItem::IsLinkedItem() const
{ ASSERT_VALID(this); return GetDocument()->m_pEmbeddedItem != this; }
_AFXOLESVR_INLINE COleDataSource* COleServerItem::GetDataSource()
{ ASSERT_VALID(this); return &m_dataSource; }
// COleServerDoc
_AFXOLESVR_INLINE void COleServerDoc::NotifyChanged()
{ ASSERT_VALID(this); NotifyAllItems(OLE_CHANGED, DVASPECT_CONTENT); }
_AFXOLESVR_INLINE void COleServerDoc::NotifyClosed()
{ ASSERT_VALID(this); NotifyAllItems(OLE_CLOSED, 0); }
_AFXOLESVR_INLINE void COleServerDoc::NotifySaved()
{ ASSERT_VALID(this); NotifyAllItems(OLE_SAVED, 0); }
_AFXOLESVR_INLINE BOOL COleServerDoc::IsEmbedded() const
{ ASSERT_VALID(this); return m_bEmbedded; }
_AFXOLESVR_INLINE BOOL COleServerDoc::IsDocObject() const
{ ASSERT_VALID(this); return m_pDocObjectServer != NULL; }
_AFXOLESVR_INLINE BOOL COleServerDoc::IsInPlaceActive() const
{ ASSERT_VALID(this); return m_pInPlaceFrame != NULL; }
#endif //_AFXOLESVR_INLINE
/////////////////////////////////////////////////////////////////////////////
| [
"danevans27e@yahoo.com"
] | danevans27e@yahoo.com |
c4e73fcdb4ea84f95dc37e76d0e209981cb17a31 | f62e37d6a8884960b8e315c61a924650d756df0d | /src/core/hw/gfxip/gfx9/gfx9UniversalEngine.h | bfd670c479b3250a2cb214238db782cea0477aa0 | [
"MIT"
] | permissive | ardacoskunses/pal | cd5f0dfd35912239c32e884005bd68b391bb96e0 | ec4457f9b005dcb7a6178debc19b1df65da57280 | refs/heads/master | 2020-03-28T18:00:47.178244 | 2018-09-12T04:59:18 | 2018-09-12T05:06:04 | 148,844,552 | 0 | 0 | MIT | 2018-09-14T21:41:30 | 2018-09-14T21:41:30 | null | UTF-8 | C++ | false | false | 2,272 | h | /*
***********************************************************************************************************************
*
* Copyright (c) 2016-2018 Advanced Micro Devices, Inc. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
**********************************************************************************************************************/
#pragma once
#include "core/engine.h"
#include "core/queueContext.h"
#include "core/hw/gfxip/gfx9/gfx9Device.h"
namespace Pal
{
namespace Gfx9
{
class UniversalEngine : public Engine
{
public:
UniversalEngine(
Device* pDevice,
EngineType type,
uint32 index);
virtual Result Init() override;
UniversalRingSet* RingSet() { return &m_ringSet; }
Result UpdateRingSet(uint32* pCounterVal, bool* pHasChanged);
private:
Device* m_pDevice;
UniversalRingSet m_ringSet;
uint32 m_currentUpdateCounter; // Current watermark for the device-initiated context updates that have
// been processed by this engine.
PAL_DISALLOW_COPY_AND_ASSIGN(UniversalEngine);
PAL_DISALLOW_DEFAULT_CTOR(UniversalEngine);
};
} // Gfx9
} // Pal
| [
"jacob.he@amd.com"
] | jacob.he@amd.com |
0f5d26a431b454bc1ce119924e90aa3003a81cd5 | d053e0e8687f122d120bcd0fa1f9076deb35afa5 | /Olymp/NEERC/Internet_olymp/2014-2015/Individual/3/C.cpp | dac97bde367a2475cd646804545c500c691fdde0 | [] | no_license | shaihitdin/CP | e8911bc543932866d6fc83eb1d48d9cf79918c61 | dc90082f3ebedaccbfb0818cc68539c887f86553 | refs/heads/master | 2021-01-11T17:10:20.356635 | 2017-10-05T08:53:56 | 2017-10-05T08:53:56 | 79,729,913 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,375 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 20, modulo = 1e9 + 7;
vector <int> a[N];
int n, m, q, x, y;
inline void do_naive () {
scanf ("%d", &q);
for (int i = 1; i <= q; ++i) {
scanf ("%d%d", &x, &y);
for (int j = 1; j <= m; ++j) {
a[x][j] += a[y][j];
if (a[x][j] >= modulo)
a[x][j] -= modulo;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
printf ("%d ", a[i][j]);
}
putchar ('\n');
}
}
long long cnt[35][35];
inline void do_smth () {
scanf ("%d", &q);
for (int i = 1; i <= n; ++i)
cnt[i][i] = 1;
for (int i = 1; i <= q; ++i) {
scanf ("%d%d", &x, &y);
for (int j = 1; j <= n; ++j) {
cnt[x][j] += cnt[y][j];
if (cnt[x][j] >= modulo)
cnt[x][j] -= modulo;
}
}
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
long long temp = 0;
for (int k = 1; k <= n; ++k)
temp = (temp + (cnt[i][k] * 1LL * a[k][j]) ) % (modulo * 1LL);
int temp1 = temp;
printf ("%d ", temp1);
}
putchar ('\n');
}
}
int main () {
freopen ("adding.in", "r", stdin);
freopen ("adding.out", "w", stdout);
scanf ("%d%d", &n, &m);
for (int i = 1; i <= n; ++i)
a[i].resize (m + 1);
for (int i = 1; i <= n; ++i)
for (int j = 1; j <= m; ++j)
scanf ("%d", &a[i][j]);
if (m <= 5000) {
do_naive();
}
else {
//assert (0);
do_smth();
}
return 0;
} | [
"shaihitdin@gmail.com"
] | shaihitdin@gmail.com |
7ec6be7d80c3bb776f748e67a5eda67073c98734 | 10f5774411120870b7188fe0dcc0480ab8aad3a3 | /streegp/mutation.hpp | 55505bf62782dc10a224e6b3605317a3a59cc18b | [] | no_license | mngr777/stree-gp | 4aaa222ec9ce9d094023c68ca31db46aded2971f | 252f96931268678b9bba71d0f368b94a09fd77a5 | refs/heads/master | 2022-05-16T14:10:36.208763 | 2022-03-10T09:30:43 | 2022-03-10T09:30:43 | 212,445,096 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,915 | hpp | #ifndef STREEGP_MUTATION_HPP_
#define STREEGP_MUTATION_HPP_
#include <stree/stree.hpp>
namespace stree { namespace gp {
// Subtree mutation
template<typename R, typename D>
Tree mutate_subtree(
Tree tree,
unsigned depth,
float p_term,
float p_term_grow,
R& prng,
D& value_dist);
template<typename R>
Tree mutate_subtree(
Tree tree,
unsigned depth,
float p_term,
float p_term_grow,
R& prng);
template<typename C>
Tree mutate_subtree(
C& context,
Tree tree,
unsigned depth,
float p_term,
float p_term_grow)
{
return mutate_subtree<typename C::PrngType, typename C::ValueDistType>(
tree, depth, p_term, p_term_grow, context.prng, context.value_dist);
}
template<typename C>
Tree mutate_subtree(C& context, const Tree& tree) {
const Config& config = context.config;
return mutate_subtree<C>(
context,
tree,
config.get<unsigned>(conf::MutationSubtreeDepth),
config.get<float>(conf::MutationSubtreePTerm),
config.get<float>(conf::MutationSubtreePTermGrow));
}
template<typename C>
typename C::IndividualType mutate_subtree(
C& context,
const typename C::IndividualType& individual)
{
return typename C::IndividualType(
mutate_subtree<C>(context, individual.tree()));
}
// Point mutation
template<typename R, typename D>
Tree mutate_point(Tree tree, float p_term, R& prng, D& value_dist);
template<typename R>
Tree mutate_point(Tree tree, float p_term, R& prng);
template<typename C>
Tree mutate_point(C& context, Tree tree, float p_term) {
return mutate_point<typename C::PrngType, typename C::ValueDistType>(
tree, p_term, context.prng, context.value_dist);
}
template<typename C>
Tree mutate_point(C& context, Tree tree) {
const Config& config = context.config;
return mutate_point<C>(
context,
tree,
config.get<float>(conf::MutationPointPTerm));
}
template<typename C>
typename C::IndividualType mutate_point(
C& context,
const typename C::IndividualType& individual)
{
return typename C::IndividualType(
mutate_point<C>(context, individual.tree()));
}
// Hoist mutation
template<typename R>
Tree mutate_hoist(Tree tree, float p_term, R& prng);
template<typename C>
Tree mutate_hoist(C& context, Tree tree, float p_term) {
return mutate_hoist<typename C::PrngType>(tree, p_term, context.prng);
}
template<typename C>
Tree mutate_hoist(C& context, Tree tree) {
const Config& config = context.config;
return mutate_hoist<C>(
context,
tree,
config.get<float>(conf::MutationHoistPTerm));
}
template<typename C>
typename C::IndividualType mutate_hoist(
C& context,
const typename C::IndividualType& individual)
{
return typename C::IndividualType(
mutate_hoist<C>(context, individual.tree()));
}
}}
#include "impl/mutation.ipp"
#endif
| [
"managerzf168@gmail.com"
] | managerzf168@gmail.com |
5448e584e89a7745a7cf277ecdc926f42f80b7c0 | 2eecc41bc8ae893490b30e3abd9808bbd2bd6bdb | /Include/scge/Math/Quaternion.h | 48ae135659ae4827aeae8278bfff57007b24c972 | [] | no_license | shadercoder/scge | d991230860573a56a44f3ecac2de38c4f25a67f3 | cec2bb285aa284206b4d41b9bbbf129a151bf200 | refs/heads/master | 2021-01-10T04:20:19.240225 | 2012-11-05T22:50:20 | 2012-11-05T22:50:20 | 44,643,412 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 6,154 | h | #ifndef __Quaternion_h__
#define __Quaternion_h__
#include "scge\Math.h"
//-----------------------------------//
class Quaternion
{
public:
// Default constructor, initializes to identity rotation (aka 0°)
inline Quaternion ()
: w(1), x(0), y(0), z(0)
{
}
// Construct from an explicit list of values
inline Quaternion (float fW, float fX, float fY, float fZ)
: w(fW), x(fX), y(fY), z(fZ)
{
}
// Construct a quaternion from a rotation matrix
inline Quaternion(const Matrix3& rot)
{
FromRotationMatrix(rot);
}
// Construct a quaternion from an angle/axis
inline Quaternion(const float& rfAngle, const Vector3& rkAxis)
{
FromAngleAxis(rfAngle, rkAxis);
}
// Construct a quaternion from 3 orthonormal local axes
inline Quaternion(const Vector3& xaxis, const Vector3& yaxis, const Vector3& zaxis)
{
FromAxes(xaxis, yaxis, zaxis);
}
inline void swap(Quaternion& other)
{
std::swap(w, other.w);
std::swap(x, other.x);
std::swap(y, other.y);
std::swap(z, other.z);
}
inline float operator[](const size_t i) const
{
return *(&w+i);
}
inline float& operator[](const size_t i)
{
return *(&w+i);
}
inline float *ptr()
{
return &w;
}
inline const float *ptr() const
{
return &w;
}
void FromRotationMatrix(const Matrix3& kRot);
Matrix3 ToRotationMatrix() const;
void FromAngleAxis(const float& rfAngle, const Vector3& rkAxis);
void ToAngleAxis(float& rfAngle, Vector3& rkAxis) const;
void FromAxes(const Vector3& xAxis, const Vector3& yAxis, const Vector3& zAxis);
void ToAxes(Vector3& xAxis, Vector3& yAxis, Vector3& zAxis) const;
Vector3 getXAxis() const;
Vector3 getYAxis() const;
Vector3 getZAxis() const;
inline Quaternion& operator=(const Quaternion& rkQ)
{
w = rkQ.w;
x = rkQ.x;
y = rkQ.y;
z = rkQ.z;
return *this;
}
Quaternion operator+(const Quaternion& other) const;
Quaternion operator-(const Quaternion& other) const;
Quaternion operator*(const Quaternion& other) const;
Quaternion operator*(float fScalar) const;
friend Quaternion operator*(float fScalar, const Quaternion& rkQ);
Quaternion operator-() const;
inline bool operator==(const Quaternion& rhs) const
{
return (rhs.x == x) && (rhs.y == y) && (rhs.z == z) && (rhs.w == w);
}
inline bool operator!=(const Quaternion& rhs) const
{
return !operator==(rhs);
}
// functions of a quaternion
float Dot(const Quaternion& rkQ) const; // dot product
inline float LengthSquared() const { return w*w + x*x + y*y + z*z; }
float Normalise();
Quaternion getInverse() const;
Quaternion getConjugate() const;
Quaternion Exp() const;
Quaternion Log() const;
// rotation of a vector by a quaternion
Vector3 operator*(const Vector3& rkVector) const;
friend Vector3 operator*(const Vector3& rkVector, const Quaternion& rkQ);
/** Calculate the local roll element of this quaternion.
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Y of the quaternion onto the X and
Y axes, the angle between them is returned. If set to false though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
float getRoll(bool reprojectAxis = true) const;
/** Calculate the local pitch element of this quaternion
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Z of the quaternion onto the X and
Y axes, the angle between them is returned. If set to true though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
float getPitch(bool reprojectAxis = true) const;
/** Calculate the local yaw element of this quaternion
@param reprojectAxis By default the method returns the 'intuitive' result
that is, if you projected the local Z of the quaternion onto the X and
Z axes, the angle between them is returned. If set to true though, the
result is the actual yaw that will be used to implement the quaternion,
which is the shortest possible path to get to the same orientation and
may involve less axial rotation.
*/
float getYaw(bool reprojectAxis = true) const;
/// Equality with tolerance (tolerance is max angle difference)
bool equals(const Quaternion& rhs, const float& tolerance) const;
// spherical linear interpolation
static Quaternion Slerp(float fT, const Quaternion& rkP, const Quaternion& rkQ, bool shortestPath = false);
static Quaternion SlerpExtraSpins(float fT, const Quaternion& rkP, const Quaternion& rkQ, int iExtraSpins);
// setup for spherical quadratic interpolation
static void Intermediate(const Quaternion& rkQ0, const Quaternion& rkQ1, const Quaternion& rkQ2, Quaternion& rka, Quaternion& rkB);
// spherical quadratic interpolation
static Quaternion Squad(float fT, const Quaternion& rkP, const Quaternion& rkA, const Quaternion& rkB, const Quaternion& rkQ, bool shortestPath = false);
// normalised linear interpolation - faster but less accurate (non-constant rotation velocity)
static Quaternion nlerp(float fT, const Quaternion& rkP, const Quaternion& rkQ, bool shortestPath = false);
// Check whether this quaternion contains valid values
inline bool isNaN() const
{
return Math::isNaN(x) || Math::isNaN(y) || Math::isNaN(z) || Math::isNaN(w);
}
// Function for writing to a stream. Outputs "Quaternion(w, x, y, z)" with w,x,y,z being the member values of the quaternion.
inline friend std::ostream& operator<<(std::ostream& o, const Quaternion& q)
{
o << "Quaternion(" << q.w << ", " << q.x << ", " << q.y << ", " << q.z << ")";
return o;
}
static const Quaternion Identity;
static const Quaternion Zero;
public:
float w, x, y, z;
};
//-----------------------------------//
#endif // __Quaternion_h__ | [
"quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a"
] | quaver.smith@0469fb3b-1f0d-998d-8d12-02512b85cd7a |
8d389f625a65eef2c8ec838f20dfde7f22a453c1 | d798bed49a523108fe38205380dcc26925bbfed0 | /trie/include/wordsearch_solver/trie/trie.hpp | 02999136d561d1b85afddb9e34ddcf4d7827a48a | [
"MIT"
] | permissive | Arghnews/wordsearch_solver | f6a06dae18176888ed20aaf5e49ae6c4670f35db | cf25db64ca3d1facd9191aad075654f124f0d580 | refs/heads/main | 2023-08-05T10:46:29.732929 | 2021-09-20T21:47:24 | 2021-09-20T21:47:24 | 395,403,517 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,813 | hpp | #ifndef TRIE_HPP
#define TRIE_HPP
#include "wordsearch_solver/trie/node.hpp"
#include "wordsearch_solver/utility/flat_char_value_map.hpp"
#include <fmt/core.h>
#include <fmt/format.h>
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <algorithm>
#include <cstdint>
#include <initializer_list>
#include <iterator>
#include <ostream>
#include <string>
#include <string_view>
#include <tuple>
#include <type_traits>
#include <utility>
#include <vector>
// TODO: test this with const_iterator not a std::tuple, and try a simple user
// defined struct/pointer to make trivial type to help the optimiser? Not even
// sure if "trivial" means what I think it does anyway, remove this likely..
// TODO: maybe look into units library for the ascii/index conversion stuff, as
// that has already wasted a significant amount of time with offset stuff
// TODO: std::bitset size on this system is 8 bytes, even though it need only be
// 4 bytes (26 bits) for lowercase ascii. Could see if writing own node without
// std::bitset that is 4 bytes big changes performance due to whole thing being
// approx half size (better for cache).
/** namespace trie */
namespace trie {
/** Recursive immutable node based trie.
*
* Recursive tree structure of nodes, where each node holds a vector-like
* container of edges, and each edge consists of a character and a pointer to
* the corresponding child node.
* To lookup a word of length "m", using a dictionary with "d" distinct
* characters, for example d == 26 for lowercase ascii and the English alphabet,
* lookup is O(m * d).
*
* Realistically, the factor of d will usually be much less
* than the actual value of d, so really more like just O(m). Could say that
* furthermore, since (in English at least) average word length is much shorter
* than max(m) anyway, essentially this becomes almost constant time lookup.
*
* @note Not thread safe even for just reading, due to use of unprotected
* internal cache.
*/
class Trie {
public:
Trie() = default;
Trie(Trie&&) = default;
Trie& operator=(Trie&&) = default;
/** @note See trie/include/wordsearch_solver/trie/node.hpp before
* changing/implementing this, must implement proper deep copy, traits don't
* behave nicely.
*/
Trie(const Trie&) = delete;
Trie& operator=(const Trie&) = delete;
Trie(const std::initializer_list<std::string_view>& words);
Trie(const std::initializer_list<std::string>& words);
Trie(const std::initializer_list<const char*>& words);
template <class Iterator1, class Iterator2>
Trie(Iterator1 first, const Iterator2 last);
// TODO: constrain this (sfinae or concepts(>=c++20))
// Strings should be a range of strings
template <class Strings> explicit Trie(Strings&& strings_in);
/** @copydoc solver::SolverDictWrapper::contains() */
bool contains(std::string_view word) const;
/** @copydoc solver::SolverDictWrapper::further() */
bool further(std::string_view word) const;
/** @copydoc solver::SolverDictWrapper::contains_further() */
template <class OutputIterator>
void contains_further(const std::string_view stem,
const std::string_view suffixes,
OutputIterator contains_further_it) const;
std::size_t size() const;
bool empty() const;
friend std::ostream& operator<<(std::ostream& os, const Trie& ct);
private:
const Node* search(std::string_view word) const;
std::pair<Node*, bool> insert(std::string_view word);
Node root_;
std::size_t size_;
mutable utility::FlatCharValueMap<const Node*> cache_;
};
namespace detail {
bool contains(const Node& node, std::string_view word);
bool further(const Node& node, std::string_view word);
} // namespace detail
} // namespace trie
#include "wordsearch_solver/trie/trie.tpp"
#endif // TRIE_HPP
| [
"arghnews@hotmail.co.uk"
] | arghnews@hotmail.co.uk |
7f646122d2676ae73229f73ed965445a566aff73 | 3b04925b4271fe921020cff037b86e4a5a2ae649 | /windows_embedded_ce_6_r3_170331/WINCE600/PRIVATE/TEST/NET/WIRELESS/COMMON/APCONTROLLER/SERVER/azimuthcontroller_t.cpp | 4160e4d3a1e2aaf5726183478972931a8f974d0b | [] | no_license | fanzcsoft/windows_embedded_ce_6_r3_170331 | e3a4d11bf2356630a937cbc2b7b4e25d2717000e | eccf906d61a36431d3a37fb146a5d04c5f4057a2 | refs/heads/master | 2022-12-27T17:14:39.430205 | 2020-09-28T20:09:22 | 2020-09-28T20:09:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,275 | cpp | //
// Copyright (c) Microsoft Corporation. All rights reserved.
//
//
// Use of this source code is subject to the terms of the Microsoft shared
// source or premium shared source license agreement under which you licensed
// this source code. If you did not accept the terms of the license agreement,
// you are not authorized to use this source code. For the terms of the license,
// please see the license agreement between you and Microsoft or, if applicable,
// see the SOURCE.RTF on your install media or the root of your tools installation.
// THE SOURCE CODE IS PROVIDED "AS IS", WITH NO WARRANTIES.
//
// ----------------------------------------------------------------------------
//
// Use of this source code is subject to the terms of the Microsoft end-user
// license agreement (EULA) under which you licensed this SOFTWARE PRODUCT.
// If you did not accept the terms of the EULA, you are not authorized to use
// this source code. For a copy of the EULA, please see the LICENSE.RTF on your
// install media.
//
// ----------------------------------------------------------------------------
//
// Implementation of the AzimuthController_t class.
//
// ----------------------------------------------------------------------------
#include "AzimuthController_t.hpp"
#include "RFAttenuatorState_t.hpp"
#include <assert.h>
#include <tchar.h>
#include <strsafe.h>
using namespace ce::qa;
// ----------------------------------------------------------------------------
//
// Constructor.
//
AzimuthController_t::
AzimuthController_t(
const TCHAR *pDeviceType,
const TCHAR *pDeviceName)
: DeviceController_t(pDeviceType, pDeviceName)
{
// nothing to do
}
// ----------------------------------------------------------------------------
//
// Destructor.
//
AzimuthController_t::
~AzimuthController_t(void)
{
// nothing to do
}
// ----------------------------------------------------------------------------
//
// Runs the specified Tcl commands and returns the results.
//
static DWORD
RunTclScript(
const TCHAR *pCommands,
ce::tstring *pResults,
long MaxSecondsToWait)
{
HRESULT hr;
DWORD result;
ce::tstring shellCmdLine;
ce::auto_handle childProcess;
TCHAR scriptInName[MAX_PATH] = TEXT("");
ce::auto_handle scriptInFile;
TCHAR scriptOutName[MAX_PATH] = TEXT("");
ce::auto_handle scriptOutFile;
// Get the name of the temporary directory.
TCHAR tempDir[MAX_PATH-14];
DWORD tempDirChars = COUNTOF(tempDir);
if (GetTempPath(tempDirChars - 1, tempDir) > tempDirChars)
{
result = ERROR_OUTOFMEMORY;
LogError(TEXT("Can't get temp directory name"));
goto Cleanup;
}
// Synchronize these operations to avoid file-system collisions.
else
{
static ce::critical_section LockObject;
ce::gate<ce::critical_section> locker(LockObject);
// Generate the temporary file names.
result = GetTempFileName(tempDir, TEXT("tci"), 0, scriptInName);
if (0 == result)
{
LogError(TEXT("Can't get temp script input file name: %s"),
Win32ErrorText(result));
goto Cleanup;
}
result = GetTempFileName(tempDir, TEXT("tco"), 0, scriptOutName);
if (0 == result)
{
LogError(TEXT("Can't get temp script output file name: %s"),
Win32ErrorText(result));
goto Cleanup;
}
// Redirect the script's output to the temporary file.
ce::tstring redirected;
result = WiFUtils::FmtMessage(&redirected,
TEXT("set OUT [ open {%s} w ]\n%s"),
scriptOutName, pCommands);
if (ERROR_SUCCESS != result)
{
goto Cleanup;
}
// Convert the commands to ASCII.
ce::string mbCommands;
hr = WiFUtils::ConvertString(&mbCommands, redirected,
"Tcl commands");
if (FAILED(hr))
{
result = HRESULT_CODE(hr);
goto Cleanup;
}
// Copy the command(s) to the temporary input file.
scriptInFile = CreateFile(scriptInName,
GENERIC_WRITE, 0, NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_TEMPORARY, NULL);
if (!scriptInFile.valid() || INVALID_HANDLE_VALUE == scriptInFile)
{
result = GetLastError();
LogError(TEXT("Can't open script file \"%s\": %s"),
scriptInName, Win32ErrorText(result));
goto Cleanup;
}
DWORD writeSize;
if (!WriteFile(scriptInFile, &mbCommands[0],
mbCommands.length(), &writeSize, NULL)
|| mbCommands.length() != writeSize)
{
result = GetLastError();
LogError(TEXT("Can't write Tcl commands to script file: %s"),
Win32ErrorText(result));
goto Cleanup;
}
scriptInFile.close();
// Generate the shell command-line.
result = WiFUtils::FmtMessage(&shellCmdLine,
TEXT("cmd.exe /Q /A /C %s %s"),
Utils::pShellExecName, scriptInName);
if (ERROR_SUCCESS != result)
{
goto Cleanup;
}
// Execute the tclsh process.
PROCESS_INFORMATION procInfo;
memset(&procInfo, 0, sizeof(procInfo));
STARTUPINFO startInfo;
memset(&startInfo, 0, sizeof(startInfo));
startInfo.cb = sizeof(startInfo);
startInfo.hStdError = GetStdHandle(STD_ERROR_HANDLE);
startInfo.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE);
startInfo.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
startInfo.dwFlags |= STARTF_USESTDHANDLES;
TCHAR *cmdLine = shellCmdLine.get_buffer();
if (!CreateProcess(NULL, cmdLine,
NULL, // process security attributes
NULL, // primary thread security attributes
TRUE, // handles are inherited
0, // creation flags
NULL, // use parent's environment
NULL, // use parent's current directory
&startInfo, // STARTUPINFO
&procInfo)) // PROCESS_INFORMATION
{
result = GetLastError();
LogError(TEXT("CreateProcess \"%s\" failed: %s"),
cmdLine, Win32ErrorText(result));
goto Cleanup;
}
childProcess = procInfo.hProcess;
CloseHandle(procInfo.hThread);
}
// Wait for the child to finish.
LogDebug(TEXT("[AC] Waiting %d seconds for Tcl script"), MaxSecondsToWait);
result = WaitForSingleObject(childProcess, MaxSecondsToWait * 1000);
if (WAIT_OBJECT_0 != result)
{
LogError(TEXT("Shell failed: %s"), Win32ErrorText(result));
goto Cleanup;
}
if (GetExitCodeProcess(childProcess, &result) && 0 != result)
{
LogError(TEXT("Shell failed: probably")
TEXT(" unable to exec Tcl Shell \"%s\""),
Utils::pShellExecName);
result = ERROR_FILE_NOT_FOUND;
goto Cleanup;
}
// Read the script output and convert it to unicode.
pResults->clear();
scriptOutFile = CreateFile(scriptOutName,
GENERIC_READ, 0, NULL,
OPEN_EXISTING, 0, NULL);
if (!scriptOutFile.valid() || INVALID_HANDLE_VALUE == scriptOutFile)
{
result = GetLastError();
LogError(TEXT("Can't open Tcl script output file \"%s\": %s"),
scriptOutName, Win32ErrorText(result));
goto Cleanup;
}
for (;;)
{
char readBuffer[1024];
DWORD bytesRead = 0;
if (!ReadFile(scriptOutFile, readBuffer,
COUNTOF(readBuffer), &bytesRead, NULL))
{
result = GetLastError();
if (ERROR_MORE_DATA != result)
{
LogError(TEXT("Can't read Tcl script output: %s"),
Win32ErrorText(result));
goto Cleanup;
}
}
if (0 == bytesRead)
break;
ce::tstring tResults;
hr = WiFUtils::ConvertString(&tResults, readBuffer,
"Tcl results", bytesRead);
if (FAILED(hr))
{
result = HRESULT_CODE(hr);
goto Cleanup;
}
if (!pResults->append(tResults))
{
result = ERROR_OUTOFMEMORY;
goto Cleanup;
}
}
result = ERROR_SUCCESS;
Cleanup:
if (TEXT('\0') != scriptInName[0])
{
scriptInFile.close();
DeleteFile(scriptInName);
}
if (TEXT('\0') != scriptOutName[0])
{
scriptOutFile.close();
DeleteFile(scriptOutName);
}
return result;
}
// ----------------------------------------------------------------------------
//
// Gets the current, minimum and maximum RF attenuation.
//
static DWORD
DoGetAttenuator(
const TCHAR *pDeviceName,
RFAttenuatorState_t *pResponse)
{
DWORD result;
ce::tstring script;
ce::tstring scriptResults;
// Build a Tcl script to retrieve the attenuation values.
static const TCHAR ScriptPattern[] =
TEXT("if { [catch {package require Azimuth-Sdk} retmsg] } {\n")
TEXT(" puts $OUT \"ERROR: cannot load Azimuth package: err=$retmsg\"\n")
TEXT(" exit\n")
TEXT("}\n")
TEXT("if { [catch {atten_init %s} retmsg] } {\n")
TEXT(" puts $OUT \"ERROR: cannot init attenuator %s: err=$retmsg\"\n")
TEXT(" exit\n")
TEXT("}\n")
TEXT("set currentAtten [ atten_get %s ]\n")
TEXT("set maximumAtten [ atten_get_max %s ]\n")
TEXT("puts $OUT \"Current Attenuation = $currentAtten\"\n")
TEXT("puts $OUT \"Maximum Attenuation = $maximumAtten\"\n");
static const TCHAR CurrentLabel[] = TEXT("Current Attenuation =");
static const TCHAR MaximumLabel[] = TEXT("Maximum Attenuation =");
result = WiFUtils::FmtMessage(&script, ScriptPattern,
pDeviceName, pDeviceName,
pDeviceName, pDeviceName);
if (ERROR_SUCCESS != result)
{
LogError(TEXT("Tcl script generation error: %s"),
Win32ErrorText(result));
return result;
}
// Run the Tcl script.
result = RunTclScript(script, &scriptResults, 20);
if (ERROR_SUCCESS != result)
{
LogError(TEXT("Tcl script processing error: %s"),
Win32ErrorText(result));
return result;
}
// Just return script errors.
if (_tcsstr(scriptResults, TEXT("ERROR")) != NULL)
{
LogError(TEXT("%s"), &scriptResults[0]);
return ERROR_INVALID_DATA;
}
// Extract the attenuation values.
const TCHAR *curStr = _tcsstr(scriptResults, CurrentLabel);
const TCHAR *maxStr = _tcsstr(scriptResults, MaximumLabel);
if (NULL == curStr || NULL == maxStr)
{
LogError(TEXT("Malformed script output:\n%s"),
&scriptResults[0]);
return ERROR_INVALID_DATA;
}
curStr += COUNTOF(CurrentLabel);
maxStr += COUNTOF(MaximumLabel);
TCHAR *curEnd;
TCHAR *maxEnd;
double curVal = _tcstod(curStr, &curEnd);
double maxVal = _tcstod(maxStr, &maxEnd);
if (NULL == curEnd || !_istspace(curEnd[0]) || 0.0 > curVal
|| NULL == maxEnd || !_istspace(maxEnd[0]) || 0.0 > maxVal)
{
LogError(TEXT("Malformed script output:\n%s"),
&scriptResults[0]);
return ERROR_INVALID_DATA;
}
pResponse->Clear();
pResponse->SetCurrentAttenuation((int)(curVal + 0.5));
pResponse->SetMinimumAttenuation(0);
pResponse->SetMaximumAttenuation((int)(maxVal + 0.5));
return ERROR_SUCCESS;
}
DWORD
AzimuthController_t::
GetAttenuator(
RFAttenuatorState_t *pResponse,
ce::tstring *pErrorMessage)
{
ErrorLock captureErrors(pErrorMessage);
DWORD result = DoGetAttenuator(GetDeviceName(), pResponse);
return result;
}
// ----------------------------------------------------------------------------
//
// Sets the current attenuation for the RF attenuator.
//
static DWORD
DoSetAttenuator(
const TCHAR *pDeviceName,
int NewAttenuation,
RFAttenuatorState_t *pResponse)
{
DWORD result;
ce::tstring script;
ce::tstring scriptResults;
// Build a Tcl script to retrieve the attenuation values.
static const TCHAR ScriptPattern[] =
TEXT("if { [catch {package require Azimuth-Sdk} retmsg] } {\n")
TEXT(" puts $OUT \"ERROR: cannot load Azimuth package: err=$retmsg\"\n")
TEXT(" exit\n")
TEXT("}\n")
TEXT("if { [catch {atten_init %s} retmsg] } {\n")
TEXT(" puts $OUT \"ERROR: cannot init attenuator %s: err=$retmsg\"\n")
TEXT(" exit\n")
TEXT("}\n")
TEXT("set currentAtten [ atten_set %s %d ]\n")
TEXT("set maximumAtten [ atten_get_max %s ]\n")
TEXT("puts $OUT \"Current Attenuation = $currentAtten\"\n")
TEXT("puts $OUT \"Maximum Attenuation = $maximumAtten\"\n");
static const TCHAR CurrentLabel[] = TEXT("Current Attenuation =");
static const TCHAR MaximumLabel[] = TEXT("Maximum Attenuation =");
result = WiFUtils::FmtMessage(&script, ScriptPattern,
pDeviceName,
pDeviceName,
pDeviceName,
NewAttenuation,
pDeviceName);
if (ERROR_SUCCESS != result)
{
LogError(TEXT("Tcl script generation error: %s"),
Win32ErrorText(result));
return result;
}
// Run the Tcl script.
result = RunTclScript(script, &scriptResults, 20);
if (ERROR_SUCCESS != result)
{
LogError(TEXT("Tcl script processing error: %s"),
Win32ErrorText(result));
return result;
}
// Just return script errors.
if (_tcsstr(scriptResults, TEXT("ERROR")) != NULL)
{
LogError(TEXT("%s"), &scriptResults[0]);
return ERROR_INVALID_DATA;
}
// Extract the attenuation values.
const TCHAR *curStr = _tcsstr(scriptResults, CurrentLabel);
const TCHAR *maxStr = _tcsstr(scriptResults, MaximumLabel);
if (NULL == curStr || NULL == maxStr)
{
LogError(TEXT("Malformed script output:\n%s"),
&scriptResults[0]);
return ERROR_INVALID_DATA;
}
curStr += COUNTOF(CurrentLabel);
maxStr += COUNTOF(MaximumLabel);
TCHAR *curEnd;
TCHAR *maxEnd;
double curVal = _tcstod(curStr, &curEnd);
double maxVal = _tcstod(maxStr, &maxEnd);
if (NULL == curEnd || !_istspace(curEnd[0]) || 0.0 > curVal
|| NULL == maxEnd || !_istspace(maxEnd[0]) || 0.0 > maxVal)
{
LogError(TEXT("Malformed script output:\n%s"),
&scriptResults[0]);
return ERROR_INVALID_DATA;
}
// Make sure the new attenuation is reasonably close.
int newAtten = (int)(curVal + 0.5);
if (newAtten != NewAttenuation)
{
LogError(TEXT("Attenuation set failed: asked for %d, got %g"),
NewAttenuation, curVal);
return ERROR_INVALID_DATA;
}
pResponse->Clear();
pResponse->SetCurrentAttenuation(newAtten);
pResponse->SetMinimumAttenuation(0);
pResponse->SetMaximumAttenuation((int)(maxVal + 0.5));
return ERROR_SUCCESS;
}
DWORD
AzimuthController_t::
SetAttenuator(
const RFAttenuatorState_t &NewState,
RFAttenuatorState_t *pResponse,
ce::tstring *pErrorMessage)
{
DWORD result = ERROR_SUCCESS;
ErrorLock captureErrors(pErrorMessage);
// Until the attenuation reaches the desired setting...
int newAtten = NewState.GetCurrentAttenuation();
long startTime = GetTickCount();
long stopTime = (long)NewState.GetAdjustTime() * 1000;
long stepTime = NewState.GetStepTimeMS();
for (;;)
{
// Set the attenuation.
result = DoSetAttenuator(GetDeviceName(), newAtten, pResponse);
if (ERROR_SUCCESS != result)
break;
// Stop if we've reached the desired attenuation setting.
int remaining = NewState.GetFinalAttenuation() - newAtten;
if (remaining == 0)
break;
// Calculate the next attenuation step and sleep until it's time.
long runDuration = WiFUtils::SubtractTickCounts(startTime,
GetTickCount());
long remainingTime = stopTime - runDuration;
if (remainingTime < 1)
{
newAtten += remaining;
}
else
{
long remainingSteps = (remainingTime + stepTime - 1) / stepTime;
if (remainingSteps < 2)
remainingSteps = 1;
else
{
while (remaining / remainingSteps == 0)
remainingSteps--;
}
newAtten += remaining / remainingSteps;
Sleep(remainingTime / remainingSteps);
}
}
return result;
}
// ----------------------------------------------------------------------------
| [
"benjamin.barratt@icloud.com"
] | benjamin.barratt@icloud.com |
0467683c93d2e29e4aeb612d66d8ebefa778f24c | 3af65491fdb452239cc090f4c200815587295bef | /kds/Dinic.h | 6fb73e45374a9d734e2db57334aa61697a25baf7 | [] | no_license | Wazti/something | eb9a00f3b60bbc686bf001dd28aeab836b72a456 | b01d7ce6c28c0f6285c0ff75e321ea9b9cde6e6d | refs/heads/master | 2020-05-07T15:48:05.787772 | 2019-04-11T21:30:43 | 2019-04-11T21:30:43 | 180,652,958 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 989 | h | //
// Created by Weezle on 2019-04-9.
//
#ifndef KDS_DINIC_H
#define KDS_DINIC_H
#include <vector>
using namespace std;
//Структура ребра между двумя вершинами
struct Edge
{
int v ; // вершина/Vertex v
int flow ; // поток в ребре
int C; // вместимость
int rev ; // To store index of reverse
// edge in adjacency list so that
// we can quickly find it.
};
// Остаточный граф
class Dinic {
int V; // количество вершин
int *level ; // уровни узла
vector<Edge> *adject;
vector<std::pair<int, int>> pairs;
public :
Dinic(vector<vector<int>> matrix, int V, vector<std::pair<int, int>> pairs);
void run();
void readFromMatrix(vector<vector<int>> matrix);
void addEdge(int u, int v, int C);
bool bfs(int s, int t);
int dfs(int s, int flow, int t, int ptr[]);
int dinicMaxflow(int s, int t);
};
#endif //KDS_DINIC_H
| [
"iakudrya@edu.hse.ru"
] | iakudrya@edu.hse.ru |
ea837243351d5a866e238ed493db0b64b3dd06db | 4bbbd35acc2f96dcb66f1a0e395d934d63866af0 | /ThamSoHinhThucVaThamSoThuc/main.cpp | b15d3e9d15b5212156650484f6a6534a6b96c46a | [] | no_license | taidangit/C-tranduythanh | f161bb33962101db68f3edc23ae438d78bcc4796 | 9a96c90bd5e5f29b8668f5bd0c655f4eb8dbee67 | refs/heads/master | 2020-12-04T18:09:48.571822 | 2020-01-05T03:27:30 | 2020-01-05T03:27:53 | 231,861,663 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 316 | cpp | #include <iostream>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
int min(int a, int b);
int main(int argc, char** argv) {
int c=5;
int d=6;
int x=min(c,d);
cout<<"Min="<<x<<endl;
return 0;
}
int min(int a, int b) {
return a<b?a:b;
}
| [
"dangphattai92@gmail.com"
] | dangphattai92@gmail.com |
56b82f58a6a1b6e8f715674922aab475c6140e67 | cb30ff3333fdde48170a5717ef92fe1a89b9f574 | /服务器端/MyGraduate_Project/MyGraduate_Project/MsgPing.h | 1c983f553b6aec7c06c4fe03ef580106807943c4 | [] | no_license | LBqqcom/MyGraduate_Project | 36d9f9e5975aaeb1f7aa86244a3b52f496f9089f | 0004499c5f76009bc34f38d1db859d2326889cc8 | refs/heads/master | 2020-05-28T12:18:10.995939 | 2019-03-01T01:38:12 | 2019-03-01T01:38:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | h | #ifndef __MSG_PING_H__
#define _MSG_PING_H__
#include "BaseMsg.h"
class MsgPing:public BaseMsg
{
public:
MsgPing();
~MsgPing();
char* EnCode(int &dataLen);
BaseMsg* DeCode(Json::Value value);
void PrintData();
private:
};
#endif // !__MSG_PING_H__
| [
"892544825@qq.com"
] | 892544825@qq.com |
e38becde7890e3c40f9d8ea7f6ee8a501d2f0e7d | 81c66c9c0b78f8e9c698dcbb8507ec2922efc8b7 | /src/domains/srcgc/kernel/SRCGCTarget.h | 0aee21f30fed6874dc62a7d80a78c12b4b64331d | [
"MIT-Modern-Variant"
] | permissive | Argonnite/ptolemy | 3394f95d3f58e0170995f926bd69052e6e8909f2 | 581de3a48a9b4229ee8c1948afbf66640568e1e6 | refs/heads/master | 2021-01-13T00:53:43.646959 | 2015-10-21T20:49:36 | 2015-10-21T20:49:36 | 44,703,423 | 0 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 7,728 | h | /* -*-C++-*-
* ###################################################################
* SRCGC - Synchronous/Reactive C code generation for Ptolemy
*
* FILE: "SRCGCTarget.h"
* created: 9/03/98 15:32:49
* last update: 13/05/98 9:21:57
* Author: Vincent Legrand, Mathilde Roger, Frédéric Boulanger
* E-mail: Frederic.Boulanger@supelec.fr
* mail: Supélec - Service Informatique
* Plateau de Moulon, F-91192 Gif-sur-Yvette cedex
* www: http://wwwsi.supelec.fr/
*
* Thomson: Xavier Warzee <XAVIER.W.X.WARZEE@tco.thomson.fr>
*
* Copyright (c) 1998 Supélec & Thomson-CSF Optronique.
* All rights reserved.
*
* Permission is hereby granted, without written agreement and without
* license or royalty fees, to use, copy, modify, and distribute this
* software and its documentation for any purpose, provided that the
* above copyright notice and the following two paragraphs appear in all
* copies of this software.
*
* IN NO EVENT SHALL SUPELEC OR THOMSON-CSF OPTRONIQUE BE LIABLE TO ANY PARTY
* FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
* SUPELEC OR THOMSON-CSF OPTRONIQUE HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* SUPELEC AND THOMSON-CSF OPTRONIQUE SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND SUPELEC OR THOMSON-CSF
* OPTRONIQUE HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS.
*
* Description:
* Basic target for C code generation.
*
* History
*
* modified by rev reason
* -------- --- --- -----------
* 9/03/98 FBO 1.0 original
* ###################################################################
*/
#ifndef _SRCGCTarget_h
#define _SRCGCTarget_h 1
#ifdef __GNUG__
#pragma interface
#endif
#include "HLLTarget.h"
#include "StringState.h"
#include "StringArrayState.h"
#include "IntState.h"
#include "HashTable.h" // To pick up the definition of TextTable
// Defined in SRCGCDomain.cc
extern const char SRCGCdomainName[];
class SRCGCStar;
class SRCGCRecursiveScheduler;
class SRCGCTarget : public HLLTarget {
public:
SRCGCTarget(const char* name, const char* starclass,
const char* desc,
const char* assocDomain = SRCGCdomainName);
/*virtual*/ Block* makeNew() const;
// Class identification.
/*virtual*/ int isA(const char*) const;
/*virtual*/ int compileCode();
/*virtual*/ int runCode();
/*virtual*/ StringList comment(const char* text, const char* begin=NULL,
const char* end=NULL, const char* cont=NULL);
/*virtual*/ void beginIteration(int repetitions, int depth);
/*virtual*/ void endIteration(int repetitions, int depth);
// virtual method to generate compiling command
virtual StringList compileLine(const char* fName);
// set the hostMachine name
void setHostName(const char* s) { targetHost = s; }
const char* hostName() { return (const char*) targetHost; }
// redefine writeCode: default file is "code.c"
/*virtual*/ void writeCode();
// static buffering option can be set by parent target
void wantStaticBuffering() { staticBuffering = TRUE; }
int useStaticBuffering() { return int(staticBuffering); }
// incrementally add a star to the code
/*virtual*/ int incrementalAdd(CGStar* s, int flag = 1);
// incremental addition of a Galaxy code
/*virtual*/ int insertGalaxyCode(Galaxy* g, SRCGCRecursiveScheduler* s);
/*virtual*/ int insertGalaxyCode2(Galaxy* g, SRCGCRecursiveScheduler* s);
// Functions defining the pragma mechanism. Currently used in
// SRCGC to support command-line arguments in the generated code.
/*virtual*/ StringList pragma () const {return "state_name_mapping STRING"; }
/*virtual*/ StringList pragma (const char* parentname,
const char* blockname) const;
/*virtual*/ StringList pragma (const char* parentname,
const char* blockname,
const char* pragmaname) const;
/*virtual*/ StringList pragma (const char* parentname,
const char* blockname,
const char* name,
const char* value);
protected:
/*virtual*/ void setup();
// code strings
// "mainClose" is separated because when we insert a galaxy code
// by insertGalaxyCode(), we need to put wrapup code at the end
// of the body.
// "commInit" is separated to support recursion construct.
// Some wormhole codes are put into several set of processor
// groups. Since commInit code is inserted by pairSendReceive()
// method of the parent target, we need to able to copy this code.
// stream.
CodeStream globalDecls;
CodeStream include;
CodeStream mainDecls;
CodeStream mainInit;
CodeStream portInit;
CodeStream commInit;
CodeStream wormIn;
CodeStream wormOut;
CodeStream mainClose;
// Four new CodeStreams to add in codes for command-line
// argument support.
CodeStream cmdargStruct;
CodeStream cmdargStructInit;
CodeStream setargFunc;
CodeStream setargFuncHelp;
CodeStream compileOptionsStream;
CodeStream linkOptionsStream;
CodeStream localLinkOptionsStream;
CodeStream remoteLinkOptionsStream;
CodeStream remoteFilesStream;
CodeStream remoteCFilesStream;
// virtual function to initialize strings
virtual void initCodeStrings();
// buffer size determination
int allocateMemory();
// code generation init routine; compute offsets, generate initCode
int codeGenInit();
// Stages of code generation.
/*virtual*/ void headerCode();
/*virtual*/ void mainLoopCode();
/*virtual*/ void trailerCode();
// Combine all sections of code;
/*virtual*/ void frameCode();
// redefine compileRun() method to switch the code streams stars
// refer to.
/*virtual*/ void compileRun(SRCGCRecursiveScheduler*);
// Redefine:
// Add wormInputCode after iteration declaration and before the
// iteration body, and wormOutputCode just before the closure of
// the iteration.
/*virtual*/ void wormInputCode(PortHole&);
/*virtual*/ void wormOutputCode(PortHole&);
// states
IntState staticBuffering;
StringState funcName;
StringState compileCommand;
StringState compileOptions;
StringState linkOptions;
StringArrayState resources;
// combined linked options
StringList getLinkOptions(int expandEnvironmentVars);
// combined compile options
StringList getCompileOptions(int expandEnvironmentVars);
// complete list of C files on which the compilation depends
StringList getDependentCFiles(int expandEnvironmentVars);
// complete list of extra source files
StringList getDependentSourceFiles(int expandEnvironmentVars);
// if a remote compilation, then copy over dependent files
// to the remote machine
int processDependentFiles();
// give a unique name for a galaxy.
int galId;
int curId;
// Generate declarations and initialization code for
// Star PortHoles and States.
virtual void declareGalaxy(Galaxy&);
virtual void declareStar(SRCGCStar*);
virtual CodeStream mainLoopBody();
CodeStream mainLoop;
private:
// Use this to store the pragmas set for the target.
TextTable mappings;
};
#endif
| [
"dermalin3k@hotmail.com"
] | dermalin3k@hotmail.com |
24f37f28f22f5f58d25abaee6ad27137c4c221ec | cfeac52f970e8901871bd02d9acb7de66b9fb6b4 | /generated/src/aws-cpp-sdk-payment-cryptography/include/aws/payment-cryptography/PaymentCryptographyEndpointRules.h | ada770bbfb9bed6d45cd978c18feea0a35541d8b | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | aws/aws-sdk-cpp | aff116ddf9ca2b41e45c47dba1c2b7754935c585 | 9a7606a6c98e13c759032c2e920c7c64a6a35264 | refs/heads/main | 2023-08-25T11:16:55.982089 | 2023-08-24T18:14:53 | 2023-08-24T18:14:53 | 35,440,404 | 1,681 | 1,133 | Apache-2.0 | 2023-09-12T15:59:33 | 2015-05-11T17:57:32 | null | UTF-8 | C++ | false | false | 495 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <cstddef>
#include <aws/payment-cryptography/PaymentCryptography_EXPORTS.h>
namespace Aws
{
namespace PaymentCryptography
{
class PaymentCryptographyEndpointRules
{
public:
static const size_t RulesBlobStrLen;
static const size_t RulesBlobSize;
static const char* GetRulesBlob();
};
} // namespace PaymentCryptography
} // namespace Aws
| [
"github-aws-sdk-cpp-automation@amazon.com"
] | github-aws-sdk-cpp-automation@amazon.com |
2f0db7bd536bba2e979b09cddd977d29bdc7354e | 8661431df6856233183830647051373e09496891 | /Contest3/n_reinas.cpp | ef81ab347f01d7c14bc62b3633bb6e3fc6ecc1cd | [] | no_license | Naateri/Competitiva | 76c2d6694c816ec695f08f65bb57c1c94e52c388 | 4778b0777d0365f8ba3d5189285fe1d6b139c232 | refs/heads/master | 2020-05-14T22:10:08.873007 | 2019-07-01T20:06:16 | 2019-07-01T20:06:16 | 181,974,768 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,807 | cpp | #include <iostream>
#include <vector>
#include <string>
typedef std::vector<int> int_vec;
int current_sum = 0;
int new_sum = 0;
int** create_matrix(int n){
int** mat = new int*[n];
mat[0] = new int[n*n];
for (int i = 1; i < n; i++){
mat[i] = mat[i-1] + n;
}
for (int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
mat[i][j] = 0;
}
}
return mat;
}
void print_matrix(int** m, int n){ //works only for squared matrices
for(int i = 0; i < n; i++){
for (int j = 0; j < n; j++){
std::cout << m[i][j] << ' ';
}
std::cout << std::endl;
}
std::cout << std::endl;
}
bool safe_queen(int** mat, const int& pos_x, const int& pos_y){
for(int i = 0; i < 8; i++){ //vertical
if (i == pos_x) continue;
if (mat[i][pos_y]) return false;
}
for(int i = 0; i < 8; i++){ //horizontal
if (i == pos_y) continue;
if (mat[pos_x][i]) return false;
}
for(int i = pos_x, j = pos_y; i >= 0 && j >= 0; i--, j--){ //upper-left
if (mat[i][j]) return false;
}
for(int i = pos_x, j = pos_y; i < 8 && j < 8; i++, j++){ //lower-right
if (mat[i][j]) return false;
}
for(int i = pos_x, j = pos_y; i >= 0 && j < 8; i--, j++){ //upper-right
if (mat[i][j]) return false;
}
for(int i = pos_x, j = pos_y; i < 8 && j >= 0; i++, j--){ //lower-left
if (mat[i][j]) return false;
}
return true;
}
bool n_queens_solver(int** mat, int queen){
if (queen >= 8) return true; //all queens placed
for (int i = 0; i < 8; i++){
if (safe_queen(mat, i, queen)){
//current_sum += mat[i][queen];
//new_sum = mat[i][queen];
mat[i][queen] = 1;
if (n_queens_solver(mat, queen+1)) return true; //it found all queens
mat[i][queen] = 0; //it failed
//current_sum -= mat[i][queen];
}
}
return false;
}
int get_sum(int** mat, int** mat2){
int cur_sum = 0;
for(int i = 0; i < 8; i++){
for (int j = 0; j < 8; j++){
if (mat2[i][j] == 1){
cur_sum += mat[i][j];
}
}
}
return cur_sum;
}
void format(int res){
std::string prnt;
prnt = std::to_string(res);
int tam = 5 - prnt.size();
for(int i = 0; i < tam; i++)
prnt = ' ' + prnt;
std::cout << prnt << std::endl;
}
void n_queens(int** mat, int** mat2){
int max_res = 0;
for(int i = 0; i < 8; i++){
if (n_queens_solver(mat, i)){
int res = get_sum(mat2, mat);
if (res > max_res) max_res = res;
//std::cout << get_sum(mat2, mat) << std::endl;
}// else std::cout << "No hay solucion.\n";
}
format(max_res);
}
int main(int argc, char *argv[]) {
int k;
int** mat;
int** mat2;
mat = new int*[8];
for(int i = 0; i < 8; i++){
mat[i] = new int[8];
}
std::cin >> k;
for(int m = 0; m < k; m++){
//input mat
for(int i = 0; i < 8; i++){
for(int j = 0; j < 8; j++){
std::cin >> mat[i][j];
}
}
mat2 = create_matrix(8);
//print_matrix(mat, 8);
n_queens(mat2, mat);
}
return 0;
}
| [
"renato.postigo@ucsp.edu.pe"
] | renato.postigo@ucsp.edu.pe |
8fbe399d73cfe85802986ae4a6bb9ba538fb5dd7 | a9e7f3724ed765430f7d6f62ece6f456b7465629 | /PrimalityTestCarmichaelNumber.cpp | 6ee03cbe0c6ac37304f1799d2341f043f280989a | [] | no_license | Shweta2016/AdvDAA | ef5b2b785bb7ba8f8413c1e99eed129b360198bf | 0718d1306cf7adf60f516080aa2023520d2b0c69 | refs/heads/master | 2020-12-14T05:38:25.074434 | 2020-01-18T00:21:06 | 2020-01-18T00:21:06 | 234,659,033 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,116 | cpp | #include <iostream>
#include <cmath>
using namespace std;
// gcd calculation
unsigned gcd(unsigned a, unsigned b)
{
if (b == 0)
return a;
return gcd(b, a % b);
}
// powermod(b, e, m) = (b^e) % m
unsigned powermod(unsigned b, unsigned e, unsigned m)
{
if (e == 0)
return 1;
unsigned temp = powermod(b, e/2, m);
unsigned ans = (temp * temp) % m;
if (e % 2 == 0)
return ans;
else
return (b * ans) % m;
}
// Carmicheal
bool checkCarmichael(unsigned n)
{
int factor = 0;
int s = sqrt(n);
for (unsigned b = 2; b < n; b++) {
if(b > s && !factor){
return false;
}
if (gcd(b, n) > 1){
factor = 1;
}
else{
if (powermod(b, n - 1, n) != 1)
return false;
}
}
return true;
}
int main()
{
unsigned int n;
int count = 0;
for(n = 3;; n++){
if(checkCarmichael(n)){
cout << n << endl;
count++;
}
if(count == 10)
break;
}
return 0;
}
| [
"shweta2016kharat@gmail.com"
] | shweta2016kharat@gmail.com |
173d5f59cdb5fc35fdb4a609cee47a43122aa381 | e1e43f3e90aa96d758be7b7a8356413a61a2716f | /commsconfig/commsdatabaseshim/TE_commdb/inc/Step_011_xx.h | cb3854b0fb93fd95622e25b3edcc1cf7c63d56d6 | [] | no_license | SymbianSource/oss.FCL.sf.os.commsfw | 76b450b5f52119f6bf23ae8a5974c9a09018fdfa | bc8ac1a6d5273cbfa7852bbb8ce27d6ddc076984 | refs/heads/master | 2021-01-18T23:55:06.285537 | 2010-10-03T23:21:43 | 2010-10-03T23:21:43 | 72,773,202 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,713 | h | /*
* Copyright (c) 2009 Nokia Corporation and/or its subsidiary(-ies).
* All rights reserved.
* This component and the accompanying materials are made available
* under the terms of "Eclipse Public License v1.0"
* which accompanies this distribution, and is available
* at the URL "http://www.eclipse.org/legal/epl-v10.html".
*
* Initial Contributors:
* Nokia Corporation - initial contribution.
*
* Contributors:
*
* Description:
*
*/
// This is the header file for CommDb test 011.XX group of scenarios
#if (!defined __STEP_011_XX_H__)
#define __STEP_011_XX_H__
////////////////////
// Test step 011.01
////////////////////
NONSHARABLE_CLASS(CCommDbTest011_01) : public CTestStepCommDb
{
public:
CCommDbTest011_01();
~CCommDbTest011_01();
virtual enum TVerdict doTestStepL( void );
TInt executeStepL();
TVerdict doTestStepPreambleL();
private:
};
///////////////////
// Test step 011.02
////////////////////
NONSHARABLE_CLASS(CCommDbTest011_02) : public CTestStepCommDb
{
public:
CCommDbTest011_02();
~CCommDbTest011_02();
virtual enum TVerdict doTestStepL( void );
TInt executeStepL();
TVerdict doTestStepPreambleL();
private:
};
///////////////////
// Test step 011.03
////////////////////
NONSHARABLE_CLASS(CCommDbTest011_03) : public CTestStepCommDb
{
public:
CCommDbTest011_03();
~CCommDbTest011_03();
virtual enum TVerdict doTestStepL( void );
TInt executeStepL();
TVerdict doTestStepPreambleL();
private:
};
///////////////////
// Test step 011.04
////////////////////
NONSHARABLE_CLASS(CCommDbTest011_04) : public CTestStepCommDb
{
public:
CCommDbTest011_04();
~CCommDbTest011_04();
enum TVerdict doTestStepL( void );
private:
};
#endif //(__STEP_011_XX_H__)
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
a218508fa914b8a95c3d7e6860ab87ad4e5890db | fd57ede0ba18642a730cc862c9e9059ec463320b | /native/libs/ui/include/ui/GraphicTypes.h | b942c4aa90be077c29632e7e55e67b4206379704 | [
"LicenseRef-scancode-unicode",
"Apache-2.0"
] | permissive | kailaisi/android-29-framwork | a0c706fc104d62ea5951ca113f868021c6029cd2 | b7090eebdd77595e43b61294725b41310496ff04 | refs/heads/master | 2023-04-27T14:18:52.579620 | 2021-03-08T13:05:27 | 2021-03-08T13:05:27 | 254,380,637 | 1 | 1 | null | 2023-04-15T12:22:31 | 2020-04-09T13:35:49 | C++ | UTF-8 | C++ | false | false | 1,427 | h | /*
* Copyright 2018 The Android Open Source Project
*
* 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 <cinttypes>
#include <cstdint>
#include <android/hardware/graphics/common/1.1/types.h>
#include <android/hardware/graphics/common/1.2/types.h>
#include <system/graphics.h>
#define ANDROID_PHYSICAL_DISPLAY_ID_FORMAT PRIu64
namespace android {
using PhysicalDisplayId = uint64_t;
// android::ui::* in this header file will alias different types as
// the HIDL interface is updated.
namespace ui {
using android::hardware::graphics::common::V1_1::RenderIntent;
using android::hardware::graphics::common::V1_2::ColorMode;
using android::hardware::graphics::common::V1_2::Dataspace;
using android::hardware::graphics::common::V1_2::Hdr;
using android::hardware::graphics::common::V1_2::PixelFormat;
} // namespace ui
} // namespace android
| [
"541018378@qq.com"
] | 541018378@qq.com |
20e69dee5e22382a2e2f8a7400107bd2809559cd | e695d0ddeffa22aed711e72aacdbd88a950a5abb | /dp 动态规划/kuangbinDP/Chdoj1069类似最长递增子序列.cpp | d12a6d98ec669ec43de6bf1c397513b86de60d62 | [] | no_license | nNbSzxx/ACM | febe12eae960950bb4f03d0e14e72d54e66b4eee | e3994e292f2848b3fbe190b6273fdc30d69e887b | refs/heads/master | 2020-03-23T22:08:11.582054 | 2019-02-07T12:45:27 | 2019-02-07T12:45:27 | 142,155,512 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 934 | cpp | #include <bits/stdc++.h>
using namespace std;
int n, dp[145];
struct box {
int a, b, c;
} bx[145];
void add(int id, int a, int b, int c)
{
bx[id].a = a;
bx[id].b = max(b, c);
bx[id].c = min(b, c);
}
bool cmp(const box& b1, const box& b2)
{
return b1.b > b2.b || (b1.b == b2.b && b1.c > b2.c);
}
int main()
{
int tc = 1;
while (scanf("%d", &n), n) {
for (int i = 1; i <= n; i ++) {
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(3 * i - 3 + 1, a, b, c);
add(3 * i - 3 + 2, b, a, c);
add(3 * i - 3 + 3, c, a, b);
}
sort(bx + 1, bx + 1 + 3 * n, cmp);
for (int i = 1; i <= 3 * n; i ++) {
dp[i] = bx[i].a;
for (int j = 1; j < i; j ++) {
if (bx[i].b < bx[j].b && bx[i].c < bx[j].c) {
dp[i] = max(dp[i], dp[j] + bx[i].a);
}
}
}
int ans = -1;
for (int i = 1; i <= 3 * n; i ++) {
ans = max(ans, dp[i]);
}
printf("Case %d: maximum height = %d\n", tc ++, ans);
}
return 0;
}
| [
"hpzhuxiaoxie@163.com"
] | hpzhuxiaoxie@163.com |
e2102066969670e06efad4e174d2a252a92f3e0e | 8f7c8beaa2fca1907fb4796538ea77b4ecddc300 | /extensions/browser/api/mime_handler_private/mime_handler_private_unittest.cc | 4ebda737f3cad74e9092a4857705ab197ebfccde | [
"BSD-3-Clause"
] | permissive | lgsvl/chromium-src | 8f88f6ae2066d5f81fa363f1d80433ec826e3474 | 5a6b4051e48b069d3eacbfad56eda3ea55526aee | refs/heads/ozone-wayland-62.0.3202.94 | 2023-03-14T10:58:30.213573 | 2017-10-26T19:27:03 | 2017-11-17T09:42:56 | 108,161,483 | 8 | 4 | null | 2017-12-19T22:53:32 | 2017-10-24T17:34:08 | null | UTF-8 | C++ | false | false | 4,099 | cc | // 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 "extensions/browser/api/mime_handler_private/mime_handler_private.h"
#include <memory>
#include <utility>
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "content/public/browser/stream_handle.h"
#include "content/public/browser/stream_info.h"
#include "extensions/browser/guest_view/mime_handler_view/mime_handler_view_guest.h"
#include "mojo/public/cpp/bindings/strong_binding.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
class TestStreamHandle : public content::StreamHandle {
public:
TestStreamHandle() : url_("stream://url") {}
~TestStreamHandle() override {
while (!close_callbacks_.empty()) {
close_callbacks_.front().Run();
close_callbacks_.pop();
}
}
const GURL& GetURL() override { return url_; }
void AddCloseListener(const base::Closure& callback) override {
close_callbacks_.push(callback);
}
private:
GURL url_;
std::queue<base::Closure> close_callbacks_;
};
class MimeHandlerServiceImplTest : public testing::Test {
public:
void SetUp() override {
std::unique_ptr<content::StreamInfo> stream_info(new content::StreamInfo);
stream_info->handle = base::WrapUnique(new TestStreamHandle);
stream_info->mime_type = "test/unit";
stream_info->original_url = GURL("test://extensions_unittests");
stream_container_.reset(
new StreamContainer(std::move(stream_info), 1, true, GURL(), ""));
service_binding_ =
mojo::MakeStrongBinding(std::make_unique<MimeHandlerServiceImpl>(
stream_container_->GetWeakPtr()),
mojo::MakeRequest(&service_ptr_));
}
void TearDown() override {
service_binding_->Close();
stream_container_.reset();
}
void AbortCallback() { abort_called_ = true; }
void GetStreamInfoCallback(mime_handler::StreamInfoPtr stream_info) {
stream_info_ = std::move(stream_info);
}
base::MessageLoop message_loop_;
std::unique_ptr<StreamContainer> stream_container_;
mime_handler::MimeHandlerServicePtr service_ptr_;
mojo::StrongBindingPtr<mime_handler::MimeHandlerService> service_binding_;
bool abort_called_ = false;
mime_handler::StreamInfoPtr stream_info_;
};
TEST_F(MimeHandlerServiceImplTest, Abort) {
service_binding_->impl()->AbortStream(base::Bind(
&MimeHandlerServiceImplTest::AbortCallback, base::Unretained(this)));
EXPECT_TRUE(abort_called_);
abort_called_ = false;
service_binding_->impl()->AbortStream(base::Bind(
&MimeHandlerServiceImplTest::AbortCallback, base::Unretained(this)));
EXPECT_TRUE(abort_called_);
stream_container_.reset();
abort_called_ = false;
service_binding_->impl()->AbortStream(base::Bind(
&MimeHandlerServiceImplTest::AbortCallback, base::Unretained(this)));
EXPECT_TRUE(abort_called_);
}
TEST_F(MimeHandlerServiceImplTest, GetStreamInfo) {
service_binding_->impl()->GetStreamInfo(
base::Bind(&MimeHandlerServiceImplTest::GetStreamInfoCallback,
base::Unretained(this)));
ASSERT_TRUE(stream_info_);
EXPECT_TRUE(stream_info_->embedded);
EXPECT_EQ(1, stream_info_->tab_id);
EXPECT_EQ("test/unit", stream_info_->mime_type);
EXPECT_EQ("test://extensions_unittests", stream_info_->original_url);
EXPECT_EQ("stream://url", stream_info_->stream_url);
service_binding_->impl()->AbortStream(base::Bind(
&MimeHandlerServiceImplTest::AbortCallback, base::Unretained(this)));
EXPECT_TRUE(abort_called_);
service_binding_->impl()->GetStreamInfo(
base::Bind(&MimeHandlerServiceImplTest::GetStreamInfoCallback,
base::Unretained(this)));
ASSERT_FALSE(stream_info_);
stream_container_.reset();
service_binding_->impl()->GetStreamInfo(
base::Bind(&MimeHandlerServiceImplTest::GetStreamInfoCallback,
base::Unretained(this)));
ASSERT_FALSE(stream_info_);
}
} // namespace extensions
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
c7e5e9ee161ba1c9faec1be54703187278c299a7 | ea9f5cd1be0b46e8d01e0ef87615c0dc007ba73b | /SourceCode/4th/string/strtype3.cpp | d5f2b3fc6d5c9b7f7844f0e9a171ef53934e5877 | [] | no_license | coolcoolercool/C-PrimePlus | ed173fa9965f9b253ad27949a7a614402f08c50d | fe7e2ae74ede9512d358013c99bdc4f644dcae6b | refs/heads/master | 2021-08-22T03:12:43.132055 | 2020-06-04T01:33:19 | 2020-06-04T01:33:19 | 191,380,720 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 766 | cpp | /**
* author: zzw5005
* date: 2019/11/7 11:15
*/
/*
* strcpy 和 strcat 函数的使用
*/
#include <iostream>
#include <string>
#include <cstring>
int main4b(){
using namespace std;
char charr1[20];
char charr2[20] = "jaguar";
string str1;
string str2 = "panther";
str1 = str2;
strcpy(charr1, charr2); //- 将字符数组charr复制给charr1
str1 += " paste";
strcat(charr1, " juice");
int len1 = str1.size(); // size() 和 strlen()都是返回字符串包含的字符数
int len2 = strlen(charr1);
cout << "The string " << str1 << " contains "
<< len1 << " characters.\n";
cout << "The string " << charr1 << " contains "
<< len2 << " characters.\n";
return 0;
}
| [
"1827952880@qq.com"
] | 1827952880@qq.com |
410960da285d3791b542dfe2d6f831f864039272 | 0c5b8aec68be8eaeb1347065a904913db685d6ff | /android-build/localhost.nummc/app/jni/src/scene_play_story.cpp | ad6f4b961d5495df6bbf1edad5f9b42adeca58d0 | [
"MIT"
] | permissive | eyzzye/nummc | 925ee33f218b3a4811f84473d7b0a696f04c525c | 53c7f029f2b574cbb1c5056d2227fa67dace5e8d | refs/heads/main | 2023-05-11T20:43:40.491206 | 2023-05-06T20:18:09 | 2023-05-06T20:18:09 | 302,451,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,775 | cpp | #include "game_common.h"
#include "gui_common.h"
#include "scene_manager.h"
#include "scene_play_story.h"
#include "resource_manager.h"
#include "memory_manager.h"
#include "sound_manager.h"
#include "story_manager.h"
#include "game_key_event.h"
#include "game_mouse_event.h"
#include "gui_loading.h"
#include "game_window.h"
#include "game_timer.h"
#include "game_utils.h"
#include "game_log.h"
#include "game_save.h"
#include "scene_play_stage.h"
#ifdef _ANDROID
#include "gui_touch_control.h"
#endif
#define SCENE_PLAY_STORY_AUTO_TEXT_END 32
tex_info_t tex_info_auto_text[SCENE_PLAY_STORY_AUTO_TEXT_END];
static int tex_info_auto_text_size;
tex_info_t tex_info_background;
tex_info_t tex_info_enter;
#define ENTER_TEXT_BLINK_TIME 1000
static int enter_text_blink_timer;
static bool auto_text_finish;
static bool enter_text_disp;
static int auto_text_timer;
static int auto_text_wait_time;
static int auto_text_index;
static char story_path[MEMORY_MANAGER_STRING_BUF_SIZE];
static void tex_info_reset();
static void unload_event();
static void set_stat_event(int stat);
static SceneManagerFunc scene_func;
static int scene_stat;
static bool is_opening;
static void pre_event() {
if (scene_stat != SCENE_STAT_ACTIVE) return;
game_mouse_event_reset();
}
static void key_event(SDL_Event* e) {
if (scene_stat != SCENE_STAT_ACTIVE) return;
game_key_event_set(e);
game_mouse_event_set(e);
}
static void main_event() {
if (!auto_text_finish) auto_text_timer += g_delta_time;
else enter_text_blink_timer += g_delta_time;
if ((!auto_text_finish) && (auto_text_timer > (auto_text_index + 1) * auto_text_wait_time)) {
auto_text_index += 1;
if (auto_text_index >= tex_info_auto_text_size) {
auto_text_finish = true;
}
}
if (auto_text_finish) {
if (enter_text_blink_timer > ENTER_TEXT_BLINK_TIME) {
enter_text_blink_timer = 0;
enter_text_disp = !enter_text_disp;
}
}
if (game_key_event_get(SDL_SCANCODE_RETURN, GUI_SELECT_WAIT_TIMER)) {
if (is_opening) {
const char* start_stage = "1";
// set loading data (set bin data)
gui_loading_set_stage(start_stage);
scene_play_stage_set_stage_id(start_stage);
// loading play stage
set_stat_event(SCENE_STAT_NONE);
unload_event();
scene_manager_load(SCENE_ID_PLAY_STAGE, true);
}
else {
set_stat_event(SCENE_STAT_NONE);
unload_event();
scene_manager_load(SCENE_ID_TOP_MENU);
}
}
}
static void pre_draw() {
}
static void draw() {
if (scene_stat != SCENE_STAT_ACTIVE) return;
// set background
SDL_SetRenderDrawColor(g_ren, 0, 0, 0, 255);
SDL_RenderClear(g_ren);
SDL_SetRenderDrawColor(g_ren, 16, 16, 16, 255);
SDL_RenderFillRect(g_ren, &g_screen_size);
// background image
if (tex_info_background.res_img) GUI_tex_info_draw(&tex_info_background);
if (auto_text_finish) {
if (enter_text_disp) GUI_tex_info_draw(&tex_info_enter);
}
else {
// auto text
GUI_tex_info_draw(&tex_info_auto_text[auto_text_index]);
}
#ifdef _ANDROID
// draw gui_touch_control
gui_touch_control_draw();
#endif
SDL_RenderPresent(g_ren);
}
static void after_draw() {
}
static void load_event() {
// load story data
auto_text_finish = false;
story_manager_init();
story_manager_load(story_path);
// reset size
tex_info_reset();
// key event switch
game_key_event_init();
game_key_event_set_key(SDL_SCANCODE_RETURN);
game_mouse_event_init(0, 400, 200, 150, 5);
auto_text_timer = 0;
auto_text_wait_time = g_story_data->auto_text_time;
auto_text_index = 0;
enter_text_blink_timer = 0;
enter_text_disp = false;
// play music
if (g_story_data->res_chunk) {
sound_manager_play(g_story_data->res_chunk, SOUND_MANAGER_CH_MUSIC, -1);
}
}
static void unload_event() {
story_manager_unload();
resource_manager_clean_up();
story_path[0] = '\0';
tex_info_auto_text_size = 0;
}
static int get_stat_event() {
return scene_stat;
}
static void set_stat_event(int stat) {
if (stat == SCENE_STAT_IDLE) {
sound_manager_stop(SOUND_MANAGER_CH_MUSIC);
}
scene_stat = stat;
}
// init draw items
static void tex_info_reset()
{
int ret = 0;
int w, h;
int w_pos = 0, h_pos = 0;
// background
if (g_story_data->res_img) {
tex_info_background.res_img = g_story_data->res_img;
ret = GUI_QueryTexture(tex_info_background.res_img, NULL, NULL, &w, &h);
if (ret == 0) {
w_pos = 0;
h_pos = 0;
GUI_tex_info_init_rect(&tex_info_background, w, h, w_pos, h_pos);
}
}
// enter
const char* enter_text_str = "{-,204:204:204:204,-,-}Press enter";
tex_info_enter.res_img = resource_manager_getFontTextureFromPath(enter_text_str);
ret = GUI_QueryTexture(tex_info_enter.res_img, NULL, NULL, &w, &h);
if (ret == 0) {
w_pos = SCREEN_WIDTH / 2 - w / 2;
h_pos = SCREEN_HEIGHT - 40 - h;
GUI_tex_info_init_rect(&tex_info_enter, w, h, w_pos, h_pos);
}
// auto_text
int auto_text_index = 0;
node_data_t* node = g_story_data->auto_text_list->start_node;
while(node != NULL) {
node_data_t* current_node = node;
node = node->next;
if (auto_text_index > SCENE_PLAY_STORY_AUTO_TEXT_END) break; // overflow tex_info
char* auto_text = ((auto_text_data_t*)current_node)->auto_text;
char auto_text_str[MEMORY_MANAGER_STRING_BUF_SIZE];
int auto_text_str_size = game_utils_string_cat(auto_text_str, (char*)"{-,204:204:204:204,-,-}", auto_text);
if (auto_text_str_size <= 0) { LOG_ERROR("Error: scene_play_story tex_info_reset() get auto_text_str\n"); continue; }
tex_info_auto_text[auto_text_index].res_img = resource_manager_getFontTextureFromPath(auto_text_str);
ret = GUI_QueryTexture(tex_info_auto_text[auto_text_index].res_img, NULL, NULL, &w, &h);
if (ret == 0) {
w_pos = SCREEN_WIDTH / 2 - w / 2;
h_pos = SCREEN_HEIGHT - 40 - h;
GUI_tex_info_init_rect(&tex_info_auto_text[auto_text_index], w, h, w_pos, h_pos);
}
auto_text_index++;
}
tex_info_auto_text_size = auto_text_index;
}
void scene_play_story_set_story(const char* path, bool is_opening_)
{
//story_path = path;
int ret = game_utils_string_copy(story_path, path);
if (ret != 0) { LOG_ERROR("Error: scene_play_story_set_story() copy path\n"); return; }
is_opening = is_opening_;
}
void scene_play_story_init()
{
// set stat
scene_stat = SCENE_STAT_NONE;
scene_func.pre_event = &pre_event;
scene_func.key_event = &key_event;
scene_func.main_event = &main_event;
scene_func.pre_draw = &pre_draw;
scene_func.draw = &draw;
scene_func.after_draw = &after_draw;
scene_func.load_event = &load_event;
scene_func.unload_event = &unload_event;
scene_func.get_stat_event = &get_stat_event;
scene_func.set_stat_event = &set_stat_event;
// load resource files
resource_manager_load_dat((char*)"scenes/scene_play_story.dat");
story_path[0] = '\0';
}
SceneManagerFunc* scene_play_story_get_func()
{
return &scene_func;
}
| [
"eyuguchi@hotmail.com"
] | eyuguchi@hotmail.com |
e124bc52cc69fb688d69e7bc956e6f4927409a48 | 5b7ae29242b4bb8cc9dfad217b0df5c16d31dc1f | /1865.cpp | f9f172e6cccdc754084d04597e4bf21452970637 | [] | no_license | voidsatisfaction/Baekjoon-Online-Judge | 63ba03bb27f99283e37245e196857c5dbf3d1d32 | 7fe9338e35f5df9d59bd04eb72d4310ff216b337 | refs/heads/master | 2021-01-11T10:27:58.039240 | 2020-07-26T10:30:12 | 2020-07-26T10:30:12 | 79,091,570 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,635 | cpp | #include <cstdio>
#include <vector>
#define INF 100000000
#define MINUS_INF -INF
#define MAX_N 501
using namespace std;
struct adjNode {
int num, times;
adjNode(int n, int t) {
num = n;
times = t;
}
};
int T, N, M, W;
int bellmanFord(int from, int to, vector<vector<adjNode> > adjList) {
bool isInfinite = false;
int takingTimes[N+1];
for(int i=0; i < N+1; i++)
takingTimes[i] = INF;
takingTimes[from] = 0;
for(int i=1; i < N+1; i++) {
for(int j=1; j < N+1; j++) {
for(int k=0; k < adjList[j].size(); k++) {
int adjNodeNum = adjList[j][k].num;
int adjNodeTimes = adjList[j][k].times;
if (takingTimes[j] != INF && takingTimes[adjNodeNum] > takingTimes[j] + adjNodeTimes) {
takingTimes[adjNodeNum] = takingTimes[j] + adjNodeTimes;
if (i == N)
isInfinite = true;
}
}
}
}
if(isInfinite) {
return MINUS_INF;
}
return takingTimes[to];
}
int main() {
scanf("%d", &T);
while (T--) {
scanf("%d %d %d", &N, &M, &W);
vector<vector<adjNode> > adjList(N+1);
for(int i=0; i < M; i++) {
int from, to, times;
scanf("%d %d %d", &from, &to, ×);
adjList[from].push_back(adjNode(to, times));
adjList[to].push_back(adjNode(from, times));
}
for(int i=0; i < W; i++) {
int from, to, times;
scanf("%d %d %d", &from, &to, ×);
adjList[from].push_back(adjNode(to, -times));
}
int minDist = bellmanFord(1, 2, adjList);
if (minDist == MINUS_INF) {
printf("%s\n", "YES");
} else {
printf("%s\n", "NO");
}
}
return 0;
} | [
"lourie@naver.com"
] | lourie@naver.com |
85cc0d5068c2a04f8f4cbc3a111f40a2befb2645 | 971713859cee54860e32dce538a7d5e796487c68 | /unisim/unisim_lib/unisim/component/tlm/message/snooping_fsb.hh | 36920d14a47c28335bf08fbe4ca1a9d70594c859 | [] | no_license | binsec/cav2021-artifacts | 3d790f1e067d1ca9c4123010e3af522b85703e54 | ab9e387122968f827f7d4df696c2ca3d56229594 | refs/heads/main | 2023-04-15T17:10:10.228821 | 2021-04-26T15:10:20 | 2021-04-26T15:10:20 | 361,684,640 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,907 | hh | /*
* Copyright (c) 2007,
* Commissariat a l'Energie Atomique (CEA)
* 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 CEA 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.
*
* Authors: Daniel Gracia Perez (daniel.gracia-perez@cea.fr)
* Gilles Mouchard (gilles.mouchard@cea.fr)
*/
#ifndef __UNISIM_COMPONENT_TLM_MESSAGE_SNOOPINGFSB_HH__
#define __UNISIM_COMPONENT_TLM_MESSAGE_SNOOPINGFSB_HH__
#include "unisim/kernel/logger/logger.hh"
#include "unisim/util/garbage_collector/garbage_collector.hh"
#include "unisim/component/tlm/debug/transaction_spy.hh"
#include <inttypes.h>
namespace unisim {
namespace component {
namespace tlm {
namespace message {
using unisim::kernel::logger::DebugInfo;
using unisim::kernel::logger::DebugWarning;
using unisim::kernel::logger::DebugError;
using unisim::kernel::logger::EndDebugInfo;
using unisim::kernel::logger::EndDebugWarning;
using unisim::kernel::logger::EndDebugError;
template <class ADDRESS, unsigned int DATA_SIZE>
class SnoopingFSBRequest;
template <unsigned int DATA_SIZE>
class SnoopingFSBResponse;
template <class ADDRESS, unsigned int DATA_SIZE>
unisim::kernel::logger::Logger& operator << (unisim::kernel::logger::Logger& os, const SnoopingFSBRequest<ADDRESS, DATA_SIZE>& req);
template <unsigned int DATA_SIZE>
unisim::kernel::logger::Logger& operator << (unisim::kernel::logger::Logger& os, const SnoopingFSBResponse<DATA_SIZE>& rsp);
template <class ADDRESS, unsigned int DATA_SIZE>
class SnoopingFSBRequest {
public:
enum Type {
READ, // Read request
READX, // Read with intent to modify
WRITE, // Write request
INV_BLOCK, // Invalidate block
FLUSH_BLOCK, // Flush block
ZERO_BLOCK, // Fill in block with zero
INV_TLB // Invalidate TLB set
};
Type type; // Request type
bool global; // true if the request must be snooped by other processors
ADDRESS addr; // Address
unsigned int size; // Size of bus transfer (<= DATA_SIZE)
uint8_t write_data[DATA_SIZE]; // Data to write into memory
friend unisim::kernel::logger::Logger& operator << <ADDRESS, DATA_SIZE>(unisim::kernel::logger::Logger& os,
const SnoopingFSBRequest<ADDRESS, DATA_SIZE>& req);
};
template <unsigned int DATA_SIZE>
class SnoopingFSBResponse {
public:
typedef enum {
RS_MISS = 0, // target processor doesn't have the block
RS_SHARED = 1, // target processor has an unmodified copy of the block
RS_MODIFIED = 2, // target processor has a modified copy of the block which need to be written back to memory
RS_BUSY = 4 // target processor is busy and can't response to the snoop request. The initiator should retry later.
} ReadStatus;
ReadStatus read_status; // Status of the target processor in case of READ or READX
uint8_t read_data[DATA_SIZE]; // Data read from memory/target processor caches
friend unisim::kernel::logger::Logger& operator << <DATA_SIZE>(unisim::kernel::logger::Logger& os,
const SnoopingFSBResponse<DATA_SIZE>& rsp);
};
template <class ADDRESS, unsigned int DATA_SIZE>
unisim::kernel::logger::Logger& operator << (unisim::kernel::logger::Logger& os,
const SnoopingFSBRequest<ADDRESS, DATA_SIZE>& req) {
typedef SnoopingFSBRequest<ADDRESS, DATA_SIZE> ReqType;
os << "- type = ";
switch(req.type) {
case ReqType::READ:
os << "READ";
break;
case ReqType::READX:
os << "READX";
break;
case ReqType::WRITE:
os << "WRITE";
break;
case ReqType::INV_BLOCK:
os << "INV_BLOCK";
break;
case ReqType::FLUSH_BLOCK:
os << "FLUSH_BLOCK";
break;
case ReqType::ZERO_BLOCK:
os << "ZERO_BLOCK";
break;
case ReqType::INV_TLB:
os << "INV_TLB";
break;
}
os << std::endl;
os << "- global = " << (req.global?"TRUE":"FALSE") << std::endl;
os << "- address = 0x" << std::hex << req.addr << std::dec << std::endl;
os << "- size = " << req.size;
if(req.type == ReqType::WRITE) {
os << std::endl;
os << "- write_data(hex) =" << std::hex;
for(unsigned int i = 0; i < req.size; i++) {
os << " " << (unsigned int)req.write_data[i];
}
os << std::dec;
}
return os;
}
template <unsigned int DATA_SIZE>
unisim::kernel::logger::Logger& operator << (unisim::kernel::logger::Logger& os,
const SnoopingFSBResponse<DATA_SIZE>& rsp) {
typedef SnoopingFSBResponse<DATA_SIZE> RspType;
os << "- read_status = ";
switch(rsp.read_status) {
case RspType::RS_MISS: os << "RS_MISS"; break;
case RspType::RS_SHARED: os << "RS_SHARED"; break;
case RspType::RS_MODIFIED: os << "RS_MODIFIED"; break;
case RspType::RS_BUSY: os << "RS_BUSY"; break;
}
os << std::endl;
os << "- read_data(hex) =" << std::hex;
for(unsigned int i = 0; i < DATA_SIZE; i++) {
os << " " << (unsigned int)rsp.read_data[i];
}
os << std::dec;
return os;
}
} // end of namespace message
} // end of namespace tlm
} // end of namespace component
} // end of namespace unisim
namespace unisim {
namespace component {
namespace tlm {
namespace debug {
template<class ADDRESS, unsigned int DATA_SIZE>
class RequestSpy<unisim::component::tlm::message::SnoopingFSBRequest<ADDRESS, DATA_SIZE> > {
private:
typedef unisim::component::tlm::message::SnoopingFSBRequest<ADDRESS, DATA_SIZE> ReqType;
typedef unisim::util::garbage_collector::Pointer<ReqType> PReqType;
public:
void Dump(unisim::kernel::logger::Logger &os, PReqType &req) {
os << "- type = ";
switch(req->type) {
case ReqType::READ:
os << "READ";
break;
case ReqType::READX:
os << "READX";
break;
case ReqType::WRITE:
os << "WRITE";
break;
case ReqType::INV_BLOCK:
os << "INV_BLOCK";
break;
case ReqType::FLUSH_BLOCK:
os << "FLUSH_BLOCK";
break;
case ReqType::ZERO_BLOCK:
os << "ZERO_BLOCK";
break;
case ReqType::INV_TLB:
os << "INV_TLB";
break;
}
os << std::endl;
os << "- global = " << (req->global?"TRUE":"FALSE") << std::endl;
os << "- address = 0x" << std::hex << req->addr << std::dec << std::endl;
os << "- size = " << req->size;
if(req->type == ReqType::WRITE) {
os << std::endl;
os << "- write_data(hex) =" << std::hex;
for(unsigned int i = 0; i < req->size; i++) {
os << " " << (unsigned int)req->write_data[i];
}
os << std::dec;
}
}
};
template <class ADDRESS, unsigned int DATA_SIZE>
class ResponseSpy<unisim::component::tlm::message::SnoopingFSBResponse<DATA_SIZE>,
unisim::component::tlm::message::SnoopingFSBRequest<ADDRESS, DATA_SIZE> > {
private:
typedef unisim::component::tlm::message::SnoopingFSBRequest<ADDRESS, DATA_SIZE> ReqType;
typedef unisim::component::tlm::message::SnoopingFSBResponse<DATA_SIZE> RspType;
typedef unisim::util::garbage_collector::Pointer<ReqType> PReqType;
typedef unisim::util::garbage_collector::Pointer<RspType> PRspType;
public:
void Dump(unisim::kernel::logger::Logger &os, PRspType &rsp,
PReqType &req) {
os << "- read_status = ";
switch(rsp->read_status) {
case RspType::RS_MISS: os << "RS_MISS"; break;
case RspType::RS_SHARED: os << "RS_SHARED"; break;
case RspType::RS_MODIFIED: os << "RS_MODIFIED"; break;
case RspType::RS_BUSY: os << "RS_BUSY"; break;
}
os << std::endl;
os << "- read_data(hex) =" << std::hex;
for(unsigned int i = 0; i < req->size; i++) {
os << " " << (unsigned int)rsp->read_data[i];
}
os << std::dec;
}
};
} // end of namespace debug
} // end of namespace tlm
} // end of namespace component
} // end of namespace unisim
#endif // __UNISIM_COMPONENT_TLM_MESSAGE_SNOOPINGFSB_HH__
| [
"guillaume.girol@cea.fr"
] | guillaume.girol@cea.fr |
f789ea05ecdccac9a9c63aede7747e67ff845e46 | e3b67db8b0ea9af2ba890dc4e119ff22876a2232 | /libminifi/src/core/flow/AdaptiveConfiguration.cpp | 5346a9c23b7136bddb39dabc82b4c41ce3561203 | [
"MPL-2.0",
"Apache-2.0",
"BSD-3-Clause",
"curl",
"OpenSSL",
"libtiff",
"bzip2-1.0.6",
"MIT",
"LicenseRef-scancode-public-domain-disclaimer",
"MIT-0",
"Beerware",
"Zlib",
"NCSA",
"ISC",
"CC0-1.0",
"LicenseRef-scancode-object-form-exception-to-mit",
"BSL-1.0",
"LicenseRef-scancode-pu... | permissive | apache/nifi-minifi-cpp | 90919e880bf7ac1ce51b8ad0f173cc4e3aded7fe | 9b55dc0c0f17a190f3e9ade87070a28faf542c25 | refs/heads/main | 2023-08-29T22:29:02.420503 | 2023-08-25T17:21:53 | 2023-08-25T17:21:53 | 56,750,161 | 131 | 114 | Apache-2.0 | 2023-09-14T05:53:30 | 2016-04-21T07:00:06 | C++ | UTF-8 | C++ | false | false | 2,785 | cpp | /**
*
* 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 "core/flow/AdaptiveConfiguration.h"
#include "rapidjson/document.h"
#include "core/json/JsonNode.h"
#include "core/yaml/YamlNode.h"
#include "yaml-cpp/yaml.h"
#include "utils/file/FileUtils.h"
#include "Defaults.h"
#include "rapidjson/error/en.h"
namespace org::apache::nifi::minifi::core::flow {
AdaptiveConfiguration::AdaptiveConfiguration(ConfigurationContext ctx)
: StructuredConfiguration(([&] {
if (!ctx.path) {
if (utils::file::exists(DEFAULT_NIFI_CONFIG_JSON)) {
ctx.path = DEFAULT_NIFI_CONFIG_JSON;
} else {
ctx.path = DEFAULT_NIFI_CONFIG_YML;
}
}
return std::move(ctx);
})(),
logging::LoggerFactory<AdaptiveConfiguration>::getLogger()) {}
std::unique_ptr<core::ProcessGroup> AdaptiveConfiguration::getRootFromPayload(const std::string &payload) {
rapidjson::Document doc;
rapidjson::ParseResult res = doc.Parse(payload.c_str(), payload.length());
if (res) {
flow::Node root{std::make_shared<JsonNode>(&doc)};
if (root[FlowSchema::getDefault().flow_header]) {
logger_->log_debug("Processing configuration as default json");
return getRootFrom(root, FlowSchema::getDefault());
} else {
logger_->log_debug("Processing configuration as nifi flow json");
return getRootFrom(root, FlowSchema::getNiFiFlowJson());
}
}
logger_->log_debug("Could not parse configuration as json, trying yaml");
try {
YAML::Node rootYamlNode = YAML::Load(payload);
flow::Node root{std::make_shared<YamlNode>(rootYamlNode)};
return getRootFrom(root, FlowSchema::getDefault());
} catch (const YAML::ParserException& ex) {
logger_->log_error("Configuration file is not valid json: %s (%zu)", rapidjson::GetParseError_En(res.Code()), gsl::narrow<size_t>(res.Offset()));
logger_->log_error("Configuration file is not valid yaml: %s", ex.what());
throw;
}
}
} // namespace org::apache::nifi::minifi::core::flow
| [
"szaszm@apache.org"
] | szaszm@apache.org |
b3ec233e73399c5fa7b00c3b3e21939f363ee60e | 591013df9fb9517dc6952ac05d4718811b1e122c | /source/executive/source/executive_body.cpp | c9a795d8a8e890f026da04de528ff6abe7cfcde9 | [] | no_license | yuanhuihe/robocar | 15232abd60cf774214fb01d147cedda73ffe3766 | c860ea08a46b08c1c07d80f070904207b16cb981 | refs/heads/master | 2021-09-15T06:15:33.779931 | 2018-05-27T17:47:32 | 2018-05-27T17:47:32 | 106,238,784 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 166 | cpp |
#include "executive_body.h"
namespace Driver
{
ExecutiveBody::ExecutiveBody()
{
}
ExecutiveBody::~ExecutiveBody()
{
}
} // namespace Driver
| [
"hyh618@gmail.com"
] | hyh618@gmail.com |
348c939f039140e6c4a5b2012e5177341ac01e2e | 7b349544c808c5c1e87928ed12f259bc4bf438f8 | /myKMP.cpp | 2b6d1d9b510a4489567f58eb6ae34e1bf8ae9557 | [] | no_license | OolongQian/Algorithm | b73916d675df2e78a373235ed9a584a53e5514bb | cfdebf84f760a069df652980dc7b09edd1115022 | refs/heads/master | 2020-03-23T01:50:07.976269 | 2018-08-13T08:00:15 | 2018-08-13T08:00:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,214 | cpp | #include <iostream>
#include <cstring>
using namespace std;
// #define _DEBUG
const int maxn = 1e6 + 5;
const int maxm = 1e4 + 5;
char p[maxm];
char str[maxn];
int lp;
int ls;
int nxt[maxm];
void KMP() {
int num = 0;
cin >> p >> str;
lp = strlen(p);
ls = strlen(str);
for(int i = 0; i < lp; ++i) {
nxt[i] = -1;
}
int k = -1;
for(int i = 1; i < lp; ++i) {
k = nxt[i - 1];
while(k != -1 && p[k + 1] != p[i]) {
k = nxt[k];
}
if(p[k + 1] == p[i]) {
nxt[i] = k + 1;
}
else {
nxt[i] = -1;
}
}
#ifdef _DEBUG
for(int i = 0; i < lp; ++i) {
cout << nxt[i] << ' ';
}
cout << endl;
#endif
/// use nxt pattern to match
k = -1;
for(int i = 0; i < ls; ++i) {
while(k != -1 && p[k + 1] != str[i]) {
k = nxt[k];
}
if(p[k + 1] == str[i]) {
++k;
if(k == lp - 1) {
++num;
k = nxt[k];
}
}
}
cout << num << endl;
}
int main() {
int n;
cin >> n;
while(n--) {
KMP();
}
return 0;
} | [
"qiansucheng2017@outlook.com"
] | qiansucheng2017@outlook.com |
afbe1ea206430661eca8e1507c2475a785f66540 | 01ec525eca69738ae90f12a6e87279c52818c9ae | /omochain/libraries/chain/protocol/operations.cpp | 8fa148b6f935c8d795f7bfc3574b97af61a93c11 | [
"MIT"
] | permissive | omochain01/omochain | 8625c55dcb229da96a741425d9216bf19495bdd7 | 532df59aa916bc04d7c989e34229344332d21bfb | refs/heads/master | 2020-03-25T10:09:44.722303 | 2018-09-27T06:54:08 | 2018-09-27T06:54:08 | 143,685,265 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,558 | cpp | /*
* Copyright (c) 2017, Respective Authors.
*
* The MIT License
*
* 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 <omo/chain/protocol/operations.hpp>
namespace omo { namespace chain {
/**
* @brief Used to validate operations in a polymorphic manner
*/
struct operation_validator
{
typedef void result_type;
template<typename T>
void operator()( const T& v )const { v.validate(); }
};
void operation_validate( const operation& op )
{
op.visit( operation_validator() );
}
} } // namespace omo::chain
| [
"omochain2@163.com"
] | omochain2@163.com |
75a8b2ec030208adfd8acbcd21f1ec3be47089b9 | 75c228fe207fab5c4c644dbfef495eb1cae804d3 | /libs/ofQuickTimePlayer/ofQtUtils.cpp | 6bf7472039932a16ee5312fa04accc405d94d0ca | [
"MIT"
] | permissive | novasfronteiras/ofxThreadedVideo | f969c3a166e2d11440ba861a32687ae6f2746fe8 | 945e71e86350b8f25650fdc97e12d249d5136a0a | refs/heads/master | 2020-05-17T22:04:55.242567 | 2016-08-07T16:49:57 | 2016-08-07T16:49:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,688 | cpp | #include "ofQtUtils.h"
#if (defined (TARGET_WIN32) || (defined TARGET_OSX)) && (defined(OF_VIDEO_CAPTURE_QUICKTIME) || defined(OF_VIDEO_PLAYER_QUICKTIME))
#include "ofUtils.h"
#include "ofGraphics.h"
static bool bQuicktimeInitialized = false;
//----------------------------------------
void initializeQuicktime(){
if (bQuicktimeInitialized == false){
//----------------------------------
// do we have quicktime installed at all?
// http://www.apple.com/quicktime/download/win.html
// can gestalt help with versions, or is that only after init?
OSErr myErr = noErr;
#ifdef TARGET_WIN32
myErr = InitializeQTML(0);
if (myErr != noErr){
ofLogFatalError("ofQtUtils.h") << "------------------------------------------------------";
ofLogFatalError("ofQtUtils.h") << "sorry, there wasa problem initing quicktime... exiting";
OF_EXIT_APP(0);
}
#endif
myErr = EnterMovies ();
if (myErr != noErr){
ofLogFatalError("ofQtUtils.h") << "------------------------------------------------------";
ofLogFatalError("ofQtUtils.h") << "sorry, there is a problem initing quicktime... exiting";
OF_EXIT_APP(0);
}
bQuicktimeInitialized = true;
}
}
//----------------------------------------
void closeQuicktime(){
if (bQuicktimeInitialized == true){
ExitMovies();
#ifdef TARGET_WIN32
TerminateQTML();
#endif
bQuicktimeInitialized = false;
}
}
//----------------------------------------
void convertPixels(unsigned char * gWorldPixels, unsigned char * rgbPixels, int w, int h){
// ok for macs?
// ok for intel macs?
int * rgbaPtr = (int *) gWorldPixels;
pix24 * rgbPtr = (pix24 *) rgbPixels;
unsigned char * rgbaStart;
// putting in the boolean, so we can work on
// 0,0 in top right...
// bool bFlipVertically = true;
bool bFlipVertically = false;
// -------------------------------------------
// we flip vertically because the 0,0 position in OF
// is the bottom left (not top left, like processing)
// since the 0,0 of a picture is top left
// if we upload and drawf the data as is
// it will be upside-down....
// -------------------------------------------
if (!bFlipVertically){
//----- argb->rgb
for (int i = 0; i < h; i++){
pix24 * rgbPtr = (pix24 *) rgbPixels + ((i) * w);
for (int j = 0; j < w; j++){
rgbaStart = (unsigned char *)rgbaPtr;
memcpy (rgbPtr, rgbaStart+1, sizeof(pix24));
rgbPtr++;
rgbaPtr++;
}
}
} else {
//----- flip while argb->rgb
for (int i = 0; i < h; i++){
pix24 * rgbPtr = (pix24 *) rgbPixels + ((h-i-1) * w);
for (int j = 0; j < w; j++){
rgbaStart = (unsigned char *)rgbaPtr;
memcpy (rgbPtr, rgbaStart+1, sizeof(pix24));
rgbPtr++;
rgbaPtr++;
}
}
}
}
//----------------------------------------
// osx needs this for modal dialogs.
Boolean SeqGrabberModalFilterUPP (DialogPtr theDialog, const EventRecord *theEvent, short *itemHit, long refCon){
#pragma unused(theDialog, itemHit)
Boolean handled = false;
if ((theEvent->what == updateEvt) &&
((WindowPtr) theEvent->message == (WindowPtr) refCon))
{
BeginUpdate ((WindowPtr) refCon);
EndUpdate ((WindowPtr) refCon);
handled = true;
}
return (handled);
}
#define kCharacteristicHasVideoFrameRate FOUR_CHAR_CODE('vfrr')
#define kCharacteristicIsAnMpegTrack FOUR_CHAR_CODE('mpeg')
/*
Calculate the static frame rate for a given movie.
*/
void MovieGetStaticFrameRate(Movie inMovie, double *outStaticFrameRate)
{
*outStaticFrameRate = 0;
Media movieMedia;
MediaHandler movieMediaHandler;
/* get the media identifier for the media that contains the first
video track's sample data, and also get the media handler for
this media. */
MovieGetVideoMediaAndMediaHandler(inMovie, &movieMedia, &movieMediaHandler);
if (movieMedia && movieMediaHandler)
{
Boolean isMPEG = false;
/* is this the MPEG-1/MPEG-2 media handler? */
OSErr err = IsMPEGMediaHandler(movieMediaHandler, &isMPEG);
if (err == noErr)
{
if (isMPEG) /* working with MPEG-1/MPEG-2 media */
{
Fixed staticFrameRate;
ComponentResult err = MPEGMediaGetStaticFrameRate(movieMediaHandler, &staticFrameRate);
if (err == noErr)
{
/* convert Fixed data result to type double */
*outStaticFrameRate = Fix2X(staticFrameRate);
}
}
else /* working with non-MPEG-1/MPEG-2 media */
{
OSErr err = MediaGetStaticFrameRate(movieMedia, outStaticFrameRate);
if (err != noErr) {
ofLogError("ofQtUtils") << "MovieGetStaticFrameRate(): couldn't get static frame rate: OSErr " << err;
}
//assert(err == noErr);
}
}
}
}
/*
Get the media identifier for the media that contains the first
video track's sample data, and also get the media handler for
this media.
*/
void MovieGetVideoMediaAndMediaHandler(Movie inMovie, Media *outMedia, MediaHandler *outMediaHandler)
{
*outMedia = nullptr;
*outMediaHandler = nullptr;
/* get first video track */
Track videoTrack = GetMovieIndTrackType(inMovie, 1, kCharacteristicHasVideoFrameRate,
movieTrackCharacteristic | movieTrackEnabledOnly);
if (videoTrack != nullptr)
{
/* get media ref. for track's sample data */
*outMedia = GetTrackMedia(videoTrack);
if (*outMedia)
{
/* get a reference to the media handler component */
*outMediaHandler = GetMediaHandler(*outMedia);
}
}
}
/*
Return true if media handler reference is from the MPEG-1/MPEG-2 media handler.
Return false otherwise.
*/
OSErr IsMPEGMediaHandler(MediaHandler inMediaHandler, Boolean *outIsMPEG)
{
/* is this the MPEG-1/MPEG-2 media handler? */
return((OSErr) MediaHasCharacteristic(inMediaHandler,
kCharacteristicIsAnMpegTrack,
outIsMPEG));
}
/*
Given a reference to the media handler used for media in a MPEG-1/MPEG-2
track, return the static frame rate.
*/
ComponentResult MPEGMediaGetStaticFrameRate(MediaHandler inMPEGMediaHandler, Fixed *outStaticFrameRate)
{
*outStaticFrameRate = 0;
MHInfoEncodedFrameRateRecord encodedFrameRate;
Size encodedFrameRateSize = sizeof(encodedFrameRate);
/* get the static frame rate */
ComponentResult err = MediaGetPublicInfo(inMPEGMediaHandler,
kMHInfoEncodedFrameRate,
&encodedFrameRate,
&encodedFrameRateSize);
if (err == noErr)
{
/* return frame rate at which the track was encoded */
*outStaticFrameRate = encodedFrameRate.encodedFrameRate;
}
return err;
}
/*
Given a reference to the media that contains the sample data for a track,
calculate the static frame rate.
*/
OSErr MediaGetStaticFrameRate(Media inMovieMedia, double *outFPS)
{
*outFPS = 0;
/* get the number of samples in the media */
long sampleCount = GetMediaSampleCount(inMovieMedia);
OSErr err = GetMoviesError();
if (sampleCount && err == noErr)
{
/* find the media duration */
//Quicktime 7.0 code
//TimeValue64 duration = GetMediaDisplayDuration(inMovieMedia);
TimeValue64 duration = GetMediaDuration(inMovieMedia);
err = GetMoviesError();
if (err == noErr)
{
/* get the media time scale */
TimeValue64 timeScale = GetMediaTimeScale(inMovieMedia);
err = GetMoviesError();
if (err == noErr)
{
/* calculate the frame rate:
frame rate = (sample count * media time scale) / media duration
*/
*outFPS = (double)sampleCount * (double)timeScale / (double)duration;
}
}
}
return err;
}
//----------------------------------------
#ifdef TARGET_OSX
// GetSettingsPreference
// Returns a preference for a specified key as QuickTime UserData
// It is your responsibility to dispose of the returned UserData
OSErr GetSettingsPreference(CFStringRef inKey, UserData *outUserData)
{
CFPropertyListRef theCFSettings;
Handle theHandle = nullptr;
UserData theUserData = nullptr;
OSErr err = paramErr;
// read the new setttings from our preferences
theCFSettings = CFPreferencesCopyAppValue(inKey,
kCFPreferencesCurrentApplication);
if (theCFSettings) {
err = PtrToHand(CFDataGetBytePtr((CFDataRef)theCFSettings), &theHandle,
CFDataGetLength((CFDataRef)theCFSettings));
CFRelease(theCFSettings);
if (theHandle) {
err = NewUserDataFromHandle(theHandle, &theUserData);
if (theUserData) {
*outUserData = theUserData;
}
DisposeHandle(theHandle);
}
}
return err;
}
//----------------------------------------
// SaveSettingsPreference
// Saves a preference for a specified key from QuickTime UserData
OSErr SaveSettingsPreference(CFStringRef inKey, UserData inUserData)
{
CFDataRef theCFSettings;
Handle hSettings;
OSErr err;
if (nullptr == inUserData) return paramErr;
hSettings = NewHandle(0);
err = MemError();
if (noErr == err) {
err = PutUserDataIntoHandle(inUserData, hSettings);
if (noErr == err) {
HLock(hSettings);
theCFSettings = CFDataCreate(kCFAllocatorDefault,
(UInt8 *)*hSettings,
GetHandleSize(hSettings));
if (theCFSettings) {
CFPreferencesSetAppValue(inKey, theCFSettings,
kCFPreferencesCurrentApplication);
CFPreferencesAppSynchronize(kCFPreferencesCurrentApplication);
CFRelease(theCFSettings);
}
}
DisposeHandle(hSettings);
}
return err;
}
//end mac specific stuff
#endif
#endif
| [
"m@gingold.com.au"
] | m@gingold.com.au |
72caaa1ed5e258768c2d3bb4139463f261103476 | 68d31a190fa86d6452405f6277f3ff2d384e3941 | /convex_hull_2_intersection/exact_exact_ch_intersection.cpp | 2441972a2f1572fcd09dbfd12bde49032dc359a0 | [] | no_license | jkulesza/cgal_play | 39381a4c1d2e5ee00bd675448573253c08a791dc | 4c9c6721c1d4b893592dba11619e31aaf710083c | refs/heads/master | 2021-01-01T16:43:07.162201 | 2017-07-31T00:03:06 | 2017-07-31T00:03:06 | 97,900,531 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,365 | cpp | #include <CGAL/Exact_predicates_exact_constructions_kernel.h>
#include <CGAL/convex_hull_2.h>
#include <CGAL/Polygon_2.h>
typedef CGAL::Exact_predicates_exact_constructions_kernel K;
typedef CGAL::Polygon_2<K> Polygon_2;
typedef K::Point_2 Point_2;
typedef K::Ray_2 Ray_2;
typedef K::Segment_2 Segment_2;
typedef K::Intersect_2 Intersect_2;
typedef Polygon_2::Edge_const_iterator EdgeIterator;
typedef std::vector<Point_2> Points;
int main() {
Points points, result;
Polygon_2 chP;
points.push_back( Point_2( -10, -10 ) );
points.push_back( Point_2( 10, -10 ) );
points.push_back( Point_2( 10, 10 ) );
points.push_back( Point_2( -10, 10 ) );
CGAL::convex_hull_2( points.begin(), points.end(), std::back_inserter(chP) );
std::cout << chP.size() << " vertices on the convex hull" << std::endl;
Ray_2 ray = Ray_2( Point_2( 0, 0 ), Point_2( 0, 1) );
for( EdgeIterator it = chP.edges_begin(); it != chP.edges_end(); ++it) {
CGAL::cpp11::result_of<Intersect_2(Segment_2, Ray_2)>::type
result = intersection(*it, ray);
if (result) {
if (const Segment_2* s = boost::get<Segment_2>(&*result)) {
std::cout << *s << std::endl;
} else {
const Point_2* p = boost::get<Point_2 >(&*result);
std::cout << "segment " << *it << " intersected at " << *p << std::endl;
}
}
}
return 0;
}
| [
"jkulesza@gmail.com"
] | jkulesza@gmail.com |
e575c15c1bace8f7d4195dff594b8b4eb75c2d93 | 1ba6179028cd524dd7eb6b7a7dce3f8878d15d6e | /MLStudio/Studio.cpp | 999cc55b5a7f089513f93de830cfef1b47654c80 | [] | no_license | MusicLab-Dev/MLStudio | 28a8f51eb122809ec2a06bb7cffc4b4ee98dcf26 | c8385099119d370b8fe175f2f71a905d4c51caf7 | refs/heads/master | 2023-01-22T10:33:36.393732 | 2020-11-19T16:33:05 | 2020-11-19T16:33:05 | 269,968,938 | 0 | 0 | null | 2020-11-09T14:38:25 | 2020-06-06T12:04:37 | C++ | UTF-8 | C++ | false | false | 562 | cpp | /**
* @ Author: Matthieu Moinvaziri
* @ Description: Studio class
*/
#include "Studio.hpp"
Studio::Studio(int argc, char *argv[])
: _application(argc, argv)
{
const QUrl url(QStringLiteral("qrc:/Main.qml"));
QObject::connect(&_engine, &QQmlApplicationEngine::objectCreated, &_application,
[url](QObject *obj, const QUrl &objUrl) {
if (!obj && url == objUrl)
QCoreApplication::exit(-1);
},
Qt::QueuedConnection);
_engine.load(url);
}
int Studio::run(void)
{
return _application.exec();
}
| [
"m.moinvaziri@gmail.com"
] | m.moinvaziri@gmail.com |
48782eebbb639cc93add9b1c64c40864136d85b0 | 9d4a24335892d489153c12ed9c382bf4662e2b56 | /src/qml/qt_native/privacydialog.h | 5dcf0f735f2c84273172abab1b2cd4e3f1e5156f | [
"MIT"
] | permissive | EULO-Project/EULO | 7e85fc462e2b9d3aa369c295990aae8cf209c520 | 26c0c5258a4673ad86663d964f57d0bf0a54941d | refs/heads/master | 2021-06-11T20:44:42.968985 | 2019-06-20T09:45:48 | 2019-06-20T09:45:48 | 136,103,782 | 10 | 6 | MIT | 2019-02-26T09:59:46 | 2018-06-05T01:43:09 | C++ | UTF-8 | C++ | false | false | 3,197 | h | // Copyright (c) 2011-2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_QT_PRIVACYDIALOG_H
#define BITCOIN_QT_PRIVACYDIALOG_H
#include "guiutil.h"
#include <QDialog>
#include <QHeaderView>
#include <QItemSelection>
#include <QKeyEvent>
#include <QMenu>
#include <QPoint>
#include <QTimer>
#include <QVariant>
class OptionsModel;
class WalletModel;
namespace Ui
{
class PrivacyDialog;
}
QT_BEGIN_NAMESPACE
class QModelIndex;
QT_END_NAMESPACE
/** Dialog for requesting payment of bitcoins */
class PrivacyDialog : public QDialog
{
Q_OBJECT
public:
enum ColumnWidths {
DATE_COLUMN_WIDTH = 130,
LABEL_COLUMN_WIDTH = 120,
AMOUNT_MINIMUM_COLUMN_WIDTH = 160,
MINIMUM_COLUMN_WIDTH = 130
};
explicit PrivacyDialog(QWidget* parent = 0);
~PrivacyDialog();
void setModel(WalletModel* model);
void showOutOfSyncWarning(bool fShow);
void setZUloControlLabels(int64_t nAmount, int nQuantity);
public slots:
void setBalance(const CAmount& balance, const CAmount& unconfirmedBalance, const CAmount& immatureBalance,
const CAmount& zerocoinBalance, const CAmount& unconfirmedZerocoinBalance, const CAmount& immatureZerocoinBalance,
const CAmount& watchOnlyBalance, const CAmount& watchUnconfBalance, const CAmount& watchImmatureBalance);
protected:
virtual void keyPressEvent(QKeyEvent* event);
private:
Ui::PrivacyDialog* ui;
QTimer* timer;
GUIUtil::TableViewLastColumnResizingFixer* columnResizingFixer;
WalletModel* walletModel;
QMenu* contextMenu;
CAmount currentBalance;
CAmount currentUnconfirmedBalance;
CAmount currentImmatureBalance;
CAmount currentZerocoinBalance;
CAmount currentUnconfirmedZerocoinBalance;
CAmount currentImmatureZerocoinBalance;
CAmount currentWatchOnlyBalance;
CAmount currentWatchUnconfBalance;
CAmount currentWatchImmatureBalance;
int nSecurityLevel = 0;
bool fMinimizeChange = false;
int nDisplayUnit;
bool updateLabel(const QString& address);
void sendzULO();
private slots:
void on_payTo_textChanged(const QString& address);
void on_addressBookButton_clicked();
// void coinControlFeatureChanged(bool);
void coinControlButtonClicked();
// void coinControlChangeChecked(int);
// void coinControlChangeEdited(const QString&);
void coinControlUpdateLabels();
void coinControlClipboardQuantity();
void coinControlClipboardAmount();
// void coinControlClipboardFee();
// void coinControlClipboardAfterFee();
// void coinControlClipboardBytes();
// void coinControlClipboardPriority();
// void coinControlClipboardLowOutput();
// void coinControlClipboardChange();
void on_pushButtonMintzULO_clicked();
void on_pushButtonMintReset_clicked();
void on_pushButtonSpentReset_clicked();
void on_pushButtonSpendzULO_clicked();
void on_pushButtonZUloControl_clicked();
void on_pasteButton_clicked();
void updateDisplayUnit();
};
#endif // BITCOIN_QT_PRIVACYDIALOG_H
| [
"kingsfinancenz18@gmail.com"
] | kingsfinancenz18@gmail.com |
19b5babaa89cb4150c8954786ed4bc47d62d1097 | 39c718e9b171c78333e9a839ab2e52f9d6cd70d9 | /Wasteland.Stratis/client/hpp/a3_common.hpp | 2fdb58ce498a9d7272abd9371039774d304976f6 | [] | no_license | JABirchall/Sa-Matra-Wasteland | 7de7430a2a6b4ab4577e907a7943038b2f8d3db6 | 75723fd1a75651ecb46a440c988350c7c38b25c9 | refs/heads/master | 2020-12-26T14:07:35.192040 | 2016-08-28T18:31:02 | 2016-08-28T18:31:02 | 66,785,652 | 0 | 1 | null | 2016-08-28T19:04:58 | 2016-08-28T19:04:58 | null | UTF-8 | C++ | false | false | 25,048 | hpp | /*
ArmA 3 Wasteland
Code written by Sa-Matra
Using this code without Sa-Matra's direct permission is forbidden
Special build for Dwarden
ESABQIEXHTFRGOFR
*/
#define a3_sizeEx_06 (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.6)
#define a3_sizeEx_08 (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)
#define a3_sizeEx_10 (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.0)
#define a3_sizeEx(x) (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * x)
#define A3_SIZE(x) (((((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * x)
#define _SPX(x) (x / 250) * (getResolution select 3) / (getResolution select 2)
#define _SPY(x) (x / 250)
class RscControlsGroup{type=15;idc=-1;x=0;y=0;w=1;h=1;shadow=0;style=16;class ScrollBar{color[]={1,1,1,0.6};colorActive[]={1,1,1,1};colorDisabled[]={1,1,1,0.3};thumb="\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";arrowFull="\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";arrowEmpty="\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";border="\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";shadow=0;scrollSpeed=0.05;};class VScrollbar:ScrollBar{width=0.021;autoScrollSpeed=-1;autoScrollDelay=5;autoScrollRewind=0;shadow=0;color[]={1,1,1,0.6};};class HScrollbar:ScrollBar{height=0.028;shadow=0;color[]={1,1,1,0.6};};class Controls{};};class RscControlsGroupNoScrollbars:RscControlsGroup{class VScrollbar:VScrollbar{width=0;};class HScrollbar:HScrollbar{height=0;};};class RscListNBox{type=102;style=16;shadow=0;font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";color[]={0.95,0.95,0.95,1};colorText[]={1,1,1,1.0};colorDisabled[]={1,1,1,0.25};colorScrollbar[]={0.95,0.95,0.95,1};colorSelect[]={0,0,0,1};colorSelect2[]={0,0,0,1};colorSelectBackground[]={0.95,0.95,0.95,1};colorSelectBackground2[]={1,1,1,0.5};colorPicture[]={1,1,1,1};colorPictureSelected[]={1,1,1,1};colorPictureDisabled[]={1,1,1,1};period=1.2;soundSelect[]={"",0.1,1};rowHeight=0.04;autoScrollRewind=0;autoScrollSpeed=-1;autoScrollDelay=5;maxHistoryDelay=1;drawSideArrows=0;idcLeft=-1;idcRight=-1;class ScrollBar{color[]={1,1,1,0.6};colorActive[]={1,1,1,1};colorDisabled[]={1,1,1,0.3};thumb="\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";arrowFull="\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";arrowEmpty="\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";border="\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";};class ListScrollBar:ScrollBar{};};class RscText{x=0;y=0;h=0.037;w=0.3;type=0;style=0;shadow=1;colorShadow[]={0,0,0,0.5};font="PuristaMedium";SizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";text="";colorText[]={1,1,1,1.0};colorBackground[]={0,0,0,0};linespacing=1;};class RscLine:RscText{idc=-1;style=176;x=0.17;y=0.48;w=0.66;h=0;text="";colorBackground[]={0,0,0,0};colorText[]={1,1,1,1.0};};class RscTree{style=2;font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";expandedTexture="A3\ui_f\data\gui\rsccommon\rsctree\expandedTexture_ca.paa";hiddenTexture="A3\ui_f\data\gui\rsccommon\rsctree\hiddenTexture_ca.paa";rowHeight=0.0439091;color[]={1,1,1,1};colorSelect[]={0.7,0.7,0.7,1};colorBackground[]={0,0,0,0};colorSelectBackground[]={0,0,0,0.5};colorBorder[]={0,0,0,0};borderSize=0;};class RscTitle:RscText{style=0;sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";colorText[]={0.95,0.95,0.95,1};};class RscPicture:RscText{style=48;shadow=0;colorText[]={1,1,1,1};x=0;y=0;w=0.2;h=0.15;};class RscPictureKeepAspect:RscPicture{style=0x30+0x800;};class RscVignette:RscPicture{x="safezoneXAbs";y="safezoneY";w="safezoneWAbs";h="safezoneH";text="\A3\ui_f\data\gui\rsccommon\rscvignette\vignette_gs.paa";colortext[]={0,0,0,0.3};};class RscStructuredText{type=13;style=0;x=0;y=0;h=0.035;w=0.1;text="";size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";colorText[]={1,1,1,1.0};shadow=1;class Attributes{font="PuristaMedium";color="#ffffff";align="left";shadow=1;};};class RscActiveText{idc=-1;type=11;style=2;x=0;y=0;h=0.035;w=0.035;font="PuristaMedium";shadow=2;sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";color[]={0,0,0,1};colorText[]={0,0,0,1};colorActive[]={0.3,0.4,0,1};soundEnter[]={"",0,1};soundPush[]={"",0,1};soundClick[]={"",0,1};soundEscape[]={"",0,1};};class RscButton{style=2;x=0;y=0;w=0.095589;h=0.039216;shadow=2;font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";colorText[]={1,1,1,1.0};colorDisabled[]={0.4,0.4,0.4,1};colorBackground[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",0.7};colorBackgroundActive[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};colorBackgroundDisabled[]={0.95,0.95,0.95,1};offsetX=0.003;offsetY=0.003;offsetPressedX=0.002;offsetPressedY=0.002;colorFocused[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};colorShadow[]={0,0,0,1};colorBorder[]={0,0,0,1};borderSize=0.0;soundEnter[]={"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1};soundPush[]={"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1};soundClick[]={"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1};soundEscape[]={"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1};};class RscButtonTextOnly:RscButton{SizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";colorBackground[]={1,1,1,0};colorBackgroundActive[]={1,1,1,0};colorBackgroundDisabled[]={1,1,1,0};colorFocused[]={1,1,1,0};colorShadow[]={1,1,1,0};borderSize=0.0;};class RscShortcutButton{idc=-1;style=0;default=0;shadow=1;w=0.183825;h="( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 20)";color[]={1,1,1,1.0};color2[]={0.95,0.95,0.95,1};colorDisabled[]={1,1,1,0.25};colorBackground[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};colorBackgroundFocused[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};colorBackground2[]={1,1,1,1};animTextureDefault="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa";animTextureNormal="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa";animTextureDisabled="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\normal_ca.paa";animTextureOver="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\over_ca.paa";animTextureFocused="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\focus_ca.paa";animTexturePressed="\A3\ui_f\data\GUI\RscCommon\RscShortcutButton\down_ca.paa";textureNoShortcut="#(argb,8,8,3)color(0,0,0,0)";periodFocus=1.2;periodOver=0.8;class HitZone{left=0.0;top=0.0;right=0.0;bottom=0.0;};class ShortcutPos{left=0;top="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2";w="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1) * (3/4)";h="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";};class TextPos{left="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1) * (3/4)";top="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2";right=0.005;bottom=0.0;};period=0.4;font="PuristaMedium";size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";text="";soundEnter[]={"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1};soundPush[]={"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1};soundClick[]={"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1};soundEscape[]={"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1};action="";class Attributes{font="PuristaMedium";color="#E5E5E5";align="left";shadow="true";};class AttributesImage{font="PuristaMedium";color="#E5E5E5";align="left";};};class RscButtonMenu:RscShortcutButton{idc=-1;type=16;style="0x02 + 0xC0";default=0;shadow=0;x=0;y=0;w=0.095589;h=0.039216;animTextureNormal="#(argb,8,8,3)color(1,1,1,1)";animTextureDisabled="#(argb,8,8,3)color(1,1,1,1)";animTextureOver="#(argb,8,8,3)color(1,1,1,0.5)";animTextureFocused="#(argb,8,8,3)color(1,1,1,1)";animTexturePressed="#(argb,8,8,3)color(1,1,1,1)";animTextureDefault="#(argb,8,8,3)color(1,1,1,1)";colorBackground[]={0,0,0,0.8};colorBackgroundFocused[]={1,1,1,1};colorBackground2[]={1,1,1,0.5};color[]={1,1,1,1};colorFocused[]={0,0,0,1};color2[]={1,1,1,1};colorText[]={1,1,1,1};colorDisabled[]={1,1,1,0.25};period=1.2;periodFocus=1.2;periodOver=1.2;size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";class TextPos{left="0.25 * ( ((safezoneW / safezoneH) min 1.2) / 40)";top="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) - ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)) / 2";right=0.005;bottom=0.0;};class Attributes{font="PuristaLight";color="#E5E5E5";align="left";shadow="false";};class ShortcutPos{left="(6.25 * ( ((safezoneW / safezoneH) min 1.2) / 40)) - 0.0225 - 0.005";top=0.005;w=0.0225;h=0.03;};};class RscShortcutButtonMain:RscShortcutButton{idc=-1;style=0;default=0;w=0.313726;h=0.104575;color[]={1,1,1,1.0};colorDisabled[]={1,1,1,0.25};class HitZone{left=0.0;top=0.0;right=0.0;bottom=0.0;};class ShortcutPos{left=0.0145;top="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 20) - ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)) / 2";w="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2) * (3/4)";h="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)";};class TextPos{left="( ((safezoneW / safezoneH) min 1.2) / 32) * 1.5";top="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 20)*2 - ( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)) / 2";right=0.005;bottom=0.0;};animTextureNormal="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\normal_ca.paa";animTextureDisabled="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\disabled_ca.paa";animTextureOver="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\over_ca.paa";animTextureFocused="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\focus_ca.paa";animTexturePressed="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\down_ca.paa";animTextureDefault="\A3\ui_f\data\GUI\RscCommon\RscShortcutButtonMain\normal_ca.paa";period=0.5;font="PuristaMedium";size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)";text="";soundEnter[]={"\A3\ui_f\data\sound\RscButton\soundEnter",0.09,1};soundPush[]={"\A3\ui_f\data\sound\RscButton\soundPush",0.09,1};soundClick[]={"\A3\ui_f\data\sound\RscButton\soundClick",0.09,1};soundEscape[]={"\A3\ui_f\data\sound\RscButton\soundEscape",0.09,1};action="";class Attributes{font="PuristaMedium";color="#E5E5E5";align="left";shadow="false";};class AttributesImage{font="PuristaMedium";color="#E5E5E5";align="false";};};class RscCheckbox{idc=-1;type=7;style=0;x="LINE_X(XVAL)";y=LINE_Y;w="LINE_W(WVAL)";h=0.029412;colorText[]={1,0,0,1};color[]={0,0,0,0};colorBackground[]={0,0,1,1};colorTextSelect[]={0,0.8,0,1};colorSelectedBg[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};colorSelect[]={0,0,0,1};colorTextDisable[]={0.4,0.4,0.4,1};colorDisable[]={0.4,0.4,0.4,1};font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";rows=1;columns=1;strings[]={UNCHECKED};checked_strings[]={CHECKED};};class RscProgress{type=8;style=0;x=0.344;y=0.619;w=0.313726;h=0.0261438;shadow=2;texture="#(argb,8,8,3)color(1,1,1,1)";colorFrame[]={0,0,0,0};colorBar[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])","(profilenamespace getvariable ['GUI_BCG_RGB_A',0.7])"};};class RscListBox{style=16;type=5;w=0.275;h=0.04;font="PuristaMedium";colorSelect[]={1,1,1,1};colorText[]={1,1,1,1};colorBackground[]={0,0,0,0.1};colorSelect2[]={0,0,0,1};colorSelectBackground[]={0.95,0.95,0.95,1};colorSelectBackground2[]={1,1,1,0.5};colorScrollbar[]={0.2,0.2,0.2,1};colorPicture[]={1,1,1,1};colorPictureSelected[]={1,1,1,1};colorPictureDisabled[]={1,1,1,1};arrowFull="\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";arrowEmpty="\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";wholeHeight=0.45;rowHeight=0.04;color[]={0.7,0.7,0.7,1};colorActive[]={0,0,0,1};colorDisabled[]={0,0,0,0.3};sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";soundSelect[]={"",0.1,1};soundExpand[]={"",0.1,1};soundCollapse[]={"",0.1,1};maxHistoryDelay=1;autoScrollSpeed=-1;autoScrollDelay=5;autoScrollRewind=0;class Scrollbar{color[]={1,1,1,0.6};colorActive[]={1,1,1,1};colorDisabled[]={1,1,1,0.3};thumb="\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";arrowEmpty="\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";arrowFull="\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";border="\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";shadow=0;scrollSpeed=0.06;width=0;height=0;autoScrollEnabled=0;autoScrollSpeed=-1;autoScrollDelay=5;autoScrollRewind=0;};class ListScrollBar:ScrollBar{};};class RscEdit{type=2;style=0x00+0x40;font="PuristaMedium";shadow=2;sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";colorBackground[]={0,0,0,1};colorText[]={0.95,0.95,0.95,1};colorDisabled[]={1,1,1,0.25};colorSelection[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",1};autocomplete=false;canModify=1;text="";};class RscSlider{h=0.025;color[]={1,1,1,0.8};colorActive[]={1,1,1,1};};class RscFrame{type=0;idc=-1;style=64;shadow=2;colorBackground[]={0,0,0,0};colorText[]={1,1,1,1};font="PuristaMedium";sizeEx=0.02;text="";};class RscBackground:RscText{type=0;IDC=-1;style=512;shadow=0;x=0.0;y=0.0;w=1.0;h=1.0;text="";ColorBackground[]={0.48,0.5,0.35,1};ColorText[]={0.1,0.1,0.1,1};font="PuristaMedium";SizeEx=1;};class RscHTML{colorText[]={1,1,1,1.0};colorBold[]={1,1,1,1.0};colorLink[]={1,1,1,0.75};colorLinkActive[]={1,1,1,1.0};sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";prevPage="\A3\ui_f\data\gui\rsccommon\rschtml\arrow_left_ca.paa";nextPage="\A3\ui_f\data\gui\rsccommon\rschtml\arrow_right_ca.paa";shadow=2;class H1{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1.2)";align="left";};class H2{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="right";};class H3{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="left";};class H4{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="left";};class H5{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="left";};class H6{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="left";};class P{font="PuristaMedium";fontBold="PuristaSemibold";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";align="left";};};class RscHitZones{x=0;y=0;w=0.1;h=0.1;xCount=1;yCount=1;xSpace=0;ySpace=0;};class RscMapControl{type=100;style=48;moveOnEdges=1;x="SafeZoneXAbs";y="SafeZoneY + 1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";w="SafeZoneWAbs";h="SafeZoneH - 1.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";shadow=0;ptsPerSquareSea=5;ptsPerSquareTxt=3;ptsPerSquareCLn=10;ptsPerSquareExp=10;ptsPerSquareCost=10;ptsPerSquareFor=9;ptsPerSquareForEdge=9;ptsPerSquareRoad=6;ptsPerSquareObj=9;showCountourInterval=0;scaleMin=0.001;scaleMax=1.0;scaleDefault=0.16;maxSatelliteAlpha=0.85;alphaFadeStartScale=0.35;alphaFadeEndScale=0.4;colorBackground[]={0.969,0.957,0.949,1.0};colorSea[]={0.467,0.631,0.851,0.5};colorForest[]={0.624,0.78,0.388,0.5};colorForestBorder[]={0.0,0.0,0.0,0.0};colorRocks[]={0.0,0.0,0.0,0.3};colorRocksBorder[]={0.0,0.0,0.0,0.0};colorLevels[]={0.286,0.177,0.094,0.5};colorMainCountlines[]={0.572,0.354,0.188,0.5};colorCountlines[]={0.572,0.354,0.188,0.25};colorMainCountlinesWater[]={0.491,0.577,0.702,0.6};colorCountlinesWater[]={0.491,0.577,0.702,0.3};colorPowerLines[]={0.1,0.1,0.1,1.0};colorRailWay[]={0.8,0.2,0.0,1.0};colorNames[]={0.1,0.1,0.1,0.9};colorInactive[]={1.0,1.0,1.0,0.5};colorOutside[]={0.0,0.0,0.0,1.0};colorTracks[]={0.84,0.76,0.65,0.15};colorTracksFill[]={0.84,0.76,0.65,1.0};colorRoads[]={0.7,0.7,0.7,1.0};colorRoadsFill[]={1.0,1.0,1.0,1.0};colorMainRoads[]={0.9,0.5,0.3,1.0};colorMainRoadsFill[]={1.0,0.6,0.4,1.0};colorGrid[]={0.1,0.1,0.1,0.6};colorGridMap[]={0.1,0.1,0.1,0.6};colorText[]={0,0,0,1};fontLabel="PuristaMedium";font="PuristaMedium";sizeExLabel="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";fontGrid="TahomaB";sizeExGrid=0.02;fontUnits="TahomaB";sizeExUnits="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";fontNames="PuristaMedium";sizeExNames="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8) * 2";fontInfo="PuristaMedium";sizeExInfo="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";fontLevel="TahomaB";sizeExLevel=0.02;text="#(argb,8,8,3)color(1,1,1,1)";class Legend{x="SafeZoneX + ( ((safezoneW / safezoneH) min 1.2) / 40)";y="SafeZoneY + safezoneH - 4.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";w="10 * ( ((safezoneW / safezoneH) min 1.2) / 40)";h="3.5 * ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25)";font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";colorBackground[]={1,1,1,0.5};color[]={0,0,0,1};};class Task{icon="\A3\ui_f\data\map\mapcontrol\taskIcon_CA.paa";iconCreated="\A3\ui_f\data\map\mapcontrol\taskIconCreated_CA.paa";iconCanceled="\A3\ui_f\data\map\mapcontrol\taskIconCanceled_CA.paa";iconDone="\A3\ui_f\data\map\mapcontrol\taskIconDone_CA.paa";iconFailed="\A3\ui_f\data\map\mapcontrol\taskIconFailed_CA.paa";color[]={"(profilenamespace getvariable ['IGUI_TEXT_RGB_R',0])","(profilenamespace getvariable ['IGUI_TEXT_RGB_G',1])","(profilenamespace getvariable ['IGUI_TEXT_RGB_B',1])","(profilenamespace getvariable ['IGUI_TEXT_RGB_A',0.8])"};colorCreated[]={1,1,1,1};colorCanceled[]={0.7,0.7,0.7,1};colorDone[]={0.7,1,0.3,1};colorFailed[]={1,0.3,0.2,1};size=27;importance=1;coefMin=1;coefMax=1;};class Waypoint{icon="\A3\ui_f\data\map\mapcontrol\waypoint_ca.paa";color[]={0,0,0,1};coefMin=1;coefMax=1;importance=1;size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";};class WaypointCompleted{icon="\A3\ui_f\data\map\mapcontrol\waypointCompleted_ca.paa";color[]={0,0,0,1};coefMin=1;coefMax=1;importance=1;size="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";};class CustomMark{icon="\A3\ui_f\data\map\mapcontrol\custommark_ca.paa";size=24;importance=1;coefMin=1;coefMax=1;color[]={0,0,0,1};};class Command{icon="\A3\ui_f\data\map\mapcontrol\waypoint_ca.paa";size=18;importance=1;coefMin=1;coefMax=1;color[]={1,1,1,1};};class Bush{icon="\A3\ui_f\data\map\mapcontrol\bush_ca.paa";color[]={0.45,0.64,0.33,0.4};size=14/2;importance=0.2*14*0.05*0.05;coefMin=0.25;coefMax=4;};class Rock{icon="\A3\ui_f\data\map\mapcontrol\rock_ca.paa";color[]={0.1,0.1,0.1,0.8};size=12;importance=0.5*12*0.05;coefMin=0.25;coefMax=4;};class SmallTree{icon="\A3\ui_f\data\map\mapcontrol\bush_ca.paa";color[]={0.45,0.64,0.33,0.4};size=12;importance=0.6*12*0.05;coefMin=0.25;coefMax=4;};class Tree{icon="\A3\ui_f\data\map\mapcontrol\bush_ca.paa";color[]={0.45,0.64,0.33,0.4};size=12;importance=0.9*16*0.05;coefMin=0.25;coefMax=4;};class busstop{icon="\A3\ui_f\data\map\mapcontrol\busstop_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class fuelstation{icon="\A3\ui_f\data\map\mapcontrol\fuelstation_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class hospital{icon="\A3\ui_f\data\map\mapcontrol\hospital_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class church{icon="\A3\ui_f\data\map\mapcontrol\church_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class lighthouse{icon="\A3\ui_f\data\map\mapcontrol\lighthouse_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class power{icon="\A3\ui_f\data\map\mapcontrol\power_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class powersolar{icon="\A3\ui_f\data\map\mapcontrol\powersolar_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class powerwave{icon="\A3\ui_f\data\map\mapcontrol\powerwave_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class powerwind{icon="\A3\ui_f\data\map\mapcontrol\powerwind_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class quay{icon="\A3\ui_f\data\map\mapcontrol\quay_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class shipwreck{icon="\A3\ui_f\data\map\mapcontrol\shipwreck_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class transmitter{icon="\A3\ui_f\data\map\mapcontrol\transmitter_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class watertower{icon="\A3\ui_f\data\map\mapcontrol\watertower_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={1,1,1,1};};class Cross{icon="\A3\ui_f\data\map\mapcontrol\Cross_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={0,0,0,1};};class Chapel{icon="\A3\ui_f\data\map\mapcontrol\Chapel_CA.paa";size=24;importance=1;coefMin=0.85;coefMax=1.0;color[]={0,0,0,1};};class Bunker{icon="\A3\ui_f\data\map\mapcontrol\bunker_ca.paa";size=14;importance=1.5*14*0.05;coefMin=0.25;coefMax=4;color[]={0,0,0,1};};class Fortress{icon="\A3\ui_f\data\map\mapcontrol\bunker_ca.paa";size=16;importance=2*16*0.05;coefMin=0.25;coefMax=4;color[]={0,0,0,1};};class Fountain{icon="\A3\ui_f\data\map\mapcontrol\fountain_ca.paa";size=11;importance=1*12*0.05;coefMin=0.25;coefMax=4;color[]={0,0,0,1};};class Ruin{icon="\A3\ui_f\data\map\mapcontrol\ruin_ca.paa";size=16;importance=1.2*16*0.05;coefMin=1;coefMax=4;color[]={0,0,0,1};};class Stack{icon="\A3\ui_f\data\map\mapcontrol\stack_ca.paa";size=20;importance=2*16*0.05;coefMin=0.9;coefMax=4;color[]={0,0,0,1};};class Tourism{icon="\A3\ui_f\data\map\mapcontrol\tourism_ca.paa";size=16;importance=1*16*0.05;coefMin=0.7;coefMax=4;color[]={0,0,0,1};};class ViewTower{icon="\A3\ui_f\data\map\mapcontrol\viewtower_ca.paa";size=16;importance=2.5*16*0.05;coefMin=0.5;coefMax=4;color[]={0,0,0,1};};};class RscCombo{type=4;style=16;x=0;y=0;w=0.12;h=0.035;shadow=0;colorSelect[]={0,0,0,1};colorText[]={0.95,0.95,0.95,1};colorBackground[]={0,0,0,1};colorSelectBackground[]={1,1,1,0.7};colorScrollbar[]={1,0,0,1};colorPicture[]={1,1,1,1};colorPictureSelected[]={1,1,1,1};colorPictureDisabled[]={1,1,1,1};arrowEmpty="\A3\ui_f\data\GUI\RscCommon\rsccombo\arrow_combo_ca.paa";arrowFull="\A3\ui_f\data\GUI\RscCommon\rsccombo\arrow_combo_active_ca.paa";wholeHeight=0.45;color[]={1,1,1,1};colorActive[]={1,0,0,1};colorDisabled[]={1,1,1,0.25};font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 1)";soundSelect[]={"",0.000000,1};soundExpand[]={"",0.000000,1};soundCollapse[]={"",0.000000,1};maxHistoryDelay=10;class ScrollBar{color[]={1,1,1,0.6};colorActive[]={1,1,1,1};colorDisabled[]={1,1,1,0.3};thumb="\A3\ui_f\data\gui\cfg\scrollbar\thumb_ca.paa";arrowFull="\A3\ui_f\data\gui\cfg\scrollbar\arrowFull_ca.paa";arrowEmpty="\A3\ui_f\data\gui\cfg\scrollbar\arrowEmpty_ca.paa";border="\A3\ui_f\data\gui\cfg\scrollbar\border_ca.paa";};class ComboScrollBar:ScrollBar{color[]={1,1,1,1};};};class RscToolbox{colorText[]={0.95,0.95,0.95,1};color[]={0.95,0.95,0.95,1};colorTextSelect[]={0.95,0.95,0.95,1};colorSelect[]={0.95,0.95,0.95,1};colorTextDisable[]={0.4,0.4,0.4,1};colorDisable[]={0.4,0.4,0.4,1};colorSelectedBg[]={"(profilenamespace getvariable ['GUI_BCG_RGB_R',0.3843])","(profilenamespace getvariable ['GUI_BCG_RGB_G',0.7019])","(profilenamespace getvariable ['GUI_BCG_RGB_B',0.8862])",0.5};font="PuristaMedium";sizeEx="( ( ( ((safezoneW / safezoneH) min 1.2) / 1.2) / 25) * 0.8)";}; | [
"armaleakteam691@gmail.com"
] | armaleakteam691@gmail.com |
39bf349028143663de8fe7c58e2d5978c3e2ddc5 | c29391e07fef21a22727c94f8f55330f43397d0c | /playerbot/strategy/actions/TrainerAction.cpp | 0e13ae99047e3d28ebb41725d781daced9523e80 | [] | no_license | 1679399242/mangosbot-bots | 5b6a65a49c7d650fc5c7114a603c290e96e55490 | 64ac440b71f54bdfd9e4c8efe1f90b62a5a908c3 | refs/heads/master | 2020-04-25T19:18:09.535736 | 2018-09-30T10:48:44 | 2018-09-30T10:48:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,689 | cpp | #include "botpch.h"
#include "../../playerbot.h"
#include "TrainerAction.h"
#include "../../ServerFacade.h"
using namespace ai;
void TrainerAction::Learn(uint32 cost, TrainerSpell const* tSpell, ostringstream& msg)
{
if (bot->GetMoney() < cost)
{
msg << " - too expensive";
return;
}
bot->ModifyMoney(-int32(cost));
#ifdef MANGOSBOT_ZERO
bot->CastSpell(bot, tSpell->spell,
#ifdef MANGOS
true
#endif
#ifdef CMANGOS
(uint32)0
#endif
);
#endif
#ifdef MANGOSBOT_ONE
bot->learnSpell(tSpell->spell, false);
#endif
msg << " - learned";
}
void TrainerAction::List(Creature* creature, TrainerSpellAction action, SpellIds& spells)
{
TellHeader(creature);
TrainerSpellData const* cSpells = creature->GetTrainerSpells();
TrainerSpellData const* tSpells = creature->GetTrainerTemplateSpells();
float fDiscountMod = bot->GetReputationPriceDiscount(creature);
uint32 totalCost = 0;
TrainerSpellData const* trainer_spells = cSpells;
if (!trainer_spells)
trainer_spells = tSpells;
for (TrainerSpellMap::const_iterator itr = trainer_spells->spellList.begin(); itr != trainer_spells->spellList.end(); ++itr)
{
TrainerSpell const* tSpell = &itr->second;
if (!tSpell)
continue;
uint32 reqLevel = 0;
reqLevel = tSpell->isProvidedReqLevel ? tSpell->reqLevel : std::max(reqLevel, tSpell->reqLevel);
TrainerSpellState state = bot->GetTrainerSpellState(tSpell, reqLevel);
if (state != TRAINER_SPELL_GREEN)
continue;
uint32 spellId = tSpell->spell;
const SpellEntry *const pSpellInfo = sServerFacade.LookupSpellInfo(spellId);
if (!pSpellInfo)
continue;
uint32 cost = uint32(floor(tSpell->spellCost * fDiscountMod));
totalCost += cost;
ostringstream out;
out << chat->formatSpell(pSpellInfo) << chat->formatMoney(cost);
if (action && (spells.empty() || spells.find(tSpell->spell) != spells.end()))
(this->*action)(cost, tSpell, out);
ai->TellMaster(out);
}
TellFooter(totalCost);
}
bool TrainerAction::Execute(Event event)
{
string text = event.getParam();
Player* master = GetMaster();
if (!master)
return false;
Creature *creature = ai->GetCreature(master->GetSelectionGuid());
if (!creature)
return false;
if (!creature->IsTrainerOf(bot, false))
{
ai->TellMaster("This trainer cannot teach me");
return false;
}
// check present spell in trainer spell list
TrainerSpellData const* cSpells = creature->GetTrainerSpells();
TrainerSpellData const* tSpells = creature->GetTrainerTemplateSpells();
if (!cSpells && !tSpells)
{
ai->TellMaster("No spells can be learned from this trainer");
return false;
}
uint32 spell = chat->parseSpell(text);
SpellIds spells;
if (spell)
spells.insert(spell);
if (text.find("learn") != string::npos)
List(creature, &TrainerAction::Learn, spells);
else
List(creature, NULL, spells);
return true;
}
void TrainerAction::TellHeader(Creature* creature)
{
ostringstream out; out << "--- Can learn from " << creature->GetName() << " ---";
ai->TellMaster(out);
}
void TrainerAction::TellFooter(uint32 totalCost)
{
if (totalCost)
{
ostringstream out; out << "Total cost: " << chat->formatMoney(totalCost);
ai->TellMaster(out);
}
}
| [
"ike@email.org"
] | ike@email.org |
8368aeb20eda8fdd495ed26418c1b0bcf066c216 | 2aee5a022239ecfb01562a46afa56706c2885936 | /src/node.cpp | 0a9cf7da996960a01c4cd2dfab3bd1fa7f1b68c4 | [] | no_license | susanbao/Batch-Error-Estimation | c2c2ae250ed0132ea802d730a25969f1b1a975ee | a64b121cf1877ce3519d1778a741da507773d9e3 | refs/heads/master | 2020-04-06T09:56:14.962132 | 2018-11-10T06:14:15 | 2018-11-10T06:14:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,220 | cpp | /*CppFile****************************************************************
FileName [node.cpp]
Synopsis []
Author [Chang Meng]
Date [09/08/2018 15:00:39]
***********************************************************************/
#include "node.h"
namespace user
{
/**Function*************************************************************
Synopsis [Get type of gate]
Description [Network must be mapped and pObj is a node]
***********************************************************************/
gate_t GetGateType( abc::Abc_Obj_t * pObj )
{
char * pSop = abc::Mio_GateReadSop( (abc::Mio_Gate_t *)pObj->pData );
if ( SopIsConst0(pSop) )
return gate_t::CONST0;
else if ( SopIsConst1(pSop) )
return gate_t::CONST1;
else if ( SopIsBuf(pSop) )
return gate_t::BUF;
else if ( SopIsInvGate(pSop) )
return gate_t::INV;
else if ( SopIsXorGate(pSop) )
return gate_t::XOR;
else if ( SopIsXnorGate(pSop) )
return gate_t::XNOR;
else if ( SopIsAndGate(pSop) ) {
assert( abc::Abc_SopGetVarNum( pSop ) == 2 );
return gate_t::AND2;
}
else if ( SopIsOrGate(pSop) ) {
assert( abc::Abc_SopGetVarNum( pSop ) == 2 );
return gate_t::OR2;
}
else if ( SopIsNandGate(pSop) ) {
assert( abc::Abc_SopGetVarNum( pSop ) <= 4 );
return (gate_t)( (int)gate_t::NAND2 + abc::Abc_SopGetVarNum( pSop ) - 2 );
}
else if ( SopIsNorGate(pSop) ) {
assert( abc::Abc_SopGetVarNum( pSop ) <= 4 );
return (gate_t)( (int)gate_t::NOR2 + abc::Abc_SopGetVarNum( pSop ) - 2 );
}
else if ( SopIsAOI21Gate(pSop) )
return gate_t::AOI21;
else if ( SopIsAOI22Gate(pSop) )
return gate_t::AOI22;
else if ( SopIsOAI21Gate(pSop) )
return gate_t::OAI21;
else if ( SopIsOAI22Gate(pSop) )
return gate_t::OAI22;
else {
std::cout << abc::Abc_ObjName( pObj ) << std::endl;
std::cout << pSop << std::endl;
assert( 0 );
}
}
/**Function*************************************************************
Synopsis [Checks if the cover is constant 0.]
Description []
***********************************************************************/
bool SopIsConst0( char * pSop )
{
return abc::Abc_SopIsConst0(pSop);
}
/**Function*************************************************************
Synopsis [Checks if the cover is constant 1.]
Description []
***********************************************************************/
bool SopIsConst1( char * pSop )
{
return abc::Abc_SopIsConst1(pSop);
}
/**Function*************************************************************
Synopsis [Checks if the gate is BUF.]
Description []
***********************************************************************/
bool SopIsBuf( char * pSop )
{
return abc::Abc_SopIsBuf(pSop);
}
/**Function*************************************************************
Synopsis [Checks if the gate is NOT.]
Description []
***********************************************************************/
bool SopIsInvGate( char * pSop )
{
return abc::Abc_SopIsInv(pSop);
}
/**Function*************************************************************
Synopsis [Checks if the gate is AND.]
Description []
***********************************************************************/
bool SopIsAndGate( char * pSop )
{
if ( !abc::Abc_SopIsComplement(pSop) ) { //111 1
char * pCur;
if ( abc::Abc_SopGetCubeNum(pSop) != 1 )
return 0;
for ( pCur = pSop; *pCur != ' '; pCur++ )
if ( *pCur != '1' )
return 0;
}
else { //0-- 0\n-0- 0\n--0 0\n
char * pCube, * pCur;
int nVars, nLits;
nVars = abc::Abc_SopGetVarNum( pSop );
if ( nVars != abc::Abc_SopGetCubeNum(pSop) )
return 0;
Abc_SopForEachCube( pSop, nVars, pCube )
{
nLits = 0;
for ( pCur = pCube; *pCur != ' '; pCur++ ) {
if ( *pCur == '0' )
nLits ++;
else if ( *pCur == '-' )
continue;
else
return 0;
}
if ( nLits != 1 )
return 0;
}
}
return 1;
}
/**Function*************************************************************
Synopsis [Checks if the gate is OR.]
Description []
***********************************************************************/
bool SopIsOrGate( char * pSop )
{
if ( abc::Abc_SopIsComplement(pSop) ) { //000 0
char * pCur;
if ( abc::Abc_SopGetCubeNum(pSop) != 1 )
return 0;
for ( pCur = pSop; *pCur != ' '; pCur++ )
if ( *pCur != '0' )
return 0;
}
else { //1-- 1\n-1- 1\n--1 1\n
char * pCube, * pCur;
int nVars, nLits;
nVars = abc::Abc_SopGetVarNum( pSop );
if ( nVars != abc::Abc_SopGetCubeNum(pSop) )
return 0;
Abc_SopForEachCube( pSop, nVars, pCube )
{
nLits = 0;
for ( pCur = pCube; *pCur != ' '; pCur++ ) {
if ( *pCur == '1' )
nLits ++;
else if ( *pCur == '-' )
continue;
else
return 0;
}
if ( nLits != 1 )
return 0;
}
}
return 1;
}
/**Function*************************************************************
Synopsis [Checks if the gate is NAND.]
Description []
***********************************************************************/
bool SopIsNandGate( char * pSop )
{
if ( abc::Abc_SopIsComplement(pSop) ) { //111 0
char * pCur;
if ( abc::Abc_SopGetCubeNum(pSop) != 1 )
return 0;
for ( pCur = pSop; *pCur != ' '; pCur++ )
if ( *pCur != '1' )
return 0;
}
else { //0-- 1\n-0- 1\n--0 1\n
char * pCube, * pCur;
int nVars, nLits;
nVars = abc::Abc_SopGetVarNum( pSop );
if ( nVars != abc::Abc_SopGetCubeNum(pSop) )
return 0;
Abc_SopForEachCube( pSop, nVars, pCube )
{
nLits = 0;
for ( pCur = pCube; *pCur != ' '; pCur++ ) {
if ( *pCur == '0' )
nLits ++;
else if ( *pCur == '-' )
continue;
else
return 0;
}
if ( nLits != 1 )
return 0;
}
}
return 1;
}
/**Function*************************************************************
Synopsis [Checks if the gate is NOR.]
Description []
***********************************************************************/
bool SopIsNorGate( char * pSop )
{
if ( !abc::Abc_SopIsComplement(pSop) ) { //000 1
char * pCur;
if ( abc::Abc_SopGetCubeNum(pSop) != 1 )
return 0;
for ( pCur = pSop; *pCur != ' '; pCur++ )
if ( *pCur != '0' )
return 0;
}
else { //1-- 0\n-1- 0\n--1 0\n
char * pCube, * pCur;
int nVars, nLits;
nVars = abc::Abc_SopGetVarNum( pSop );
if ( nVars != abc::Abc_SopGetCubeNum(pSop) )
return 0;
Abc_SopForEachCube( pSop, nVars, pCube )
{
nLits = 0;
for ( pCur = pCube; *pCur != ' '; pCur++ ) {
if ( *pCur == '1' )
nLits ++;
else if ( *pCur == '-' )
continue;
else
return 0;
}
if ( nLits != 1 )
return 0;
}
}
return 1;
}
/**Function*************************************************************
Synopsis [Checks if the gate is XOR.]
Description []
***********************************************************************/
bool SopIsXorGate( char * pSop )
{
if ( !abc::Abc_SopIsComplement(pSop) ) { //01 1\n10 1\n
char * pCube, * pCur;
int nVars, nLits;
nVars = abc::Abc_SopGetVarNum( pSop );
if ( nVars != 2 )
return 0;
Abc_SopForEachCube( pSop, nVars, pCube )
{
nLits = 0;
for ( pCur = pCube; *pCur != ' '; pCur++ ) {
if ( *pCur == '1' )
nLits ++;
else if ( *pCur == '-' )
return 0;
}
if ( nLits != 1 )
return 0;
}
}
else
return 0;
return 1;
}
/**Function*************************************************************
Synopsis [Checks if the gate is XNOR.]
Description []
***********************************************************************/
bool SopIsXnorGate( char * pSop )
{
if ( strcmp( pSop, "00 1\n11 1\n" ) == 0 )
return 1;
else if ( strcmp( pSop, "11 1\n00 1\n" ) == 0 )
return 1;
else
return 0;
}
/**Function*************************************************************
Synopsis [Checks if the gate is AOI21.]
Description []
***********************************************************************/
bool SopIsAOI21Gate( char * pSop )
{
if ( strcmp( pSop, "-00 1\n0-0 1\n" ) == 0 )
return 1;
else
return 0;
}
/**Function*************************************************************
Synopsis []
Description []
***********************************************************************/
bool SopIsAOI22Gate( char * pSop )
{
if ( strcmp( pSop, "--11 0\n11-- 0\n" ) == 0 )
return 1;
else
return 0;
}
/**Function*************************************************************
Synopsis []
Description []
***********************************************************************/
bool SopIsOAI21Gate( char * pSop )
{
if ( strcmp( pSop, "--0 1\n00- 1\n" ) == 0 )
return 1;
else
return 0;
}
/**Function*************************************************************
Synopsis []
Description []
***********************************************************************/
bool SopIsOAI22Gate( char * pSop )
{
if ( strcmp( pSop, "--00 1\n00-- 1\n" ) == 0 )
return 1;
else
return 0;
}
}
| [
"sdmengchang@yahoo.com"
] | sdmengchang@yahoo.com |
326d22773864ad50b7a166ea0773770496ffe3f5 | 6be4cb424dec9586f2699a1b6fd9c1f07e449d9f | /design_pattern/02struct/composite/component.h | bfda457385f7668b00a84d37c3e3199e4491c930 | [] | no_license | feishengfei/workspace | f1a3214a9f02d8b69d50a740ebfd199253edf129 | faf45ddcd900067df3968c24228cd82b1d40e448 | refs/heads/master | 2021-10-21T00:21:34.334239 | 2021-10-10T13:34:24 | 2021-10-12T00:23:53 | 8,425,289 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 295 | h | #ifndef _COMPONENT_H_
#define _COMPONENT_H_
class Component
{
public:
Component();
virtual ~Component();
public:
virtual void operation()=0;
virtual void add(Component*);
virtual void remove(Component*);
virtual Component* getChild(int);
protected:
private:
};
#endif//~_COMPONENT_H_
| [
"feishengfei@126.com"
] | feishengfei@126.com |
d25298f5390537fd78a2356c7a0e142a5e4fe3ba | b1f749ee047b06df9930b76d03f272d997e49af0 | /VisionSolutionMinSH/VisionProject/SocketClient.cpp | 57730294c1dee371ea2a613b7f81055eb1913071 | [] | no_license | chejingguo/VisionSolutionMinSH | 86c609c1aa6a0a115913ece3832dc24166220847 | c63700e7379bf15b37878cd2ef42caefb13c4610 | refs/heads/master | 2020-12-24T21:22:58.888788 | 2016-05-17T07:03:50 | 2016-05-17T07:03:50 | 58,172,321 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 570 | cpp | // SocketClient.cpp : implementation file
//
#include "stdafx.h"
#include "SocketClient.h"
// CSocketClient
CSocketClient::CSocketClient()
{
AfxSocketInit();
}
CSocketClient::~CSocketClient()
{
}
void CSocketClient::OnReceive(int nErrorCode)
{
// TODO: Add your specialized code here and/or call the base class
TCHAR s[2048];CString szIP;UINT szPort;
GetPeerName(szIP,szPort);
int nLen = Receive(s,2048);
s[nLen]=_T('\0');
CString strText(s);
//
SetInfoReceive(strText);
SetServerIP(szIP);
SetServerPort(szPort);
//
CSocket::OnReceive(nErrorCode);
}
| [
"chejingguo@163.com"
] | chejingguo@163.com |
7366783c506dca4ac874fbe48079e20f9cd3aaab | deb47ca830ae62ec553e66f7d7bbda9c1c663d66 | /Task_E/src/Wheel.cpp | d15f79c2e85c8f9e0c89251445d5911ee7f2ee11 | [
"WTFPL"
] | permissive | rkoch/uzh-inf02b-a1 | c0005e768817fd31de22f8ebdac5dbfadbd225d4 | 415bf542f68f876a8e2fc834143a7e15c1b9d099 | refs/heads/master | 2021-01-25T05:11:22.529834 | 2013-03-03T21:02:33 | 2013-03-03T21:02:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 342 | cpp | //
// Authored by Remo Koch
// Public repository at https://github.com/rkoch/uzh-inf02b-a1
//
#include <iostream>
#include "Wheel.h"
Wheel::Wheel(bool isSummerWheel) {
size_in_inches = 25.4f;
model = isSummerWheel;
}
Wheel::~Wheel() {
}
float Wheel::size() {
return size_in_inches;
}
bool Wheel::isSummerWheel() {
return model;
}
| [
"me@rko.io"
] | me@rko.io |
257b6190592253c6f6ddb5f1882d39826ba61b20 | c51febc209233a9160f41913d895415704d2391f | /library/ATF/GUILD_BATTLE__CNormalGuildBattleGuildMemberDetail.hpp | 910705466d920699990f7c591c15ae8fb25c5758 | [
"MIT"
] | permissive | roussukke/Yorozuya | 81f81e5e759ecae02c793e65d6c3acc504091bc3 | d9a44592b0714da1aebf492b64fdcb3fa072afe5 | refs/heads/master | 2023-07-08T03:23:00.584855 | 2023-06-29T08:20:25 | 2023-06-29T08:20:25 | 463,330,454 | 0 | 0 | MIT | 2022-02-24T23:15:01 | 2022-02-24T23:15:00 | null | UTF-8 | C++ | false | false | 483 | hpp | // This file auto generated by plugin for ida pro. Generated code only for x64. Please, dont change manually
#pragma once
#include <common/common.h>
#include <GUILD_BATTLE__CNormalGuildBattleGuildMemberInfo.hpp>
START_ATF_NAMESPACE
namespace GUILD_BATTLE
{
namespace Detail
{
extern ::std::array<hook_record, 28> CNormalGuildBattleGuildMember_functions;
}; // end namespace Detail
}; // end namespace GUILD_BATTLE
END_ATF_NAMESPACE
| [
"b1ll.cipher@yandex.ru"
] | b1ll.cipher@yandex.ru |
c603389cd2e2a177b85ccf35c807e82e14a1dde5 | bd893ed31f5a50d5be969625f8c6c233734b60ac | /sprout/compost/formats/right_channel.hpp | fc28d9586a701634b1da6dd88f33129caa1a244b | [
"BSL-1.0"
] | permissive | kennethho/Sprout | 021fb3b7583fcf05e59c6c2916292073cd210981 | dad087cd69627897da31a531c9da989c661866cc | refs/heads/master | 2021-01-22T00:50:54.516815 | 2013-12-12T14:38:33 | 2013-12-12T14:38:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,497 | hpp | /*=============================================================================
Copyright (c) 2011-2013 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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 SPROUT_COMPOST_FORMATS_RIGHT_CHANNEL_HPP
#define SPROUT_COMPOST_FORMATS_RIGHT_CHANNEL_HPP
#include <sprout/config.hpp>
#include <sprout/utility/forward.hpp>
#include <sprout/range/adaptor/steps.hpp>
namespace sprout {
namespace compost {
namespace formats {
//
// right_channel_forwarder
//
class right_channel_forwarder {};
//
// right_channel
//
namespace {
SPROUT_STATIC_CONSTEXPR sprout::compost::formats::right_channel_forwarder right_channel = {};
} // anonymous-namespace
//
// operator|
//
template<typename Range, typename T>
inline SPROUT_CONSTEXPR auto
operator|(Range&& lhs, right_channel_forwarder const&)
-> decltype(
sprout::forward<Range>(lhs)
| sprout::adaptors::steps(2, 1)
)
{
return sprout::forward<Range>(lhs)
| sprout::adaptors::steps(2, 1)
;
}
} // namespace formats
using sprout::compost::formats::right_channel;
} // namespace compost
} // namespace sprout
#endif // #ifndef SPROUT_COMPOST_FORMATS_RIGHT_CHANNEL_HPP
| [
"bolero.murakami@gmail.com"
] | bolero.murakami@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.