blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 2 247 | content_id stringlengths 40 40 | detected_licenses listlengths 0 57 | license_type stringclasses 2 values | repo_name stringlengths 4 111 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringlengths 4 58 | visit_date timestamp[ns]date 2015-07-25 18:16:41 2023-09-06 10:45:08 | revision_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | committer_date timestamp[ns]date 1970-01-14 14:03:36 2023-09-06 06:22:19 | github_id int64 3.89k 689M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 25 values | gha_event_created_at timestamp[ns]date 2012-06-07 00:51:45 2023-09-14 21:58:52 ⌀ | gha_created_at timestamp[ns]date 2008-03-27 23:40:48 2023-08-24 19:49:39 ⌀ | gha_language stringclasses 159 values | src_encoding stringclasses 34 values | language stringclasses 1 value | is_vendor bool 1 class | is_generated bool 2 classes | length_bytes int64 7 10.5M | extension stringclasses 111 values | filename stringlengths 1 195 | text stringlengths 7 10.5M |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ed742284a73ecfdbaa3d3fc22ed2744c823d9ca6 | bf6da9e95008743dad974f2b74f2988852e2896a | /Source/Processors/PythonProcessor/PythonPlugin.h | 14ea7f73201a482faaab46d915c716e0189b1cab | [] | no_license | fpbattaglia/GUI | 632e5d719e780ca0b3c937c0f4e06d46a8f9c1b8 | 408cd22e7006215f5fc6204be5b9e1b50eb46580 | refs/heads/master | 2020-12-26T04:38:15.499428 | 2016-03-07T11:40:20 | 2016-03-07T11:40:20 | 19,777,143 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,451 | h | PythonPlugin.h | /*
------------------------------------------------------------------
This file is part of the Open Ephys GUI
Copyright (C) 2015 Open Ephys
------------------------------------------------------------------
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*
==============================================================================
PythonPlugin.h
Created: 13 Jun 2014 5:56:17pm
Author: fpbatta
==============================================================================
*/
#ifndef __PYTHONPLUGIN_H_2DB70FC9__
#define __PYTHONPLUGIN_H_2DB70FC9__
#include <Python.h>
#if PY_MAJOR_VERSION>=3
#define DL_IMPORT PyAPI_FUNC
#endif
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#include "PythonParamConfig.h"
#include "PythonEvent.h"
//extern "C" typedef void (*initfunc_t)(void);
#if PY_MAJOR_VERSION>=3
typedef PyObject * (*initfunc_t)(void);
#else
typedef PyMODINIT_FUNC (*initfunc_t)(void);
#endif
typedef DL_IMPORT(void) (*startupfunc_t)(float); // passes the sampling rate
typedef DL_IMPORT(void) (*pluginfunc_t)(float *, int, int, int, PythonEvent *);
typedef DL_IMPORT(int) (*isreadyfunc_t)(void);
typedef DL_IMPORT(int) (*getparamnumfunc_t)(void);
typedef DL_IMPORT(void) (*getparamconfigfunc_t)(struct ParamConfig*);
typedef DL_IMPORT(void) (*setintparamfunc_t)(char*, int);
typedef DL_IMPORT(void) (*setfloatparamfunc_t)(char*, float);
typedef DL_IMPORT(int) (*getintparamfunc_t)(char*);
typedef DL_IMPORT(float) (*getfloatparamfunc_t)(char*);
#ifdef _WIN32
#include <Windows.h>
#endif
#include "../../JuceLibraryCode/JuceHeader.h"
#include "../GenericProcessor/GenericProcessor.h"
//=============================================================================
/*
*/
class PythonPlugin : public GenericProcessor
{
public:
/** The class constructor, used to initialize any members. */
PythonPlugin(const String &processorName = "Python Plugin");
/** The class destructor, used to deallocate memory */
~PythonPlugin();
/** Determines whether the processor is treated as a source. */
virtual bool isSource()
{
return false;
}
/** Determines whether the processor is treated as a sink. */
virtual bool isSink()
{
return false;
}
/** Defines the functionality of the processor.
The process method is called every time a new data buffer is available.
Processors can either use this method to add new data, manipulate existing
data, or send data to an external target (such as a display or other hardware).
Continuous signals arrive in the "buffer" variable, event data (such as TTLs
and spikes) is contained in the "events" variable, and "nSamples" holds the
number of continous samples in the current buffer (which may differ from the
size of the buffer).
*/
virtual void process(AudioSampleBuffer& buffer, MidiBuffer& events);
/** Any variables used by the "process" function _must_ be modified only through
this method while data acquisition is active. If they are modified in any
other way, the application will crash. */
void setParameter(int parameterIndex, float newValue);
AudioProcessorEditor* createEditor();
bool hasEditor() const
{
return true;
}
void updateSettings();
void setFile(String fullpath);
String getFile();
bool isReady();
void setIntPythonParameter(String name, int value);
void setFloatPythonParameter(String name, float value);
int getNumPythonParams()
{
return numPythonParams;
}
ParamConfig *getPythonParams() const
{
return params;
}
Component **getParamsControl() const
{
return paramsControl;
}
int getIntPythonParameter(String name);
float getFloatPythonParameter(String name);
void resetConnections();
private:
String filePath;
void *plugin;
// private members and methods go here
//
// e.g.:
//
// float threshold;
// bool state;
int numPythonParams = 0;
ParamConfig *params;
Component **paramsControl;
// function pointers to the python plugin
pluginfunc_t pluginFunction;
isreadyfunc_t pluginIsReady;
startupfunc_t pluginStartupFunction;
getparamnumfunc_t getParamNumFunction;
getparamconfigfunc_t getParamConfigFunction;
setintparamfunc_t setIntParamFunction;
setfloatparamfunc_t setFloatParamFunction;
getintparamfunc_t getIntParamFunction;
getfloatparamfunc_t getFloatParamFunction;
PyThreadState *GUIThreadState = 0;
PyThreadState *processThreadState = 0;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR(PythonPlugin);
};
#endif // __PYTHONPLUGIN_H_2DB70FC9__
|
52a4131ebec065292d3997be7801a5e0e2f3f9f7 | 86535d64213d939a507cb45ea5627d89b910f6bb | /abel/base/profile/compiler_traits.h | 7912e3f56568e31e88e8a5af24b1b2ee59f40087 | [
"BSD-3-Clause"
] | permissive | Conun/abel | 4afcd24d844e5380abde3cb8a8fbb88b2274bb4c | 485ef38c917c0df3750242cc38966a2bcb163588 | refs/heads/master | 2020-12-29T13:51:26.721782 | 2020-02-07T07:35:04 | 2020-02-07T07:35:04 | 238,627,584 | 0 | 0 | BSD-3-Clause | 2020-02-06T07:02:49 | 2020-02-06T07:02:48 | null | UTF-8 | C++ | false | false | 106,199 | h | compiler_traits.h | //
// Created by liyinbin on 2019/12/11.
//
#ifndef ABEL_BASE_PROFILE_COMPILER_TRAITS_H_
#define ABEL_BASE_PROFILE_COMPILER_TRAITS_H_
#include <abel/base/profile/platform.h>
#include <abel/base/profile/compiler.h>
// Metrowerks uses #defines in its core C header files to define
// the kind of information we need below (e.g. C99 compatibility)
// Determine if this compiler is ANSI C compliant and if it is C99 compliant.
#if defined(__STDC__)
#define ABEL_COMPILER_IS_ANSIC 1 // The compiler claims to be ANSI C
// Is the compiler a C99 compiler or equivalent?
// From ISO/IEC 9899:1999:
// 6.10.8 Predefined macro names
// __STDC_VERSION__ The integer constant 199901L. (150)
//
// 150) This macro was not specified in ISO/IEC 9899:1990 and was
// specified as 199409L in ISO/IEC 9899/AMD1:1995. The intention
// is that this will remain an integer constant of type long int
// that is increased with each revision of this International Standard.
//
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901L)
#define ABEL_COMPILER_IS_C99 1
#endif
// Is the compiler a C11 compiler?
// From ISO/IEC 9899:2011:
// Page 176, 6.10.8.1 (Predefined macro names) :
// __STDC_VERSION__ The integer constant 201112L. (178)
//
#if defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 201112L)
#define ABEL_COMPILER_IS_C11 1
#endif
#endif
// Some compilers (e.g. GCC) define __USE_ISOC99 if they are not
// strictly C99 compilers (or are simply C++ compilers) but are set
// to use C99 functionality. Metrowerks defines _MSL_C99 as 1 in
// this case, but 0 otherwise.
#if (defined(__USE_ISOC99) || (defined(_MSL_C99) && (_MSL_C99 == 1))) && !defined(ABEL_COMPILER_IS_C99)
#define ABEL_COMPILER_IS_C99 1
#endif
// Metrowerks defines C99 types (e.g. intptr_t) instrinsically when in C99 mode (-lang C99 on the command line).
#if (defined(_MSL_C99) && (_MSL_C99 == 1))
#define ABEL_COMPILER_HAS_C99_TYPES 1
#endif
#if defined(__GNUC__)
#if (((__GNUC__ * 100) + __GNUC_MINOR__) >= 302) // Also, GCC defines _HAS_C9X.
#define ABEL_COMPILER_HAS_C99_TYPES 1 // The compiler is not necessarily a C99 compiler, but it defines C99 types.
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS 1
#endif
#ifndef __STDC_CONSTANT_MACROS
#define __STDC_CONSTANT_MACROS 1 // This tells the GCC compiler that we want it to use its native C99 types.
#endif
#endif
#endif
#if defined(_MSC_VER) && (_MSC_VER >= 1600)
#define ABEL_COMPILER_HAS_C99_TYPES 1
#endif
#ifdef __cplusplus
#define ABEL_COMPILER_IS_CPLUSPLUS 1
#endif
// ------------------------------------------------------------------------
// ABEL_PREPROCESSOR_JOIN
//
// This macro joins the two arguments together, even when one of
// the arguments is itself a macro (see 16.3.1 in C++98 standard).
// This is often used to create a unique name with __LINE__.
//
// For example, this declaration:
// char ABEL_PREPROCESSOR_JOIN(unique_, __LINE__);
// expands to this:
// char unique_73;
//
// Note that all versions of MSVC++ up to at least version 7.1
// fail to properly compile macros that use __LINE__ in them
// when the "program database for edit and continue" option
// is enabled. The result is that __LINE__ gets converted to
// something like __LINE__(Var+37).
//
#ifndef ABEL_PREPROCESSOR_JOIN
#define ABEL_PREPROCESSOR_JOIN(a, b) ABEL_PREPROCESSOR_JOIN1(a, b)
#define ABEL_PREPROCESSOR_JOIN1(a, b) ABEL_PREPROCESSOR_JOIN2(a, b)
#define ABEL_PREPROCESSOR_JOIN2(a, b) a##b
#endif
// ------------------------------------------------------------------------
// ABEL_STRINGIFY
//
// Example usage:
// printf("Line: %s", ABEL_STRINGIFY(__LINE__));
//
#ifndef ABEL_STRINGIFY
#define ABEL_STRINGIFY(x) ABEL_STRINGIFYIMPL(x)
#define ABEL_STRINGIFYIMPL(x) #x
#endif
// ------------------------------------------------------------------------
// ABEL_IDENTITY
//
#ifndef ABEL_IDENTITY
#define ABEL_IDENTITY(x) x
#endif
// ------------------------------------------------------------------------
// ABEL_COMPILER_MANAGED_CPP
// Defined if this is being compiled with Managed C++ extensions
#ifdef ABEL_COMPILER_MSVC
#if ABEL_COMPILER_VERSION >= 1300
#ifdef _MANAGED
#define ABEL_COMPILER_MANAGED_CPP 1
#endif
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_COMPILER_INTMAX_SIZE
//
// This is related to the concept of intmax_t uintmax_t, but is available
// in preprocessor form as opposed to compile-time form. At compile-time
// you can use intmax_t and uintmax_t to use the actual types.
//
#if defined(__GNUC__) && defined(__x86_64__)
#define ABEL_COMPILER_INTMAX_SIZE 16 // intmax_t is __int128_t (GCC extension) and is 16 bytes.
#else
#define ABEL_COMPILER_INTMAX_SIZE 8 // intmax_t is int64_t and is 8 bytes.
#endif
// ------------------------------------------------------------------------
// ABEL_LPAREN / ABEL_RPAREN / ABEL_COMMA / ABEL_SEMI
//
// These are used for using special characters in macro-using expressions.
// Note that this macro intentionally uses (), as in some cases it can't
// work unless it does.
//
// Example usage:
// int x = SOME_MACRO(SomeTemplate<int ABEL_COMMA() int CBCOMMA() char>);
//
#ifndef ABEL_LPAREN
#define ABEL_LPAREN() (
#endif
#ifndef ABEL_RPAREN
#define ABEL_RPAREN() )
#endif
#ifndef ABEL_COMMA
#define ABEL_COMMA() ,
#endif
#ifndef ABEL_SEMI
#define ABEL_SEMI() ;
#endif
// ------------------------------------------------------------------------
// ABEL_OFFSETOF
// Implements a portable version of the non-standard offsetof macro.
//
// The offsetof macro is guaranteed to only work with POD types. However, we wish to use
// it for non-POD types but where we know that offsetof will still work for the cases
// in which we use it. GCC unilaterally gives a warning when using offsetof with a non-POD,
// even if the given usage happens to work. So we make a workaround version of offsetof
// here for GCC which has the same effect but tricks the compiler into not issuing the warning.
// The 65536 does the compiler fooling; the reinterpret_cast prevents the possibility of
// an overloaded operator& for the class getting in the way.
//
// Example usage:
// struct A{ int x; int y; };
// size_t n = ABEL_OFFSETOF(A, y);
//
#if defined(__GNUC__) // We can't use GCC 4's __builtin_offsetof because it mistakenly complains about non-PODs that are really PODs.
#define ABEL_OFFSETOF(struct_, member_) ((size_t)(((uintptr_t)&reinterpret_cast<const volatile char&>((((struct_*)65536)->member_))) - 65536))
#else
#define ABEL_OFFSETOF(struct_, member_) offsetof(struct_, member_)
#endif
// ------------------------------------------------------------------------
// ABEL_SIZEOF_MEMBER
// Implements a portable way to determine the size of a member.
//
// The ABEL_SIZEOF_MEMBER simply returns the size of a member within a class or struct; member
// access rules still apply. We offer two approaches depending on the compiler's support for non-static member
// initializers although most C++11 compilers support this.
//
// Example usage:
// struct A{ int x; int y; };
// size_t n = ABEL_SIZEOF_MEMBER(A, y);
//
#ifndef ABEL_COMPILER_NO_EXTENDED_SIZEOF
#define ABEL_SIZEOF_MEMBER(struct_, member_) (sizeof(struct_::member_))
#else
#define ABEL_SIZEOF_MEMBER(struct_, member_) (sizeof(((struct_*)0)->member_))
#endif
// ------------------------------------------------------------------------
// alignment expressions
//
// Here we define
// ABEL_ALIGN_OF(type) // Returns size_t.
// ABEL_ALIGN_MAX_STATIC // The max align value that the compiler will respect for ABEL_ALIGN for static data (global and static variables). Some compilers allow high values, some allow no more than 8. ABEL_ALIGN_MIN is assumed to be 1.
// ABEL_ALIGN_MAX_AUTOMATIC // The max align value for automatic variables (variables declared as local to a function).
// ABEL_ALIGN(n) // Used as a prefix. n is byte alignment, with being a power of two. Most of the time you can use this and avoid using ABEL_PREFIX_ALIGN/ABEL_POSTFIX_ALIGN.
// ABEL_ALIGNED(t, v, n) // Type, variable, alignment. Used to align an instance. You should need this only for unusual compilers.
// ABEL_PACKED // Specifies that the given structure be packed (and not have its members aligned).
//
// Also we define the following for rare cases that it's needed.
// ABEL_PREFIX_ALIGN(n) // n is byte alignment, with being a power of two. You should need this only for unusual compilers.
// ABEL_POSTFIX_ALIGN(n) // Valid values for n are 1, 2, 4, 8, etc. You should need this only for unusual compilers.
//
// Example usage:
// size_t x = ABEL_ALIGN_OF(int); Non-aligned equivalents. Meaning
// ABEL_PREFIX_ALIGN(8) int x = 5; int x = 5; Align x on 8 for compilers that require prefix attributes. Can just use ABEL_ALIGN instead.
// ABEL_ALIGN(8) int x; int x; Align x on 8 for compilers that allow prefix attributes.
// int x ABEL_POSTFIX_ALIGN(8); int x; Align x on 8 for compilers that require postfix attributes.
// int x ABEL_POSTFIX_ALIGN(8) = 5; int x = 5; Align x on 8 for compilers that require postfix attributes.
// int x ABEL_POSTFIX_ALIGN(8)(5); int x(5); Align x on 8 for compilers that require postfix attributes.
// struct ABEL_PREFIX_ALIGN(8) X { int x; } ABEL_POSTFIX_ALIGN(8); struct X { int x; }; Define X as a struct which is aligned on 8 when used.
// ABEL_ALIGNED(int, x, 8) = 5; int x = 5; Align x on 8.
// ABEL_ALIGNED(int, x, 16)(5); int x(5); Align x on 16.
// ABEL_ALIGNED(int, x[3], 16); int x[3]; Align x array on 16.
// ABEL_ALIGNED(int, x[3], 16) = { 1, 2, 3 }; int x[3] = { 1, 2, 3 }; Align x array on 16.
// int x[3] ABEL_PACKED; int x[3]; Pack the 3 ints of the x array. GCC doesn't seem to support packing of int arrays.
// struct ABEL_ALIGN(32) X { int x; int y; }; struct X { int x; }; Define A as a struct which is aligned on 32 when used.
// ABEL_ALIGN(32) struct X { int x; int y; } Z; struct X { int x; } Z; Define A as a struct, and align the instance Z on 32.
// struct X { int x ABEL_PACKED; int y ABEL_PACKED; }; struct X { int x; int y; }; Pack the x and y members of struct X.
// struct X { int x; int y; } ABEL_PACKED; struct X { int x; int y; }; Pack the members of struct X.
// typedef ABEL_ALIGNED(int, int16, 16); int16 n16; typedef int int16; int16 n16; Define int16 as an int which is aligned on 16.
// typedef ABEL_ALIGNED(X, X16, 16); X16 x16; typedef X X16; X16 x16; Define X16 as an X which is aligned on 16.
#if !defined(ABEL_ALIGN_MAX) // If the user hasn't globally set an alternative value...
#if defined(ABEL_PROCESSOR_ARM) // ARM compilers in general tend to limit automatic variables to 8 or less.
#define ABEL_ALIGN_MAX_STATIC 1048576
#define ABEL_ALIGN_MAX_AUTOMATIC 1 // Typically they support only built-in natural aligment types (both arm-eabi and apple-abi).
#elif defined(ABEL_PLATFORM_APPLE)
#define ABEL_ALIGN_MAX_STATIC 1048576
#define ABEL_ALIGN_MAX_AUTOMATIC 16
#else
#define ABEL_ALIGN_MAX_STATIC 1048576 // Arbitrarily high value. What is the actual max?
#define ABEL_ALIGN_MAX_AUTOMATIC 1048576
#endif
#endif
// EDG intends to be compatible with GCC but has a bug whereby it
// fails to support calling a constructor in an aligned declaration when
// using postfix alignment attributes. Prefix works for alignment, but does not align
// the size like postfix does. Prefix also fails on templates. So gcc style post fix
// is still used, but the user will need to use ABEL_POSTFIX_ALIGN before the constructor parameters.
#if defined(__GNUC__) && (__GNUC__ < 3)
#define ABEL_ALIGN_OF(type) ((size_t)__alignof__(type))
#define ABEL_ALIGN(n)
#define ABEL_PREFIX_ALIGN(n)
#define ABEL_POSTFIX_ALIGN(n) __attribute__((aligned(n)))
#define ABEL_ALIGNED(variable_type, variable, n) variable_type variable __attribute__((aligned(n)))
#define ABEL_PACKED __attribute__((packed))
// GCC 3.x+, IBM, and clang support prefix attributes.
#elif (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__xlC__) || defined(__clang__)
#define ABEL_ALIGN_OF(type) ((size_t)__alignof__(type))
#define ABEL_ALIGN(n) __attribute__((aligned(n)))
#define ABEL_PREFIX_ALIGN(n)
#define ABEL_POSTFIX_ALIGN(n) __attribute__((aligned(n)))
#define ABEL_ALIGNED(variable_type, variable, n) variable_type variable __attribute__((aligned(n)))
#define ABEL_PACKED __attribute__((packed))
// Metrowerks supports prefix attributes.
// Metrowerks does not support packed alignment attributes.
#elif defined(ABEL_COMPILER_INTEL) || defined(CS_UNDEFINED_STRING) || (defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1300))
#define ABEL_ALIGN_OF(type) ((size_t)__alignof(type))
#define ABEL_ALIGN(n) __declspec(align(n))
#define ABEL_PREFIX_ALIGN(n) ABEL_ALIGN(n)
#define ABEL_POSTFIX_ALIGN(n)
#define ABEL_ALIGNED(variable_type, variable, n) ABEL_ALIGN(n) variable_type variable
#define ABEL_PACKED // See ABEL_PRAGMA_PACK_VC for an alternative.
// Arm brand compiler
#elif defined(ABEL_COMPILER_ARM)
#define ABEL_ALIGN_OF(type) ((size_t)__ALIGNOF__(type))
#define ABEL_ALIGN(n) __align(n)
#define ABEL_PREFIX_ALIGN(n) __align(n)
#define ABEL_POSTFIX_ALIGN(n)
#define ABEL_ALIGNED(variable_type, variable, n) __align(n) variable_type variable
#define ABEL_PACKED __packed
#else // Unusual compilers
// There is nothing we can do about some of these. This is not as bad a problem as it seems.
// If the given platform/compiler doesn't support alignment specifications, then it's somewhat
// likely that alignment doesn't matter for that platform. Otherwise they would have defined
// functionality to manipulate alignment.
#define ABEL_ALIGN(n)
#define ABEL_PREFIX_ALIGN(n)
#define ABEL_POSTFIX_ALIGN(n)
#define ABEL_ALIGNED(variable_type, variable, n) variable_type variable
#define ABEL_PACKED
#ifdef __cplusplus
template <typename T> struct CBAlignOf1 { enum { s = sizeof (T), value = s ^ (s & (s - 1)) }; };
template <typename T> struct CBlignOf2;
template <int size_diff> struct helper { template <typename T> struct Val { enum { value = size_diff }; }; };
template <> struct helper<0> { template <typename T> struct Val { enum { value = CBlignOf2<T>::value }; }; };
template <typename T> struct CBAlignOf2 { struct Big { T x; char c; };
enum { diff = sizeof (Big) - sizeof (T), value = helper<diff>::template Val<Big>::value }; };
template <typename T> struct CBAlignof3 { enum { x = CBAlignOf2<T>::value, y = CBlignOf1<T>::value, value = x < y ? x : y }; };
template <typename T> struct CBAlignof3 { enum { x = CBAlignOf2<T>::value, y = CBlignOf1<T>::value, value = x < y ? x : y }; };
#define ABEL_ALIGN_OF(type) ((size_t)CBAlignof3<type>::value)
#else
// C implementation of ABEL_ALIGN_OF
// This implementation works for most cases, but doesn't directly work
// for types such as function pointer declarations. To work with those
// types you need to typedef the type and then use the typedef in ABEL_ALIGN_OF.
#define ABEL_ALIGN_OF(type) ((size_t)offsetof(struct { char c; type m; }, m))
#endif
#endif
// ABEL_PRAGMA_PACK_VC
//
// Wraps #pragma pack in a way that allows for cleaner code.
//
// Example usage:
// ABEL_PRAGMA_PACK_VC(push, 1)
// struct X{ char c; int i; };
// ABEL_PRAGMA_PACK_VC(pop)
//
#if !defined(ABEL_PRAGMA_PACK_VC)
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_PRAGMA_PACK_VC(...) __pragma(pack(__VA_ARGS__))
#elif !defined(ABEL_COMPILER_NO_VARIADIC_MACROS)
#define ABEL_PRAGMA_PACK_VC(...)
#else
// No support. However, all compilers of significance to us support variadic macros.
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_LIKELY / ABEL_UNLIKELY
//
// Defined as a macro which gives a hint to the compiler for branch
// prediction. GCC gives you the ability to manually give a hint to
// the compiler about the result of a comparison, though it's often
// best to compile shipping code with profiling feedback under both
// GCC (-fprofile-arcs) and VC++ (/LTCG:PGO, etc.). However, there
// are times when you feel very sure that a boolean expression will
// usually evaluate to either true or false and can help the compiler
// by using an explicity directive...
//
// Example usage:
// if(ABEL_LIKELY(a == 0)) // Tell the compiler that a will usually equal 0.
// { ... }
//
// Example usage:
// if(ABEL_UNLIKELY(a == 0)) // Tell the compiler that a will usually not equal 0.
// { ... }
//
#ifndef ABEL_LIKELY
#if (defined(__GNUC__) && (__GNUC__ >= 3)) || defined(__clang__)
#if defined(__cplusplus)
#define ABEL_LIKELY(x) __builtin_expect(!!(x), true)
#define ABEL_UNLIKELY(x) __builtin_expect(!!(x), false)
#else
#define ABEL_LIKELY(x) __builtin_expect(!!(x), 1)
#define ABEL_UNLIKELY(x) __builtin_expect(!!(x), 0)
#endif
#else
#define ABEL_LIKELY(x) (x)
#define ABEL_UNLIKELY(x) (x)
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_INIT_PRIORITY_AVAILABLE
//
// This value is either not defined, or defined to 1.
// Defines if the GCC attribute init_priority is supported by the compiler.
//
#if !defined(ABEL_INIT_PRIORITY_AVAILABLE)
#if defined(__GNUC__) && !defined(__EDG__) // EDG typically #defines __GNUC__ but doesn't implement init_priority.
#define ABEL_INIT_PRIORITY_AVAILABLE 1
#elif defined(__clang__)
#define ABEL_INIT_PRIORITY_AVAILABLE 1 // Clang implements init_priority
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_INIT_PRIORITY
//
// This is simply a wrapper for the GCC init_priority attribute that allows
// multiplatform code to be easier to read. This attribute doesn't apply
// to VC++ because VC++ uses file-level pragmas to control init ordering.
//
// Example usage:
// SomeClass gSomeClass ABEL_INIT_PRIORITY(2000);
//
#if !defined(ABEL_INIT_PRIORITY)
#if defined(ABEL_INIT_PRIORITY_AVAILABLE)
#define ABEL_INIT_PRIORITY(x) __attribute__ ((init_priority (x)))
#else
#define ABEL_INIT_PRIORITY(x)
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_MAY_ALIAS_AVAILABLE
//
// Defined as 0, 1, or 2.
// Defines if the GCC attribute may_alias is supported by the compiler.
// Consists of a value 0 (unsupported, shouldn't be used), 1 (some support),
// or 2 (full proper support).
//
#ifndef ABEL_MAY_ALIAS_AVAILABLE
#if defined(__GNUC__) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 303)
#if !defined(__EDG__) // define it as 1 while defining GCC's support as 2.
#define ABEL_MAY_ALIAS_AVAILABLE 2
#else
#define ABEL_MAY_ALIAS_AVAILABLE 0
#endif
#else
#define ABEL_MAY_ALIAS_AVAILABLE 0
#endif
#endif
// ABEL_MAY_ALIAS
//
// Defined as a macro that wraps the GCC may_alias attribute. This attribute
// has no significance for VC++ because VC++ doesn't support the concept of
// strict aliasing. Users should avoid writing code that breaks strict
// aliasing rules; ABEL_MAY_ALIAS is for cases with no alternative.
//
// Example usage:
// void* ABEL_MAY_ALIAS gPtr = NULL;
//
// Example usage:
// typedef void* ABEL_MAY_ALIAS pvoid_may_alias;
// pvoid_may_alias gPtr = NULL;
//
#if ABEL_MAY_ALIAS_AVAILABLE
#define ABEL_MAY_ALIAS __attribute__((__may_alias__))
#else
#define ABEL_MAY_ALIAS
#endif
// ------------------------------------------------------------------------
// ABEL_ASSUME
//
// This acts the same as the VC++ __assume directive and is implemented
// simply as a wrapper around it to allow portable usage of it and to take
// advantage of it if and when it appears in other compilers.
//
// Example usage:
// void Function(int a) {
// switch(a) {
// case 1:
// DoSomething(1);
// break;
// case 2:
// DoSomething(-1);
// break;
// default:
// ABEL_ASSUME(0); // This tells the optimizer that the default cannot be reached.
// }
// }
//
#ifndef ABEL_ASSUME
#if defined(_MSC_VER) && (_MSC_VER >= 1300) // If VC7.0 and later
#define ABEL_ASSUME(x) __assume(x)
#else
#define ABEL_ASSUME(x)
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_ANALYSIS_ASSUME
//
// This acts the same as the VC++ __analysis_assume directive and is implemented
// simply as a wrapper around it to allow portable usage of it and to take
// advantage of it if and when it appears in other compilers.
//
// Example usage:
// char Function(char* p) {
// ABEL_ANALYSIS_ASSUME(p != NULL);
// return *p;
// }
//
#ifndef ABEL_ANALYSIS_ASSUME
#if defined(_MSC_VER) && (_MSC_VER >= 1300) // If VC7.0 and later
#define ABEL_ANALYSIS_ASSUME(x) __analysis_assume(!!(x)) // !! because that allows for convertible-to-bool in addition to bool.
#else
#define ABEL_ANALYSIS_ASSUME(x)
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_VC_WARNING / ABEL_RESTORE_VC_WARNING
//
// Disable and re-enable warning(s) within code.
// This is simply a wrapper for VC++ #pragma warning(disable: nnnn) for the
// purpose of making code easier to read due to avoiding nested compiler ifdefs
// directly in code.
//
// Example usage:
// ABEL_DISABLE_VC_WARNING(4127 3244)
// <code>
// ABEL_RESTORE_VC_WARNING()
//
#ifndef ABEL_DISABLE_VC_WARNING
#if defined(_MSC_VER)
#define ABEL_DISABLE_VC_WARNING(w) \
__pragma(warning(push)) \
__pragma(warning(disable:w))
#else
#define ABEL_DISABLE_VC_WARNING(w)
#endif
#endif
#ifndef ABEL_RESTORE_VC_WARNING
#if defined(_MSC_VER)
#define ABEL_RESTORE_VC_WARNING() \
__pragma(warning(pop))
#else
#define ABEL_RESTORE_VC_WARNING()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_ENABLE_VC_WARNING_AS_ERROR / ABEL_DISABLE_VC_WARNING_AS_ERROR
//
// Disable and re-enable treating a warning as error within code.
// This is simply a wrapper for VC++ #pragma warning(error: nnnn) for the
// purpose of making code easier to read due to avoiding nested compiler ifdefs
// directly in code.
//
// Example usage:
// ABEL_ENABLE_VC_WARNING_AS_ERROR(4996)
// <code>
// ABEL_DISABLE_VC_WARNING_AS_ERROR()
//
#ifndef ABEL_ENABLE_VC_WARNING_AS_ERROR
#if defined(_MSC_VER)
#define ABEL_ENABLE_VC_WARNING_AS_ERROR(w) \
__pragma(warning(push)) \
__pragma(warning(error:w))
#else
#define ABEL_ENABLE_VC_WARNING_AS_ERROR(w)
#endif
#endif
#ifndef ABEL_DISABLE_VC_WARNING_AS_ERROR
#if defined(_MSC_VER)
#define ABEL_DISABLE_VC_WARNING_AS_ERROR() \
__pragma(warning(pop))
#else
#define ABEL_DISABLE_VC_WARNING_AS_ERROR()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_GCC_WARNING / ABEL_RESTORE_GCC_WARNING
//
// Example usage:
// // Only one warning can be ignored per statement, due to how GCC works.
// ABEL_DISABLE_GCC_WARNING(-Wuninitialized)
// ABEL_DISABLE_GCC_WARNING(-Wunused)
// <code>
// ABEL_RESTORE_GCC_WARNING()
// ABEL_RESTORE_GCC_WARNING()
//
#ifndef ABEL_DISABLE_GCC_WARNING
#if defined(ABEL_COMPILER_GNUC)
#define CBGCCWHELP0(x) #x
#define CBGCCWHELP1(x) CBGCCWHELP0(GCC diagnostic ignored x)
#define CBGCCWHELP2(x) CBGCCWHELP1(#x)
#endif
#if defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4006) // Can't test directly for __GNUC__ because some compilers lie.
#define ABEL_DISABLE_GCC_WARNING(w) \
_Pragma("GCC diagnostic push") \
_Pragma(CBGCCWHELP2(w))
#elif defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4004)
#define ABEL_DISABLE_GCC_WARNING(w) \
_Pragma(CBGCCWHELP2(w))
#else
#define ABEL_DISABLE_GCC_WARNING(w)
#endif
#endif
#ifndef ABEL_RESTORE_GCC_WARNING
#if defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4006)
#define ABEL_RESTORE_GCC_WARNING() \
_Pragma("GCC diagnostic pop")
#else
#define ABEL_RESTORE_GCC_WARNING()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_GCC_WARNINGS / ABEL_RESTORE_ALL_GCC_WARNINGS
//
// This isn't possible except via using _Pragma("GCC system_header"), though
// that has some limitations in how it works. Another means is to manually
// disable individual warnings within a GCC diagnostic push statement.
// GCC doesn't have as many warnings as VC++ and EDG and so this may be feasible.
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ABEL_ENABLE_GCC_WARNING_AS_ERROR / ABEL_DISABLE_GCC_WARNING_AS_ERROR
//
// Example usage:
// // Only one warning can be treated as an error per statement, due to how GCC works.
// ABEL_ENABLE_GCC_WARNING_AS_ERROR(-Wuninitialized)
// ABEL_ENABLE_GCC_WARNING_AS_ERROR(-Wunused)
// <code>
// ABEL_DISABLE_GCC_WARNING_AS_ERROR()
// ABEL_DISABLE_GCC_WARNING_AS_ERROR()
//
#ifndef ABEL_ENABLE_GCC_WARNING_AS_ERROR
#if defined(ABEL_COMPILER_GNUC)
#define CBGCCWERRORHELP0(x) #x
#define CBGCCWERRORHELP1(x) CBGCCWERRORHELP0(GCC diagnostic error x)
#define CBGCCWERRORHELP2(x) CBGCCWERRORHELP1(#x)
#endif
#if defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4006) // Can't test directly for __GNUC__ because some compilers lie.
#define ABEL_ENABLE_GCC_WARNING_AS_ERROR(w) \
_Pragma("GCC diagnostic push") \
_Pragma(CBGCCWERRORHELP2(w))
#elif defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4004)
#define ABEL_DISABLE_GCC_WARNING(w) \
_Pragma(CBGCCWERRORHELP2(w))
#else
#define ABEL_DISABLE_GCC_WARNING(w)
#endif
#endif
#ifndef ABEL_DISABLE_GCC_WARNING_AS_ERROR
#if defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION >= 4006)
#define ABEL_DISABLE_GCC_WARNING_AS_ERROR() \
_Pragma("GCC diagnostic pop")
#else
#define ABEL_DISABLE_GCC_WARNING_AS_ERROR()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_CLANG_WARNING / ABEL_RESTORE_CLANG_WARNING
//
// Example usage:
// // Only one warning can be ignored per statement, due to how clang works.
// ABEL_DISABLE_CLANG_WARNING(-Wuninitialized)
// ABEL_DISABLE_CLANG_WARNING(-Wunused)
// <code>
// ABEL_RESTORE_CLANG_WARNING()
// ABEL_RESTORE_CLANG_WARNING()
//
#ifndef ABEL_DISABLE_CLANG_WARNING
#if defined(ABEL_COMPILER_CLANG) || defined(ABEL_COMPILER_CLANG_CL)
#define CBCLANGWHELP0(x) #x
#define CBCLANGWHELP1(x) CBCLANGWHELP0(clang diagnostic ignored x)
#define CBCLANGWHELP2(x) CBCLANGWHELP1(#x)
#define ABEL_DISABLE_CLANG_WARNING(w) \
_Pragma("clang diagnostic push") \
_Pragma(CBCLANGWHELP2(-Wunknown-warning-option))\
_Pragma(CBCLANGWHELP2(w))
#else
#define ABEL_DISABLE_CLANG_WARNING(w)
#endif
#endif
#ifndef ABEL_RESTORE_CLANG_WARNING
#if defined(ABEL_COMPILER_CLANG) || defined(ABEL_COMPILER_CLANG_CL)
#define ABEL_RESTORE_CLANG_WARNING() \
_Pragma("clang diagnostic pop")
#else
#define ABEL_RESTORE_CLANG_WARNING()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_CLANG_WARNINGS / ABEL_RESTORE_ALL_CLANG_WARNINGS
//
// The situation for clang is the same as for GCC. See above.
// ------------------------------------------------------------------------
// ------------------------------------------------------------------------
// ABEL_ENABLE_CLANG_WARNING_AS_ERROR / ABEL_DISABLE_CLANG_WARNING_AS_ERROR
//
// Example usage:
// // Only one warning can be treated as an error per statement, due to how clang works.
// ABEL_ENABLE_CLANG_WARNING_AS_ERROR(-Wuninitialized)
// ABEL_ENABLE_CLANG_WARNING_AS_ERROR(-Wunused)
// <code>
// ABEL_DISABLE_CLANG_WARNING_AS_ERROR()
// ABEL_DISABLE_CLANG_WARNING_AS_ERROR()
//
#ifndef ABEL_ENABLE_CLANG_WARNING_AS_ERROR
#if defined(ABEL_COMPILER_CLANG) || defined(ABEL_COMPILER_CLANG_CL)
#define CBCLANGWERRORHELP0(x) #x
#define CBCLANGWERRORHELP1(x) CBCLANGWERRORHELP0(clang diagnostic error x)
#define CBCLANGWERRORHELP2(x) CBCLANGWERRORHELP1(#x)
#define ABEL_ENABLE_CLANG_WARNING_AS_ERROR(w) \
_Pragma("clang diagnostic push") \
_Pragma(CBCLANGWERRORHELP2(w))
#else
#define ABEL_DISABLE_CLANG_WARNING(w)
#endif
#endif
#ifndef ABEL_DISABLE_CLANG_WARNING_AS_ERROR
#if defined(ABEL_COMPILER_CLANG) || defined(ABEL_COMPILER_CLANG_CL)
#define ABEL_DISABLE_CLANG_WARNING_AS_ERROR() \
_Pragma("clang diagnostic pop")
#else
#define ABEL_DISABLE_CLANG_WARNING_AS_ERROR()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_SN_WARNING / ABEL_RESTORE_SN_WARNING
//
// Note that we define this macro specifically for the SN compiler instead of
// having a generic one for EDG-based compilers. The reason for this is that
// while SN is indeed based on EDG, SN has different warning value mappings
// and thus warning 1234 for SN is not the same as 1234 for all other EDG compilers.
//
// Example usage:
// // Currently we are limited to one warning per line.
// ABEL_DISABLE_SN_WARNING(1787)
// ABEL_DISABLE_SN_WARNING(552)
// <code>
// ABEL_RESTORE_SN_WARNING()
// ABEL_RESTORE_SN_WARNING()
//
#ifndef ABEL_DISABLE_SN_WARNING
#define ABEL_DISABLE_SN_WARNING(w)
#endif
#ifndef ABEL_RESTORE_SN_WARNING
#define ABEL_RESTORE_SN_WARNING()
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_SN_WARNINGS / ABEL_RESTORE_ALL_SN_WARNINGS
//
// Example usage:
// ABEL_DISABLE_ALL_SN_WARNINGS()
// <code>
// ABEL_RESTORE_ALL_SN_WARNINGS()
//
#ifndef ABEL_DISABLE_ALL_SN_WARNINGS
#define ABEL_DISABLE_ALL_SN_WARNINGS()
#endif
#ifndef ABEL_RESTORE_ALL_SN_WARNINGS
#define ABEL_RESTORE_ALL_SN_WARNINGS()
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_GHS_WARNING / ABEL_RESTORE_GHS_WARNING
//
// Disable warnings from the Green Hills compiler.
//
// Example usage:
// ABEL_DISABLE_GHS_WARNING(193)
// ABEL_DISABLE_GHS_WARNING(236, 5323)
// <code>
// ABEL_RESTORE_GHS_WARNING()
// ABEL_RESTORE_GHS_WARNING()
//
#ifndef ABEL_DISABLE_GHS_WARNING
#define ABEL_DISABLE_GHS_WARNING(w)
#endif
#ifndef ABEL_RESTORE_GHS_WARNING
#define ABEL_RESTORE_GHS_WARNING()
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_GHS_WARNINGS / ABEL_RESTORE_ALL_GHS_WARNINGS
//
// #ifndef ABEL_DISABLE_ALL_GHS_WARNINGS
// #if defined(ABEL_COMPILER_GREEN_HILLS)
// #define ABEL_DISABLE_ALL_GHS_WARNINGS(w) \_
// _Pragma("_________")
// #else
// #define ABEL_DISABLE_ALL_GHS_WARNINGS(w)
// #endif
// #endif
//
// #ifndef ABEL_RESTORE_ALL_GHS_WARNINGS
// #if defined(ABEL_COMPILER_GREEN_HILLS)
// #define ABEL_RESTORE_ALL_GHS_WARNINGS() \_
// _Pragma("_________")
// #else
// #define ABEL_RESTORE_ALL_GHS_WARNINGS()
// #endif
// #endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_EDG_WARNING / ABEL_RESTORE_EDG_WARNING
//
// Example usage:
// // Currently we are limited to one warning per line.
// ABEL_DISABLE_EDG_WARNING(193)
// ABEL_DISABLE_EDG_WARNING(236)
// <code>
// ABEL_RESTORE_EDG_WARNING()
// ABEL_RESTORE_EDG_WARNING()
//
#ifndef ABEL_DISABLE_EDG_WARNING
// EDG-based compilers are inconsistent in how the implement warning pragmas.
#if defined(ABEL_COMPILER_EDG) && !defined(ABEL_COMPILER_INTEL) && !defined(ABEL_COMPILER_RVCT)
#define CBEDGWHELP0(x) #x
#define CBEDGWHELP1(x) CBEDGWHELP0(diag_suppress x)
#define ABEL_DISABLE_EDG_WARNING(w) \
_Pragma("control %push diag") \
_Pragma(CBEDGWHELP1(w))
#else
#define ABEL_DISABLE_EDG_WARNING(w)
#endif
#endif
#ifndef ABEL_RESTORE_EDG_WARNING
#if defined(ABEL_COMPILER_EDG) && !defined(ABEL_COMPILER_INTEL) && !defined(ABEL_COMPILER_RVCT)
#define ABEL_RESTORE_EDG_WARNING() \
_Pragma("control %pop diag")
#else
#define ABEL_RESTORE_EDG_WARNING()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_EDG_WARNINGS / ABEL_RESTORE_ALL_EDG_WARNINGS
//
//#ifndef ABEL_DISABLE_ALL_EDG_WARNINGS
// #if defined(ABEL_COMPILER_EDG) && !defined(ABEL_COMPILER_SN)
// #define ABEL_DISABLE_ALL_EDG_WARNINGS(w) \_
// _Pragma("_________")
// #else
// #define ABEL_DISABLE_ALL_EDG_WARNINGS(w)
// #endif
//#endif
//
//#ifndef ABEL_RESTORE_ALL_EDG_WARNINGS
// #if defined(ABEL_COMPILER_EDG) && !defined(ABEL_COMPILER_SN)
// #define ABEL_RESTORE_ALL_EDG_WARNINGS() \_
// _Pragma("_________")
// #else
// #define ABEL_RESTORE_ALL_EDG_WARNINGS()
// #endif
//#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_CW_WARNING / ABEL_RESTORE_CW_WARNING
//
// Note that this macro can only control warnings via numbers and not by
// names. The reason for this is that the compiler's syntax for such
// warnings is not the same as for numbers.
//
// Example usage:
// // Currently we are limited to one warning per line and must also specify the warning in the restore macro.
// ABEL_DISABLE_CW_WARNING(10317)
// ABEL_DISABLE_CW_WARNING(10324)
// <code>
// ABEL_RESTORE_CW_WARNING(10317)
// ABEL_RESTORE_CW_WARNING(10324)
//
#ifndef ABEL_DISABLE_CW_WARNING
#define ABEL_DISABLE_CW_WARNING(w)
#endif
#ifndef ABEL_RESTORE_CW_WARNING
#define ABEL_RESTORE_CW_WARNING(w)
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_ALL_CW_WARNINGS / ABEL_RESTORE_ALL_CW_WARNINGS
//
#ifndef ABEL_DISABLE_ALL_CW_WARNINGS
#define ABEL_DISABLE_ALL_CW_WARNINGS()
#endif
#ifndef ABEL_RESTORE_ALL_CW_WARNINGS
#define ABEL_RESTORE_ALL_CW_WARNINGS()
#endif
// ------------------------------------------------------------------------
// ABEL_PURE
//
// This acts the same as the GCC __attribute__ ((pure)) directive and is
// implemented simply as a wrapper around it to allow portable usage of
// it and to take advantage of it if and when it appears in other compilers.
//
// A "pure" function is one that has no effects except its return value and
// its return value is a function of only the function's parameters or
// non-volatile global variables. Any parameter or global variable access
// must be read-only. Loop optimization and subexpression elimination can be
// applied to such functions. A common example is strlen(): Given identical
// inputs, the function's return value (its only effect) is invariant across
// multiple invocations and thus can be pulled out of a loop and called but once.
//
// Example usage:
// ABEL_PURE void Function();
//
#ifndef ABEL_PURE
#if defined(ABEL_COMPILER_GNUC)
#define ABEL_PURE __attribute__((pure))
#elif defined(ABEL_COMPILER_ARM) // Arm brand compiler for ARM CPU
#define ABEL_PURE __pure
#else
#define ABEL_PURE
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_WEAK
// ABEL_WEAK_SUPPORTED -- defined as 0 or 1.
//
// GCC
// The weak attribute causes the declaration to be emitted as a weak
// symbol rather than a global. This is primarily useful in defining
// library functions which can be overridden in user code, though it
// can also be used with non-function declarations.
//
// VC++
// At link time, if multiple definitions of a COMDAT are seen, the linker
// picks one and discards the rest. If the linker option /OPT:REF
// is selected, then COMDAT elimination will occur to remove all the
// unreferenced data items in the linker output.
//
// Example usage:
// ABEL_WEAK void Function();
//
#ifndef ABEL_WEAK
#if defined(_MSC_VER) && (_MSC_VER >= 1300) // If VC7.0 and later
#define ABEL_WEAK __declspec(selectany)
#define ABEL_WEAK_SUPPORTED 1
#elif defined(_MSC_VER) || (defined(__GNUC__) && defined(__CYGWIN__))
#define ABEL_WEAK
#define ABEL_WEAK_SUPPORTED 0
#elif defined(ABEL_COMPILER_ARM) // Arm brand compiler for ARM CPU
#define ABEL_WEAK __weak
#define ABEL_WEAK_SUPPORTED 1
#else // GCC and IBM compilers, others.
#define ABEL_WEAK __attribute__((weak))
#define ABEL_WEAK_SUPPORTED 1
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_UNUSED
//
// Makes compiler warnings about unused variables go away.
//
// Example usage:
// void Function(int x)
// {
// int y;
// ABEL_UNUSED(x);
// ABEL_UNUSED(y);
// }
//
#ifndef ABEL_UNUSED
// The EDG solution below is pretty weak and needs to be augmented or replaced.
// It can't handle the C language, is limited to places where template declarations
// can be used, and requires the type x to be usable as a functions reference argument.
#if defined(__cplusplus) && defined(__EDG__)
template <typename T>
inline void CBBaseUnused(T const volatile & x) { (void)x; }
#define ABEL_UNUSED(x) CBBaseUnused(x)
#else
#define ABEL_UNUSED(x) (void)x
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_EMPTY
//
// Allows for a null statement, usually for the purpose of avoiding compiler warnings.
//
// Example usage:
// #ifdef ABEL_DEBUG
// #define MyDebugPrintf(x, y) printf(x, y)
// #else
// #define MyDebugPrintf(x, y) ABEL_EMPTY
// #endif
//
#ifndef ABEL_EMPTY
#define ABEL_EMPTY (void)0
#endif
#ifndef ABEL_NULL
#if defined(ABEL_COMPILER_NO_NULLPTR) && ABEL_COMPILER_NO_NULLPTR == 1
#define ABEL_NULL NULL
#else
#define ABEL_NULL nullptr
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_CURRENT_FUNCTION
//
// Provides a consistent way to get the current function name as a macro
// like the __FILE__ and __LINE__ macros work. The C99 standard specifies
// that __func__ be provided by the compiler, but most compilers don't yet
// follow that convention. However, many compilers have an alternative.
//
// We also define ABEL_CURRENT_FUNCTION_SUPPORTED for when it is not possible
// to have ABEL_CURRENT_FUNCTION work as expected.
//
// Defined inside a function because otherwise the macro might not be
// defined and code below might not compile. This happens with some
// compilers.
//
#ifndef ABEL_CURRENT_FUNCTION
#if defined __GNUC__ || (defined __ICC && __ICC >= 600)
#define ABEL_CURRENT_FUNCTION __PRETTY_FUNCTION__
#elif defined(__FUNCSIG__)
#define ABEL_CURRENT_FUNCTION __FUNCSIG__
#elif (defined __INTEL_COMPILER && __INTEL_COMPILER >= 600) || (defined __IBMCPP__ && __IBMCPP__ >= 500) || (defined CS_UNDEFINED_STRING && CS_UNDEFINED_STRING >= 0x4200)
#define ABEL_CURRENT_FUNCTION __FUNCTION__
#elif defined __STDC_VERSION__ && __STDC_VERSION__ >= 199901
#define ABEL_CURRENT_FUNCTION __func__
#else
#define ABEL_CURRENT_FUNCTION "(unknown function)"
#endif
#endif
// ------------------------------------------------------------------------
// wchar_t
// Here we define:
// ABEL_WCHAR_T_NON_NATIVE
// ABEL_WCHAR_SIZE = <sizeof(wchar_t)>
//
#ifndef ABEL_WCHAR_T_NON_NATIVE
// Compilers that always implement wchar_t as native include:
// COMEAU, new SN, and other EDG-based compilers.
// GCC
// Borland
// SunPro
// IBM Visual Age
#if defined(ABEL_COMPILER_INTEL)
#if (ABEL_COMPILER_VERSION < 700)
#define ABEL_WCHAR_T_NON_NATIVE 1
#else
#if (!defined(_WCHAR_T_DEFINED) && !defined(_WCHAR_T))
#define ABEL_WCHAR_T_NON_NATIVE 1
#endif
#endif
#elif defined(ABEL_COMPILER_MSVC) || defined(ABEL_COMPILER_BORLAND) || (defined(ABEL_COMPILER_CLANG) && defined(ABEL_PLATFORM_WINDOWS))
#ifndef _NATIVE_WCHAR_T_DEFINED
#define ABEL_WCHAR_T_NON_NATIVE 1
#endif
#elif defined(__EDG_VERSION__) && (!defined(_WCHAR_T) && (__EDG_VERSION__ < 400)) // EDG prior to v4 uses _WCHAR_T to indicate if wchar_t is native. v4+ may define something else, but we're not currently aware of it.
#define ABEL_WCHAR_T_NON_NATIVE 1
#endif
#endif
#ifndef ABEL_WCHAR_SIZE // If the user hasn't specified that it is a given size...
#if defined(__WCHAR_MAX__) // GCC defines this for most platforms.
#if (__WCHAR_MAX__ == 2147483647) || (__WCHAR_MAX__ == 4294967295)
#define ABEL_WCHAR_SIZE 4
#elif (__WCHAR_MAX__ == 32767) || (__WCHAR_MAX__ == 65535)
#define ABEL_WCHAR_SIZE 2
#elif (__WCHAR_MAX__ == 127) || (__WCHAR_MAX__ == 255)
#define ABEL_WCHAR_SIZE 1
#else
#define ABEL_WCHAR_SIZE 4
#endif
#elif defined(WCHAR_MAX) // The SN and Arm compilers define this.
#if (WCHAR_MAX == 2147483647) || (WCHAR_MAX == 4294967295)
#define ABEL_WCHAR_SIZE 4
#elif (WCHAR_MAX == 32767) || (WCHAR_MAX == 65535)
#define ABEL_WCHAR_SIZE 2
#elif (WCHAR_MAX == 127) || (WCHAR_MAX == 255)
#define ABEL_WCHAR_SIZE 1
#else
#define ABEL_WCHAR_SIZE 4
#endif
#elif defined(__WCHAR_BIT) // Green Hills (and other versions of EDG?) uses this.
#if (__WCHAR_BIT == 16)
#define ABEL_WCHAR_SIZE 2
#elif (__WCHAR_BIT == 32)
#define ABEL_WCHAR_SIZE 4
#elif (__WCHAR_BIT == 8)
#define ABEL_WCHAR_SIZE 1
#else
#define ABEL_WCHAR_SIZE 4
#endif
#elif defined(_WCMAX) // The SN and Arm compilers define this.
#if (_WCMAX == 2147483647) || (_WCMAX == 4294967295)
#define ABEL_WCHAR_SIZE 4
#elif (_WCMAX == 32767) || (_WCMAX == 65535)
#define ABEL_WCHAR_SIZE 2
#elif (_WCMAX == 127) || (_WCMAX == 255)
#define ABEL_WCHAR_SIZE 1
#else
#define ABEL_WCHAR_SIZE 4
#endif
#elif defined(ABEL_PLATFORM_UNIX)
// It is standard on Unix to have wchar_t be int32_t or uint32_t.
// All versions of GNUC default to a 32 bit wchar_t, but CB has used
// the -fshort-wchar GCC command line option to force it to 16 bit.
// If you know that the compiler is set to use a wchar_t of other than
// the default, you need to manually define ABEL_WCHAR_SIZE for the build.
#define ABEL_WCHAR_SIZE 4
#else
// It is standard on Windows to have wchar_t be uint16_t. GCC
// defines wchar_t as int by default. Electronic Arts has
// standardized on wchar_t being an unsigned 16 bit value on all
// console platforms. Given that there is currently no known way to
// tell at preprocessor time what the size of wchar_t is, we declare
// it to be 2, as this is the Electronic Arts standard. If you have
// ABEL_WCHAR_SIZE != sizeof(wchar_t), then your code might not be
// broken, but it also won't work with wchar libraries and data from
// other parts of CB. Under GCC, you can force wchar_t to two bytes
// with the -fshort-wchar compiler argument.
#define ABEL_WCHAR_SIZE 2
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_RESTRICT
//
// The C99 standard defines a new keyword, restrict, which allows for the
// improvement of code generation regarding memory usage. Compilers can
// generate significantly faster code when you are able to use restrict.
//
// Example usage:
// void DoSomething(char* ABEL_RESTRICT p1, char* ABEL_RESTRICT p2);
//
#ifndef ABEL_RESTRICT
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1400) // If VC8 (VS2005) or later...
#define ABEL_RESTRICT __restrict
#elif defined(ABEL_COMPILER_CLANG)
#define ABEL_RESTRICT __restrict
#elif defined(ABEL_COMPILER_GNUC) // Includes GCC and other compilers emulating GCC.
#define ABEL_RESTRICT __restrict // GCC defines 'restrict' (as opposed to __restrict) in C99 mode only.
#elif defined(ABEL_COMPILER_ARM)
#define ABEL_RESTRICT __restrict
#elif defined(ABEL_COMPILER_IS_C99)
#define ABEL_RESTRICT restrict
#else
// If the compiler didn't support restricted pointers, defining ABEL_RESTRICT
// away would result in compiling and running fine but you just wouldn't
// the same level of optimization. On the other hand, all the major compilers
// support restricted pointers.
#define ABEL_RESTRICT
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_DEPRECATED // Used as a prefix.
// ABEL_PREFIX_DEPRECATED // You should need this only for unusual compilers.
// ABEL_POSTFIX_DEPRECATED // You should need this only for unusual compilers.
// ABEL_DEPRECATED_MESSAGE // Used as a prefix and provides a deprecation message.
//
// Example usage:
// ABEL_DEPRECATED void Function();
// ABEL_DEPRECATED_MESSAGE("Use 1.0v API instead") void Function();
//
// or for maximum portability:
// ABEL_PREFIX_DEPRECATED void Function() ABEL_POSTFIX_DEPRECATED;
//
#ifndef ABEL_DEPRECATED
#if defined(ABEL_COMPILER_CPP14_ENABLED)
#define ABEL_DEPRECATED [[deprecated]]
#elif defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION > 1300) // If VC7 (VS2003) or later...
#define ABEL_DEPRECATED __declspec(deprecated)
#elif defined(ABEL_COMPILER_MSVC)
#define ABEL_DEPRECATED
#else
#define ABEL_DEPRECATED __attribute__((deprecated))
#endif
#endif
#ifndef ABEL_PREFIX_DEPRECATED
#if defined(ABEL_COMPILER_CPP14_ENABLED)
#define ABEL_PREFIX_DEPRECATED [[deprecated]]
#define ABEL_POSTFIX_DEPRECATED
#elif defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION > 1300) // If VC7 (VS2003) or later...
#define ABEL_PREFIX_DEPRECATED __declspec(deprecated)
#define ABEL_POSTFIX_DEPRECATED
#elif defined(ABEL_COMPILER_MSVC)
#define ABEL_PREFIX_DEPRECATED
#define ABEL_POSTFIX_DEPRECATED
#else
#define ABEL_PREFIX_DEPRECATED
#define ABEL_POSTFIX_DEPRECATED __attribute__((deprecated))
#endif
#endif
#ifndef ABEL_DEPRECATED_MESSAGE
#if defined(ABEL_COMPILER_CPP14_ENABLED)
#define ABEL_DEPRECATED_MESSAGE(msg) [[deprecated(#msg)]]
#else
// Compiler does not support depreaction messages, explicitly drop the msg but still mark the function as deprecated
#define ABEL_DEPRECATED_MESSAGE(msg) ABEL_DEPRECATED
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_FORCE_INLINE // Used as a prefix.
// ABEL_PREFIX_FORCE_INLINE // You should need this only for unusual compilers.
// ABEL_POSTFIX_FORCE_INLINE // You should need this only for unusual compilers.
//
// Example usage:
// ABEL_FORCE_INLINE void Foo(); // Implementation elsewhere.
// ABEL_PREFIX_FORCE_INLINE void Foo() ABEL_POSTFIX_FORCE_INLINE; // Implementation elsewhere.
//
// Note that when the prefix version of this function is used, it replaces
// the regular C++ 'inline' statement. Thus you should not use both the
// C++ inline statement and this macro with the same function declaration.
//
// To force inline usage under GCC 3.1+, you use this:
// inline void Foo() __attribute__((always_inline));
// or
// inline __attribute__((always_inline)) void Foo();
//
// The CodeWarrior compiler doesn't have the concept of forcing inlining per function.
//
#ifndef ABEL_FORCE_INLINE
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_FORCE_INLINE __forceinline
#elif defined(ABEL_COMPILER_GNUC) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 301) || defined(ABEL_COMPILER_CLANG)
#if defined(__cplusplus)
#define ABEL_FORCE_INLINE inline __attribute__((always_inline))
#else
#define ABEL_FORCE_INLINE __inline__ __attribute__((always_inline))
#endif
#else
#if defined(__cplusplus)
#define ABEL_FORCE_INLINE inline
#else
#define ABEL_FORCE_INLINE __inline
#endif
#endif
#endif
#if defined(ABEL_COMPILER_GNUC) && (((__GNUC__ * 100) + __GNUC_MINOR__) >= 301) || defined(ABEL_COMPILER_CLANG)
#define ABEL_PREFIX_FORCE_INLINE inline
#define ABEL_POSTFIX_FORCE_INLINE __attribute__((always_inline))
#else
#define ABEL_PREFIX_FORCE_INLINE inline
#define ABEL_POSTFIX_FORCE_INLINE
#endif
// ------------------------------------------------------------------------
// ABEL_FORCE_INLINE_LAMBDA
//
// ABEL_FORCE_INLINE_LAMBDA is used to force inline a call to a lambda when possible.
// Force inlining a lambda can be useful to reduce overhead in situations where a lambda may
// may only be called once, or inlining allows the compiler to apply other optimizations that wouldn't
// otherwise be possible.
//
// The ability to force inline a lambda is currently only available on a subset of compilers.
//
// Example usage:
//
// auto lambdaFunction = []() ABEL_FORCE_INLINE_LAMBDA
// {
// };
//
#ifndef ABEL_FORCE_INLINE_LAMBDA
#if defined(ABEL_COMPILER_GNUC) || defined(ABEL_COMPILER_CLANG)
#define ABEL_FORCE_INLINE_LAMBDA __attribute__((always_inline))
#else
#define ABEL_FORCE_INLINE_LAMBDA
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NO_INLINE // Used as a prefix.
// ABEL_PREFIX_NO_INLINE // You should need this only for unusual compilers.
// ABEL_POSTFIX_NO_INLINE // You should need this only for unusual compilers.
//
// Example usage:
// ABEL_NO_INLINE void Foo(); // Implementation elsewhere.
// ABEL_PREFIX_NO_INLINE void Foo() ABEL_POSTFIX_NO_INLINE; // Implementation elsewhere.
//
// That this declaration is incompatbile with C++ 'inline' and any
// variant of ABEL_FORCE_INLINE.
//
// To disable inline usage under VC++ priof to VS2005, you need to use this:
// #pragma inline_depth(0) // Disable inlining.
// void Foo() { ... }
// #pragma inline_depth() // Restore to default.
//
// Since there is no easy way to disable inlining on a function-by-function
// basis in VC++ prior to VS2005, the best strategy is to write platform-specific
// #ifdefs in the code or to disable inlining for a given module and enable
// functions individually with ABEL_FORCE_INLINE.
//
#ifndef ABEL_NO_INLINE
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1400) // If VC8 (VS2005) or later...
#define ABEL_NO_INLINE __declspec(noinline)
#elif defined(ABEL_COMPILER_MSVC)
#define ABEL_NO_INLINE
#else
#define ABEL_NO_INLINE __attribute__((noinline))
#endif
#endif
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1400) // If VC8 (VS2005) or later...
#define ABEL_PREFIX_NO_INLINE __declspec(noinline)
#define ABEL_POSTFIX_NO_INLINE
#elif defined(ABEL_COMPILER_MSVC)
#define ABEL_PREFIX_NO_INLINE
#define ABEL_POSTFIX_NO_INLINE
#else
#define ABEL_PREFIX_NO_INLINE
#define ABEL_POSTFIX_NO_INLINE __attribute__((noinline))
#endif
// ------------------------------------------------------------------------
// ABEL_NO_VTABLE
//
// Example usage:
// class ABEL_NO_VTABLE X {
// virtual void InterfaceFunction();
// };
//
// ABEL_CLASS_NO_VTABLE(X) {
// virtual void InterfaceFunction();
// };
//
#ifdef ABEL_COMPILER_MSVC
#define ABEL_NO_VTABLE __declspec(novtable)
#define ABEL_CLASS_NO_VTABLE(x) class __declspec(novtable) x
#define ABEL_STRUCT_NO_VTABLE(x) struct __declspec(novtable) x
#else
#define ABEL_NO_VTABLE
#define ABEL_CLASS_NO_VTABLE(x) class x
#define ABEL_STRUCT_NO_VTABLE(x) struct x
#endif
// ------------------------------------------------------------------------
// ABEL_PASCAL
//
// Also known on PC platforms as stdcall.
// This convention causes the compiler to assume that the called function
// will pop off the stack space used to pass arguments, unless it takes a
// variable number of arguments.
//
// Example usage:
// this:
// void DoNothing(int x);
// void DoNothing(int x){}
// would be written as this:
// void ABEL_PASCAL_FUNC(DoNothing(int x));
// void ABEL_PASCAL_FUNC(DoNothing(int x)){}
//
#ifndef ABEL_PASCAL
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_PASCAL __stdcall
#elif defined(ABEL_COMPILER_GNUC) && defined(ABEL_PROCESSOR_X86)
#define ABEL_PASCAL __attribute__((stdcall))
#else
// Some compilers simply don't support pascal calling convention.
// As a result, there isn't an issue here, since the specification of
// pascal calling convention is for the purpose of disambiguating the
// calling convention that is applied.
#define ABEL_PASCAL
#endif
#endif
#ifndef ABEL_PASCAL_FUNC
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_PASCAL_FUNC(funcname_and_paramlist) __stdcall funcname_and_paramlist
#elif defined(ABEL_COMPILER_GNUC) && defined(ABEL_PROCESSOR_X86)
#define ABEL_PASCAL_FUNC(funcname_and_paramlist) __attribute__((stdcall)) funcname_and_paramlist
#else
#define ABEL_PASCAL_FUNC(funcname_and_paramlist) funcname_and_paramlist
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_SSE
// Visual C Processor Packs define _MSC_FULL_VER and are needed for SSE
// Intel C also has SSE support.
// ABEL_SSE is used to select FPU or SSE versions in hw_select.inl
//
// ABEL_SSE defines the level of SSE support:
// 0 indicates no SSE support
// 1 indicates SSE1 is supported
// 2 indicates SSE2 is supported
// 3 indicates SSE3 (or greater) is supported
//
// Note: SSE support beyond SSE3 can't be properly represented as a single
// version number. Instead users should use specific SSE defines (e.g.
// ABEL_SSE4_2) to detect what specific support is available. ABEL_SSE being
// equal to 3 really only indicates that SSE3 or greater is supported.
#ifndef ABEL_SSE
#if defined(ABEL_COMPILER_GNUC) || defined(ABEL_COMPILER_CLANG)
#if defined(__SSE3__)
#define ABEL_SSE 3
#elif defined(__SSE2__)
#define ABEL_SSE 2
#elif defined(__SSE__) && __SSE__
#define ABEL_SSE 1
#else
#define ABEL_SSE 0
#endif
#elif (defined(ABEL_SSE3) && ABEL_SSE3) || defined ABEL_PLATFORM_XBOXONE
#define ABEL_SSE 3
#elif defined(ABEL_SSE2) && ABEL_SSE2
#define ABEL_SSE 2
#elif defined(ABEL_PROCESSOR_X86) && defined(_MSC_FULL_VER) && !defined(__NOSSE__) && defined(_M_IX86_FP)
#define ABEL_SSE _M_IX86_FP
#elif defined(ABEL_PROCESSOR_X86) && defined(ABEL_COMPILER_INTEL) && !defined(__NOSSE__)
#define ABEL_SSE 1
#elif defined(ABEL_PROCESSOR_X86_64)
// All x64 processors support SSE2 or higher
#define ABEL_SSE 2
#else
#define ABEL_SSE 0
#endif
#endif
// ------------------------------------------------------------------------
// We define separate defines for SSE support beyond SSE1. These defines
// are particularly useful for detecting SSE4.x features since there isn't
// a single concept of SSE4.
//
// The following SSE defines are always defined. 0 indicates the
// feature/level of SSE is not supported, and 1 indicates support is
// available.
#ifndef ABEL_SSE2
#if ABEL_SSE >= 2
#define ABEL_SSE2 1
#else
#define ABEL_SSE2 0
#endif
#endif
#ifndef ABEL_SSE3
#if ABEL_SSE >= 3
#define ABEL_SSE3 1
#else
#define ABEL_SSE3 0
#endif
#endif
#ifndef ABEL_SSSE3
#if defined __SSSE3__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_SSSE3 1
#else
#define ABEL_SSSE3 0
#endif
#endif
#ifndef ABEL_SSE4_1
#if defined __SSE4_1__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_SSE4_1 1
#else
#define ABEL_SSE4_1 0
#endif
#endif
#ifndef ABEL_SSE4_2
#if defined __SSE4_2__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_SSE4_2 1
#else
#define ABEL_SSE4_2 0
#endif
#endif
#ifndef ABEL_SSE4A
#if defined __SSE4A__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_SSE4A 1
#else
#define ABEL_SSE4A 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_AVX
// ABEL_AVX may be used to determine if Advanced Vector Extensions are available for the target architecture
//
// ABEL_AVX defines the level of AVX support:
// 0 indicates no AVX support
// 1 indicates AVX1 is supported
// 2 indicates AVX2 is supported
#ifndef ABEL_AVX
#if defined __AVX2__
#define ABEL_AVX 2
#elif defined __AVX__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_AVX 1
#else
#define ABEL_AVX 0
#endif
#endif
#ifndef ABEL_AVX2
#if ABEL_AVX >= 2
#define ABEL_AVX2 1
#else
#define ABEL_AVX2 0
#endif
#endif
// ABEL_FP16C may be used to determine the existence of float <-> half conversion operations on an x86 CPU.
// (For example to determine if _mm_cvtph_ps or _mm_cvtps_ph could be used.)
#ifndef ABEL_FP16C
#if defined __F16C__ || defined ABEL_PLATFORM_XBOXONE
#define ABEL_FP16C 1
#else
#define ABEL_FP16C 0
#endif
#endif
// ABEL_FP128 may be used to determine if __float128 is a supported type for use. This type is enabled by a GCC extension (_GLIBCXX_USE_FLOAT128)
// but has support by some implementations of clang (__FLOAT128__)
// PS4 does not support __float128 as of SDK 5.500 https://ps4.siedev.net/resources/documents/SDK/5.500/CPU_Compiler_ABI-Overview/0003.html
#ifndef ABEL_FP128
#if (defined __FLOAT128__ || defined _GLIBCXX_USE_FLOAT128) && !defined(ABEL_PLATFORM_SONY)
#define ABEL_FP128 1
#else
#define ABEL_FP128 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_ABM
// ABEL_ABM may be used to determine if Advanced Bit Manipulation sets are available for the target architecture (POPCNT, LZCNT)
//
#ifndef ABEL_ABM
#if defined(__ABM__) || defined(ABEL_PLATFORM_XBOXONE) || defined(ABEL_PLATFORM_SONY)
#define ABEL_ABM 1
#else
#define ABEL_ABM 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NEON
// ABEL_NEON may be used to determine if NEON is supported.
#ifndef ABEL_NEON
#if defined(__ARM_NEON__) || defined(__ARM_NEON)
#define ABEL_NEON 1
#else
#define ABEL_NEON 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_BMI
// ABEL_BMI may be used to determine if Bit Manipulation Instruction sets are available for the target architecture
//
// ABEL_BMI defines the level of BMI support:
// 0 indicates no BMI support
// 1 indicates BMI1 is supported
// 2 indicates BMI2 is supported
#ifndef ABEL_BMI
#if defined(__BMI2__)
#define ABEL_BMI 2
#elif defined(__BMI__) || defined(ABEL_PLATFORM_XBOXONE)
#define ABEL_BMI 1
#else
#define ABEL_BMI 0
#endif
#endif
#ifndef ABEL_BMI2
#if ABEL_BMI >= 2
#define ABEL_BMI2 1
#else
#define ABEL_BMI2 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_FMA3
// ABEL_FMA3 may be used to determine if Fused Multiply Add operations are available for the target architecture
// __FMA__ is defined only by GCC, Clang, and ICC; MSVC only defines __AVX__ and __AVX2__
// FMA3 was introduced alongside AVX2 on Intel Haswell
// All AMD processors support FMA3 if AVX2 is also supported
//
// ABEL_FMA3 defines the level of FMA3 support:
// 0 indicates no FMA3 support
// 1 indicates FMA3 is supported
#ifndef ABEL_FMA3
#if defined(__FMA__) || ABEL_AVX2 >= 1
#define ABEL_FMA3 1
#else
#define ABEL_FMA3 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_TBM
// ABEL_TBM may be used to determine if Trailing Bit Manipulation instructions are available for the target architecture
#ifndef ABEL_TBM
#if defined(__TBM__)
#define ABEL_TBM 1
#else
#define ABEL_TBM 0
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_IMPORT
// import declaration specification
// specifies that the declared symbol is imported from another dynamic library.
#ifndef ABEL_IMPORT
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_IMPORT __declspec(dllimport)
#else
#define ABEL_IMPORT
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_EXPORT
// export declaration specification
// specifies that the declared symbol is exported from the current dynamic library.
// this is not the same as the C++ export keyword. The C++ export keyword has been
// removed from the language as of C++11.
#ifndef ABEL_EXPORT
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_EXPORT __declspec(dllexport)
#else
#define ABEL_EXPORT
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_OVERRIDE
//
// C++11 override
// See http://msdn.microsoft.com/en-us/library/jj678987.aspx for more information.
// You can use ABEL_FINAL_OVERRIDE to combine usage of ABEL_OVERRIDE and ABEL_INHERITANCE_FINAL in a single statement.
//
// Example usage:
// struct B { virtual void f(int); };
// struct D : B { void f(int) ABEL_OVERRIDE; };
//
#ifndef ABEL_OVERRIDE
#if defined(ABEL_COMPILER_NO_OVERRIDE)
#define ABEL_OVERRIDE
#else
#define ABEL_OVERRIDE override
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_INHERITANCE_FINAL
//
// Portably wraps the C++11 final specifier.
// See http://msdn.microsoft.com/en-us/library/jj678985.aspx for more information.
// You can use ABEL_FINAL_OVERRIDE to combine usage of ABEL_OVERRIDE and ABEL_INHERITANCE_FINAL in a single statement.
// This is not called ABEL_FINAL because that term is used within CB to denote debug/release/final builds.
//
// Example usage:
// struct B { virtual void f() ABEL_INHERITANCE_FINAL; };
//
#ifndef ABEL_INHERITANCE_FINAL
#if defined(ABEL_COMPILER_NO_INHERITANCE_FINAL)
#define ABEL_INHERITANCE_FINAL
#elif (defined(_MSC_VER) && (ABEL_COMPILER_VERSION < 1700)) // Pre-VS2012
#define ABEL_INHERITANCE_FINAL sealed
#else
#define ABEL_INHERITANCE_FINAL final
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_FINAL_OVERRIDE
//
// Portably wraps the C++11 override final specifiers combined.
//
// Example usage:
// struct A { virtual void f(); };
// struct B : public A { virtual void f() ABEL_FINAL_OVERRIDE; };
//
#ifndef ABEL_FINAL_OVERRIDE
#define ABEL_FINAL_OVERRIDE ABEL_OVERRIDE ABEL_INHERITANCE_FINAL
#endif
// ------------------------------------------------------------------------
// ABEL_SEALED
//
// This is deprecated, as the C++11 Standard has final (ABEL_INHERITANCE_FINAL) instead.
// See http://msdn.microsoft.com/en-us/library/0w2w91tf.aspx for more information.
// Example usage:
// struct B { virtual void f() ABEL_SEALED; };
//
#ifndef ABEL_SEALED
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1400) // VS2005 (VC8) and later
#define ABEL_SEALED sealed
#else
#define ABEL_SEALED
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_ABSTRACT
//
// This is a Microsoft language extension.
// See http://msdn.microsoft.com/en-us/library/b0z6b513.aspx for more information.
// Example usage:
// struct X ABEL_ABSTRACT { virtual void f(){} };
//
#ifndef ABEL_ABSTRACT
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1400) // VS2005 (VC8) and later
#define ABEL_ABSTRACT abstract
#else
#define ABEL_ABSTRACT
#endif
#endif
#ifndef ABEL_EXPLICIT
#if defined(ABEL_COMPILER_NO_EXPLICIT_CONVERSION_OPERATORS) && ABEL_COMPILER_NO_EXPLICIT_CONVERSION_OPERATORS == 1
#define ABEL_EXPLICIT
#else
#define ABEL_EXPLICIT explicit
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_CONSTEXPR
// ABEL_CONSTEXPR_OR_CONST
//
// Portable wrapper for C++11's 'constexpr' support.
//
// See http://www.cprogramming.com/c++11/c++11-compile-time-processing-with-constexpr.html for more information.
// Example usage:
// ABEL_CONSTEXPR int GetValue() { return 37; }
// ABEL_CONSTEXPR_OR_CONST double gValue = std::sin(kTwoPi);
//
#ifndef ABEL_CONSTEXPR_MEMBER
#if ABEL_COMPILER_CPP14_ENABLED
#define ABEL_CONSTEXPR_MEMBER constexpr
#else
#define ABEL_CONSTEXPR_MEMBER
#endif
#endif
#ifndef ABEL_CONSTEXPR_VARIABLE
#if ABEL_COMPILER_CPP14_ENABLED
#define ABEL_CONSTEXPR_VARIABLE constexpr
#else
#define ABEL_CONSTEXPR_VARIABLE const
#endif
#endif
#ifndef ABEL_CONSTEXPR_FUNCTION
#if ABEL_COMPILER_CPP14_ENABLED
#define ABEL_CONSTEXPR_FUNCTION constexpr
#else
#define ABEL_CONSTEXPR_FUNCTION inline
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_CONSTEXPR_IF
//
// Portable wrapper for C++17's 'constexpr if' support.
//
// https://en.cppreference.com/w/cpp/language/if
//
// Example usage:
//
// ABEL_CONSTEXPR_IF(eastl::is_copy_constructible_v<T>)
// { ... }
//
#if !defined(ABEL_CONSTEXPR_IF)
#if defined(ABEL_COMPILER_NO_CONSTEXPR_IF)
#define ABEL_CONSTEXPR_IF(predicate) if ((predicate))
#else
#define ABEL_CONSTEXPR_IF(predicate) if constexpr ((predicate))
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_EXTERN_TEMPLATE
//
// Portable wrapper for C++11's 'extern template' support.
//
// Example usage:
// ABEL_EXTERN_TEMPLATE(class basic_string<char>);
//
#if !defined(ABEL_EXTERN_TEMPLATE)
#if defined(ABEL_COMPILER_NO_EXTERN_TEMPLATE)
#define ABEL_EXTERN_TEMPLATE(declaration)
#else
#define ABEL_EXTERN_TEMPLATE(declaration) extern template declaration
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NOEXCEPT
// ABEL_NOEXCEPT_IF(predicate)
// ABEL_NOEXCEPT_EXPR(expression)
//
// Portable wrapper for C++11 noexcept
// http://en.cppreference.com/w/cpp/language/noexcept
// http://en.cppreference.com/w/cpp/language/noexcept_spec
//
// Example usage:
// ABEL_NOEXCEPT
// ABEL_NOEXCEPT_IF(predicate)
// ABEL_NOEXCEPT_EXPR(expression)
//
// This function never throws an exception.
// void DoNothing() ABEL_NOEXCEPT
// { }
//
// This function throws an exception of T::T() throws an exception.
// template <class T>
// void DoNothing() ABEL_NOEXCEPT_IF(ABEL_NOEXCEPT_EXPR(T()))
// { T t; }
//
#if !defined(ABEL_NOEXCEPT)
#if defined(ABEL_COMPILER_NO_NOEXCEPT)
#define ABEL_NOEXCEPT
#define ABEL_NOEXCEPT_IF(predicate)
#define ABEL_NOEXCEPT_EXPR(expression) false
#else
#define ABEL_NOEXCEPT noexcept
#define ABEL_NOEXCEPT_IF(predicate) noexcept((predicate))
#define ABEL_NOEXCEPT_EXPR(expression) noexcept((expression))
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NORETURN
//
// Wraps the C++11 noreturn attribute. See ABEL_COMPILER_NO_NORETURN
// http://en.cppreference.com/w/cpp/language/attributes
// http://msdn.microsoft.com/en-us/library/k6ktzx3s%28v=vs.80%29.aspx
// http://blog.aaronballman.com/2011/09/understanding-attributes/
//
// Example usage:
// ABEL_NORETURN void SomeFunction()
// { throw "error"; }
//
#if !defined(ABEL_NORETURN)
#if defined(ABEL_COMPILER_MSVC) && (ABEL_COMPILER_VERSION >= 1300) // VS2003 (VC7) and later
#define ABEL_NORETURN __declspec(noreturn)
#elif defined(ABEL_COMPILER_NO_NORETURN)
#define ABEL_NORETURN
#else
#define ABEL_NORETURN [[noreturn]]
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_CARRIES_DEPENDENCY
//
// Wraps the C++11 carries_dependency attribute
// http://en.cppreference.com/w/cpp/language/attributes
// http://blog.aaronballman.com/2011/09/understanding-attributes/
//
// Example usage:
// ABEL_CARRIES_DEPENDENCY int* SomeFunction()
// { return &mX; }
//
//
#if !defined(ABEL_CARRIES_DEPENDENCY)
#if defined(ABEL_COMPILER_NO_CARRIES_DEPENDENCY)
#define ABEL_CARRIES_DEPENDENCY
#else
#define ABEL_CARRIES_DEPENDENCY [[carries_dependency]]
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_FALLTHROUGH
//
// [[fallthrough] is a C++17 standard attribute that appears in switch
// statements to indicate that the fallthrough from the previous case in the
// switch statement is intentially and not a bug.
//
// http://en.cppreference.com/w/cpp/language/attributes
//
// Example usage:
// void f(int n)
// {
// switch(n)
// {
// case 1:
// DoCase1();
// // Compiler may generate a warning for fallthrough behaviour
//
// case 2:
// DoCase2();
//
// ABEL_FALLTHROUGH;
// case 3:
// DoCase3();
// }
// }
//
#if !defined(ABEL_FALLTHROUGH)
#if defined(ABEL_COMPILER_NO_FALLTHROUGH)
#define ABEL_FALLTHROUGH
#else
#define ABEL_FALLTHROUGH [[fallthrough]]
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NODISCARD
//
// [[nodiscard]] is a C++17 standard attribute that can be applied to a
// function declaration, enum, or class declaration. If a any of the list
// previously are returned from a function (without the user explicitly
// casting to void) the addition of the [[nodiscard]] attribute encourages
// the compiler to generate a warning about the user discarding the return
// value. This is a useful practice to encourage client code to check API
// error codes.
//
// http://en.cppreference.com/w/cpp/language/attributes
//
// Example usage:
//
// ABEL_NODISCARD int baz() { return 42; }
//
// void foo()
// {
// baz(); // warning: ignoring return value of function declared with 'nodiscard' attribute
// }
//
#if !defined(ABEL_NODISCARD)
#if defined(ABEL_COMPILER_NO_NODISCARD)
#define ABEL_NODISCARD
#else
#define ABEL_NODISCARD [[nodiscard]]
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_MAYBE_UNUSED
//
// [[maybe_unused]] is a C++17 standard attribute that suppresses warnings
// on unused entities that are declared as maybe_unused.
//
// http://en.cppreference.com/w/cpp/language/attributes
//
// Example usage:
// void foo(ABEL_MAYBE_UNUSED int i)
// {
// assert(i == 42); // warning suppressed when asserts disabled.
// }
//
#if !defined(ABEL_MAYBE_UNUSED)
#if defined(ABEL_COMPILER_NO_MAYBE_UNUSED)
#define ABEL_MAYBE_UNUSED
#else
#define ABEL_MAYBE_UNUSED [[maybe_unused]]
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NO_UBSAN
//
// The LLVM/Clang undefined behaviour sanitizer will not analyse a function tagged with the following attribute.
//
// https://clang.llvm.org/docs/UndefinedBehaviorSanitizer.html#disabling-instrumentation-with-attribute-no-sanitize-undefined
//
// Example usage:
// ABEL_NO_UBSAN int SomeFunction() { ... }
//
#ifndef ABEL_NO_UBSAN
#if defined(ABEL_COMPILER_CLANG)
#define ABEL_NO_UBSAN __attribute__((no_sanitize("undefined")))
#else
#define ABEL_NO_UBSAN
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_NO_ASAN
//
// The LLVM/Clang address sanitizer will not analyse a function tagged with the following attribute.
//
// https://clang.llvm.org/docs/AddressSanitizer.html#disabling-instrumentation-with-attribute-no-sanitize-address
//
// Example usage:
// ABEL_NO_ASAN int SomeFunction() { ... }
//
#ifndef ABEL_NO_ASAN
#if defined(ABEL_COMPILER_CLANG)
#define ABEL_NO_ASAN __attribute__((no_sanitize("address")))
#else
#define ABEL_NO_ASAN
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_ASAN_ENABLED
//
// Defined as 0 or 1. It's value depends on the compile environment.
// Specifies whether the code is being built with Clang's Address Sanitizer.
//
#if defined(__has_feature)
#if __has_feature(address_sanitizer)
#define ABEL_ASAN_ENABLED 1
#else
#define ABEL_ASAN_ENABLED 0
#endif
#else
#define ABEL_ASAN_ENABLED 0
#endif
// ------------------------------------------------------------------------
// ABEL_NON_COPYABLE
//
// This macro defines as a class as not being copy-constructable
// or assignable. This is useful for preventing class instances
// from being passed to functions by value, is useful for preventing
// compiler warnings by some compilers about the inability to
// auto-generate a copy constructor and assignment, and is useful
// for simply declaring in the interface that copy semantics are
// not supported by the class. Your class needs to have at least a
// default constructor when using this macro.
//
// Beware that this class works by declaring a private: section of
// the class in the case of compilers that don't support C++11 deleted
// functions.
//
// Note: With some pre-C++11 compilers (e.g. Green Hills), you may need
// to manually define an instances of the hidden functions, even
// though they are not used.
//
// Example usage:
// class Widget {
// Widget();
// . . .
// ABEL_NON_COPYABLE(Widget)
// };
//
#if !defined(ABEL_NON_COPYABLE)
#if defined(ABEL_COMPILER_NO_DELETED_FUNCTIONS)
#define ABEL_NON_COPYABLE(CBClass_) \
private: \
ABEL_DISABLE_VC_WARNING(4822); /* local class member function does not have a body */ \
CBClass_(const CBClass_&); \
void operator=(const CBClass_&); \
ABEL_RESTORE_VC_WARNING()
#else
#define ABEL_NON_COPYABLE(CBClass_) \
ABEL_DISABLE_VC_WARNING(4822); /* local class member function does not have a body */ \
CBClass_(const CBClass_&) = delete; \
void operator=(const CBClass_&) = delete; \
ABEL_RESTORE_VC_WARNING()
#endif
#endif
// ------------------------------------------------------------------------
// ABEL_FUNCTION_DELETE
//
// Semi-portable way of specifying a deleted function which allows for
// cleaner code in class declarations.
//
// Example usage:
//
// class Example
// {
// private: // For portability with pre-C++11 compilers, make the function private.
// void foo() ABEL_FUNCTION_DELETE;
// };
//
// Note: ABEL_FUNCTION_DELETE'd functions should be private to prevent the
// functions from being called even when the compiler does not support
// deleted functions. Some compilers (e.g. Green Hills) that don't support
// C++11 deleted functions can require that you define the function,
// which you can do in the associated source file for the class.
//
#if defined(ABEL_COMPILER_NO_DELETED_FUNCTIONS)
#define ABEL_FUNCTION_DELETE
#else
#define ABEL_FUNCTION_DELETE = delete
#endif
// ------------------------------------------------------------------------
// ABEL_DISABLE_DEFAULT_CTOR
//
// Disables the compiler generated default constructor. This macro is
// provided to improve portability and clarify intent of code.
//
// Example usage:
//
// class Example
// {
// private:
// ABEL_DISABLE_DEFAULT_CTOR(Example);
// };
//
#define ABEL_DISABLE_DEFAULT_CTOR(ClassName) ClassName() ABEL_FUNCTION_DELETE
// ------------------------------------------------------------------------
// ABEL_DISABLE_COPY_CTOR
//
// Disables the compiler generated copy constructor. This macro is
// provided to improve portability and clarify intent of code.
//
// Example usage:
//
// class Example
// {
// private:
// ABEL_DISABLE_COPY_CTOR(Example);
// };
//
#define ABEL_DISABLE_COPY_CTOR(ClassName) ClassName(const ClassName &) ABEL_FUNCTION_DELETE
// ------------------------------------------------------------------------
// ABEL_DISABLE_MOVE_CTOR
//
// Disables the compiler generated move constructor. This macro is
// provided to improve portability and clarify intent of code.
//
// Example usage:
//
// class Example
// {
// private:
// ABEL_DISABLE_MOVE_CTOR(Example);
// };
//
#define ABEL_DISABLE_MOVE_CTOR(ClassName) ClassName(ClassName&&) ABEL_FUNCTION_DELETE
// ------------------------------------------------------------------------
// ABEL_DISABLE_ASSIGNMENT_OPERATOR
//
// Disables the compiler generated assignment operator. This macro is
// provided to improve portability and clarify intent of code.
//
// Example usage:
//
// class Example
// {
// private:
// ABEL_DISABLE_ASSIGNMENT_OPERATOR(Example);
// };
//
#define ABEL_DISABLE_ASSIGNMENT_OPERATOR(ClassName) ClassName & operator=(const ClassName &) ABEL_FUNCTION_DELETE
// ------------------------------------------------------------------------
// ABEL_DISABLE_MOVE_OPERATOR
//
// Disables the compiler generated move operator. This macro is
// provided to improve portability and clarify intent of code.
//
// Example usage:
//
// class Example
// {
// private:
// ABEL_DISABLE_MOVE_OPERATOR(Example);
// };
//
#define ABEL_DISABLE_MOVE_OPERATOR(ClassName) ClassName & operator=(ClassName&&) ABEL_FUNCTION_DELETE
#define ABEL_DISABLE_IMPLICIT_CTOR(ClassName) \
ABEL_NON_COPYABLE(ClassName); \
ABEL_DISABLE_DEFAULT_CTOR(ClassName)
// ------------------------------------------------------------------------
// CBNonCopyable
//
// Declares a class as not supporting copy construction or assignment.
// May be more reliable with some situations that ABEL_NON_COPYABLE alone,
// though it may result in more code generation.
//
// Note that VC++ will generate warning C4625 and C4626 if you use CBNonCopyable
// and you are compiling with /W4 and /Wall. There is no resolution but
// to redelare ABEL_NON_COPYABLE in your subclass or disable the warnings with
// code like this:
// ABEL_DISABLE_VC_WARNING(4625 4626)
// ...
// ABEL_RESTORE_VC_WARNING()
//
// Example usage:
// struct Widget : CBNonCopyable {
// . . .
// };
//
#ifdef __cplusplus
struct CBNonCopyable {
#if defined(ABEL_COMPILER_NO_DEFAULTED_FUNCTIONS) || defined(__EDG__) // EDG doesn't appear to behave properly for the case of defaulted constructors; it generates a mistaken warning about missing default constructors.
CBNonCopyable(){} // Putting {} here has the downside that it allows a class to create itself,
~CBNonCopyable(){} // but avoids linker errors that can occur with some compilers (e.g. Green Hills).
#else
CBNonCopyable () = default;
~CBNonCopyable () = default;
#endif
ABEL_NON_COPYABLE(CBNonCopyable)
};
#endif
// ------------------------------------------------------------------------
// ABEL_OPTIMIZE_OFF / ABEL_OPTIMIZE_ON
//
// Implements portable inline optimization enabling/disabling.
// Usage of these macros must be in order OFF then ON. This is
// because the OFF macro pushes a set of settings and the ON
// macro pops them. The nesting of OFF/ON sets (e.g. OFF, OFF, ON, ON)
// is not guaranteed to work on all platforms.
//
// This is often used to allow debugging of some code that's
// otherwise compiled with undebuggable optimizations. It's also
// useful for working around compiler code generation problems
// that occur in optimized builds.
//
// Some compilers (e.g. VC++) don't allow doing this within a function and
// so the usage must be outside a function, as with the example below.
// GCC on x86 appears to have some problem with argument passing when
// using ABEL_OPTIMIZE_OFF in optimized builds.
//
// Example usage:
// // Disable optimizations for SomeFunction.
// ABEL_OPTIMIZE_OFF()
// void SomeFunction()
// {
// ...
// }
// ABEL_OPTIMIZE_ON()
//
#if !defined(ABEL_OPTIMIZE_OFF)
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_OPTIMIZE_OFF() __pragma(optimize("", off))
#elif defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION > 4004) && (defined(__i386__) || defined(__x86_64__)) // GCC 4.4+ - Seems to work only on x86/Linux so far. However, GCC 4.4 itself appears broken and screws up parameter passing conventions.
#define ABEL_OPTIMIZE_OFF() \
_Pragma("GCC push_options") \
_Pragma("GCC optimize 0")
#elif defined(ABEL_COMPILER_CLANG) && (!defined(ABEL_PLATFORM_ANDROID) || (ABEL_COMPILER_VERSION >= 380))
#define ABEL_OPTIMIZE_OFF() \
ABEL_DISABLE_CLANG_WARNING(-Wunknown-pragmas) \
_Pragma("clang optimize off") \
ABEL_RESTORE_CLANG_WARNING()
#else
#define ABEL_OPTIMIZE_OFF()
#endif
#endif
#if !defined(ABEL_OPTIMIZE_ON)
#if defined(ABEL_COMPILER_MSVC)
#define ABEL_OPTIMIZE_ON() __pragma(optimize("", on))
#elif defined(ABEL_COMPILER_GNUC) && (ABEL_COMPILER_VERSION > 4004) && (defined(__i386__) || defined(__x86_64__)) // GCC 4.4+ - Seems to work only on x86/Linux so far. However, GCC 4.4 itself appears broken and screws up parameter passing conventions.
#define ABEL_OPTIMIZE_ON() _Pragma("GCC pop_options")
#elif defined(ABEL_COMPILER_CLANG) && (!defined(ABEL_PLATFORM_ANDROID) || (ABEL_COMPILER_VERSION >= 380))
#define ABEL_OPTIMIZE_ON() \
ABEL_DISABLE_CLANG_WARNING(-Wunknown-pragmas) \
_Pragma("clang optimize on") \
ABEL_RESTORE_CLANG_WARNING()
#else
#define ABEL_OPTIMIZE_ON()
#endif
#endif
// ABEL_BLOCK_TAIL_CALL_OPTIMIZATION
//
// Instructs the compiler to avoid optimizing tail-call recursion. Use of this
// macro is useful when you wish to preserve the existing function order within
// a stack trace for logging, debugging, or profiling purposes.
//
// Example:
//
// int f() {
// int result = g();
// ABEL_BLOCK_TAIL_CALL_OPTIMIZATION();
// return result;
// }
#if defined(__pnacl__)
#define ABEL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
#elif defined(__clang__)
// Clang will not tail call given inline volatile assembly.
#define ABEL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
#elif defined(__GNUC__)
// GCC will not tail call given inline volatile assembly.
#define ABEL_BLOCK_TAIL_CALL_OPTIMIZATION() __asm__ __volatile__("")
#elif defined(_MSC_VER)
#include <intrin.h>
// The __nop() intrinsic blocks the optimisation.
#define ABEL_BLOCK_TAIL_CALL_OPTIMIZATION() __nop()
#else
#define ABEL_BLOCK_TAIL_CALL_OPTIMIZATION() if (volatile int x = 0) { (void)x; }
#endif
#ifndef ABEL_WARN_UNUSED_RESULT
#if defined(ABEL_COMPILER_GNUC) && ABEL_COMPILER_VERSION >= 4007 && ABEL_COMPILER_CPP11_ENABLED
#define ABEL_WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define ABEL_WARN_UNUSED_RESULT
#endif
#endif //WARN_UNUSED_RESULT
#ifndef ABEL_PRINTF_FORMAT
#if defined(ABEL_COMPILER_GNUC)
#define ABEL_PRINTF_FORMAT(format_param, dots_param) __attribute__((format(printf, format_param, dots_param)))
#else
#define ABEL_PRINTF_FORMAT(format_param, dots_param)
#endif
#endif //ABEL_PRINTF_FORMAT
#define ABEL_WPRINTF_FORMAT(format_param, dots_param)
#ifndef ABEL_CDECL
#if defined(ABEL_PLATFORM_WINDOWS)
#define ABEL_CDECL __cdecl
#else
#define ABEL_CDECL
#endif
#endif //ABEL_CDECL
#if defined(COMPILER_GCC)
#define ABEL_ALLOW_UNUSED __attribute__((unused))
#else
#define ABEL_ALLOW_UNUSED
#endif
#ifndef ABEL_ALLOW_UNUSED
#if defined(ABEL_COMPILER_GNUC)
#define ABEL_ALLOW_UNUSED __attribute__((unused))
#else
#define ABEL_ALLOW_UNUSED
#endif
#endif //ABEL_ALLOW_UNUSED
#ifndef ABEL_CACHE_LINE_ALIGNED
#define ABEL_CACHE_LINE_ALIGNED ABEL_ALIGN(ABEL_CACHE_LINE_SIZE)
#endif //ABEL_CACHE_LINE_ALIGNED
// ABEL_PRINTF
// ABEL_SCANF
//
// Tells the compiler to perform `printf` format string checking if the
// compiler supports it; see the 'format' attribute in
// <https://gcc.gnu.org/onlinedocs/gcc-4.7.0/gcc/Function-Attributes.html>.
//
// Note: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
#if ABEL_COMPILER_HAS_ATTRIBUTE(format) || (defined(__GNUC__) && !defined(__clang__))
#define ABEL_PRINTF(string_index, first_to_check) \
__attribute__((__format__(__printf__, string_index, first_to_check)))
#define ABEL_SCANF(string_index, first_to_check) \
__attribute__((__format__(__scanf__, string_index, first_to_check)))
#else
#define ABEL_PRINTF(string_index, first_to_check)
#define ABEL_SCANF(string_index, first_to_check)
#endif
// ABEL_ATTRIBUTE_NONNULL
//
// Tells the compiler either (a) that a particular function parameter
// should be a non-null pointer, or (b) that all pointer arguments should
// be non-null.
//
// Note: As the GCC manual states, "[s]ince non-static C++ methods
// have an implicit 'this' argument, the arguments of such methods
// should be counted from two, not one."
//
// Args are indexed starting at 1.
//
// For non-static class member functions, the implicit `this` argument
// is arg 1, and the first explicit argument is arg 2. For static class member
// functions, there is no implicit `this`, and the first explicit argument is
// arg 1.
//
// Example:
//
// /* arg_a cannot be null, but arg_b can */
// void Function(void* arg_a, void* arg_b) ABEL_ATTRIBUTE_NONNULL(1);
//
// class C {
// /* arg_a cannot be null, but arg_b can */
// void Method(void* arg_a, void* arg_b) ABEL_ATTRIBUTE_NONNULL(2);
//
// /* arg_a cannot be null, but arg_b can */
// static void StaticMethod(void* arg_a, void* arg_b)
// ABEL_ATTRIBUTE_NONNULL(1);
// };
//
// If no arguments are provided, then all pointer arguments should be non-null.
//
// /* No pointer arguments may be null. */
// void Function(void* arg_a, void* arg_b, int arg_c) ABEL_ATTRIBUTE_NONNULL();
//
// NOTE: The GCC nonnull attribute actually accepts a list of arguments, but
// ABEL_ATTRIBUTE_NONNULL does not.
#if ABEL_COMPILER_HAS_ATTRIBUTE(nonnull) || (defined(__GNUC__) && !defined(__clang__))
#define ABEL_NONNULL(arg_index) __attribute__((nonnull(arg_index)))
#else
#define ABEL_NONNULL(...)
#endif
// ABEL_NO_SANITIZE_ADDRESS
//
// Tells the AddressSanitizer (or other memory testing tools) to ignore a given
// function. Useful for cases when a function reads random locations on stack,
// calls _exit from a cloned subprocess, deliberately accesses buffer
// out of bounds or does other scary things with memory.
// NOTE: GCC supports AddressSanitizer(asan) since 4.8.
// https://gcc.gnu.org/gcc-4.8/changes.html
#if defined(__GNUC__)
#define ABEL_NO_SANITIZE_ADDRESS __attribute__((no_sanitize_address))
#else
#define ABEL_NO_SANITIZE_ADDRESS
#endif
// ABEL_NO_SANITIZE_MEMORY
//
// Tells the MemorySanitizer to relax the handling of a given function. All
// "Use of uninitialized value" warnings from such functions will be suppressed,
// and all values loaded from memory will be considered fully initialized.
// This attribute is similar to the ADDRESS_SANITIZER attribute above, but deals
// with initialized-ness rather than addressability issues.
// NOTE: MemorySanitizer(msan) is supported by Clang but not GCC.
#if defined(__clang__)
#define ABEL_NO_SANITIZE_MEMORY __attribute__((no_sanitize_memory))
#else
#define ABEL_NO_SANITIZE_MEMORY
#endif
// ABEL_NO_SANITIZE_THREAD
//
// Tells the ThreadSanitizer to not instrument a given function.
// NOTE: GCC supports ThreadSanitizer(tsan) since 4.8.
// https://gcc.gnu.org/gcc-4.8/changes.html
#if defined(__GNUC__)
#define ABEL_NO_SANITIZE_THREAD __attribute__((no_sanitize_thread))
#else
#define ABEL_NO_SANITIZE_THREAD
#endif
// ABEL_NO_SANITIZE_UNDEFINED
//
// Tells the UndefinedSanitizer to ignore a given function. Useful for cases
// where certain behavior (eg. division by zero) is being used intentionally.
// NOTE: GCC supports UndefinedBehaviorSanitizer(ubsan) since 4.9.
// https://gcc.gnu.org/gcc-4.9/changes.html
#if defined(__GNUC__) && \
(defined(UNDEFINED_BEHAVIOR_SANITIZER) || defined(ADDRESS_SANITIZER))
#define ABEL_NO_SANITIZE_UNDEFINED \
__attribute__((no_sanitize("undefined")))
#else
#define ABEL_NO_SANITIZE_UNDEFINED
#endif
// ABEL_NO_SANITIZE_CFI
//
// Tells the ControlFlowIntegrity sanitizer to not instrument a given function.
// See https://clang.llvm.org/docs/ControlFlowIntegrity.html for details.
#if defined(__GNUC__) && defined(CONTROL_FLOW_INTEGRITY)
#define ABEL_NO_SANITIZE_CFI __attribute__((no_sanitize("cfi")))
#else
#define ABEL_NO_SANITIZE_CFI
#endif
// ABEL_NO_SANITIZE_SAFESTACK
//
// Tells the SafeStack to not instrument a given function.
// See https://clang.llvm.org/docs/SafeStack.html for details.
#if defined(__GNUC__) && defined(SAFESTACK_SANITIZER)
#define ABEL_NO_SANITIZE_SAFESTACK \
__attribute__((no_sanitize("safe-stack")))
#else
#define ABEL_NO_SANITIZE_SAFESTACK
#endif
// ABEL_RETURNS_NONNULL
//
// Tells the compiler that a particular function never returns a null pointer.
#if ABEL_COMPILER_HAS_ATTRIBUTE(returns_nonnull) || \
(defined(__GNUC__) && \
(__GNUC__ > 5 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9)) && \
!defined(__clang__))
#define ABEL_RETURNS_NONNULL __attribute__((returns_nonnull))
#else
#define ABEL_RETURNS_NONNULL
#endif
// -----------------------------------------------------------------------------
// Variable Attributes
// -----------------------------------------------------------------------------
// ABEL_ATTRIBUTE_UNUSED
//
// Prevents the compiler from complaining about variables that appear unused.
#if ABEL_COMPILER_HAS_ATTRIBUTE(unused) || (defined(__GNUC__) && !defined(__clang__))
#undef ABEL_ATTRIBUTE_UNUSED
#define ABEL_ATTRIBUTE_UNUSED __attribute__((__unused__))
#else
#define ABEL_ATTRIBUTE_UNUSED
#endif
// ABEL_CONST_INIT
//
// A variable declaration annotated with the `ABEL_CONST_INIT` attribute will
// not compile (on supported platforms) unless the variable has a constant
// initializer. This is useful for variables with static and thread storage
// duration, because it guarantees that they will not suffer from the so-called
// "static init order fiasco". Prefer to put this attribute on the most visible
// declaration of the variable, if there's more than one, because code that
// accesses the variable can then use the attribute for optimization.
//
// Example:
//
// class MyClass {
// public:
// ABEL_CONST_INIT static MyType my_var;
// };
//
// MyType MyClass::my_var = MakeMyType(...);
//
// Note that this attribute is redundant if the variable is declared constexpr.
#if ABEL_COMPILER_HAS_CPP_ATTRIBUTE(clang::require_constant_initialization)
#define ABEL_CONST_INIT [[clang::require_constant_initialization]]
#else
#define ABEL_CONST_INIT
#endif // ABEL_COMPILER_HAS_CPP_ATTRIBUTE(clang::require_constant_initialization)
// ABEL_FUNC_ALIGN
//
// Tells the compiler to align the function start at least to certain
// alignment boundary
#if ABEL_COMPILER_HAS_ATTRIBUTE(aligned) || (defined(__GNUC__) && !defined(__clang__))
#define ABEL_FUNC_ALIGN(bytes) __attribute__((aligned(bytes)))
#else
#define ABEL_FUNC_ALIGN(bytes)
#endif
// ABEL_FALLTHROUGH_INTENDED
//
// Annotates implicit fall-through between switch labels, allowing a case to
// indicate intentional fallthrough and turn off warnings about any lack of a
// `break` statement. The ABEL_FALLTHROUGH_INTENDED macro should be followed by
// a semicolon and can be used in most places where `break` can, provided that
// no statements exist between it and the next switch label.
//
// Example:
//
// switch (x) {
// case 40:
// case 41:
// if (truth_is_out_there) {
// ++x;
// ABEL_FALLTHROUGH_INTENDED; // Use instead of/along with annotations
// // in comments
// } else {
// return x;
// }
// case 42:
// ...
//
// Notes: when compiled with clang in C++11 mode, the ABEL_FALLTHROUGH_INTENDED
// macro is expanded to the [[clang::fallthrough]] attribute, which is analysed
// when performing switch labels fall-through diagnostic
// (`-Wimplicit-fallthrough`). See clang documentation on language extensions
// for details:
// http://clang.llvm.org/docs/AttributeReference.html#fallthrough-clang-fallthrough
//
// When used with unsupported compilers, the ABEL_FALLTHROUGH_INTENDED macro
// has no effect on diagnostics. In any case this macro has no effect on runtime
// behavior and performance of code.
#ifdef ABEL_FALLTHROUGH_INTENDED
#error "ABEL_FALLTHROUGH_INTENDED should not be defined."
#endif
// TODO(zhangxy): Use c++17 standard [[fallthrough]] macro, when supported.
#if defined(__clang__) && defined(__has_warning)
#if __has_feature(cxx_attributes) && __has_warning("-Wimplicit-fallthrough")
#define ABEL_FALLTHROUGH_INTENDED [[clang::fallthrough]]
#endif
#elif defined(__GNUC__) && __GNUC__ >= 7
#define ABEL_FALLTHROUGH_INTENDED [[gnu::fallthrough]]
#endif
#ifndef ABEL_FALLTHROUGH_INTENDED
#define ABEL_FALLTHROUGH_INTENDED \
do { \
} while (0)
#endif
// ABEL_BAD_CALL_IF()
//
// Used on a function overload to trap bad calls: any call that matches the
// overload will cause a compile-time error. This macro uses a clang-specific
// "enable_if" attribute, as described at
// http://clang.llvm.org/docs/AttributeReference.html#enable-if
//
// Overloads which use this macro should be bracketed by
// `#ifdef ABEL_BAD_CALL_IF`.
//
// Example:
//
// int isdigit(int c);
// #ifdef ABEL_BAD_CALL_IF
// int isdigit(int c)
// ABEL_BAD_CALL_IF(c <= -1 || c > 255,
// "'c' must have the value of an unsigned char or EOF");
// #endif // ABEL_BAD_CALL_IF
#if ABEL_COMPILER_HAS_ATTRIBUTE(enable_if)
#define ABEL_BAD_CALL_IF(expr, msg) \
__attribute__((enable_if(expr, "Bad call trap"), unavailable(msg)))
#endif
// ABEL_REINITIALIZES
//
// Indicates that a member function reinitializes the entire object to a known
// state, independent of the previous state of the object.
//
// The clang-tidy check bugprone-use-after-move allows member functions marked
// with this attribute to be called on objects that have been moved from;
// without the attribute, this would result in a use-after-move warning.
#if ABEL_COMPILER_HAS_CPP_ATTRIBUTE(clang::reinitializes)
#define ABEL_REINITIALIZES [[clang::reinitializes]]
#else
#define ABEL_REINITIALIZES
#endif
// ABEL_HAVE_ATTRIBUTE_SECTION
//
// Indicates whether labeled sections are supported. Weak symbol support is
// a prerequisite. Labeled sections are not supported on Darwin/iOS.
#ifdef ABEL_HAVE_ATTRIBUTE_SECTION
#error ABEL_HAVE_ATTRIBUTE_SECTION cannot be directly set
#elif (ABEL_COMPILER_HAS_ATTRIBUTE(section) || \
(defined(__GNUC__) && !defined(__clang__))) && \
!defined(__APPLE__) && ABEL_WEAK_SUPPORTED
#define ABEL_HAVE_ATTRIBUTE_SECTION 1
// ABEL_ATTRIBUTE_SECTION
//
// Tells the compiler/linker to put a given function into a section and define
// `__start_ ## name` and `__stop_ ## name` symbols to bracket the section.
// This functionality is supported by GNU linker. Any function annotated with
// `ABEL_ATTRIBUTE_SECTION` must not be inlined, or it will be placed into
// whatever section its caller is placed into.
//
#ifndef ABEL_ATTRIBUTE_SECTION
#define ABEL_ATTRIBUTE_SECTION(name) \
__attribute__((section(#name))) __attribute__((noinline))
#endif
// ABEL_ATTRIBUTE_SECTION_VARIABLE
//
// Tells the compiler/linker to put a given variable into a section and define
// `__start_ ## name` and `__stop_ ## name` symbols to bracket the section.
// This functionality is supported by GNU linker.
#ifndef ABEL_ATTRIBUTE_SECTION_VARIABLE
#define ABEL_ATTRIBUTE_SECTION_VARIABLE(name) __attribute__((section(#name)))
#endif
// ABEL_DECLARE_ATTRIBUTE_SECTION_VARS
//
// A weak section declaration to be used as a global declaration
// for ABEL_ATTRIBUTE_SECTION_START|STOP(name) to compile and link
// even without functions with ABEL_ATTRIBUTE_SECTION(name).
// ABEL_DEFINE_ATTRIBUTE_SECTION should be in the exactly one file; it's
// a no-op on ELF but not on Mach-O.
//
#ifndef ABEL_DECLARE_ATTRIBUTE_SECTION_VARS
#define ABEL_DECLARE_ATTRIBUTE_SECTION_VARS(name) \
extern char __start_##name[] ABEL_WEAK; \
extern char __stop_##name[] ABEL_WEAK
#endif
#ifndef ABEL_DEFINE_ATTRIBUTE_SECTION_VARS
#define ABEL_INIT_ATTRIBUTE_SECTION_VARS(name)
#define ABEL_DEFINE_ATTRIBUTE_SECTION_VARS(name)
#endif
// ABEL_ATTRIBUTE_SECTION_START
//
// Returns `void*` pointers to start/end of a section of code with
// functions having ABEL_ATTRIBUTE_SECTION(name).
// Returns 0 if no such functions exist.
// One must ABEL_DECLARE_ATTRIBUTE_SECTION_VARS(name) for this to compile and
// link.
//
#define ABEL_ATTRIBUTE_SECTION_START(name) \
(reinterpret_cast<void *>(__start_##name))
#define ABEL_ATTRIBUTE_SECTION_STOP(name) \
(reinterpret_cast<void *>(__stop_##name))
#else // !ABEL_HAVE_ATTRIBUTE_SECTION
#define ABEL_HAVE_ATTRIBUTE_SECTION 0
// provide dummy definitions
#define ABEL_ATTRIBUTE_SECTION(name)
#define ABEL_ATTRIBUTE_SECTION_VARIABLE(name)
#define ABEL_INIT_ATTRIBUTE_SECTION_VARS(name)
#define ABEL_DEFINE_ATTRIBUTE_SECTION_VARS(name)
#define ABEL_DECLARE_ATTRIBUTE_SECTION_VARS(name)
#define ABEL_ATTRIBUTE_SECTION_START(name) (reinterpret_cast<void *>(0))
#define ABEL_ATTRIBUTE_SECTION_STOP(name) (reinterpret_cast<void *>(0))
#endif // ABEL_ATTRIBUTE_SECTION
// ABEL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
//
// Support for aligning the stack on 32-bit x86.
#if ABEL_COMPILER_HAS_ATTRIBUTE(force_align_arg_pointer) || \
(defined(__GNUC__) && !defined(__clang__))
#if defined(__i386__)
#define ABEL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC \
__attribute__((force_align_arg_pointer))
#define ABEL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#elif defined(__x86_64__)
#define ABEL_REQUIRE_STACK_ALIGN_TRAMPOLINE (1)
#define ABEL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#else // !__i386__ && !__x86_64
#define ABEL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#define ABEL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#endif // __i386__
#else
#define ABEL_ATTRIBUTE_STACK_ALIGN_FOR_OLD_LIBC
#define ABEL_REQUIRE_STACK_ALIGN_TRAMPOLINE (0)
#endif
// ABEL_MUST_USE_RESULT
//
// Tells the compiler to warn about unused results.
//
// When annotating a function, it must appear as the first part of the
// declaration or definition. The compiler will warn if the return value from
// such a function is unused:
//
// ABEL_MUST_USE_RESULT Sprocket* AllocateSprocket();
// AllocateSprocket(); // Triggers a warning.
//
// When annotating a class, it is equivalent to annotating every function which
// returns an instance.
//
// class ABEL_MUST_USE_RESULT Sprocket {};
// Sprocket(); // Triggers a warning.
//
// Sprocket MakeSprocket();
// MakeSprocket(); // Triggers a warning.
//
// Note that references and pointers are not instances:
//
// Sprocket* SprocketPointer();
// SprocketPointer(); // Does *not* trigger a warning.
//
// ABEL_MUST_USE_RESULT allows using cast-to-void to suppress the unused result
// warning. For that, warn_unused_result is used only for clang but not for gcc.
// https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425
//
// Note: past advice was to place the macro after the argument list.
#if ABEL_COMPILER_HAS_ATTRIBUTE(nodiscard)
#define ABEL_MUST_USE_RESULT [[nodiscard]]
#elif defined(__clang__) && ABEL_COMPILER_HAS_ATTRIBUTE(warn_unused_result)
#define ABEL_MUST_USE_RESULT __attribute__((warn_unused_result))
#else
#define ABEL_MUST_USE_RESULT
#endif
// ABEL_HOT, ABEL_COLD
//
// Tells GCC that a function is hot or cold. GCC can use this information to
// improve static analysis, i.e. a conditional branch to a cold function
// is likely to be not-taken.
// This annotation is used for function declarations.
//
// Example:
//
// int foo() ABEL_HOT;
#if ABEL_COMPILER_HAS_ATTRIBUTE(hot) || (defined(__GNUC__) && !defined(__clang__))
#define ABEL_HOT __attribute__((hot))
#else
#define ABEL_HOT
#endif
#if ABEL_COMPILER_HAS_ATTRIBUTE(cold) || (defined(__GNUC__) && !defined(__clang__))
#define ABEL_COLD __attribute__((cold))
#else
#define ABEL_COLD
#endif
// ABEL_XRAY_ALWAYS_INSTRUMENT, ABEL_XRAY_NEVER_INSTRUMENT, ABEL_XRAY_LOG_ARGS
//
// We define the ABEL_XRAY_ALWAYS_INSTRUMENT and ABEL_XRAY_NEVER_INSTRUMENT
// macro used as an attribute to mark functions that must always or never be
// instrumented by XRay. Currently, this is only supported in Clang/LLVM.
//
// For reference on the LLVM XRay instrumentation, see
// http://llvm.org/docs/XRay.html.
//
// A function with the XRAY_ALWAYS_INSTRUMENT macro attribute in its declaration
// will always get the XRay instrumentation sleds. These sleds may introduce
// some binary size and runtime overhead and must be used sparingly.
//
// These attributes only take effect when the following conditions are met:
//
// * The file/target is built in at least C++11 mode, with a Clang compiler
// that supports XRay attributes.
// * The file/target is built with the -fxray-instrument flag set for the
// Clang/LLVM compiler.
// * The function is defined in the translation unit (the compiler honors the
// attribute in either the definition or the declaration, and must match).
//
// There are cases when, even when building with XRay instrumentation, users
// might want to control specifically which functions are instrumented for a
// particular build using special-case lists provided to the compiler. These
// special case lists are provided to Clang via the
// -fxray-always-instrument=... and -fxray-never-instrument=... flags. The
// attributes in source take precedence over these special-case lists.
//
// To disable the XRay attributes at build-time, users may define
// ABEL_NO_XRAY_ATTRIBUTES. Do NOT define ABEL_NO_XRAY_ATTRIBUTES on specific
// packages/targets, as this may lead to conflicting definitions of functions at
// link-time.
//
#if ABEL_COMPILER_HAS_CPP_ATTRIBUTE(clang::xray_always_instrument) && \
!defined(ABEL_NO_XRAY_ATTRIBUTES)
#define ABEL_XRAY_ALWAYS_INSTRUMENT [[clang::xray_always_instrument]]
#define ABEL_XRAY_NEVER_INSTRUMENT [[clang::xray_never_instrument]]
#if ABEL_COMPILER_HAS_CPP_ATTRIBUTE(clang::xray_log_args)
#define ABEL_XRAY_LOG_ARGS(N) \
[[clang::xray_always_instrument, clang::xray_log_args(N)]]
#else
#define ABEL_XRAY_LOG_ARGS(N) [[clang::xray_always_instrument]]
#endif
#else
#define ABEL_XRAY_ALWAYS_INSTRUMENT
#define ABEL_XRAY_NEVER_INSTRUMENT
#define ABEL_XRAY_LOG_ARGS(N)
#endif
#endif //ABEL_BASE_PROFILE_COMPILER_TRAITS_H_
|
aa5a5ccbc0cc2522b1a066321b1e72c772d9509d | 26751ccf3847dbeb935d14de75c538dc2c2ad78e | /Base/ctkCommandLineParser.cpp | ada920f6a5a31d177b6992a5a4a0f3e7f06e3ef8 | [
"Apache-2.0"
] | permissive | commontk/AppLauncher | 6335b0266d80d279d67f0279f6e9e152f114732a | 8109ffb2f1ae3038bb5a955bff1a5f07dd1400d2 | refs/heads/main | 2023-04-13T05:27:55.704265 | 2023-04-07T22:57:22 | 2023-04-07T22:57:22 | 720,777 | 22 | 28 | Apache-2.0 | 2023-04-07T22:40:52 | 2010-06-14T19:43:30 | CMake | UTF-8 | C++ | false | false | 26,963 | cpp | ctkCommandLineParser.cpp | // STL includes
#include <stdexcept>
// Qt includes
#include <QHash>
#include <QStringList>
#include <QTextStream>
#include <QDebug>
#include <QSettings>
#include <QPointer>
// CTK includes
#include "ctkCommandLineParser.h"
#if defined (_WIN32)
#include <windows.h>
#endif
namespace
{
// --------------------------------------------------------------------------
class CommandLineParserArgumentDescription
{
public:
CommandLineParserArgumentDescription(
const QString& longArg, const QString& longArgPrefix,
const QString& shortArg, const QString& shortArgPrefix,
QVariant::Type type, const QString& argHelp,
const QVariant& defaultValue, bool ignoreRest,
bool deprecated)
: LongArg(longArg), LongArgPrefix(longArgPrefix),
ShortArg(shortArg), ShortArgPrefix(shortArgPrefix),
ArgHelp(argHelp), IgnoreRest(ignoreRest), NumberOfParametersToProcess(0),
Deprecated(deprecated), DefaultValue(defaultValue), Value(type), ValueType(type)
{
if (defaultValue.isValid())
{
Value = defaultValue;
}
switch (type)
{
case QVariant::String:
{
NumberOfParametersToProcess = 1;
RegularExpression = ".*";
}
break;
case QVariant::Bool:
{
NumberOfParametersToProcess = 0;
RegularExpression = "";
}
break;
case QVariant::StringList:
{
NumberOfParametersToProcess = -1;
RegularExpression = ".*";
}
break;
case QVariant::Int:
{
NumberOfParametersToProcess = 1;
RegularExpression = "-?[0-9]+";
ExactMatchFailedMessage = "A negative or positive integer is expected.";
}
break;
default:
ExactMatchFailedMessage = QString("Type %1 not supported.").arg(static_cast<int>(type));
}
}
~CommandLineParserArgumentDescription(){}
bool addParameter(const QString& value);
QString helpText(int fieldWidth, const char charPad, const QString& settingsValue = "");
QString LongArg;
QString LongArgPrefix;
QString ShortArg;
QString ShortArgPrefix;
QString ArgHelp;
bool IgnoreRest;
int NumberOfParametersToProcess;
QString RegularExpression;
QString ExactMatchFailedMessage;
bool Deprecated;
QVariant DefaultValue;
QVariant Value;
QVariant::Type ValueType;
};
// --------------------------------------------------------------------------
bool CommandLineParserArgumentDescription::addParameter(const QString& value)
{
if (!RegularExpression.isEmpty())
{
// Validate value
QRegExp regexp(this->RegularExpression);
if (!regexp.exactMatch(value))
{
return false;
}
}
switch (Value.type())
{
case QVariant::String:
{
Value.setValue(value);
}
break;
case QVariant::Bool:
{
Value.setValue(!QString::compare(value, "true", Qt::CaseInsensitive));
}
break;
case QVariant::StringList:
{
if (Value.isNull())
{
QStringList list;
list << value;
Value.setValue(list);
}
else
{
QStringList list = Value.toStringList();
list << value;
Value.setValue(list);
}
}
break;
case QVariant::Int:
{
Value.setValue(value.toInt());
}
break;
default:
return false;
}
return true;
}
// --------------------------------------------------------------------------
QString CommandLineParserArgumentDescription::helpText(int fieldWidth, const char charPad,
const QString& settingsValue)
{
QString text;
QTextStream stream(&text);
stream.setFieldAlignment(QTextStream::AlignLeft);
stream.setPadChar(charPad);
QString shortAndLongArg;
if (!this->ShortArg.isEmpty())
{
shortAndLongArg += QString(" %1%2").arg(this->ShortArgPrefix).arg(this->ShortArg);
}
if (!this->LongArg.isEmpty())
{
if (this->ShortArg.isEmpty())
{
shortAndLongArg.append(" ");
}
else
{
shortAndLongArg.append(", ");
}
shortAndLongArg += QString("%1%2").arg(this->LongArgPrefix).arg(this->LongArg);
}
if(!this->ArgHelp.isEmpty())
{
stream.setFieldWidth(fieldWidth);
}
stream << shortAndLongArg;
stream.setFieldWidth(0);
stream << this->ArgHelp;
if (!settingsValue.isNull())
{
stream << " (default: " << settingsValue << ")";
}
else if (!this->DefaultValue.isNull())
{
stream << " (default: " << this->DefaultValue.toString() << ")";
}
stream << "\n";
return text;
}
}
// --------------------------------------------------------------------------
// ctkCommandLineParser::ctkInternal class
// --------------------------------------------------------------------------
class ctkCommandLineParser::ctkInternal
{
public:
ctkInternal(QSettings* settings)
: Debug(false), FieldWidth(0), UseQSettings(false),
Settings(settings), MergeSettings(true), StrictMode(false)
{}
~ctkInternal() { qDeleteAll(ArgumentDescriptionList); }
CommandLineParserArgumentDescription* argumentDescription(const QString& argument);
QList<CommandLineParserArgumentDescription*> ArgumentDescriptionList;
QHash<QString, CommandLineParserArgumentDescription*> ArgNameToArgumentDescriptionMap;
QMap<QString, QList<CommandLineParserArgumentDescription*> > GroupToArgumentDescriptionListMap;
QStringList UnparsedArguments;
QStringList ProcessedArguments;
QString ErrorString;
bool Debug;
int FieldWidth;
QString LongPrefix;
QString ShortPrefix;
QString CurrentGroup;
bool UseQSettings;
QPointer<QSettings> Settings;
QString DisableQSettingsLongArg;
QString DisableQSettingsShortArg;
bool MergeSettings;
bool StrictMode;
};
// --------------------------------------------------------------------------
// ctkCommandLineParser::ctkInternal methods
// --------------------------------------------------------------------------
CommandLineParserArgumentDescription*
ctkCommandLineParser::ctkInternal::argumentDescription(const QString& argument)
{
QString unprefixedArg = argument;
if (!LongPrefix.isEmpty() && argument.startsWith(LongPrefix))
{
// Case when (ShortPrefix + UnPrefixedArgument) matches LongPrefix
if (argument == LongPrefix && !ShortPrefix.isEmpty() && argument.startsWith(ShortPrefix))
{
unprefixedArg = argument.mid(ShortPrefix.length());
}
else
{
unprefixedArg = argument.mid(LongPrefix.length());
}
}
else if (!ShortPrefix.isEmpty() && argument.startsWith(ShortPrefix))
{
unprefixedArg = argument.mid(ShortPrefix.length());
}
else if (!LongPrefix.isEmpty() && !ShortPrefix.isEmpty())
{
return 0;
}
if (this->ArgNameToArgumentDescriptionMap.contains(unprefixedArg))
{
return this->ArgNameToArgumentDescriptionMap[unprefixedArg];
}
return 0;
}
// --------------------------------------------------------------------------
// ctkCommandLineParser methods
// --------------------------------------------------------------------------
ctkCommandLineParser::ctkCommandLineParser(QSettings* settings)
{
this->Internal = new ctkInternal(settings);
}
// --------------------------------------------------------------------------
ctkCommandLineParser::~ctkCommandLineParser()
{
delete this->Internal;
}
// --------------------------------------------------------------------------
QHash<QString, QVariant> ctkCommandLineParser::parseArguments(const QStringList& arguments,
bool* ok)
{
// Reset
this->Internal->UnparsedArguments.clear();
this->Internal->ProcessedArguments.clear();
this->Internal->ErrorString.clear();
foreach (CommandLineParserArgumentDescription* desc,
this->Internal->ArgumentDescriptionList)
{
desc->Value = QVariant(desc->ValueType);
if (desc->DefaultValue.isValid())
{
desc->Value = desc->DefaultValue;
}
}
bool error = false;
bool ignoreRest = false;
bool useSettings = this->Internal->UseQSettings;
CommandLineParserArgumentDescription * currentArgDesc = 0;
QList<CommandLineParserArgumentDescription*> parsedArgDescriptions;
for(int i = 1; i < arguments.size(); ++i)
{
QString argument = arguments.at(i);
if (this->Internal->Debug) { qDebug() << "Processing" << argument; }
// should argument be ignored ?
if (ignoreRest)
{
if (this->Internal->Debug)
{
qDebug() << " Skipping: IgnoreRest flag was been set";
}
this->Internal->UnparsedArguments << argument;
continue;
}
// Skip if the argument does not start with the defined prefix
if (!(argument.startsWith(this->Internal->LongPrefix)
|| argument.startsWith(this->Internal->ShortPrefix)))
{
if (this->Internal->StrictMode)
{
this->Internal->ErrorString = QString("Unknown argument %1").arg(argument);
error = true;
break;
}
if (this->Internal->Debug)
{
qDebug() << " Skipping: It does not start with the defined prefix";
}
this->Internal->UnparsedArguments << argument;
continue;
}
// Skip if argument has already been parsed ...
if (this->Internal->ProcessedArguments.contains(argument))
{
if (this->Internal->StrictMode)
{
this->Internal->ErrorString = QString("Argument %1 already processed !").arg(argument);
error = true;
break;
}
if (this->Internal->Debug)
{
qDebug() << " Skipping: Already processed !";
}
continue;
}
// Retrieve corresponding argument description
currentArgDesc = this->Internal->argumentDescription(argument);
// Is there a corresponding argument description ?
if (currentArgDesc)
{
// If the argument is deprecated, print the help text but continue processing
if (currentArgDesc->Deprecated)
{
qWarning().nospace() << "Deprecated argument " << argument << ": " << currentArgDesc->ArgHelp;
}
else
{
parsedArgDescriptions.push_back(currentArgDesc);
}
// Is the argument the special "disable QSettings" argument?
if ((!currentArgDesc->LongArg.isEmpty() && currentArgDesc->LongArg == this->Internal->DisableQSettingsLongArg)
|| (!currentArgDesc->ShortArg.isEmpty() && currentArgDesc->ShortArg == this->Internal->DisableQSettingsShortArg))
{
useSettings = false;
}
this->Internal->ProcessedArguments << currentArgDesc->ShortArg << currentArgDesc->LongArg;
int numberOfParametersToProcess = currentArgDesc->NumberOfParametersToProcess;
ignoreRest = currentArgDesc->IgnoreRest;
if (this->Internal->Debug && ignoreRest)
{
qDebug() << " IgnoreRest flag is True";
}
// Is the number of parameters associated with the argument being processed known ?
if (numberOfParametersToProcess == 0)
{
currentArgDesc->addParameter("true");
}
else if (numberOfParametersToProcess > 0)
{
QString missingParameterError =
"Argument %1 has %2 value(s) associated whereas exacly %3 are expected.";
for(int j=1; j <= numberOfParametersToProcess; ++j)
{
if (i + j >= arguments.size())
{
this->Internal->ErrorString =
missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess);
if (this->Internal->Debug) { qDebug() << this->Internal->ErrorString; }
if (ok) { *ok = false; }
return QHash<QString, QVariant>();
}
QString parameter = arguments.at(i + j);
if (this->Internal->Debug)
{
qDebug() << " Processing parameter" << j << ", value:" << parameter;
}
if (this->argumentAdded(parameter))
{
this->Internal->ErrorString =
missingParameterError.arg(argument).arg(j-1).arg(numberOfParametersToProcess);
if (this->Internal->Debug) { qDebug() << this->Internal->ErrorString; }
if (ok) { *ok = false; }
return QHash<QString, QVariant>();
}
if (!currentArgDesc->addParameter(parameter))
{
this->Internal->ErrorString = QString(
"Value(s) associated with argument %1 are incorrect. %2").
arg(argument).arg(currentArgDesc->ExactMatchFailedMessage);
if (this->Internal->Debug) { qDebug() << this->Internal->ErrorString; }
if (ok) { *ok = false; }
return QHash<QString, QVariant>();
}
}
// Update main loop increment
i = i + numberOfParametersToProcess;
}
else if (numberOfParametersToProcess == -1)
{
if (this->Internal->Debug)
{
qDebug() << " Proccessing StringList ...";
}
int j = 1;
while(j + i < arguments.size())
{
if (this->argumentAdded(arguments.at(j + i)))
{
if (this->Internal->Debug)
{
qDebug() << " No more parameter for" << argument;
}
break;
}
QString parameter = arguments.at(j + i);
if (this->Internal->Debug)
{
qDebug() << " Processing parameter" << j << ", value:" << parameter;
}
if (!currentArgDesc->addParameter(parameter))
{
this->Internal->ErrorString = QString(
"Value(s) associated with argument %1 are incorrect. %2").
arg(argument).arg(currentArgDesc->ExactMatchFailedMessage);
if (this->Internal->Debug) { qDebug() << this->Internal->ErrorString; }
if (ok) { *ok = false; }
return QHash<QString, QVariant>();
}
j++;
}
// Update main loop increment
i = i + j;
}
}
else
{
if (this->Internal->StrictMode)
{
this->Internal->ErrorString = QString("Unknown argument %1").arg(argument);
error = true;
break;
}
if (this->Internal->Debug)
{
qDebug() << " Skipping: Unknown argument";
}
this->Internal->UnparsedArguments << argument;
}
}
if (ok)
{
*ok = !error;
}
QSettings* settings = 0;
if (this->Internal->UseQSettings && useSettings)
{
if (this->Internal->Settings)
{
settings = this->Internal->Settings;
}
else
{
// Use a default constructed QSettings instance
settings = new QSettings();
}
}
QHash<QString, QVariant> parsedArguments;
QListIterator<CommandLineParserArgumentDescription*> it(this->Internal->ArgumentDescriptionList);
while (it.hasNext())
{
QString key;
CommandLineParserArgumentDescription* desc = it.next();
if (!desc->LongArg.isEmpty())
{
key = desc->LongArg;
}
else
{
key = desc->ShortArg;
}
if (parsedArgDescriptions.contains(desc))
{
// The argument was supplied on the command line, so use the given value
if (this->Internal->MergeSettings && settings)
{
// Merge with QSettings
QVariant settingsVal = settings->value(key);
if (desc->ValueType == QVariant::StringList &&
settingsVal.canConvert(QVariant::StringList))
{
QStringList stringList = desc->Value.toStringList();
stringList.append(settingsVal.toStringList());
parsedArguments.insert(key, stringList);
}
else
{
// do a normal insert
parsedArguments.insert(key, desc->Value);
}
}
else
{
// No merging, just insert all user values
parsedArguments.insert(key, desc->Value);
}
}
else
{
if (settings)
{
// If there is a valid QSettings entry for the argument, use the value
QVariant settingsVal = settings->value(key, desc->Value);
if (!settingsVal.isNull())
{
parsedArguments.insert(key, settingsVal);
}
}
else
{
// Just insert the arguments with valid default values
if (!desc->Value.isNull())
{
parsedArguments.insert(key, desc->Value);
}
}
}
}
// If we created a default QSettings instance, delete it
if (settings && !this->Internal->Settings)
{
delete settings;
}
return parsedArguments;
}
// -------------------------------------------------------------------------
QHash<QString, QVariant> ctkCommandLineParser::parseArguments(int argc, char** argv, bool* ok)
{
QStringList arguments;
// Create a QStringList of arguments
for(int i = 0; i < argc; ++i)
{
arguments << argv[i];
}
return this->parseArguments(arguments, ok);
}
// -------------------------------------------------------------------------
QString ctkCommandLineParser::errorString() const
{
return this->Internal->ErrorString;
}
// -------------------------------------------------------------------------
const QStringList& ctkCommandLineParser::unparsedArguments() const
{
return this->Internal->UnparsedArguments;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::addArgument(const QString& longarg, const QString& shortarg,
QVariant::Type type, const QString& argHelp,
const QVariant& defaultValue, bool ignoreRest,
bool deprecated)
{
Q_ASSERT_X(!(longarg.isEmpty() && shortarg.isEmpty()), "addArgument",
"both long and short argument names are empty");
if (longarg.isEmpty() && shortarg.isEmpty()) { return; }
Q_ASSERT_X(!defaultValue.isValid() || defaultValue.type() == type, "addArgument",
"defaultValue type does not match");
if (defaultValue.isValid() && defaultValue.type() != type)
throw std::logic_error("The QVariant type of defaultValue does not match the specified type");
/* Make sure it's not already added */
bool added = this->Internal->ArgNameToArgumentDescriptionMap.contains(longarg);
Q_ASSERT_X(!added, "addArgument", "long argument already added");
if (added) { return; }
added = this->Internal->ArgNameToArgumentDescriptionMap.contains(shortarg);
Q_ASSERT_X(!added, "addArgument", "short argument already added");
if (added) { return; }
CommandLineParserArgumentDescription* argDesc =
new CommandLineParserArgumentDescription(longarg, this->Internal->LongPrefix,
shortarg, this->Internal->ShortPrefix, type,
argHelp, defaultValue, ignoreRest, deprecated);
int argWidth = 0;
if (!longarg.isEmpty())
{
this->Internal->ArgNameToArgumentDescriptionMap[longarg] = argDesc;
argWidth += longarg.length() + this->Internal->LongPrefix.length();
}
if (!shortarg.isEmpty())
{
this->Internal->ArgNameToArgumentDescriptionMap[shortarg] = argDesc;
argWidth += shortarg.length() + this->Internal->ShortPrefix.length() + 2;
}
argWidth += 5;
// Set the field width for the arguments
if (argWidth > this->Internal->FieldWidth)
{
this->Internal->FieldWidth = argWidth;
}
this->Internal->ArgumentDescriptionList << argDesc;
this->Internal->GroupToArgumentDescriptionListMap[this->Internal->CurrentGroup] << argDesc;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::addDeprecatedArgument(
const QString& longarg, const QString& shortarg, const QString& argHelp)
{
addArgument(longarg, shortarg, QVariant::StringList, argHelp, QVariant(), false, true);
}
// --------------------------------------------------------------------------
bool ctkCommandLineParser::setExactMatchRegularExpression(
const QString& argument, const QString& expression, const QString& exactMatchFailedMessage)
{
CommandLineParserArgumentDescription * argDesc =
this->Internal->argumentDescription(argument);
if (!argDesc)
{
return false;
}
if (argDesc->Value.type() == QVariant::Bool)
{
return false;
}
argDesc->RegularExpression = expression;
argDesc->ExactMatchFailedMessage = exactMatchFailedMessage;
return true;
}
// --------------------------------------------------------------------------
int ctkCommandLineParser::fieldWidth() const
{
return this->Internal->FieldWidth;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::beginGroup(const QString& description)
{
this->Internal->CurrentGroup = description;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::endGroup()
{
this->Internal->CurrentGroup.clear();
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::enableSettings(const QString& disableLongArg, const QString& disableShortArg)
{
this->Internal->UseQSettings = true;
this->Internal->DisableQSettingsLongArg = disableLongArg;
this->Internal->DisableQSettingsShortArg = disableShortArg;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::mergeSettings(bool merge)
{
this->Internal->MergeSettings = merge;
}
// --------------------------------------------------------------------------
bool ctkCommandLineParser::settingsEnabled() const
{
return this->Internal->UseQSettings;
}
// --------------------------------------------------------------------------
QString ctkCommandLineParser::helpText(const char charPad) const
{
QString text;
QTextStream stream(&text);
QList<CommandLineParserArgumentDescription*> deprecatedArgs;
// Loop over grouped argument descriptions
QMapIterator<QString, QList<CommandLineParserArgumentDescription*> > it(
this->Internal->GroupToArgumentDescriptionListMap);
while(it.hasNext())
{
it.next();
if (!it.key().isEmpty())
{
stream << "\n" << it.key() << "\n";
}
foreach(CommandLineParserArgumentDescription* argDesc, it.value())
{
if (argDesc->Deprecated)
{
deprecatedArgs << argDesc;
}
else
{
// Extract associated value from settings if any
QString settingsValue;
if (this->Internal->Settings)
{
QString key;
if (!argDesc->LongArg.isEmpty())
{
key = argDesc->LongArg;
}
else
{
key = argDesc->ShortArg;
}
settingsValue = this->Internal->Settings->value(key).toString();
}
stream << argDesc->helpText(this->Internal->FieldWidth, charPad, settingsValue);
}
}
}
if (!deprecatedArgs.empty())
{
stream << "\nDeprecated arguments:\n";
foreach(CommandLineParserArgumentDescription* argDesc, deprecatedArgs)
{
stream << argDesc->helpText(this->Internal->FieldWidth, charPad);
}
}
return text;
}
// --------------------------------------------------------------------------
bool ctkCommandLineParser::argumentAdded(const QString& argument) const
{
return this->Internal->ArgNameToArgumentDescriptionMap.contains(argument);
}
// --------------------------------------------------------------------------
bool ctkCommandLineParser::argumentParsed(const QString& argument) const
{
return this->Internal->ProcessedArguments.contains(argument);
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::setArgumentPrefix(const QString& longPrefix, const QString& shortPrefix)
{
this->Internal->LongPrefix = longPrefix;
this->Internal->ShortPrefix = shortPrefix;
}
// --------------------------------------------------------------------------
QString ctkCommandLineParser::longPrefix()const
{
return this->Internal->LongPrefix;
}
// --------------------------------------------------------------------------
QString ctkCommandLineParser::shortPrefix()const
{
return this->Internal->ShortPrefix;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::setStrictModeEnabled(bool strictMode)
{
this->Internal->StrictMode = strictMode;
}
// --------------------------------------------------------------------------
void ctkCommandLineParser::convertWindowsCommandLineToUnixArguments(
const char *cmd_line, int *argc, char ***argv)
{
if (!cmd_line || !argc || !argv)
{
return;
}
// A space delimites an argument except when it is inside a quote
(*argc) = 1;
size_t cmd_line_len = strlen(cmd_line);
size_t i;
for (i = 0; i < cmd_line_len; i++)
{
while (isspace(cmd_line[i]) && i < cmd_line_len)
{
i++;
}
if (i < cmd_line_len)
{
if (cmd_line[i] == '\"')
{
i++;
while (cmd_line[i] != '\"' && i < cmd_line_len)
{
i++;
}
(*argc)++;
}
else
{
while (!isspace(cmd_line[i]) && i < cmd_line_len)
{
i++;
}
(*argc)++;
}
}
}
(*argv) = new char* [(*argc) + 1];
(*argv)[(*argc)] = NULL;
// Set the first arg to be the exec name
(*argv)[0] = new char [1024];
#ifdef _WIN32
::GetModuleFileName(0, (*argv)[0], 1024);
#else
(*argv)[0][0] = '\0';
#endif
// Allocate the others
int j;
for (j = 1; j < (*argc); j++)
{
(*argv)[j] = new char [cmd_line_len + 10];
}
// Grab the args
size_t pos;
int argc_idx = 1;
for (i = 0; i < cmd_line_len; i++)
{
while (isspace(cmd_line[i]) && i < cmd_line_len)
{
i++;
}
if (i < cmd_line_len)
{
if (cmd_line[i] == '\"')
{
i++;
pos = i;
while (cmd_line[i] != '\"' && i < cmd_line_len)
{
i++;
}
memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
(*argv)[argc_idx][i - pos] = '\0';
argc_idx++;
}
else
{
pos = i;
while (!isspace(cmd_line[i]) && i < cmd_line_len)
{
i++;
}
memcpy((*argv)[argc_idx], &cmd_line[pos], i - pos);
(*argv)[argc_idx][i - pos] = '\0';
argc_idx++;
}
}
}
}
|
2f6fafb4e11144e717205e8a17c5b2211c820480 | e505f4a0f1f479374e25fd4650b2a700ecbc221f | /source/state/MainMenu.h | 520e7a97ead93ef6f9d46226f8795baccaa9b44b | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | dexter3k/Stranded2pp | 89ec16946771b462f07454bdde90c786deb54d56 | 022df9becf9931f8437e81bb405bacf168884c8d | refs/heads/master | 2023-04-02T08:54:21.403931 | 2021-04-04T18:01:52 | 2021-04-04T18:01:52 | 58,408,094 | 2 | 1 | MIT | 2023-03-23T15:07:37 | 2016-05-09T21:04:41 | C++ | UTF-8 | C++ | false | false | 763 | h | MainMenu.h | #pragma once
#include "State.h"
#include "graphics/gui/GuiElement.h"
namespace state
{
class MainMenu : public State
{
typedef State super;
public:
MainMenu(Stranded & game);
void show() override;
void hide() override;
bool processEvent(Event event) override;
private:
void loadGame();
void loadInterface();
private:
static std::string const menuMap;
static std::string const logoImage;
private:
gfx::gui::GuiElement * menuRoot;
gfx::gui::GuiElement * mainMenu;
gfx::gui::GuiElement * randomMenu;
gfx::gui::GuiElement * customMenu;
gfx::gui::GuiElement * loadGameMenu;
gfx::gui::GuiElement * multiplayerMenu;
gfx::gui::GuiElement * optionsMenu;
gfx::gui::GuiElement * creditsMenu;
gfx::gui::GuiElement * quitMenu;
};
} // namespace state
|
92523ef9c8879bbc88e85699b491d0b102ff754a | a5a99f646e371b45974a6fb6ccc06b0a674818f2 | /CondFormats/RPCObjects/src/RPCObPVSSmap.cc | a1282d1af100078032431a5a6dd81891eb5c8e39 | [
"Apache-2.0"
] | permissive | cms-sw/cmssw | 4ecd2c1105d59c66d385551230542c6615b9ab58 | 19c178740257eb48367778593da55dcad08b7a4f | refs/heads/master | 2023-08-23T21:57:42.491143 | 2023-08-22T20:22:40 | 2023-08-22T20:22:40 | 10,969,551 | 1,006 | 3,696 | Apache-2.0 | 2023-09-14T19:14:28 | 2013-06-26T14:09:07 | C++ | UTF-8 | C++ | false | false | 109 | cc | RPCObPVSSmap.cc | #include "CondFormats/RPCObjects/interface/RPCObPVSSmap.h"
#include "FWCore/Utilities/interface/Exception.h"
|
42974e820b35d736a1a1436fa1e3171aca25127d | 88ae8695987ada722184307301e221e1ba3cc2fa | /third_party/pdfium/fpdfsdk/cpdfsdk_helpers_unittest.cpp | ac1320efd96dfa3e543ce46db20d25a6ffbd6834 | [
"BSD-3-Clause",
"Apache-2.0",
"LGPL-2.0-or-later",
"MIT",
"GPL-1.0-or-later"
] | permissive | iridium-browser/iridium-browser | 71d9c5ff76e014e6900b825f67389ab0ccd01329 | 5ee297f53dc7f8e70183031cff62f37b0f19d25f | refs/heads/master | 2023-08-03T16:44:16.844552 | 2023-07-20T15:17:00 | 2023-07-23T16:09:30 | 220,016,632 | 341 | 40 | BSD-3-Clause | 2021-08-13T13:54:45 | 2019-11-06T14:32:31 | null | UTF-8 | C++ | false | false | 4,094 | cpp | cpdfsdk_helpers_unittest.cpp | // Copyright 2020 The PDFium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "fpdfsdk/cpdfsdk_helpers.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::ElementsAre;
using ::testing::IsEmpty;
TEST(CPDFSDK_HelpersTest, NulTerminateMaybeCopyAndReturnLength) {
{
const ByteString to_be_copied("toBeCopied");
constexpr size_t kExpectedToBeCopiedLen = 10;
ASSERT_EQ(kExpectedToBeCopiedLen, to_be_copied.GetLength());
EXPECT_EQ(kExpectedToBeCopiedLen + 1,
NulTerminateMaybeCopyAndReturnLength(to_be_copied, nullptr, 0));
// Buffer should not change if declared length is too short.
char buf[kExpectedToBeCopiedLen + 1];
memset(buf, 0x42, kExpectedToBeCopiedLen + 1);
ASSERT_EQ(kExpectedToBeCopiedLen + 1,
NulTerminateMaybeCopyAndReturnLength(to_be_copied, buf,
kExpectedToBeCopiedLen));
for (char c : buf)
EXPECT_EQ(0x42, c);
// Buffer should copy over if long enough.
ASSERT_EQ(kExpectedToBeCopiedLen + 1,
NulTerminateMaybeCopyAndReturnLength(to_be_copied, buf,
kExpectedToBeCopiedLen + 1));
EXPECT_EQ(to_be_copied, ByteString(buf));
}
{
// Empty ByteString should still copy NUL terminator.
const ByteString empty;
char buf[1];
ASSERT_EQ(1u, NulTerminateMaybeCopyAndReturnLength(empty, buf, 1));
EXPECT_EQ(empty, ByteString(buf));
}
}
TEST(CPDFSDK_HelpersTest, ParsePageRangeString) {
EXPECT_THAT(ParsePageRangeString("", 1), IsEmpty());
EXPECT_THAT(ParsePageRangeString(" ", 1), IsEmpty());
EXPECT_THAT(ParsePageRangeString("clams", 1), IsEmpty());
EXPECT_THAT(ParsePageRangeString("0", 0), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1", 0), IsEmpty());
EXPECT_THAT(ParsePageRangeString(",1", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1,", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1,clams", 1), IsEmpty());
EXPECT_THAT(ParsePageRangeString("clams,1", 1), IsEmpty());
EXPECT_THAT(ParsePageRangeString("0-1", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-0", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-5", 4), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-11,", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString(",1-1", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-,", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("-2,", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-clams", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("clams-1,", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-2clams", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("0,1", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1,0", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-2,,,,3-4", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-2-", 10), IsEmpty());
EXPECT_THAT(ParsePageRangeString("1-1", 10), ElementsAre(0));
EXPECT_THAT(ParsePageRangeString("1", 1), ElementsAre(0));
EXPECT_THAT(ParsePageRangeString("1-4", 4), ElementsAre(0, 1, 2, 3));
EXPECT_THAT(ParsePageRangeString("1- 4", 4), ElementsAre(0, 1, 2, 3));
EXPECT_THAT(ParsePageRangeString("1 -4", 4), ElementsAre(0, 1, 2, 3));
EXPECT_THAT(ParsePageRangeString("1,2", 10), ElementsAre(0, 1));
EXPECT_THAT(ParsePageRangeString("2,1", 10), ElementsAre(1, 0));
EXPECT_THAT(ParsePageRangeString("1,50,2", 100), ElementsAre(0, 49, 1));
EXPECT_THAT(ParsePageRangeString("1-4,50", 100), ElementsAre(0, 1, 2, 3, 49));
EXPECT_THAT(ParsePageRangeString("50,1-2", 100), ElementsAre(49, 0, 1));
EXPECT_THAT(ParsePageRangeString("5 0, 1-2 ", 100),
ElementsAre(49, 0, 1)); // ???
EXPECT_THAT(ParsePageRangeString("1-3,4-6", 10),
ElementsAre(0, 1, 2, 3, 4, 5));
EXPECT_THAT(ParsePageRangeString("1-4,3-6", 10),
ElementsAre(0, 1, 2, 3, 2, 3, 4, 5));
}
|
b705be2bfa2a31e28fc571c68a1da4376bf087dc | e2b5b45afefbd79f3c1d1a3c411b90001ea6d7e4 | /clay-gui-qt/base/QtListDialog.h | 3b9b9df6cc7e3f8ebc4ba148db9737c76e7daadc | [] | no_license | cbastuck/clay | 67e2858bbec56dace425692400d2ef92ef1a1791 | 35a9f6ad582888eeddb2e5ef069d2a3b6f21086a | refs/heads/master | 2021-01-20T02:16:58.274920 | 2013-10-06T17:49:01 | 2013-10-06T17:49:01 | 2,477,137 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,421 | h | QtListDialog.h | /**************************************************************************\
*
* This file is part of the C++ Modular Development Framework.
* Copyright (C) 2009 by Christoph Bastuck. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* ("GPL") version 2 as published by the Free Software Foundation.
* See the file LICENSE.GPL at the root directory of this source
* distribution for additional information about the GNU GPL.
*
* For using this framework with software that can not be combined with the GNU
* GPL please contact mail@cbastuck about acquiring a commercial license.
*
* See http://www.cbastuck.de/ for more information.
*
\**************************************************************************/
#ifndef QtListDialog_H_
#define QtListDialog_H_
#include <QDialog>
#include <deque>
#include <QVariant>
#include "ui_QListDialog.h"
namespace CLAY
{
namespace UI
{
class QtListDialog : public QDialog
{
public:
typedef QDialog tBase;
QtListDialog(QWidget* pParent=NULL);
void init();
void addEntry(const QString& sEntry, const QVariant& aUserData=QVariant());
int getSelectedRow() const;
QVariant getSelectedUserData() const;
private:
Ui::QListDialog m_aUI;
std::deque<QVariant> m_collUserData;
};
}
}
#endif
|
1320acb51df15642ab2c6707a35393b74cb87168 | 785463ea0d81e1ab888a858e31ab8cf8b24e4ce6 | /src/shared/datalib/data_info/default.hpp | a7f58f5ea90b0de7f2cf0a226462b1c633af4a35 | [
"MIT"
] | permissive | GTAResources/modloader | 475853390165290d0b5f37f239f3e6b15f36195a | 18f85c2766d4e052a452c7b1d8f5860a6daac24b | refs/heads/master | 2021-02-07T17:32:29.299117 | 2018-01-20T16:23:25 | 2018-01-20T16:23:25 | 244,057,341 | 1 | 1 | MIT | 2020-02-29T23:33:52 | 2020-02-29T23:33:51 | null | MacCentralEurope | C++ | false | false | 3,655 | hpp | default.hpp | /*
* Copyright (C) 2014 Denilson das MercÍs Amorim (aka LINK/2012)
* Licensed under the Boost Software License v1.0 (http://opensource.org/licenses/BSL-1.0)
*
*/
#pragma once
#include <type_traits>
#include <iosfwd>
//
// This header contains:
// [*] default data_info<> objects, including data_info_base
// [*] delimopt type (delimiter for optional params in data_slice<>)
//
//
namespace datalib {
#ifdef DATALIB_FAST_COMPILATION
# ifndef DATALIB_DATAINFO_NOPRECOMP
# define DATALIB_DATAINFO_NOPRECOMP
# endif
#endif
/*
* delimopt
* Any type coming after this type is optional
*/
struct delimopt
{
bool operator==(const delimopt& rhs) const { return true; } // Always
bool operator<(const delimopt& rhs) const { return false; } // ...equal
};
/*
* data_info_base
* Any data_info<> specialization should inherit from this base type
* This type defines default (common) values for the child data_info, you can then override a specific setting if needed
* Check the explanation for each property in the member's comments
*/
struct data_info_base
{
// Should this type get ignored?
static const bool ignore = false;
// The character written after this type (could be '\0' for no separator)
static const char separator = ' ';
// The complexity to compare two objects of this type. Notice this is the complexity AFTER 'precompare' happened.
// (0 means no complexity (no operation); 1 means fundamental complexity; Negative numbers are undefined behaviour)
static const int complexity = 1;
// This should do a very cheap comparision which will run before comparing any other type, it's used to avoid going further in comparisions
// when a cheaper comparision is available before.
// NOTE: NO ONE (not even datalib) should call data_info<T>::precompare directly, use datalib::precompare instead!!!!!!
template<class T>
static bool precompare(const T& a, const T& b)
{
return true;
}
};
/*
* data_info
* Default data_info<> specialization, used mostly by fundamental types
*/
template<typename T>
struct data_info : data_info_base
{
static const int complexity = std::is_floating_point<T>::value?
10 : // <- Operating on a float takes aproximately the same as operating on 10 ints
1; // <- Fundamental complexity
};
/*
* data_info
* data_info<> specialization for void, which should be ignored and is a no-op
*/
template<>
struct data_info<void> : data_info_base
{
static const bool ignore = true; // Should be ignored
static const int complexity = 0; // No-op comparision
};
/*
* data_info
* data_info<> specialization for delimopt
*/
template<>
struct data_info<delimopt> : data_info_base
{
static const bool ignore = true; // The type should be ignored but it is handled internally to allow optional types after it
static const int complexity = 0; // Unecessary since we won't touch it at all, only used by compile time compares, but yeah lets use
};
template<class T>
inline bool precompare(const T& a, const T& b)
{
#if !defined(DATALIB_DATAINFO_NOPRECOMP)
return data_info<T>::precompare(a, b);
#else
return true;
#endif
}
template<class T, class CharT, class Traits>
inline std::basic_ostream<CharT, Traits>& print_separator(std::basic_ostream<CharT, Traits>& os)
{
auto separator = data_info<T>::separator;
if(separator) os << separator;
return os;
}
} // namespace datalib
|
567a6a586011dbce21ee821ecf8f002c0480e743 | 5ccff983ae803171689a5fb8d57485c20d70c428 | /evaluation_platform_connect_to_AR605/evaluation_platform.cpp | 29a81e80d7e40f3ff6bb886becb6d904b9ce274c | [] | no_license | trigrass2/gazebo | bee196ca3ba9021f05844953428e1df49314062e | 8dfd4d96fd92ab61c6ad0055b2f633d8587e0d42 | refs/heads/master | 2021-09-15T12:39:38.965177 | 2018-06-01T15:12:47 | 2018-06-01T15:12:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 56,383 | cpp | evaluation_platform.cpp | /*
* evaluation_platform.cpp
*
* Created on: Feb 15, 2017
* Author: kevin
*/
#include "evaluation_platform.h"
#include <sstream>
#include <fstream>
#include <gazebo/msgs/request.pb.h>
#include "gazebo/physics/physics.hh"
#include "gazebo/common/common.hh"
#include "gazebo/gazebo.hh"
// for loading parameters from xml
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
// for loading parameters from xml
// for logging to file
#define BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/filesystem/operations.hpp>
#undef BOOST_NO_CXX11_SCOPED_ENUMS
#include <boost/date_time/posix_time/posix_time.hpp>
// for logging to file
#define COUT_PREFIX "\033[1;33m" << "[EvaluationPlatform] " << "\033[0m"
#define CERR_PREFIX "\033[1;31m" << "[EvaluationPlatform] " << "\033[0m"
void EvaluationPlatform::Load(physics::WorldPtr _world, sdf::ElementPtr /*_sdf*/)
{
// Store the world pointer
m_world = _world;
// Listen to the update event. This event is broadcast every simulation iteration.
this->m_update_connection = event::Events::ConnectWorldUpdateBegin( boost::bind(&EvaluationPlatform::_onUpdate, this, _1 ) );
// initialize global flags
m_rethrowed = true;
m_inestimable_state = false;
m_skip_receive_result = false;
// load parameters
_initParameters( "parameters.xml" );
// ********************* //
// construct environment //
// ********************* //
this->_environmentConstruction();
// initialize logging
_initLog( "parameters.xml" );
// ********************************** //
// setup connection with depth sensor //
// ********************************** //
m_node_ptr = transport::NodePtr( new transport::Node() );
// Initialize the node with the world name
m_node_ptr->Init( m_world->GetName() );
m_publisher_ptr = m_node_ptr->Advertise< gazebo::msgs::Request >( "~/evaluation_platform/take_picture_request" );
m_resimulate_publisher_ptr = m_node_ptr->Advertise< gazebo::msgs::Request >( "~/evaluation_platform/resimulate_request" );
m_test_publisher_ptr = m_node_ptr->Advertise<gazebo::msgs::Request>( "~/evaluation_platform/GGininder" );
m_evaluation_result_publisher_ptr = m_node_ptr->Advertise< gazebo::msgs::Request >( "~/evaluation_platform/evaluation_result" );
// ************************************ //
// setup connection with pose estimator //
// ************************************ //
// subscribe to the result of PoseEstimation
m_subscriber_ptr = m_node_ptr->Subscribe( "~/pose_estimation/estimate_result",
&EvaluationPlatform::_receiveResult,
this );
// subscribe to the ended signal of PoseEstimation
m_ended_subscriber_ptr = m_node_ptr->Subscribe( "~/pose_estimation/estimation_ended",
&EvaluationPlatform::_receiveEnded,
this );
// print info
cout << COUT_PREFIX << "Seed : " << gazebo::math::Rand::GetSeed() << endl;
}
void EvaluationPlatform::DummyUpdate( const common::UpdateInfo & /*_info*/ )
{
if(dummyupdate==1)
{
//cout << COUT_PREFIX << "\033[7;32m in DummyUpdate \033[m" << endl;
// if( m_estimated_models[ i ] )
// {
// continue;
// }
//
// physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
for(int i=0;i<m_models_name.size();i++) //需要被固定的只有那些只有socket_
{
//if(m_world->GetModel(i)->GetName()=="result_visualize_socket")
// continue;
//cout<<COUT_PREFIX<<m_world->GetModel(i)->GetName()<<endl;
if( m_estimated_models[ i ] )//不要鎖住被估測到的到的工件
{
//cout<<"socket_"<<i<<"skipped"<<endl;
continue;
}
//cout<<m_world->GetModel(m_models_name[ i ])->GetName()<<endl;
m_world->GetModel(m_models_name[ i ])->SetStatic(true);
m_world->GetModel(m_models_name[ i ])->SetEnabled(false);
}
// for( unsigned int i = 0; i < m_models_name.size(); i++ )
// {
// // check if this model have been estimated
// if( m_estimated_models[ i ] )
// {
// continue;
// }
//
// physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
// cur_model->SetEnabled( false );
// cur_model->SetStatic( true );
// cur_model->SetGravityMode( false );
// cur_model->SetLinearVel( math::Vector3( 0, 0, 0 ) );
// cur_model->SetLinearAccel( math::Vector3( 0, 0, 0 ) );
// cur_model->SetAngularVel( math::Vector3( 0, 0, 0 ) );
// cur_model->SetAngularAccel( math::Vector3( 0, 0, 0 ) );
//
// vector< physics::LinkPtr > links = cur_model->GetLinks();
// for( unsigned int j = 0; j < links.size(); j++ )
// {
// links[ j ]->SetKinematic( true ); // this is important
// }
// }
}
else if(dummyupdate==0)
{
for(int i=6;i<m_world->GetModelCount();i++) // 編號6之前是我的手臂 平台 之類的東西
{
m_world->GetModel(i)->SetStatic(false);
m_world->GetModel(i)->SetEnabled(true);
}
cout << COUT_PREFIX << "\033[7;32m return to EvaluationPlatform::_onUpdate \033[m" << endl;
// for( unsigned int i = 0; i < m_models_name.size(); i++ )
// {
// physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
// cur_model->SetEnabled( true );
// cur_model->SetStatic( false );
// cur_model->SetGravityMode( true );
//
// vector< physics::LinkPtr > links = cur_model->GetLinks();
// for( unsigned int j = 0; j < links.size(); j++ )
// {
// links[ j ]->SetKinematic( true ); // this is important
// }
// }
event::Events::DisconnectWorldUpdateBegin( m_update_connection );
this->m_update_connection = event::Events::ConnectWorldUpdateBegin( boost::bind(&EvaluationPlatform::_onUpdate, this, _1 ) );
}
}
void EvaluationPlatform::_onUpdate( const common::UpdateInfo & /*_info*/ )
{
// steady counter
static double cur_time = 0.0;
static int steady_count = 0;
// start stacking time ( Real Time )
static double start_stacking_time;
static bool get_time_stamp = true;
if( get_time_stamp )
{
start_stacking_time = m_world->GetRealTime().Double();
get_time_stamp = false;
}
// check time interval
if( m_world->GetSimTime().Double() - cur_time > m_check_steady_interval )
{
// print current sim time
cout << COUT_PREFIX << "SimTime: " << m_world->GetSimTime().Double() << endl;
// reset cur_time
cur_time = m_world->GetSimTime().Double();
// check object's movement state
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
if( cur_model->GetWorldLinearVel().Distance( 0, 0, 0 ) < m_linear_vel_threshold )
{
if( cur_model->GetWorldAngularVel().Distance( 0, 0, 0 ) < 5 ) // deprecated
{
//cout << "\033[1;31m" << "object stopped!" << "\033[0m" << endl;;
}
else
{
cout << m_models_name[ i ] << endl;
cout << "angular vel : " << cur_model->GetWorldAngularVel() << endl;
steady_count = 0;
return;
}
}
else
{
cout << m_models_name[ i ] << endl;
cout << "linear vel : " << cur_model->GetWorldLinearVel().Distance( 0, 0, 0 ) << endl;
steady_count = 0;
return;
}
}
// *************************************************** //
// all objects are in steady state ( below threshold ) //
// *************************************************** //
steady_count++;
std::cout << "steady_count\tm_consecutive_steady_threshold" << std::endl;
std::cout << steady_count<<"\t"<<m_consecutive_steady_threshold << std::endl;
if( steady_count >= m_consecutive_steady_threshold )
{
// ****************** //
// get time to steady //
// ****************** //
double current_time = m_world->GetRealTime().Double();
// store time_to_steady only when re-throwing a new pile
if( m_rethrowed )
{
double time_to_steady = current_time - start_stacking_time;
// save time to steady info
string out_filename = m_log_directory + "time_to_steady";
ofstream file;
file.open( out_filename.c_str(), ios::out | ios::app );
if( file.is_open() )
{
file << time_to_steady << endl;
file.close();
}
else
{
cout << CERR_PREFIX << "Unable to open time_to_steady file" << endl;
exit( -1 );
}
m_rethrowed = false;
}
// get time stamp at next iteration
get_time_stamp = true;
// ***************************** //
// set stacking models to static //
// ***************************** //
cout << COUT_PREFIX << "object stopped!" << endl;
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
cur_model->SetEnabled( false );
cur_model->SetStatic( true );
cur_model->SetGravityMode( false );
cur_model->SetLinearVel( math::Vector3( 0, 0, 0 ) );
cur_model->SetLinearAccel( math::Vector3( 0, 0, 0 ) );
cur_model->SetAngularVel( math::Vector3( 0, 0, 0 ) );
cur_model->SetAngularAccel( math::Vector3( 0, 0, 0 ) );
vector< physics::LinkPtr > links = cur_model->GetLinks();
for( unsigned int j = 0; j < links.size(); j++ )
{
links[ j ]->SetKinematic( true ); // this is important
}
}
//**********************//
//顯示label //
//各model pose輸出到檔案 //
//*********************//
// cout << "\033[0;32;34msave workpieces' pose \033[0m" << endl;
// ofstream fout("OUT.txt");
// math::Matrix3 rot;
// math::Vector3 pos;
// for( unsigned int i = 0; i < m_models_name.size(); i++ )
// {
// physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
// rot=cur_model->GetWorldPose().rot.GetAsMatrix3();
// pos=cur_model->GetWorldPose().pos;
// pos.x/=6;
// pos.y/=6;
// pos.z=0.8;
//
//
// fout<<cur_model->GetName()<<endl;
// fout<<rot.m[0][0]<<"\t"<<rot.m[0][1]<<"\t"<<rot.m[0][2]<<"\t"<<pos.x<<endl;
// fout<<rot.m[1][0]<<"\t"<<rot.m[1][1]<<"\t"<<rot.m[1][2]<<"\t"<<pos.y<<endl;
// fout<<rot.m[2][0]<<"\t"<<rot.m[2][1]<<"\t"<<rot.m[2][2]<<"\t"<<pos.z<<endl;
// fout<<"0\t0\t0\t1\t"<<endl;
//
// stringstream int_to_string;
// int_to_string<<i;
// if(i<10)//要幫補0
// {
// m_world->GetModel("billboard0"+int_to_string.str())->SetWorldPose(math::Pose(pos,math::Quaternion(1,0,0,0)));
// m_world->GetModel("billboard0"+int_to_string.str())->SetGravityMode( false );
// m_world->GetModel("billboard0"+int_to_string.str())->SetStatic( true );
//
// }
// else
// {
// m_world->GetModel("billboard"+int_to_string.str())->SetWorldPose(math::Pose(pos,math::Quaternion(1,0,0,0)));
// m_world->GetModel("billboard"+int_to_string.str())->SetGravityMode( false );
// m_world->GetModel("billboard"+int_to_string.str())->SetStatic( true );
// }
// }
// fout.close();
// cout<<"fout.close();"<<endl;
//
// ********************************** //
// ask depth sensor to take a picture //
// ********************************** //
msgs::Request take_pic_request;
take_pic_request.set_id( 0 );
take_pic_request.set_request( "take_one_picture" );
cout << COUT_PREFIX << "take picture request\n";
while( !m_publisher_ptr->HasConnections() )
{
cout << COUT_PREFIX << "\033[1;31m" << "have no depth sensor connected!" << "\033[0m" << endl;
gazebo::common::Time::Sleep(10 );
}
//cout << COUT_PREFIX << "Take one shot request." << endl;
// ****************************************************** //
// obtain sensor pose at the time the sensor take picture //
// ****************************************************** //
m_publisher_ptr->Publish( take_pic_request );
// ****************************************************** //
// obtain sensor pose at the time the sensor take picture //
// ****************************************************** //
math::Pose sensor_model_pose = m_world->GetModel( "depth_sensor" )->GetWorldPose();
// convert math::Pose to Matrix4
math::Matrix4 sensor_model_pose_mat = sensor_model_pose.rot.GetAsMatrix4();
sensor_model_pose_mat.SetTranslate( sensor_model_pose.pos );
// obtain sensor pose ( NOTE: m_sensor_pose is different from sensor_model_pose
m_sensor_pose = sensor_model_pose_mat *
math::Quaternion( 0, - M_PI / 2, 0 ).GetAsMatrix4() *
math::Quaternion( 0, 0, - M_PI / 2 ).GetAsMatrix4();
m_wld_to_cam_mat = m_sensor_pose.Inverse();
// allow subscrber
m_skip_receive_result = false;
// ******************************** //
// disconnect with WorldUpdateBegin //
// ******************************** //
cout << COUT_PREFIX << "\033[1;35;45m exit onupdate! \033[m" << endl;
event::Events::DisconnectWorldUpdateBegin( m_update_connection );
this->m_update_connection = event::Events::ConnectWorldUpdateBegin( boost::bind(&EvaluationPlatform::DummyUpdate, this, _1 ) );
dummyupdate=1;
// reset steady counter
steady_count = 0;
}
}
}
void EvaluationPlatform::_receiveResult( ConstMsgsPoseEstimationResultPtr &_msg )
{
if( m_skip_receive_result )
{
return;
}
// check data validation
if( _msg->pose_matrix4_size() != 16 )
{
cerr << CERR_PREFIX << "error data_size of Matrix4" << endl;
return;
}
// save and print received matrix
math::Matrix4 result;
for( int j = 0; j < 4; j++ )
{
for( int i = 0; i < 4; i++ )
{
result[j][i] = _msg->pose_matrix4( i + j * 4 );
}
}
// convert millimeter to meter
result[0][3] *= 0.001;
result[1][3] *= 0.001;
result[2][3] *= 0.001;
// transform result to world coordinates
math::Matrix4 result_world = result;
result_world = m_sensor_pose * result_world;
cout << "------------------------------------------------------------" << endl;
cout << COUT_PREFIX << "Recognized Object : " << _msg->object_name() << endl;
cout << COUT_PREFIX << "Pose Estimation Result ( world coordinate ):" << endl;
cout << result_world << endl;
// ******************************************* //
// find nearest object to the estimated result //
// ******************************************* //
physics::ModelPtr cur_nearest_object;
int cur_nearest_idx = -1;
double translate_error = std::numeric_limits< double >::max();
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
double cur_dist = result_world.GetTranslation().Distance( cur_model->GetWorldPose().pos );
if( cur_dist < translate_error )
{
cur_nearest_object = cur_model;
translate_error = cur_dist;
cur_nearest_idx = i;
}
}
// handle no more object
if( !cur_nearest_object )
{
return;
}
// print out object correspond to estimation target
cout << COUT_PREFIX << "Nearest Object : " << cur_nearest_object->GetName() << endl;
math::Pose nearest_model_pose = cur_nearest_object->GetWorldPose();
math::Matrix4 nearest_model_pose_matrix4 = nearest_model_pose.rot.GetAsMatrix4();
nearest_model_pose_matrix4.SetTranslate( nearest_model_pose.pos );
cout << nearest_model_pose_matrix4 << endl;
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
//check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
//原先被鎖住的model,如果是cur_nearest_object的話 可以進入這個判斷式後解鎖
else if(m_models_name[ i ].compare(0,m_models_name[ i ].size(),cur_nearest_object->GetName())==0)
{
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
cur_model->SetEnabled( false );
cur_model->SetStatic( true );
cur_model->SetGravityMode( true );
cur_model->SetLinearVel( math::Vector3( 0, 0, 0 ) );
cur_model->SetLinearAccel( math::Vector3( 0, 0, 0 ) );
cur_model->SetAngularVel( math::Vector3( 0, 0, 0 ) );
cur_model->SetAngularAccel( math::Vector3( 0, 0, 0 ) );
vector< physics::LinkPtr > links = cur_model->GetLinks();
for( unsigned int j = 0; j < links.size(); j++ )
{
links[ j ]->SetKinematic( true ); // this is important
}
}
continue;
}
// calculate error
// 這裡的inverse應該是要將result world的座標原點移到 nearest_model_pose_matrix4
// error_matrix 的長度就直接是誤差了
// calculate error
math::Matrix4 error_matrix = nearest_model_pose_matrix4.Inverse() * result_world; // in ground_truth frame
cout << "Error Euler (degree): " << error_matrix.GetEulerRotation() * 180 / M_PI << endl;
double error_quaternion_angle;
math::Vector3 error_quaternion_axis;
error_matrix.GetRotation().GetAsAxis( error_quaternion_axis, error_quaternion_angle );
cout << "Error Quaternion Axis : " << error_quaternion_axis << endl;
cout << "Error Quaternion Angle (degree) : " << error_quaternion_angle * 180 / M_PI << endl;
cout << "Error Translation : " << error_matrix.GetTranslation() << endl;
cout << "Error Translation Length: " << error_matrix.GetTranslation().GetLength() << endl;
// ****************************** //
// visualize object's pose result //
// ****************************** //
int recognized_idx = -1;
for( uint i = 0; i < m_target_model_names.size(); i++ )
{
if( _msg->object_name().compare( 0, m_target_model_names[ i ].size(), m_target_model_names[ i ] ) == 0 )
{ // is the result_visualize for estimated object
_resultVisualize( i, result_world.GetAsPose() );
recognized_idx = i;
}
else // hide the others
{
_resultVisualize( i, math::Pose( -m_stacking_distance * 2 * (i + 1), 1, 2, 0, 0, 0 ) );
}
}
// check if recognized object is identified
if( recognized_idx < 0 )
{
cerr << CERR_PREFIX << "can't identify recognized object!" << endl;
exit( -1 );
}
// ************************************* //
// check validation of estimation result //
// ************************************* //
bool estimate_correct = false;
// check model recognition
if( cur_nearest_object->GetName().compare( 0, m_target_model_names[ recognized_idx ].size(), m_target_model_names[ recognized_idx ] ) == 0 )
{
const EvaluationCriteria &criteria = m_criteria[ recognized_idx ];
// check success criteria - translation
if( translate_error < criteria.translation_threshold )
{
cout << COUT_PREFIX << "translation_threshold: " << criteria.translation_threshold << endl;
cout << COUT_PREFIX << "quaternion_degree_threshold" << criteria.quaternion_degree_threshold << endl;
// check success criteria - rotation
if( error_quaternion_angle < criteria.quaternion_degree_threshold * M_PI / 180 )
{
estimate_correct = true;
}
else
{
if( criteria.is_cylinder_like ) // is cylinder like
{
if( abs( M_PI - error_quaternion_angle ) < criteria.quaternion_degree_threshold * M_PI / 180 )
{
estimate_correct = true;
}
else
{
float axis_bias_degree = acos( criteria.cylinder_axis.Dot( error_quaternion_axis ) );
if( axis_bias_degree < criteria.cylinder_axis_deviation_threshold ||
180 - axis_bias_degree < criteria.cylinder_axis_deviation_threshold )
{
estimate_correct = true;
}
else
{
cout << CERR_PREFIX << "axis deviation is too large" << endl;
cout << "axis deviation degree : " << axis_bias_degree << endl;
}
}
}
else //
{
// check circular symmetry
if( criteria.has_circular_symmetry )
{
float axis_bias_degree = acos( criteria.cir_sym_axis.Dot( error_quaternion_axis ) ) * 180 / M_PI;
if( axis_bias_degree < criteria.cir_sym_axis_deviation_degree ||
180 - axis_bias_degree < criteria.cir_sym_axis_deviation_degree )
{
estimate_correct = true;
}
else
{
cout << CERR_PREFIX << "Circular symmetry didn't pass" << endl;
cout << CERR_PREFIX << "axis deviation degree : " << axis_bias_degree << endl;
}
}
// check rotational symmetry
if( !estimate_correct && criteria.has_rotational_symmetry )
{
for( uint i = 0; i < criteria.rot_sym_axes.size(); i++ )
{
float axis_bias_degree = acos( criteria.rot_sym_axes[ i ].Dot( error_quaternion_axis ) ) * 180 / M_PI;
float degree_interval = 360 / criteria.rot_sym_order[ i ];
float radian_interval = degree_interval * M_PI / 180;
if( axis_bias_degree < criteria.rot_sym_axis_deviation_degree[ i ] ||
180 - axis_bias_degree < criteria.rot_sym_axis_deviation_degree[ i ] )
{
for( int j = 0; j < criteria.rot_sym_order[ i ]; j++ )
{
if( abs( error_quaternion_angle - radian_interval * j ) < criteria.rot_sym_tolerance_degree[ i ] * M_PI / 180 )
{
estimate_correct = true;
break;
}
}
if( !estimate_correct )
{
cout << CERR_PREFIX << "tolerance of rotational symmetry is too big" << endl;
}
}
else
{
cout << CERR_PREFIX << "deviation of rotational symmetry axis is too big" << endl;
cout << CERR_PREFIX << "axis deviation degree : " << axis_bias_degree << endl;
}
}
}
if( !estimate_correct ) // still not correct
{
cout << CERR_PREFIX << "Rotation error is too large" << endl;
}
}
}
}
else
{
cout << CERR_PREFIX << "Translate_error is too large" << endl;
}
}
else
{
cout << CERR_PREFIX << "Wrong model recognized!" << endl;
}
// ****************** //
// estimation logging //
// ****************** //
string error_filename = m_log_directory + "error_log";
string success_filename = m_log_directory + "success_log";
static int error_log_count = 0;
static int success_log_count = 0;
bool do_log = ( estimate_correct && m_success_logging ) || ( !estimate_correct && m_error_logging ) ? true : false;
if( do_log )
{
// save error info
ofstream file;
file.open( ( estimate_correct ? success_filename : error_filename ).c_str(), ios::out | ios::app );
if( file.is_open() )
{
file << "[" << ( estimate_correct ? success_log_count : error_log_count ) << "]" << endl;
// log estimate object
file << "@Object_Recognized:" << m_target_model_names[ recognized_idx ] << endl;
// log closest object
file << "@Closest_Object:" << cur_nearest_object->GetName() << endl;
// log error info
file << "@Error Euler (degree):" << error_matrix.GetEulerRotation() * 180 / M_PI << endl;
file << "@Error Quaternion Axis:" << error_quaternion_axis << endl;
file << "@Error Quaternion Angle (degree):" << error_quaternion_angle * 180 / M_PI << endl;
file << "@Error Translation:" << error_matrix.GetTranslation() << endl;
file << "@Error Translation Length:" << error_matrix.GetTranslation().GetLength() << endl;
// log estimated pose
file << "@Estimate_result:" << endl;
file << result_world;
// log sensor info
file << "@Sensor_Pose(not sensor model):" << endl;
file << m_sensor_pose.GetAsPose() << endl;
// log every objects
file << "@Object_Pose:" << endl;
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
file << m_models_name[ i ] << ":";
file << m_world->GetModel( m_models_name[ i ] )->GetWorldPose() << endl;
}
// log other object
unsigned int num_model = m_world->GetModelCount();
// go through every model in world
for( unsigned int i = 0; i < num_model; i++ )
{
physics::ModelPtr cur_model = m_world->GetModel( i );
if( cur_model && find( m_models_name.begin(), m_models_name.end(), cur_model->GetName() ) == m_models_name.end() )
{
file << cur_model->GetName() << ":";
file << cur_model->GetWorldPose() << endl;
}
}
file << endl;
file.close();
// counter
if( estimate_correct )
{
success_log_count++;
}
else
{
error_log_count++;
}
}
else
{
cout << CERR_PREFIX << "Unable to open file" << endl;
exit( -1 );
}
}
// ****************************** //
// save success_between_fail info //
// ****************************** //
static int success_before_fail_count = 0;
// handle inestimable_state
if( m_inestimable_state )
{
m_inestimable_state = false;
string out_filename = m_log_directory + "success_between_fail_count";
ofstream file;
file.open( out_filename.c_str(), ios::out | ios::app );
if( file.is_open() )
{
file << success_before_fail_count << endl;
file.close();
}
else
{
cout << CERR_PREFIX << "Unable to open file" << endl;
exit( -1 );
}
// reset counter
success_before_fail_count = 0;
}
// handle normal situation
if( estimate_correct )
{
success_before_fail_count++;
}
else
{
string out_filename = m_log_directory + "success_between_fail_count";
ofstream file;
file.open( out_filename.c_str(), ios::out | ios::app );
if( file.is_open() )
{
file << success_before_fail_count << endl;
file.close();
}
else
{
cout << CERR_PREFIX << "Unable to open file" << endl;
exit( -1 );
}
// reset counter
success_before_fail_count = 0;
}
// ************************ //
// estimation result handle //
// ************************ //
// send evaluation result
gazebo::msgs::Request evaluation_result_request;
if( estimate_correct )
{
evaluation_result_request.set_id( 1 );
}
else
{
evaluation_result_request.set_id( 0 );
}
evaluation_result_request.set_request( "" );
/* while( !m_evaluation_result_publisher_ptr->HasConnections() )
{
cout << "\033[1;31m" << "evaluation result signal is not connected." << "\033[0m" << endl;
gazebo::common::Time::MSleep( 10 );
}*/
m_evaluation_result_publisher_ptr->Publish( evaluation_result_request );
if( estimate_correct )
{
// hide the correctly estimated object
// 將成功的工件移走
m_estimated_models[ cur_nearest_idx ] = true;
//cur_nearest_object->SetWorldPose( math::Pose( m_stacking_distance * 2 * cur_nearest_idx, 1, 2, 0, 0, 0 ) );
//就交給arm control移走吧
//送msg給 arm control 告知最近的model
msgs::Request GGininder;
GGininder.set_id( 0 );
GGininder.set_request( cur_nearest_object->GetName() );
m_test_publisher_ptr->Publish( GGininder );
cout << COUT_PREFIX << "\033[1;31m" << "send to Arm_Control" << "\033[0m" << endl;}
else // estimation incorrect
{
// ********************* //
// resimulate after_fail //
// ********************* //
if( m_resimulate_after_fail )
{
// send resimulate request
msgs::Request resimulate_request;
resimulate_request.set_id( 0 );
resimulate_request.set_request( "resimulate" );
while( !m_resimulate_publisher_ptr->HasConnections() )
{
cout << COUT_PREFIX << "\033[1;31m" << "no connection to resimulate request!" << "\033[0m" << endl;
gazebo::common::Time::MSleep( 10 );
}
cout << COUT_PREFIX << "Resimulate request..." << endl;
m_resimulate_publisher_ptr->Publish( resimulate_request );
// fake all models are estimated, so the simulation will restart
m_estimated_models.assign( m_estimated_models.size(), true );
//this->_receiveEnded( ConstMsgsRequestPtr() );
// skip this function
m_skip_receive_result = true;
}
}
}
void EvaluationPlatform::_receiveEnded( ConstMsgsRequestPtr &_msg )
{
cout << COUT_PREFIX << "Estimation process finished." << endl;
// ********************************************************************** //
// check whether unestimate count have changed comparing to previous loop //
// ********************************************************************** //
static uint prev_unestimate_count = m_stacking_width * m_stacking_height * m_stacking_layers;
static uint unchange_count = 0;
uint unestimate_count = 0;
for( uint i = 0; i < m_models_name.size(); i++ )
{
// unestimate
if( !m_estimated_models[ i ] )
{
unestimate_count++;
}
}
unchange_count = unestimate_count != 0 && unestimate_count == prev_unestimate_count ? unchange_count + 1 : 0;
prev_unestimate_count = unestimate_count;
// ************************* //
// handle unchange_count >= 3 //
// ************************* //
uint unchange_count_threshold = 3;
if( unchange_count >= unchange_count_threshold )
{
m_inestimable_state = true;
// reset variables
prev_unestimate_count = m_stacking_width * m_stacking_height * m_stacking_layers;
// save current models configurations
string inestimable = m_log_directory + "inestimable_log";
static uint inestimable_count = 0;
ofstream file;
file.open( inestimable.c_str(), ios::out | ios::app );
if( file.is_open() )
{
file << "[" << inestimable_count << "]" << endl;
// log estimate object
file << "@Object_Recognized:" << m_target_model_names[ 0 ] << endl;
// log closest object
file << "@Closest_Object:" << "result_visualize_" + m_target_model_names[ 0 ] << endl;
// log error info
file << "@Error Euler (degree):" << "0 0 0" << endl;
file << "@Error Quaternion Axis:" << math::Vector3( 0, 0, 0 ) << endl;
file << "@Error Quaternion Angle (degree):" << 0 << endl;
file << "@Error Translation:" << math::Vector3( 0, 0, 0 ) << endl;
file << "@Error Translation Length:" << 0 << endl;
// log estimated pose
file << "@Estimate_result:" << endl;
file << math::Matrix4( 1, 0, 0, -1,
0, 1, 0, 1,
0, 0, 1, 2,
0, 0, 0, 1 );
// log sensor info
file << "@Sensor_Pose(not sensor model):" << endl;
file << m_sensor_pose.GetAsPose() << endl;
// log every objects
file << "@Object_Pose:" << endl;
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
file << m_models_name[ i ] << ":";
file << m_world->GetModel( m_models_name[ i ] )->GetWorldPose() << endl;
}
// log other object
unsigned int num_model = m_world->GetModelCount();
// go through every model in world
for( unsigned int i = 0; i < num_model; i++ )
{
physics::ModelPtr cur_model = m_world->GetModel( i );
if( cur_model && find( m_models_name.begin(), m_models_name.end(), cur_model->GetName() ) == m_models_name.end() )
{
file << cur_model->GetName() << ":";
file << cur_model->GetWorldPose() << endl;
}
}
file << endl;
file.close();
inestimable_count++;
}
else
{
cout << CERR_PREFIX << "Unable to open file" << endl;
exit( -1 );
}
// send evaluation result
gazebo::msgs::Request evaluation_result_request;
evaluation_result_request.set_id( 2 ); // inestimable
evaluation_result_request.set_request( "" );
m_evaluation_result_publisher_ptr->Publish( evaluation_result_request );
}
// ******** //
//
// ******** //
// if all objects have been estimated, reset all models
if( unestimate_count == 0 || unchange_count >= unchange_count_threshold )
{
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
cur_model->SetEnabled( true );
cur_model->SetStatic( false );
cur_model->SetGravityMode( true );
vector< physics::LinkPtr > links = cur_model->GetLinks();
for( unsigned int j = 0; j < links.size(); j++ )
{
links[ j ]->SetKinematic( false ); // this is important
}
}
// reset m_estimated_models
m_estimated_models.assign( m_models_name.size(), false );
// re-throw objects
this->_throwObjects();
// set m_rethrowed flag
m_rethrowed = true;
// reset variables
if( unchange_count >= 5 )
{
unchange_count = 0;
}
}
else
{
// reactivate the objects staking simulation
for( unsigned int i = 0; i < m_models_name.size(); i++ )
{
// check if this model have been estimated
if( m_estimated_models[ i ] )
{
continue;
}
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i ] );
cur_model->SetEnabled( true );
cur_model->SetStatic( false );
cur_model->SetGravityMode( true );
vector< physics::LinkPtr > links = cur_model->GetLinks();
for( unsigned int j = 0; j < links.size(); j++ )
{
links[ j ]->SetKinematic( false ); // this is important
}
}
}
// hide all result_visualize
for( uint i = 0; i < m_target_model_names.size(); i++ )
{
_resultVisualize( i, math::Pose( -m_stacking_distance * 2 * (i + 1), 1, 2, 0, 0, 0 ) );
}
// *************************************** //
// reconnect the world update begin events //
// *************************************** //
//this->m_update_connection = event::Events::ConnectWorldUpdateBegin( boost::bind(&EvaluationPlatform::_onUpdate, this, _1 ) );
dummyupdate=0;
cout << COUT_PREFIX << "\033[1;35;45m receive END! \033[m" << endl;
}
void EvaluationPlatform::_environmentConstruction()
{
// starting position of the box
m_box_center = math::Vector3( 0, 0, 0 );
m_stacking_center = math::Vector3( 0, 0, m_box_size.z + m_box_wall_thickness + m_throwing_height ) +
math::Vector3( m_box_center.x, m_box_center.y, 0 );
// ************* //
// construct bin //
// ************* //
sdf::SDF box_sdf;
// read ascii file into string
string filename = m_box_model_sdf_file_path;
std::string contents;
// method from http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
std::ifstream box_in( filename.c_str(), std::ios::in );
if( box_in )
{
box_in.seekg(0, std::ios::end);
contents.resize(box_in.tellg());
box_in.seekg(0, std::ios::beg);
box_in.read(&contents[0], contents.size());
box_in.close();
}
// set box sdf from string
box_sdf.SetFromString( contents );
// calculate box parameters
float wall_thickness = m_box_wall_thickness;
math::Vector3 bottom_size( m_box_size.x, m_box_size.y, wall_thickness );
math::Pose bottom_pose( 0, 0, wall_thickness / 2, 0, 0, 0 );
math::Vector3 front_size( m_box_size.x + 2 * wall_thickness, wall_thickness, m_box_size.z + wall_thickness );
math::Pose front_pose( 0, m_box_size.y / 2 + wall_thickness / 2, front_size.z / 2, 0, 0, 0 );
math::Vector3 back_size( m_box_size.x + 2 * wall_thickness, wall_thickness, m_box_size.z + wall_thickness );
math::Pose back_pose( 0, -(m_box_size.y / 2 + wall_thickness / 2), back_size.z / 2, 0, 0, 0 );
math::Vector3 left_size( wall_thickness, m_box_size.y, m_box_size.z + wall_thickness );
math::Pose left_pose( -(m_box_size.x / 2 + wall_thickness / 2), 0, left_size.z / 2, 0, 0, 0 );
math::Vector3 right_size( wall_thickness, m_box_size.y, m_box_size.z + wall_thickness );
math::Pose right_pose( m_box_size.x / 2 + wall_thickness / 2, 0, right_size.z / 2, 0, 0, 0 );
// resize the box as specified in parameters file
sdf::ElementPtr box_link = box_sdf.root->GetElement( "model" )->GetElement( "link" );
// set bottom box
sdf::ElementPtr box_collision = box_link->GetElement( "collision" );
sdf::ElementPtr box_visual = box_link->GetElement( "visual" );
box_collision->GetElement( "pose" )->Set( bottom_pose );
box_collision->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( bottom_size );
box_visual->GetElement( "pose" )->Set( bottom_pose );
box_visual->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( bottom_size );
// set front box
box_collision = box_collision->GetNextElement( "collision" );
box_visual = box_visual->GetNextElement( "visual" );
box_collision->GetElement( "pose" )->Set( front_pose );
box_collision->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( front_size );
box_visual->GetElement( "pose" )->Set( front_pose );
box_visual->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( front_size );
// set back box
box_collision = box_collision->GetNextElement( "collision" );
box_visual = box_visual->GetNextElement( "visual" );
box_collision->GetElement( "pose" )->Set( back_pose );
box_collision->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( back_size );
box_visual->GetElement( "pose" )->Set( back_pose );
box_visual->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( back_size );
// set left box
box_collision = box_collision->GetNextElement( "collision" );
box_visual = box_visual->GetNextElement( "visual" );
box_collision->GetElement( "pose" )->Set( left_pose );
box_collision->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( left_size );
box_visual->GetElement( "pose" )->Set( left_pose );
box_visual->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( left_size );
// set right box
box_collision = box_collision->GetNextElement( "collision" );
box_visual = box_visual->GetNextElement( "visual" );
box_collision->GetElement( "pose" )->Set( right_pose );
box_collision->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( right_size );
box_visual->GetElement( "pose" )->Set( right_pose );
box_visual->GetElement( "geometry" )->GetElement( "box" )->GetElement( "size" )->Set( right_size );
// insert box model sdf to world
m_world->InsertModelSDF( box_sdf );
// ************************************ //
// read multiple target model sdf files //
// ************************************ //
// store multiple target model sdfs //
vector< sdf::SDF > model_sdfs;
vector< sdf::ElementPtr > sdf_model_elements;
vector< sdf::ParamPtr > sdf_model_names;
vector< sdf::ParamPtr > sdf_model_poses;
for( uint i = 0; i < m_target_model_sdf_file_paths.size(); i++ )
{
sdf::SDF cur_sdf;
// read ascii file into string
filename = m_target_model_sdf_file_paths[ i ];
// method from http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
std::ifstream in( filename.c_str(), std::ios::in );
if( in )
{
in.seekg(0, std::ios::end);
contents.resize(in.tellg());
in.seekg(0, std::ios::beg);
in.read(&contents[0], contents.size());
in.close();
}
// set model sdf from string
cur_sdf.SetFromString( contents );
// store current target model sdf
model_sdfs.push_back( cur_sdf );
// do not use cur_sdf afterwards
// get template SDF's model name pointer
sdf::ElementPtr model_element = model_sdfs.back().root->GetElement( "model" );
sdf::ParamPtr model_name;
if( model_element->HasAttribute( "name" ) )
{
model_name = model_element->GetAttribute( "name" );
m_target_model_names.push_back( model_name->GetAsString() );
sdf_model_elements.push_back( model_element );
sdf_model_names.push_back( model_name );
}
else
{
gzerr << "weird result occured ( element[model] doesn't have attribute[name]" << endl;
return;
}
sdf::ElementPtr pose_element;
sdf::ParamPtr model_pose;
if( model_element->HasElement( "pose" ) )
{
pose_element = model_element->GetElement( "pose" );
model_pose = pose_element->GetValue();
sdf_model_poses.push_back( model_pose );
}
else
{
gzerr << "no model pose in model file" << endl;
return;
}
}
// ************************** //
// create a handful of object //
// ************************** //
// store each model count
vector< int > each_model_counts( m_target_model_names.size(), 0 );
// create random pose
int width = m_stacking_width;
int height = m_stacking_height;
int layers = m_stacking_layers;
for( int j = 0; j < layers ; j++ )
{
for( int i = 0; i < width * height; i++ )
{
// current object's position
math::Vector3 position = m_stacking_center + j * math::Vector3( 0, 0, m_stacking_distance );
// x position
if( width % 2 == 0 ) // even number
{
position += ( ( i % width ) - width / 2 + 0.5 ) * math::Vector3( m_stacking_distance, 0, 0 );
}
else // odd number
{
position += ( ( i % width ) - width / 2 ) * math::Vector3( m_stacking_distance, 0, 0 );
}
// y position
if( height % 2 == 0 ) // even number
{
position += ( ( i / width ) - height / 2 + 0.5 ) * math::Vector3( 0, m_stacking_distance, 0 );
}
else // odd number
{
position += ( ( i / width ) - height / 2 ) * math::Vector3( 0, m_stacking_distance, 0 );
}
// randomize the pose
int angleIndex = math::Rand::GetIntUniform( 0, 7 ); //0~7 0~359 0=0 ; 1=45 ... 7=315
int axisIndex = math::Rand::GetIntUniform( 0, 1 ); //0 = x-axis ; 1 = y-axis
math::Vector3 rotate_axis;
if( axisIndex == 1 )
rotate_axis = math::Vector3( 0, 1, 0 );
else
rotate_axis = math::Vector3( 1, 0, 0 );
math::Angle angle;
angle.SetFromDegree( 45 * angleIndex );
math::Quaternion orientation = math::Quaternion( rotate_axis, angle.Degree() );
math::Vector3 euler = orientation.GetAsEuler();
// randomly choose one of the target models according to the proportion
int total_proportion = std::accumulate( m_target_model_proportions.begin(), m_target_model_proportions.end(), 0 );
int cur_idx = math::Rand::GetIntUniform( 0, total_proportion - 1 );
int cur_proportion = 0;
int chose_model_idx = -1;
for( uint idx = 0; idx < m_target_model_proportions.size(); idx++ )
{
cur_proportion += m_target_model_proportions[ idx ];
if( cur_idx <= cur_proportion - 1 )
{
chose_model_idx = idx;
break;
}
}
if( chose_model_idx < 0 || chose_model_idx >= (int)m_target_model_names.size() )
{
cerr << CERR_PREFIX << "error when choosing random target model" << endl;
exit( -1 );
}
// create models from SDF template
stringstream ss;
ss << each_model_counts[ chose_model_idx ];
each_model_counts[ chose_model_idx ]++;
string cur_model_name = m_target_model_names[ chose_model_idx ] + "_" + ss.str();
sdf_model_names[ chose_model_idx ]->Set( cur_model_name );
sdf_model_poses[ chose_model_idx ]->Set( math::Pose( position.x, position.y, position.z, euler.x, euler.y, euler.z ) );
m_world->InsertModelSDF( model_sdfs[ chose_model_idx ] );
m_models_name.push_back( cur_model_name );
}
}
// initialize some variables
m_estimated_models.assign( m_models_name.size(), false );
// *********************************************** //
// create result visualizer for every target model //
// *********************************************** //
for( uint i = 0; i < m_target_model_names.size(); i++ )
{
// remove physics ( inertial, collision, etc.
sdf::ElementPtr link_element = sdf_model_elements[ i ]->GetElement( "link" );
if( link_element->HasElement( "inertial" ) )
{
link_element->RemoveChild( link_element->GetElement( "inertial" ) );
}
if( link_element->HasElement( "collision" ) )
{
link_element->RemoveChild( link_element->GetElement( "collision" ) );
}
// set object to kinematics
if( !link_element->HasElement( "gravity" ) )
{
link_element->AddElement( "gravity" );
}
link_element->GetElement( "gravity" )->GetValue()->Set( false );
// set object to kinematics
if( !link_element->HasElement( "kinematic" ) )
{
link_element->AddElement( "kinematic" );
}
link_element->GetElement( "kinematic" )->GetValue()->Set( true );
// set material
sdf::ElementPtr visual = link_element->GetElement( "visual" );
// handle multiple visuals
while( visual )
{
// TODO : according to sdf API, should remove <script> element before color elements can be effective
if( !visual->HasElement( "material" ) )
{
visual->AddElement( "material" );
}
sdf::ElementPtr material = visual->GetElement( "material" );
if( !material->HasElement( "ambient" ) )
{
material->AddElement( "ambient" );
}
if( !material->HasElement( "diffuse" ) )
{
material->AddElement( "diffuse" );
}
if( !material->HasElement( "specular" ) )
{
material->AddElement( "specular" );
}
material->GetElement( "ambient" )->GetValue()->Set( sdf::Color( 0, 1, 0, 1 ) );
material->GetElement( "diffuse" )->GetValue()->Set( sdf::Color( 0, 1, 0, 1 ) );
material->GetElement( "specular" )->GetValue()->Set( sdf::Color( 0, 0.5, 0, 1 ) );
// get next visual element
visual = visual->GetNextElement( "visual" );
}
// insert result visualize
sdf_model_names[ i ]->Set( "result_visualize_" + m_target_model_names[ i ] );
sdf_model_poses[ i ]->Set( math::Pose( -m_stacking_distance * 2 * (i + 1), 1, 2, 0, 0, 0 ) );
m_world->InsertModelSDF( model_sdfs[ i ] );
}
cout << COUT_PREFIX << "creation complete" << endl;
}
void EvaluationPlatform::_throwObjects()
{
// create random pose
int width = m_stacking_width;
int height = m_stacking_height;
int layers = m_stacking_layers;
for( int j = 0; j < layers ; j++ )
{
for( int i = 0; i < width * height; i++ )
{
// current object's position
math::Vector3 position = m_stacking_center + j * math::Vector3( 0, 0, m_stacking_distance );
// x position
if( width % 2 == 0 ) // even number
{
position += ( ( i % width ) - width / 2 + 0.5 ) * math::Vector3( m_stacking_distance, 0, 0 );
}
else // odd number
{
position += ( ( i % width ) - width / 2 ) * math::Vector3( m_stacking_distance, 0, 0 );
}
// y position
if( height % 2 == 0 ) // even number
{
position += ( ( i / width ) - height / 2 + 0.5 ) * math::Vector3( 0, m_stacking_distance, 0 );
}
else // odd number
{
position += ( ( i / width ) - height / 2 ) * math::Vector3( 0, m_stacking_distance, 0 );
}
// randomize the pose
int angleIndex = math::Rand::GetIntUniform( 0, 7 ); //0~7 0~359 0=0 ; 1=45 ... 7=315
int axisIndex = math::Rand::GetIntUniform( 0, 1 ); //0 = x-axis ; 1 = y-axis
math::Vector3 rotate_axis;
if( axisIndex == 1 )
rotate_axis = math::Vector3( 0, 1, 0 );
else
rotate_axis = math::Vector3( 1, 0, 0 );
math::Angle angle;
angle.SetFromDegree( 45 * angleIndex );
math::Quaternion orientation = math::Quaternion( rotate_axis, angle.Degree() );
math::Vector3 euler = orientation.GetAsEuler();
// set pose
physics::ModelPtr cur_model = m_world->GetModel( m_models_name[ i + width * height * j ] );
cur_model->SetWorldPose( math::Pose( position.x, position.y, position.z, euler.x, euler.y, euler.z ) );
}
}
}
void EvaluationPlatform::_resultVisualize( const int _model_idx, const math::Pose _pose )
{
physics::ModelPtr visual_model = m_world->GetModel( "result_visualize_" + m_target_model_names[ _model_idx ] );
if( visual_model )
{
visual_model->SetWorldPose( _pose );
}
else
{
cout << CERR_PREFIX << "Model : result_visualize not ready yet" << endl;
}
}
void EvaluationPlatform::_initParameters( const std::string &_filename )
{
// ************************* //
// read parameters from file //
// ************************* //
try
{
using namespace boost::property_tree;
// read parameters file
ptree pt;
read_xml( _filename, pt );
// read attributes parameters
m_resimulate_after_fail = pt.get< bool >( "evaluation_platform.attribute.resimulate_after_fail", false );
// ************************ //
// read stacking parameters //
// ************************ //
m_box_model_sdf_file_path = pt.get< string >( "evaluation_platform.stacking.box_model_sdf_file_path", string() );
_optimizePathFromXML( m_box_model_sdf_file_path );
m_box_size = pt.get< math::Vector3 >( "evaluation_platform.stacking.box_size", math::Vector3( 0.21, 0.16, 0.08 ) );
m_box_wall_thickness = pt.get< float >( "evaluation_platform.stacking.box_wall_thickness", 0.02f );
// load target models parameters
ptree child_pt = pt.get_child( "evaluation_platform.stacking" );
string template_path = "target_model_";
for( int i = 0; true; i++ )
{
stringstream ss;
ss << i;
string key_name = template_path + ss.str();
if( child_pt.find( key_name ) == child_pt.not_found() )
{
break;
}
ptree cur_pt = child_pt.get_child( key_name );
int cur_proportion = cur_pt.get< int >( "proportion", 0 );
if( cur_proportion > 0 )
{
string sdf_file_path = cur_pt.get< string >( "sdf_file_path", string() );
_optimizePathFromXML( sdf_file_path );
m_target_model_sdf_file_paths.push_back( sdf_file_path );
cout<<"OOO"<<sdf_file_path<<endl;
m_target_model_proportions.push_back( cur_proportion );
// extract evaluation criteria
EvaluationCriteria criteria;
criteria.translation_threshold = cur_pt.get< float >( "translation_threshold", 0.0025 );
criteria.quaternion_degree_threshold = cur_pt.get< float >( "quaternion_degree_threshold", 10 );
// rotational symmetry
criteria.has_rotational_symmetry = cur_pt.get< bool >( "rotational_symmetry.<xmlattr>.enable", false );
if( criteria.has_rotational_symmetry )
{
ptree rot_pt = cur_pt.get_child( "rotational_symmetry" );
// extract rotational symmetry axes
for( int idx = 0; true; idx++ )
{
stringstream ss;
ss << idx;
string axis_name = "axis_" + ss.str();
if( rot_pt.find( axis_name ) == rot_pt.not_found() )
{
break;
}
ptree cur_pt = rot_pt.get_child( axis_name );
int order = cur_pt.get< int >( "order", -987654 );
float tolerance_degree = cur_pt.get< float >( "tolerance_degree", -987654 );
float axis_deviation_degree = cur_pt.get< float >( "axis_deviation_threshold", -987654 );
// check validation of rotational symmetry parameters
if( order == -987654||
tolerance_degree == -987654 ||
axis_deviation_degree == -987654 )
{
cerr << CERR_PREFIX << "problem in (" << key_name << "," << axis_name << ")" << endl;
continue;
}
if( order < 2 )
{
cerr << CERR_PREFIX << "order of rotational symmetry is not valid (" << key_name << "," << axis_name << ")" << endl;
cerr << "\t" << "should be bigger than 2 " << endl;
continue;
}
if( tolerance_degree < 0 || axis_deviation_degree < 0 )
{
cerr << CERR_PREFIX << "tolerance_degree and axis deviation should be bigger than 0 (" << key_name << "," << axis_name << ")" << endl;
continue;
}
// save cur rotational symmetric axis
math::Vector3 cur_axis = cur_pt.get< math::Vector3 >( "<xmlattr>.axis", math::Vector3( 0, 0, 0 ) );
if( cur_axis == math::Vector3( 0, 0, 0 ) )
{
cerr << CERR_PREFIX << "problem with the rotational axis (" << key_name << "," << axis_name << ")" << endl;
continue;
}
cur_axis = cur_axis.Normalize();
criteria.rot_sym_axes.push_back( cur_axis );
criteria.rot_sym_order.push_back( order );
criteria.rot_sym_tolerance_degree.push_back( tolerance_degree );
criteria.rot_sym_axis_deviation_degree.push_back( axis_deviation_degree );
}
// check if any axis is extracted, if not, set "has_rotational_symmetry" to false
if( criteria.rot_sym_axes.size() == 0 )
{
criteria.has_rotational_symmetry = false;
}
}
// circular symmetry
criteria.has_circular_symmetry = cur_pt.get< bool >( "circular_symmetry.<xmlattr>.enable", false );
if( criteria.has_circular_symmetry )
{
ptree cir_pt = cur_pt.get_child( "circular_symmetry" );
// extract circular symmetry axis ( should only be one axis
criteria.cir_sym_axis = cir_pt.get< math::Vector3 >( "axis", math::Vector3( 0, 0, 0 ) );
criteria.cir_sym_axis_deviation_degree = cir_pt.get< float >( "axis_deviation_threshold", -987654 );
if( criteria.cir_sym_axis == math::Vector3( 0, 0, 0 ) || criteria.cir_sym_axis_deviation_degree < 0 )
{
cerr << CERR_PREFIX << "problem with the circular symmetry (" << key_name << ")" << endl;
criteria.has_circular_symmetry = false;
}
criteria.cir_sym_axis = criteria.cir_sym_axis.Normalize();
}
// cylinder like evaluation criteria
criteria.is_cylinder_like = cur_pt.get< bool >( "cylinder_like.<xmlattr>.enable", false );
if( criteria.is_cylinder_like )
{
ptree cyl_pt = cur_pt.get_child( "cylinder_like" );
// extract circular symmetry axis ( should only be one axis
criteria.cylinder_axis = cyl_pt.get< math::Vector3 >( "cylinder_axis", math::Vector3( 0, 0, 0 ) );
criteria.cylinder_axis_deviation_threshold = cyl_pt.get< float >( "axis_deviation_threshold", -987654 );
if( criteria.cylinder_axis == math::Vector3( 0, 0, 0 ) || criteria.cylinder_axis_deviation_threshold < 0 )
{
cerr << CERR_PREFIX << "problem with the cylinder_like (" << key_name << ")" << endl;
criteria.is_cylinder_like = false;
}
criteria.cylinder_axis = criteria.cylinder_axis.Normalize();
}
// push back criteria
m_criteria.push_back( criteria );
}
}
for( uint i = 0; i < m_target_model_proportions.size(); i++ )
{
cout << "target model " << i << " :" << endl;
cout << "\t" << "sdf_file_path : " << m_target_model_sdf_file_paths[ i ] << endl;
cout << "\t" << "proportion : " << m_target_model_proportions[ i ] << endl;
cout << m_criteria[ i ] << endl;
}
// steady parameters
m_check_steady_interval = pt.get< double >( "evaluation_platform.stacking.check_steady_interval", 0.1 );
m_consecutive_steady_threshold = pt.get< int >( "evaluation_platform.stacking.consecutive_steady_threshold", 5 );
m_linear_vel_threshold = pt.get< double >( "evaluation_platform.stacking.linear_vel_threshold", 0.03 );
// stacking parameters
m_stacking_width = pt.get< int >( "evaluation_platform.stacking.width", 3 );
m_stacking_height = pt.get< int >( "evaluation_platform.stacking.height", 3 );
m_stacking_layers = pt.get< int >( "evaluation_platform.stacking.layers", 1 );
m_stacking_distance = pt.get< float >( "evaluation_platform.stacking.distance_between_objects", 0.07 );
m_throwing_height = pt.get< float >( "evaluation_platform.stacking.throwing_height", 0.15 );
// read log parameters
m_log_directory = pt.get< string >( "evaluation_platform.log.path", "evaluation_log" );
m_error_logging = pt.get< bool >( "evaluation_platform.log.error_logging", true );
m_success_logging = pt.get< bool >( "evaluation_platform.log.success_logging", false );
}
catch (...)
{
std::cerr << "[ERROR] Cannot load the parameter file!" << std::endl;
exit( -1 );
}
}
void EvaluationPlatform::_initLog( const std::string &_param_filename )
{
// ****************************** //
// create directories for logging //
// ****************************** //
_optimizePathFromXML( m_log_directory );
if( *( m_log_directory.end() - 1 ) != '/' ) // check whether last char is '/'
{
// if not, add '/' to the end
m_log_directory.push_back( '/' );
}
boost::filesystem::create_directory( m_log_directory );
stringstream ss;
ss << gazebo::math::Rand::GetSeed();
// time
m_log_directory += boost::posix_time::to_iso_string( boost::posix_time::second_clock::local_time() ) + "_";
// seed
m_log_directory += ss.str();
// add model name in directory
for( uint i = 0; i < m_target_model_names.size(); i++ )
{
if( m_target_model_proportions[ i ] > 0 )
{
m_log_directory += "_" + m_target_model_names[ i ];
}
}
// add total objects in direcotry path
ss.clear();
ss.str( "" );
ss << m_stacking_width * m_stacking_height * m_stacking_layers;
m_log_directory += "_" + ss.str();
m_log_directory += "/";
boost::filesystem::create_directory( m_log_directory );
// ************************************* //
// copy parameters file to log directory //
// ************************************* //
// boost::filesystem::copy_file( _param_filename, m_log_directory + _param_filename );
}
void EvaluationPlatform::_optimizePathFromXML( string &_path )
{
while( *_path.begin() == ' ' ) // check if there is ' ' in the beginning
{
_path.erase( _path.begin() );
}
while( *( _path.end() - 1 ) == ' ' ) // check if there is ' ' in the end
{
_path.erase( _path.end() - 1 );
}
}
|
1392a3faae660e662c1b165e8f24ee952a028ed7 | 349637addf241283ae52fc08e15be5ddbf77e892 | /CompilerBookTest/CompilerBookTest/Modelo/Lexico/Token.h | da37bb22672fc625ac6b33935a613a3fd265cc21 | [] | no_license | LarenaCode/CompilerBookTests | e882fed6b1ce48bc2cfa87f5f3dfa362cdcf6182 | c1095b59bbd93e1a81387cb321d16860e19a0602 | refs/heads/master | 2020-07-02T18:35:56.441726 | 2019-08-19T06:02:46 | 2019-08-19T06:02:46 | 201,624,321 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | h | Token.h | #pragma once
namespace Enumerados {
enum class Token {
ALIGNAS = 256, ALIGNOF = 257, AND = 258, AND_EQ = 259, ASM = 260,
ATOMIC_CANCEL = 261, ATOMIC_COMMIT = 262, ATOMIC_NOEXCEPT = 267,
AUTO = 268, BITAND = 269, BITOR = 270, BOOL = 271, BREAK = 272,
CASE = 273, CATCH = 274, CHAR8_T = 275, CHAR16_T = 276, CHAR32_T = 277,
CLASS = 278, COMPL = 279, CONCEPT = 280, CONST = 281, CONSTEVAL = 282,
CONSTEXPR = 283, CONST_CAST = 284, CONTINUE = 285, CO_AWAIT = 286,
CO_RETURN = 287, CO_YIELD = 288, DECLTYPE = 289, DEFAULT = 290, DELETE = 291,
DO = 292, DOUBLE = 293, DYNAMIC_CAST = 294, ELSE = 295, ENUM = 296, EXPLICIT = 297,
EXPORT = 298, EXTERN = 299, FALSE = 300, FLOAT = 301, FOR = 302, FRIEND = 303,
GOTO = 304, IF = 305, INLINE = 306, INT = 307, LONG = 308, MUTABLE = 309, NAMESPACE = 310,
NEW = 311, NOEXCEPT = 312, NOT = 313, NOT_EQ = 314, PRIVATE = 315, PROTECTED = 316,
PUBLIC = 317, REFLEXPR = 318, REGISTER = 319, REINTERPRET_CAST = 320,
REQUIRES = 321, RETURN = 322, SHORT = 323, SIGNED = 324, SIZEOF = 325, STATIC = 3226,
STATIC_ASSERT = 237, STATIC_CAST = 328, STRUCT = 329, SWITCH = 330,
SYNCHRONIZED = 331, TEMPLATE = 332, THIS = 333, THREAD_LOCAL = 334, THROW = 335,
TRUE = 336, TRY = 337, TYPEDEF = 338, TYPEID = 339, TYPENAME = 340, UNION = 341,
UNSIGNED = 342, USING = 343, VIRTUAL = 344, VOID = 345, VOLATILE = 346, WCHAR_T = 347,
WHILE = 348, XOR = 349, XOR_EQ = 350, OVERRIDE = 351, FINAL = 352, IMPORT = 353,
MODULE = 354, TRANSACTION_SAFE = 355, TRANSACTION_SAFE_DYNAMIC = 356,
ID = 500,
OP_ASIGN = 501,
OP_LOGICO = 502, OP_MAT = 503, OP_MEM_ACCESS = 504
};
}
class Token
{
public:
Token(Enumerados::Token codigo) {
_codigo = codigo;
};
~Token() {
};
Enumerados::Token getCodigo() {
return _codigo;
};
private:
Enumerados::Token _codigo;
};
|
cf61f5a2c06c086f1ba5476e8f51f99af7a9f3db | 0bba390cffc1d0e492df12d4912b83b7b85bb97b | /YU.cpp | fbc13f5f0b9ba851c203b6133f7a5a6920b78af7 | [] | no_license | 201524508/FileProcessing | 43f92a5beb363724e7acec93c5c87e2d17951b3a | 4fcec3d95e9dff8e3cbe2404fcf15f0fdc0fdd65 | refs/heads/master | 2021-01-20T00:48:14.789740 | 2017-06-02T00:42:28 | 2017-06-02T00:42:28 | 89,192,727 | 0 | 0 | null | 2017-04-24T03:11:51 | 2017-04-24T03:11:51 | null | UHC | C++ | false | false | 6,181 | cpp | YU.cpp | #include <iostream>
#include <direct.h>
#include <Windows.h>
#include <shellapi.h>
#include <atlstr.h>
#include <string>
#include <tchar.h>
#include <io.h>
using namespace std;
int CopyDir(TCHAR* src, TCHAR* dest); //directory 복사
int updir(TCHAR* src, TCHAR* dest); //업데이트 - 에러(무한루프)
int UpDataTime(TCHAR* aaa); //파일 시간
int _tmain(int argc, TCHAR *argv[]) {
if (argc != 3) {
cout << "error!\n";
return 1;
}
TCHAR* src = argv[1]; //source path
TCHAR* dest = argv[2]; //destination path
if (!CreateDirectory((LPCWSTR)dest, NULL)) { //directory 생성
int n = GetLastError();
if (n == ERROR_ALREADY_EXISTS) { //존재하는 directory -> 업데이트
cout << "exist directory\n";
updir(src, dest);
}
else if (n == ERROR_PATH_NOT_FOUND) { //잘못된 path
cout << "error for path\n";
return 1;
}
else {
cout << "error for create directory\n";
return 1;
}
}
else { //directory가 생성되면
int nD = 0;
nD = CopyDir(src, dest); //directory 복사
if (nD == 0) {
cout << "complete copy directory\n";
}
else {
cout << "failed copy\n";
return 1;
}
}
return 0;
}
int CopyDir(TCHAR* src, TCHAR* dest) { //directory 복사
int result = 1;
TCHAR* src_path = new TCHAR[_tcslen(src) + 2](); //source path
TCHAR* dest_path = new TCHAR[_tcslen(dest) + 2](); //destination path
/*path 끝 2자리는 NULL 문자*/
_tcscat(src_path, src);
_tcscat(dest_path, dest);
/*source directory를 통째로 destination path에 복사*/
SHFILEOPSTRUCT sf;
sf.hwnd = NULL;
sf.wFunc = FO_COPY;
sf.pFrom = (PCZZWSTR)src_path;
sf.pTo = (PCZZWSTR)dest_path;
sf.fFlags = FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT;
sf.fAnyOperationsAborted = false;
sf.hNameMappings = NULL;
sf.lpszProgressTitle = NULL;
result = SHFileOperation(&sf); //success : 0, non-success : !0
cout << result << endl;
return result;
}
int updir(TCHAR* src, TCHAR* dest) { //수정된 부분 업데이트 - 에러(무한루프)
cout << src<<endl;
cout << dest << endl;
int result = 1;
WIN32_FIND_DATA fd_s;
WIN32_FIND_DATA fd_d;
HANDLE hf_s = FindFirstFile(src, &fd_s);
HANDLE hf_d = FindFirstFile(dest, &fd_d);
if (hf_s == INVALID_HANDLE_VALUE || hf_d == INVALID_HANDLE_VALUE) {
//_tprintf(TEXT("1 %s\n"), fd_s.cFileName);
//_tprintf(TEXT("2 %s\n"), fd_d.cFileName);
cout << "FindFirstFile failed "<< GetLastError()<<endl;
return result;
}
if (GetFileAttributes((LPCWSTR)src) == FILE_ATTRIBUTE_DIRECTORY && GetFileAttributes((LPCWSTR)dest) == FILE_ATTRIBUTE_DIRECTORY) { //src, dest가 폴더
TCHAR* n_src = new TCHAR[MAX_PATH];
TCHAR* n_dest = new TCHAR[MAX_PATH];
_tcscpy(n_src, src);
_tcscpy(n_dest, dest);
//_tprintf(TEXT("5 %s\n"), n_src);
//_tprintf(TEXT("6 %s\n"), n_dest);
updir(n_src, n_dest);
}
else if (GetFileAttributes((LPCWSTR)src) == FILE_ATTRIBUTE_ARCHIVE && GetFileAttributes((LPCWSTR)dest) == FILE_ATTRIBUTE_ARCHIVE) { //src, dest가 일반 파일
if ((LPCWSTR)fd_s.cFileName == (LPCWSTR)fd_d.cFileName) {
int updatefile = UpDataTime(src);
int backupfile = UpDataTime(dest);
if (updatefile > backupfile) {
if (!CopyFile((LPCWSTR)src, (LPCWSTR)dest, NULL)) {
cout << "copy file error\n";
return result;
}
else {
cout << "copy file success\n";
result = 0;
}
}
else { //업데이트 필요x
cout << "No need to update" << endl;
}
}
if (FindNextFile(hf_s, &fd_s) && FindNextFile(hf_d, &fd_d)) {
TCHAR* n_src = new TCHAR[MAX_PATH];
TCHAR* n_dest = new TCHAR[MAX_PATH];
_tcscpy(n_src, src);
_tcscpy(n_dest, dest);
_tcscat(n_src, TEXT("\\*"));
_tcscat(n_dest, TEXT("\\*"));
_tcscat(n_src, fd_s.cFileName);
_tcscat(n_dest, fd_d.cFileName);
updir(n_src, n_dest);
delete[] n_src;
delete[] n_dest;
}
else {
return result;
}
FindClose(hf_s);
FindClose(hf_d);
}
return result;
}
int UpDataTime(TCHAR *aaa) {
//filename
TCHAR* fname = aaa;
//temporary storage for file sizes
DWORD dwFileSize;
DWORD dwFileType;
//the files handle
HANDLE hFile1;
FILETIME ftCreate, ftAccess, ftWrite;
SYSTEMTIME stUTC, stLocal, stUTC1, stLocal1, stUTC2, stLocal2;
//Opening the existing file
hFile1 = CreateFile((LPCTSTR)aaa, //file to open
GENERIC_READ, //open for reading
FILE_SHARE_READ, //share for reading
NULL, //default security
OPEN_EXISTING, //existing file only
FILE_FLAG_BACKUP_SEMANTICS, //for directory
NULL); //no attribute template
if (hFile1 == INVALID_HANDLE_VALUE) {
printf("Could not open %s file, error %d\n", aaa/*fname1*/, GetLastError());
return 4;
}
dwFileType = GetFileType(hFile1);
dwFileSize = GetFileSize(hFile1, NULL);
printf("%s size is %d bytes and file type is %d\n", aaa/*fname1*/, dwFileSize, dwFileType);
//Retrieve the file times for the file.
if (!GetFileTime(hFile1, &ftCreate, &ftAccess, &ftWrite)) {
printf("Something wrong lol!\n");
return FALSE;
}
//Convert the last-write time to local time.
FileTimeToSystemTime(&ftWrite, &stUTC2);
SystemTimeToTzSpecificLocalTime(NULL, &stUTC2, &stLocal2);
//Build a string showing the date and time.
printf("Last written: %02d/%02d/%d %02d:%02d\n", stLocal2.wMonth, stLocal2.wDay,
stLocal2.wYear, stLocal2.wHour, stLocal2.wMinute);
FILE *fout = fopen("lastdata.txt", "w");
fprintf(fout, "%02d%02d%d%02d%02d\n", stLocal2.wMonth, stLocal2.wDay,
stLocal2.wYear, stLocal2.wHour, stLocal2.wMinute);
fclose(fout);
FILE *fin = fopen("lastdata.txt", "r");
char lastdata[100];
if (fin == NULL) {//업데이트 된 파일이 없으면
cout << "no update" << endl;
}
else { //업데이트 파일이 있으면
if (fgets(lastdata, sizeof(lastdata), fin) != NULL) {
puts(lastdata);//시간을 가져온다
}
//printf("%s", lastdata[0]); // mm dd yy hh:mm
fclose(fin);
}
CloseHandle(hFile1);
return lastdata[0];
} |
fb4a69e48e32b941cf9dbf4cfc3c31eccc977ad2 | 5b2d59b1c149669b37c605d25291c56dcff225a5 | /source/errors.h | 47366160b61706c01e7e2b61c2039d171c9e3882 | [] | no_license | isolomon/netcpp | f118ddb4e736952d67e5e9d1478aa1684a37c110 | 8fac48393dd0f8353a79c6458f1b0855d192036b | refs/heads/master | 2021-06-02T13:39:34.038537 | 2021-03-10T13:29:53 | 2021-03-10T13:29:53 | 48,838,256 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,261 | h | errors.h | #ifndef LIB_ERRORS_H
#define LIB_ERRORS_H
#include "types.h"
void print_trace();
BEGIN_NAMESPACE_LIB
struct Error { enum Codes
{
None = 0,
General = -1,
Timeout = -2,
Denied = -3,
Aborted = -4,
NotReady = -5,
InProgress = -6,
Suspended = -7,
Closed = -8,
NotFound = -9,
AlreadyExists = -10,
NotSupported = -11,
NotImplemented = -12,
InvalidArgument = -13,
InvalidOperation = -14,
NotEnoughSpace = -15,
OutOfMemory = -17,
IO = -20,
EndOfStream = -21,
Format = -22,
Socket = -23,
Protocol = -24,
TooManyOpens = -25,
TooManyRetries = -26,
Hardware = -91,
Internal = -92,
}; };
enum
{
NoError = 0,
GeneralExceptionType,
InvalidArgumentExceptionType,
InvalidOperationExceptionType,
BufferOverflowExceptionType,
IndexOutOfRangeExceptionType,
NotSupportedExceptionType,
NotImplementedExceptionType,
NotFoundExceptionType,
AbortedExceptionType,
RuntimeExceptionType,
FormatExceptionType,
IOExceptionType,
EndOfStreamExceptionType,
FileNotFoundExceptionType,
TimeoutExceptionType,
SocketExceptionType,
XmlExceptionType,
ProtocolExceptionType,
HardwareExceptionType,
UserExceptionBase = 1000,
};
class Exception
{
public:
int type () { return m_type; }
const char* message () { return m_message; }
Exception(int type = 0, const char* msg = 0) : m_type(type)
{
m_message[0] = 0;
if (msg) strncat(m_message, msg, 127);
}
protected:
int m_type;
char m_message[128];
};
// Timeout is a special exception since it is thrown all the time
class TimeoutException : public Exception
{
public:
TimeoutException(const char* msg = 0) : Exception(TimeoutExceptionType, msg)
{
if (msg) log_info("\n***** Timeout Exception: %s *****\n", msg);
}
};
class SystemException : public Exception
{
public:
SystemException(int type = 0, const char* msg = 0) : Exception(type, msg)
{
if (msg) log_error("\n***** System Exception: %s *****\n", msg);
}
};
class InvalidArgumentException : public SystemException
{
public:
InvalidArgumentException(const char* msg = 0) : SystemException(InvalidArgumentExceptionType, msg) {}
};
class InvalidOperationException : public SystemException
{
public:
InvalidOperationException(const char* msg = 0) : SystemException(InvalidOperationExceptionType, msg) {}
};
class IndexOutOfRangeException : SystemException
{
public:
IndexOutOfRangeException(const char* msg = 0) : SystemException(IndexOutOfRangeExceptionType, msg) {}
};
class BufferOverflowException : SystemException
{
public:
BufferOverflowException(const char* msg = 0) : SystemException(BufferOverflowExceptionType, msg) {}
};
class NotFoundException : public SystemException
{
public:
NotFoundException(const char* msg = 0) : SystemException(NotFoundExceptionType, msg) {}
};
class NotSupportedException : SystemException
{
public:
NotSupportedException(const char* msg = 0) : SystemException(NotSupportedExceptionType, msg) {}
};
class NotImplementedException : public SystemException
{
public:
NotImplementedException(const char* msg = 0) : SystemException(NotImplementedExceptionType, msg) {}
};
class AbortedException : public SystemException
{
public:
AbortedException(const char* msg = 0) : SystemException(AbortedExceptionType, msg) {}
};
class IOException : public SystemException
{
public:
IOException(const char* msg = 0) : SystemException(IOExceptionType, msg) {}
};
class EndOfStreamException : public IOException
{
public:
EndOfStreamException(const char* msg = 0) : IOException(msg) {}
};
class FileNotFoundException : IOException
{
public:
FileNotFoundException(const char* msg = 0) : IOException(msg) {}
};
class SocketException : public SystemException
{
public:
int m_socketError;
SocketException(const char* msg = 0) : SystemException(SocketExceptionType, msg) {}
};
class XmlException : public SystemException
{
public:
XmlException(const char* msg = 0) : SystemException(XmlExceptionType, msg) {}
};
class RuntimeException : public SystemException
{
public:
RuntimeException(const char* msg = 0) : SystemException(RuntimeExceptionType, msg) {}
};
class FormatException : public SystemException
{
public:
FormatException(const char* msg = 0) : SystemException(FormatExceptionType, msg) {}
};
class ProtocolException : public SystemException
{
public:
ProtocolException(const char* msg = 0) : SystemException(ProtocolExceptionType, msg) {}
};
class HardwareException : public SystemException
{
public:
HardwareException(const char* msg = 0) : SystemException(HardwareExceptionType, msg) {}
};
END_NAMESPACE_LIB
#endif//LIB_ERRORS_H |
a1cd3645c571de8a6657277bf29bc0c9f9756b47 | e0dc85984d383b9f0a8c9aaa465a4c3268eb1dba | /Nätverksimplementationen/GUIWindow.h | 26447a09b496a40df0ae538c499a619e82a09497 | [] | no_license | jonwa/Nukes-of-the-Patriots | db782b08060320753026f051043a0151fa74e5aa | a1ec6e65b3d4dd34ae1a69a2098608a5e04fe928 | refs/heads/master | 2020-04-10T03:57:10.287166 | 2013-02-07T14:28:14 | 2013-02-07T14:28:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 274 | h | GUIWindow.h | #ifndef _GUI_WINDOW_H
#define _GUI_WINDOW_H
#include "GUIElement.h"
class GUIWindow: public GUIElement
{
public:
GUIWindow(int x, int y, int width, int height, std::shared_ptr<GUIElement> parent = 0);
void render(sf::RenderWindow &window);
~GUIWindow(){}
};
#endif |
2dc65547e365262908cc61639ab08a00bc9f902c | e2d56cd0e9f5c2a50bc6ddec5ecc0811a6e8a3fc | /Core/Shapes/BoxShape.cpp | 701cf597a6b799a36211afef32588661fd6e85b2 | [
"MIT"
] | permissive | Witek902/Raytracer | 4ec308db1b3fc8761e50acdaff09492a23958a3e | 3e38a82a5ea28e64793e98efc5b8e2643ceb8e9d | refs/heads/master | 2021-01-19T11:42:04.697848 | 2020-07-11T14:28:46 | 2020-07-11T14:28:46 | 87,984,960 | 107 | 7 | null | null | null | null | UTF-8 | C++ | false | false | 4,813 | cpp | BoxShape.cpp | #include "PCH.h"
#include "BoxShape.h"
#include "Math/Geometry.h"
#include "Math/Simd8Geometry.h"
#include "Rendering/ShadingData.h"
#include "Traversal/TraversalContext.h"
namespace rt {
using namespace math;
namespace helper
{
const Matrix4 g_faceFrames[] =
{
{ { 0.0f, 0.0f, 1.0f, 0.0f}, { 0.0f, 1.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, -1.0f, 0.0f} },
{ { 0.0f, 0.0f, -1.0f, 0.0f}, { 0.0f, 1.0f, 0.0f, 0.0f}, {+1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, 1.0f, 0.0f} },
{ {+1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, 1.0f, 0.0f}, { 0.0f, -1.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f, 0.0f} },
{ {+1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, -1.0f, 0.0f}, { 0.0f, +1.0f, 0.0f, 0.0f}, {-1.0f, 0.0f, 0.0f, 0.0f} },
{ {-1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 1.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, -1.0f, 0.0f}, { 1.0f, 0.0f, 0.0f, 0.0f} },
{ {+1.0f, 0.0f, 0.0f, 0.0f}, { 0.0f, 1.0f, 0.0f, 0.0f}, { 0.0f, 0.0f, +1.0f, 0.0f}, {-1.0f, 0.0f, 0.0f, 0.0f} },
};
RT_FORCE_INLINE int32 ConvertXYZtoCubeUV(const Vector4& p, Vector4& outUV)
{
const Vector4 abs = Vector4::Abs(p);
const int32 isXPositive = p.x > 0 ? 1 : 0;
const int32 isYPositive = p.y > 0 ? 1 : 0;
const int32 isZPositive = p.z > 0 ? 1 : 0;
float maxAxis, uc, vc;
int32 side;
if (abs.x >= abs.y && abs.x >= abs.z)
{
if (isXPositive) // +X
{
uc = -p.z;
}
else // -X
{
uc = p.z;
}
side = isXPositive;
maxAxis = abs.x;
vc = p.y;
}
else if (abs.y >= abs.x && abs.y >= abs.z)
{
if (isYPositive) // +Y
{
vc = -p.z;
}
else // -Y
{
vc = p.z;
}
side = isYPositive + 2;
maxAxis = abs.y;
uc = p.x;
}
else
{
if (isZPositive) // +Z
{
uc = p.x;
}
else // -Z
{
uc = -p.x;
}
side = isZPositive + 4;
maxAxis = abs.z;
vc = p.y;
}
// Convert range from -1 to 1 to 0 to 1
outUV = Vector4(uc, vc, 0.0f, 0.0f) / (2.0f * maxAxis) + Vector4(0.5f);
return side;
}
} // helper
BoxShape::BoxShape(const Vector4& size)
: mSize(size)
, mInvSize(VECTOR_ONE / mSize)
{
RT_ASSERT(mSize.x > 0.0f);
RT_ASSERT(mSize.y > 0.0f);
RT_ASSERT(mSize.z > 0.0f);
mSize.w = 0.0f;
mInvSize.w = 0.0f;
{
mFaceCdf.x = mSize.y * mSize.z;
mFaceCdf.y = mFaceCdf.x + mSize.z * mSize.x;
mFaceCdf.z = mFaceCdf.y + mSize.x * mSize.y;
}
}
const Box BoxShape::GetBoundingBox() const
{
return Box(-mSize, mSize);
}
float BoxShape::GetSurfaceArea() const
{
return 8.0f * (mSize.x * (mSize.y + mSize.z) + mSize.y * mSize.z);
}
bool BoxShape::Intersect(const math::Ray& ray, ShapeIntersection& outResult) const
{
const Box box(-mSize, mSize);
outResult.subObjectId = 0;
return Intersect_BoxRay_TwoSided(ray, box, outResult.nearDist, outResult.farDist);
}
const Vector4 BoxShape::Sample(const Float3& u, math::Vector4* outNormal, float* outPdf) const
{
float v = u.z;
// select dimension for the normal vector (Z axis in local space)
uint32 zAxis;
{
// TODO could be optimized by storing normalized CDF
v *= mFaceCdf.z;
if (v < mFaceCdf.x)
{
v /= mFaceCdf.x;
zAxis = 0;
}
else if (v < mFaceCdf.y)
{
v = (v - mFaceCdf.x) / (mFaceCdf.y - mFaceCdf.x);
zAxis = 1;
}
else
{
v = (v - mFaceCdf.y) / (mFaceCdf.z - mFaceCdf.y);
zAxis = 2;
}
}
// compute remaining axes
const uint32 xAxis = (zAxis + 1) % 3u;
const uint32 yAxis = (zAxis + 2) % 3u;
// generate normal vector (2 possible directions for already chosen axis)
Vector4 normal = Vector4::Zero();
normal[zAxis] = v < 0.5f ? -1.0f : 1.0f;
// generate position by filling up remaining coordinates
Vector4 pos = Vector4::Zero();
pos[xAxis] = (2.0f * u.x - 1.0f) * mSize[xAxis];
pos[yAxis] = (2.0f * u.y - 1.0f) * mSize[yAxis];
pos[zAxis] = normal[zAxis] * mSize[zAxis];
if (outPdf)
{
*outPdf = 1.0f / GetSurfaceArea();
}
if (outNormal)
{
*outNormal = normal;
}
return pos;
}
void BoxShape::EvaluateIntersection(const HitPoint& hitPoint, IntersectionData& outData) const
{
using namespace helper;
RT_UNUSED(hitPoint);
const int32 side = ConvertXYZtoCubeUV(outData.frame.GetTranslation() * mInvSize, outData.texCoord);
outData.frame[0] = g_faceFrames[side][0];
outData.frame[1] = g_faceFrames[side][1];
outData.frame[2] = g_faceFrames[side][2];
}
} // namespace rt
|
568adcff81583b8e96a8d79c8eac37418e4dd077 | fd2ddfccadbd932452faf9ac47fb11938260660e | /Codeforces/413_div2/C.cpp | c3c39b7a3707cc192aad554b77f5327796af69ee | [] | no_license | cqj8660/Code_Record | 450c827bf9a98ac8860abafc8fb811b6ee8c221a | 6d148810ce3b0c7b545a4d3061dbe8780626bd9d | refs/heads/master | 2021-12-22T08:37:01.621325 | 2021-11-19T08:09:26 | 2021-11-19T08:09:26 | 149,244,038 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,608 | cpp | C.cpp | #include <bits/stdc++.h>
#define ll long long
#define pii pair<int, int>
using namespace std;
struct node{
int bea, cost;
};
vector<node> co, di;
bool cmp(node& pa, node& pb)
{
if(pa.cost == pb.cost)
return pa.bea > pb.bea;
return pa.cost < pb.cost;
}
int solve(vector<node>& t, int val)
{
sort(t.begin(), t.end(), cmp);
vector<int> price;
int len = (int)t.size(), rul = 0;
for(int i = 0; i < len; i++)
{
rul = max(rul, t[i].bea);
price.push_back(rul);
}
int ans = 0;
for(int i = len - 1; i > 0; i--)
{
int l = 0, r = i;
for(int j = 0; j < 100; j++)//二分找到cost满足条件的最大的
{
int mid = (l + r) / 2;
if(t[mid].cost + t[i].cost <= val)
{
ans = max(ans, price[mid] + t[i].bea);
l = mid;
}
else
r = mid;
}
}
return ans;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n, c, d;
cin >> n >> c >> d;
int mc = 0, md = 0;
for(int i = 0; i < n; i++)
{
int b, m;
char ch;
cin >> b >> m >> ch;
if(ch == 'C' && m <= c)
{
co.push_back(node{b, m});
mc = max(mc, b);
}
if(ch == 'D' && m <= d)
{
di.push_back(node{b, m});
md = max(md, b);
}
}
if(mc == 0 || md == 0)
mc = md = 0;
int res = mc + md;
res = max(res, solve(co, c));
res = max(res, solve(di, d));
cout << res << endl;
return 0;
}
|
2aad8783024a474d6c193ef869e2730b582912c0 | 4ed6886a816c528f46bf3e1ae06729aed2404a81 | /service/time/timeservicebase.h | 4677cf9e42ba4810d100990c253d0c5625ccbae4 | [] | no_license | kapilpipaliya/todo_drogon_server | 0931cc5f9e2a6777c3dc306c0803ad3a2e0f0d28 | 86e46371785e25a085518232d95f86b880c526c0 | refs/heads/caf | 2020-09-04T04:05:56.364929 | 2019-11-05T03:09:43 | 2019-11-05T03:09:43 | 219,647,048 | 3 | 1 | null | 2019-11-05T03:14:45 | 2019-11-05T03:10:39 | C++ | UTF-8 | C++ | false | false | 1,245 | h | timeservicebase.h | #ifndef TIMESERVICEBASE_H
#define TIMESERVICEBASE_H
#include <drogon/WebSocketController.h>
#include <drogon/drogon.h>
#include <memory>
#include "../../wscontroller/context/todocontext.h"
#include "../../dgraph/orm/dgraphorm.h"
#include "../../dgraph/orm/model.h"
//#include "../../dgraph/orm/schema.h"
#include "dgraph/dgraphclientmanger.h"
#include "json.hpp"
class TimeServiceBase {
public:
TimeServiceBase(int event1, int event2,
const drogon::WebSocketConnectionPtr &wsConnPtr,
std::shared_ptr<websocket::todo::TodoContext> context_,
std::string &&message);
template <typename T>
T *getmsg() {
auto m = new T;
m->ParseFromString(message);
return m;
}
template <typename T>
void sendmsg(T *response) {
auto s = new std::string;
*s += static_cast<char>(event1);
*s += static_cast<char>(event2);
response->AppendToString(s);
wsConnPtr->send(*s, drogon::WebSocketMessageType::Binary);
delete s;
}
int event1;
int event2;
drogon::WebSocketConnectionPtr wsConnPtr;
std::shared_ptr<websocket::todo::TodoContext> context;
std::string message;
std::shared_ptr<dgraph::orm::DGraphOrm> dgraphorm;
};
#endif // SERVICEBASE_H
|
9c11297e6dd860f3ead51d8340d85f53b7c0ba07 | fa242702f8fb89968f05574c2cf1b159894051d6 | /B. Mike and Shortcuts.cpp | f0fc62ecc4cb561bb8f3f39bc778083bd1065f34 | [] | no_license | jack-coder5416/Codeforces | d9ffd444a77a32520ae6da6e9bfa5efca1e95239 | de4b334d5f3f063f73ed09f28e31a40e728a20dc | refs/heads/master | 2023-03-15T23:26:31.708197 | 2017-08-06T09:26:19 | 2017-08-06T09:26:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 652 | cpp | B. Mike and Shortcuts.cpp | #include<cstdio>
#include<queue>
#include<cstring>
#define maxn 200010
using namespace std;
int i;
unsigned n,f;
int way[maxn];
unsigned a[maxn];
queue<unsigned> q;
int main(){
// freopen("test.in","r",stdin);
// freopen("test.out","w",stdout);
scanf("%u",&n);
memset(way,-1,sizeof(way));
for(i=1;i<=n;++i)
scanf("%u",&a[i]);
way[1]=0;
q.push(1);
while(!q.empty()){
f=q.front();
q.pop();
if(f>1&&way[f-1]<0){
way[f-1]=way[f]+1;
q.push(f-1);
}
if(way[f+1]<0){
way[f+1]=way[f]+1;
q.push(f+1);
}
if(way[a[f]]<0){
way[a[f]]=way[f]+1;
q.push(a[f]);
}
}
for(i=1;i<=n;++i)
printf("%d ",way[i]);
return 0;
}
|
71ea7984ca5aea97c6bd3536e6a766515c0b64d4 | 15ee8ce339cfd54d344eccf7d9b7459b7343e447 | /src/inputManager.cpp | 43f10ac90b97026461a9e3d8eee38bebe6580fd0 | [] | no_license | davids3/vitalalpha | 0e2e7fecd6fb739b88fe65d0a87389d28b1dfadf | 3d0a35c48c5b85c707fc0079a33ad2fb7e052b94 | refs/heads/master | 2021-01-10T11:51:35.520897 | 2016-03-16T02:06:40 | 2016-03-16T02:06:40 | 53,993,008 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,325 | cpp | inputManager.cpp | #include "inputManager.h"
inputManager::inputManager()
{
//ctor
}
inputManager::~inputManager()
{
//dtor
}
void inputManager::update(sf::Event event)
{
//makes a local copy of the event
this->event = event;
}
bool inputManager::keyPressed(int key)
{
if(event.key.code == key && event.type == sf::Event::KeyPressed)
return true;
return false;
}
bool inputManager::keyPressed(std::vector<int> keys)
{
for(int i = 0; i <keys.size(); i++)
{
if(keyPressed(keys[i]))
return true;
}
return false;
}
bool inputManager::keyReleased(int key)
{
if(event.key.code == key && event.type == sf::Event::KeyReleased)
return true;
return false;
}
bool inputManager::keyReleased(std::vector<int> keys)
{
for(int i = 0; i <keys.size(); i++)
{
if(keyReleased(keys[i]))
return true;
}
return false;
}
bool inputManager::keyDown(sf::Keyboard::Key key)
{
if(sf::Keyboard::isKeyPressed((key)))
return true;
return false;
}
bool inputManager::keyDown(std::vector<sf::Keyboard::Key> keys)
{
for(int i = 0; i < keys.size(); i++)
{
if(sf::Keyboard::isKeyPressed((keys[i])))
return true;
}
return false;
}
|
ecd979311071686beedcad8a6fad71a8cec8631a | 5816f1fcafab854c576ebdc201038cac6a1c8d46 | /fem_ofv/src/UTIL/geometricentity.cpp | acdbf74f8a68a7c18e1db7fcaf95e6af05fddb67 | [
"CC0-1.0",
"LicenseRef-scancode-generic-cla"
] | permissive | OlegJakushkin/ARL_Topologies | 26edb221d3e27e68eee324dc74522c8971c1d2c0 | 2c0d3d806b34171c824705b3e1a00e12460c0930 | refs/heads/master | 2021-09-25T07:55:32.474242 | 2018-10-19T20:30:53 | 2018-10-19T20:30:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,370 | cpp | geometricentity.cpp | /*
* ARL_Topologies - An extensible topology optimization program
*
* Written in 2017 by Raymond A. Wildman <raymond.a.wildman.civ@mail.mil>
* This project constitutes a work of the United States Government and is not
* subject to domestic copyright protection under 17 USC Sec. 105.
* Release authorized by the US Army Research Laboratory
*
* To the extent possible under law, the author(s) have dedicated all copyright
* and related and neighboring rights to this software to the public domain
* worldwide. This software is distributed without any warranty.
*
* You should have received a copy of the CC0 Public Domain Dedication along
* with this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>.
*
*/
#include "geometricentity.h"
#include <memory>
const double defaultTol = 1e-15;
using namespace Topologies;
// ******** Point in 3D space (used for both 2d and 3d)
Point::Point(const Point_2_base& inP) :
GeometricEntity(0, 2),
p(Point_3_base(inP.x(), inP.y(), 0.))
{
}
Point::Point(const Point_3_base& inP) :
GeometricEntity(0, 3),
p(inP)
{
}
bool Point::isPointCoincident(const Point_2_base& testP, const double tol) const
{
return isPointCoincident(Point_3_base(testP.x(), testP.y(), 0.), tol);
}
bool Point::isPointCoincident(const Point_3_base& testP, const double tol) const
{
return CGAL::squared_distance(testP, p) < tol*tol;
}
bool Point::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
Mesh_K::Segment_2 tmpSeg2(inP1, inP2);
Point_2_base tmpp(p.x(), p.y());
return CGAL::do_intersect(tmpSeg2, tmpp);
}
bool Point::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
const Mesh_K::Segment_3 tmpSeg3(inP1, inP2);
return tmpSeg3.has_on(p);
}
// ******** Infinite line in 2d space: Defined by a point and an angle
InfiniteLine::InfiniteLine(const Point_2_base& inOrigin, const double inAngle) :
GeometricEntity(1, 2),
origin(inOrigin),
angle(inAngle)
{
} // Point/angle form
InfiniteLine::InfiniteLine(const double m, const double b) : // Standard form, y = m*x + b
GeometricEntity(1, 2),
origin(Point_2_base(0., b)),
angle(atan(m))
{
}
InfiniteLine::InfiniteLine(const double intercept, bool isHorizontal) : // Horizontal/vertical line form
GeometricEntity(1, 2),
origin(isHorizontal ? Point_2_base(0., intercept) : Point_2_base(intercept, 0.)),
angle(isHorizontal ? 0. : PI*0.5)
{
}
bool InfiniteLine::isPointCoincident(const Point_2_base& testP, const double tol) const
{
Mesh_K::Vector_2 tmpVec(cos(angle), sin(angle));
Mesh_K::Line_2 tmpLine(origin, tmpVec);
return CGAL::squared_distance(testP, tmpLine) < tol*tol;
}
bool InfiniteLine::isPointCoincident(const Point_3_base& testP, const double tol) const
{
return isPointCoincident(Point_2_base(testP.x(), testP.y()), tol);
}
Point_2_base InfiniteLine::getNormal(const Point_2_base& inP, const double tol) const
{
return Point_2_base(-sin(angle), cos(angle));
}
Point_3_base InfiniteLine::getNormal(const Point_3_base& inP, const double tol) const
{
Point_2_base tmp = getNormal(Point_2_base(inP.x(), inP.y()), tol);
return Point_3_base(tmp.x(), tmp.y(), 0.);
}
bool InfiniteLine::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
Mesh_K::Segment_2 tmpSeg2(inP1, inP2);
Mesh_K::Vector_2 tmpVec(cos(angle), sin(angle));
Mesh_K::Line_2 tmpLine(origin, tmpVec);
return CGAL::do_intersect(tmpSeg2, tmpLine);
}
bool InfiniteLine::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
// Not implemented
return false;
}
// ********** Line segment in 2d space: Defined by two end points
LineSegment::LineSegment(const Point_2_base& inP1, const Point_2_base& inP2) :
GeometricEntity(1, 2),
p1(inP1),
p2(inP2)
{
}
bool LineSegment::isPointCoincident(const Point_2_base& testP, const double tol) const
{
Mesh_K::Segment_2 tmpSeg2(p1, p2);
return CGAL::squared_distance(tmpSeg2, testP) < tol*tol;
}
bool LineSegment::isPointCoincident(const Point_3_base& testP, const double tol) const
{
return isPointCoincident(Point_2_base(testP.x(), testP.y()), tol);
}
Point_2_base LineSegment::getNormal(const Point_2_base& inP, const double tol) const
{
Mesh_K::Vector_2 v1 = p2 - p1;
Mesh_K::Vector_2 n1(v1.y(), -v1.x());
return CGAL::ORIGIN + n1/sqrt(n1.squared_length());
}
Point_3_base LineSegment::getNormal(const Point_3_base& inP, const double tol) const
{
Point_2_base tmp = getNormal(Point_2_base(inP.x(), inP.y()), tol);
return Point_3_base(tmp.x(), tmp.y(), 0.);
}
bool LineSegment::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
Mesh_K::Segment_2 tmpSeg1(p1, p2);
Mesh_K::Segment_2 tmpSeg2(inP1, inP2);
return CGAL::do_intersect(tmpSeg1, tmpSeg2);
}
bool LineSegment::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
// Not implemented
return false;
}
std::vector<Point_2_base> LineSegment::getDefiningPoints() const
{
std::vector<Point_2_base> ptVec(2);
ptVec[0] = p1;
ptVec[1] = p2;
return ptVec;
}
// ********** Polygon in 2d space: Polygon defined by a set of points, applies only to the boundary
Polygon2D::Polygon2D(const std::vector<Point_2_base>& inVerts) :
GeometricEntity(2, 2)
{
assert(inVerts.size() >= 3);
for(unsigned k = 0; k < inVerts.size(); ++k)
{
unsigned kp1 = (k + 1) % inVerts.size();
lineSegVec.push_back(std::unique_ptr<LineSegment>(new LineSegment(inVerts[k], inVerts[kp1])));
}
}
Polygon2D::Polygon2D(const Polygon2D& rhsP) :
GeometricEntity(rhsP)
{
for(unsigned k = 0; k < rhsP.lineSegVec.size(); ++k)
lineSegVec.push_back(std::unique_ptr<LineSegment>(new LineSegment(*rhsP.lineSegVec[k])));
}
Polygon2D::Polygon2D(Polygon2D&& other) :
GeometricEntity(other)
{
swap(*this, other);
}
Polygon2D& Polygon2D::operator=(Polygon2D rhsP)
{
swap(*this, rhsP);
return *this;
}
bool Polygon2D::isPointCoincident(const Point_2_base& testP, const double tol) const
{
// Use class LineSegment to do checks
if(lineSegVec.size() < 3)
return false;
for(unsigned k = 0; k < lineSegVec.size(); ++k)
{
if(lineSegVec[k]->isPointCoincident(testP, tol))
return true;
}
return false;
}
bool Polygon2D::isPointCoincident(const Point_3_base& testP, const double tol) const
{
return isPointCoincident(Point_2_base(testP.x(), testP.y()), tol);
}
Point_2_base Polygon2D::getNormal(const Point_2_base& inP, const double tol) const
{
// Loops over all sides and takes sum of normal if point is coincident w/ 2 sides (i.e. a corner)
Mesh_K::Vector_2 nhat(0.,0.);
for(unsigned k = 0; k < lineSegVec.size(); ++k)
{
if(lineSegVec[k]->isPointCoincident(inP, tol))
nhat = nhat + (lineSegVec[k]->getNormal(inP, tol) - CGAL::ORIGIN);
}
nhat = nhat/sqrt(nhat.squared_length());
return CGAL::ORIGIN + nhat;
}
Point_3_base Polygon2D::getNormal(const Point_3_base& inP, const double tol) const
{
Point_2_base tmp = getNormal(Point_2_base(inP.x(), inP.y()), tol);
return Point_3_base(tmp.x(), tmp.y(), 0.);
}
bool Polygon2D::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
// Use class LineSegment to do checks
if(lineSegVec.size() < 3)
return false;
for(unsigned k = 0; k < lineSegVec.size(); ++k)
{
if(lineSegVec[k]->doesLineSegmentIntersect(inP1, inP2))
return true;
}
return false;
}
bool Polygon2D::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
// Not implemented
return false;
}
std::vector<Point_2_base> Polygon2D::getDefiningPoints() const
{
std::vector<Point_2_base> ptVec(lineSegVec.size());
for(unsigned k = 0; k < lineSegVec.size(); ++k)
{
std::vector<Point_2_base> tmppts = lineSegVec[k]->getDefiningPoints();
ptVec[k] = tmppts[0];
}
return ptVec;
}
// ********* Line segment in 3d space
LineSegment3D::LineSegment3D(const Point_3_base& inP1, const Point_3_base& inP2):
GeometricEntity(1, 3),
p1(inP1),
p2(inP2)
{
}
bool LineSegment3D::isPointCoincident(const Point_3_base& testP, const double tol) const
{
Mesh_K::Segment_3 tmpSeg2(p1, p2);
return CGAL::squared_distance(tmpSeg2, testP) < tol*tol;
}
Point_3_base LineSegment3D::getNormal(const Point_3_base& inP, const double tol) const
{
// This is not correct, though nothing in this code uses getNormal
Point_2_base p12(p1.x(), p1.y()), p22(p2.x(), p2.y());
Mesh_K::Vector_2 v1 = p22 - p12;
Mesh_K::Vector_2 n1(v1.y(), -v1.x());
Point_2_base tmp = CGAL::ORIGIN + n1/sqrt(n1.squared_length());
return Point_3_base(tmp.x(), tmp.y(), 0.);
}
bool LineSegment3D::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
Mesh_K::Segment_3 tmpSeg1(p1, p2);
Mesh_K::Segment_3 tmpSeg2(inP1, inP2);
return CGAL::do_intersect(tmpSeg1, tmpSeg2);
}
bool LineSegment3D::isPointCoincident(const Point_2_base& testP, const double tol) const
{
return false;
}
Point_2_base LineSegment3D::getNormal(const Point_2_base& inP, const double tol) const
{
return Point_2_base(0., 0.);
}
bool LineSegment3D::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
return false;
}
// ********* Infinite plane in 3d space: Defined by a point and a normal
InfinitePlane::InfinitePlane(const Point_3_base& inP1, const Point_3_base& inN1) :
GeometricEntity(2, 3),
p1(inP1),
n1(CGAL::ORIGIN, inN1)
{
}
InfinitePlane::InfinitePlane(const double intercept, const GeometryEntityFactory::PlaneOrientation inPO, double normalDir):
GeometricEntity(2, 3),
p1(inPO == GeometryEntityFactory::poXY ? Point_3_base(0., 0., intercept) : (inPO == GeometryEntityFactory::poYZ ? Point_3_base(intercept, 0., 0.) : Point_3_base(0., intercept, 0.))),
n1(inPO == GeometryEntityFactory::poXY ? Mesh_K::Vector_3(0., 0., 1.) : (inPO == GeometryEntityFactory::poYZ ? Mesh_K::Vector_3(1., 0., 0.) : Mesh_K::Vector_3(0., 1., 0.)))
{
n1 = (normalDir >= 0. ? 1. : -1.)*n1;
}
InfinitePlane::InfinitePlane(const double a, const double b, const double c, const double d):
GeometricEntity(2, 3),
p1(c != 0. ? Point_3_base(0., 0., d/c) : (b != 0. ? Point_3_base(0., d/b, 0.) : Point_3_base(d/a, 0., 0.))),
n1(a, b, c)
{
}
InfinitePlane::InfinitePlane(const Point_3_base& inP1, const Point_3_base& inP2, const Point_3_base& inP3):
GeometricEntity(2, 3),
p1(inP1),
n1(CGAL::cross_product(inP2 - inP1, inP3 - inP1))
{
}
bool InfinitePlane::isPointCoincident(const Point_2_base& testP, const double tol) const
{
return isPointCoincident(Point_3_base(testP.x(), testP.y(), 0.), tol);
}
bool InfinitePlane::isPointCoincident(const Point_3_base& testP, const double tol) const
{
Mesh_K::Plane_3 tmpPlane(p1,n1);
return CGAL::squared_distance(testP, tmpPlane) < tol*tol;
}
Point_2_base InfinitePlane::getNormal(const Point_2_base& inP, const double tol) const
{
Point_3_base tmp = getNormal(Point_3_base(inP.x(), inP.y(), 0.), tol);
return Point_2_base(tmp.x(),tmp.y());
}
Point_3_base InfinitePlane::getNormal(const Point_3_base& inP, const double tol) const
{
double len = sqrt(n1.squared_length());
return Point_3_base(n1.x()/len, n1.y()/len, n1.z()/len);
}
bool InfinitePlane::doesLineSegmentIntersect(const Point_2_base& inP1, const Point_2_base& inP2) const
{
// Not implemented
return false;
}
bool InfinitePlane::doesLineSegmentIntersect(const Point_3_base& inP1, const Point_3_base& inP2) const
{
Mesh_K::Plane_3 tmpPlane(p1,n1);
Mesh_K::Segment_3 tmpSeg3(inP1, inP2);
return CGAL::do_intersect(tmpPlane, tmpSeg3);
}
// Factory function to generate GeometricEntity objects from BCType and appropriate text inputs from Parser
/* All constructors:
Point(const Point_2_base& inP)
Point(const Point_3_base& inP)
InfiniteLine(const Point_2_base& inOrigin, const double inAngle)
InfiniteLine(const double m, const double b)
InfiniteLine(const double intercept, bool isHorizontal)
LineSegment(const Point_2_base& inP1, const Point_2_base& inP2)
InfinitePlane(const Point_3_base& inP1, const Point_3_base& inN1)
InfinitePlane(const double intercept, const PlaneOrientation inPO)
InfinitePlane(const double a, const double b, const double c, const double d)
Polygon(const std::vector<Point_3_base>& inVerts)
*/
namespace GeometryEntityFactory
{
namespace
{
using namespace InputLoader;
Point_2_base readPoint2(const pugi::xml_node& rootNode)
{
double x = readDoubleAttribute(rootNode, "x");
double y = readDoubleAttribute(rootNode, "y");
return Point_2_base(x, y);
}
Point_3_base readPoint3(const pugi::xml_node& rootNode)
{
double x = readDoubleAttribute(rootNode, "x");
double y = readDoubleAttribute(rootNode, "y");
double z = readDoubleAttribute(rootNode, "z");
return Point_3_base(x, y, z);
}
std::pair<Point_2_base, Point_2_base> readLineSegment2(const pugi::xml_node& rootNode)
{
pugi::xml_node cn = rootNode.child("point_2");
std::pair<Point_2_base, Point_2_base> outLS;
outLS.first = readPoint2(cn);
cn = cn.next_sibling("point_2");
outLS.second = readPoint2(cn);
return outLS;
}
std::pair<Point_3_base, Point_3_base> readLineSegment3(const pugi::xml_node& rootNode)
{
pugi::xml_node cn = rootNode.child("point_3");
std::pair<Point_3_base, Point_3_base> outLS;
outLS.first = readPoint3(cn);
cn = cn.next_sibling("point_3");
outLS.second = readPoint3(cn);
return outLS;
}
std::vector<Point_2_base> readPolygon2(const pugi::xml_node& rootNode)
{
std::vector<Point_2_base> ptVec;
for(pugi::xml_node cn = rootNode.child("point_2"); cn; cn = cn.next_sibling("point_2"))
ptVec.push_back(readPoint2(cn));
return ptVec;
}
std::vector<Point_3_base> readPolygon3(const pugi::xml_node& rootNode)
{
std::vector<Point_3_base> ptVec;
for(pugi::xml_node cn = rootNode.child("point_3"); cn; cn = cn.next_sibling("point_3"))
ptVec.push_back(readPoint3(cn));
return ptVec;
}
}
std::unique_ptr<GeometricEntity> createGeometricEntity(const BCType inBCT, const pugi::xml_node& rootNode,
const DiscretizationParameters& discParams)
{
using namespace InputLoader;
std::unique_ptr<GeometricEntity> outGE;
if(inBCT == bctPoint2D)
{
Point_2_base p = readPoint2(rootNode);
outGE = std::unique_ptr<GeometricEntity>(new Point(p));
}
else if(inBCT == bctVLine || inBCT == bctHLine)
{
double intercept = readDoubleAttribute(rootNode, "intercept");
outGE = std::unique_ptr<GeometricEntity>(new InfiniteLine(intercept, inBCT == bctHLine));
}
else if(inBCT == bctLineSeg)
{
std::pair<Point_2_base, Point_2_base> ls = readLineSegment2(rootNode);
outGE = std::unique_ptr<GeometricEntity>(new LineSegment(ls.first, ls.second));
}
else if(inBCT == bctLineSeg3D)
{
std::pair<Point_3_base, Point_3_base> ls = readLineSegment3(rootNode);
outGE = std::unique_ptr<GeometricEntity>(new LineSegment3D(ls.first, ls.second));
}
else if(inBCT == bctPolygon2D)
{
std::vector<Point_2_base> vertices = readPolygon2(rootNode);
outGE = std::unique_ptr<GeometricEntity>(new Polygon2D(vertices));
}
else if(inBCT == bctPoint3D)
{
Point_3_base p = readPoint3(rootNode);
outGE = std::unique_ptr<GeometricEntity>(new Point(p));
}
else if(inBCT == bctXYPlane || inBCT == bctYZPlane || inBCT == bctXZPlane)
{
double intercept = readDoubleAttribute(rootNode, "intercept");
PlaneOrientation curPO = inBCT == bctXYPlane ? poXY : (inBCT == bctYZPlane ? poYZ : poXZ);
outGE = std::unique_ptr<GeometricEntity>(new InfinitePlane(intercept, curPO));
}
else if(inBCT == bctInfinitePlane)
{
Point_3_base p = readPoint3(rootNode.child("point"));
Point_3_base n = readPoint3(rootNode.child("normal"));;
outGE = std::unique_ptr<GeometricEntity>(new InfinitePlane(p, n));
}
return outGE;
}
std::unique_ptr<GeometricEntity> createGeometricEntity(const BCType inBCT, const pugi::xml_node& rootNode)
{
return createGeometricEntity(inBCT, rootNode, DiscretizationParameters());
}
Point_2_base point2Dfrom3D(const Point_3_base& inPt3, GeometryEntityFactory::PlaneOrientation projPO)
{
double val1 = 0., val2 = 0.;
if(projPO == GeometryEntityFactory::poXY)
{
val1 = inPt3.x();
val2 = inPt3.y();
}
else if(projPO == GeometryEntityFactory::poYZ)
{
val1 = inPt3.y();
val2 = inPt3.z();
}
else if(projPO == GeometryEntityFactory::poXZ)
{
val1 = inPt3.x();
val2 = inPt3.z();
}
return Point_2_base(val1, val2);
}
}
|
e5036314255467c412d9eb84a2112a98e2bfb2ba | 15b49499051b61b22fa0b5262c81b57c47d63500 | /BOJ/push/1000-4999/2455.cpp | 206887fe170634ec4767379fca38a92e2d96a933 | [] | no_license | murras/algorithm | fcc03bf4d74192a0efe39304e4d801f53bd85e0f | 987a8c171e2935fefee752b292a4df8844c825fe | refs/heads/master | 2021-06-04T09:49:35.728245 | 2020-01-25T10:00:01 | 2020-01-25T10:00:01 | 106,243,746 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 240 | cpp | 2455.cpp | #include <bits/stdc++.h>
using namespace std;
int people, ans;
int main() {
for (int i = 0; i < 4; i++) {
int a, b;
cin >> a >> b;
people = people - a + b;
ans = max(ans, people);
}
cout << ans;
} |
ca7334f70a596500728974ba328069338339c395 | b934b2330c9c70924a4ccb1ee140f46162b08978 | /C_Language_Promgram-TanHaoQiang/5_loop/L0503_for 用for语句计算m+(m+1)+(m+2)+...+n的值.cpp | 0e10ed9ee466830f8f17f78c4f635b564012b55d | [] | no_license | Hailaylin/C | a53eb23e1c6106ce84edd4238e39ef0c747c1112 | e5901fafc9ebe9b912030baf853f415874f2bd17 | refs/heads/master | 2023-02-21T10:00:31.259634 | 2021-01-26T02:06:28 | 2021-01-26T02:06:28 | 94,003,613 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 539 | cpp | L0503_for 用for语句计算m+(m+1)+(m+2)+...+n的值.cpp | /*
题号:L0503_for 题目:用for语句计算m+(m+1)+(m+2)+...+n的值 得分:0
作业提交截止时间:2020/11/15 0:00:00
题目内容:
从键盘上输入两个正整数m和n,要求m小于或者等于n,计算m+(m+1)+(m+2)+...+n的值。
例:
(1)输入:1,100 输出:sum=5050
(2)输入:3,333 输出:sum=55608
(3)输入:100,100 输出:sum=100
*/
#include<stdio.h>
int main(){
int m,n,sum;
scanf("%d,%d",&m,&n);
for(;m<=n;m++)
sum=sum+m;
printf("sum=%d",sum);
return 0;
}
|
8c2aa60b992301454f34d3aa6b04d193069813f1 | a54b9281ca07481cfef74c39d3cd300e105745f2 | /AresAPI/include/Ares/Core/Debug.h | 34d2ea39dc6c7d4239d08569f69a95aba86a3967 | [
"Apache-2.0"
] | permissive | tiredamage42/AresEngine | b77b6856b23ea756fd9092efc4efdce5a0cf0c66 | 1543942b47af85e5bb43e5f0c7bb06a255b1af6b | refs/heads/main | 2023-04-22T10:08:01.975498 | 2021-05-16T03:07:36 | 2021-05-16T03:07:36 | 366,220,577 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,581 | h | Debug.h | #pragma once
#include "config.h"
#pragma warning(push)
#pragma warning(disable:26812 26495 26451 26498)
#include <spdlog/spdlog.h>
#include <spdlog/fmt/ostr.h>
#pragma warning(pop)
#define DEBUG_DECLARATION(name, internalcall) \
template<typename... Args> \
static void name(const char* fmt, Args &&...args) \
{ \
if (s_Logger != nullptr) \
{ \
s_Logger->internalcall(fmt, std::forward<Args>(args)...); \
} \
} \
template<typename T> \
static void name(const T& msg) \
{ \
if (s_Logger != nullptr) \
{ \
s_Logger->internalcall(msg); \
} \
}
namespace AresInternal
{
struct _ARES_API Debugging
{
static void Initialize();
};
class _ARES_API Debug
{
friend struct Debugging;
public:
DEBUG_DECLARATION(Log, trace)
DEBUG_DECLARATION(Info, info)
DEBUG_DECLARATION(Warn, warn)
DEBUG_DECLARATION(Error, error)
DEBUG_DECLARATION(Critical, critical)
private:
static std::shared_ptr<spdlog::logger> s_Logger;
};
}
namespace Ares
{
class _ARES_API Debug
{
friend struct AresInternal::Debugging;
public:
DEBUG_DECLARATION(Log, trace)
DEBUG_DECLARATION(Info, info)
DEBUG_DECLARATION(Warn, warn)
DEBUG_DECLARATION(Error, error)
DEBUG_DECLARATION(Critical, critical)
private:
static std::shared_ptr<spdlog::logger> s_Logger;
};
}
#ifdef _ARES_DEBUG
#define _ARES_DEBUGBREAK() __debugbreak()
#define _ARES_ASSERT(x, errMsg) { if (!(x)) { AresInternal::Debug::Critical("Assertion Failed: {}", errMsg); _ARES_DEBUGBREAK(); } }
#else
#define _ARES_DEBUGBREAK()
#define _ARES_ASSERT(x, errMsg)
#endif
#undef DEBUG_DECLARATION |
3c4f2c11f3247b9dfdd0648a4669a2e2b26fd7ab | 5a980d185577ed17bea4bc4bb9b49b22a88a12ed | /include/Protocol/PackageSerialize.hpp | b9cf20147ff7d6d3e39cffbaef2a596c0297cdb0 | [] | no_license | LeonardoRicky/rtype | 90120c175212ddca76aef8e94fec5ad0a05194d3 | d721f26800cc09114a02138e5e8bbc82a10033b6 | refs/heads/master | 2022-05-05T05:11:24.696050 | 2017-01-02T19:25:56 | 2017-01-02T19:25:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | hpp | PackageSerialize.hpp | //
// Created by victor on 21/11/16.
//
#ifndef RTYPE_ROOMPACKAGESERIALIZE_HPP
#define RTYPE_ROOMPACKAGESERIALIZE_HPP
#include <cstring>
#include <iostream>
#include "Common/DLLexport.hpp"
class PREF_EXPORT PackageSerialize {
public:
template <typename T>
static void print(T const &obj) {
unsigned char const *data;
data = (unsigned char const *)&obj;
write(1, data, sizeof(obj));
}
};
#endif //RTYPE_ROOMPACKAGESERIALIZE_HPP
|
ab040498b6b5fdd6def5fd2ae207a32cc364ac2e | 420656b39d9b185e7211c56cbbadfc8ba2461806 | /Inject/main.cpp | bb96bc01fb6e3899588d4d917df6241108c03ef8 | [] | no_license | staring/Injector | bf1fd75f7d7e017696ba2b4fa7c5027d1cadcd88 | 9cc89a35d5f9774a7399033c0e53484787678075 | refs/heads/master | 2021-01-17T13:43:29.135514 | 2014-11-20T15:11:32 | 2014-11-20T15:11:32 | null | 0 | 0 | null | null | null | null | WINDOWS-1251 | C++ | false | false | 809 | cpp | main.cpp | // Inject.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <cstdlib>
#include <Injector.h>
#define TARGET_DLL "C:\\Users\\Rain\\Documents\\Visual Studio 2013\\Projects\\Inject\\x64\\Debug\\SimpleDll.dll"
//#define TARGET_DLL L"Shlwapi.dll"
int main(int argc, char* argv[])
{
Inject::Injector* injector;
try {
injector = Inject::Injector::CreateInstance(L"notepad.exe", TARGET_DLL);
if (injector == nullptr) {
throw std::runtime_error("injector is nullptr (target process not found)");
}
std::cout << "succesfull injected!" << std::endl;
delete injector;
}
catch (const std::exception& ex) {
std::cout << "Exception: " << ex.what() << std::endl;
}
system("PAUSE");
return 0;
}
|
e29026f8fb12a58f18db463f9045b3242563eb51 | a879bcb6a5dbd40a1c4815dc00291fca458dcc01 | /mapping.cpp | 6e638df11271537baaa0840c70503ac8973aab55 | [] | no_license | hgedek/cpp-samples | 38a5b44c43589bf441f4205bff2cb8a1e9f2c136 | 2f69954de8627fe2065a9958f997eee56d48f135 | refs/heads/main | 2023-04-20T06:24:36.931213 | 2021-05-01T14:41:20 | 2021-05-01T14:41:20 | 329,326,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 215 | cpp | mapping.cpp | #include <iostream>
#include <tuple>
int main() {
const auto tpl = std::make_tuple(1, 1.1f, "sample");
const auto [a,b,c] = tpl;
std::cout << a << ":" << b << ":" << c << std::endl;
return 0;
}
|
edb226e6d618bf5161648283cbcb076521c9f448 | 07a41d98b4000326eb6e5b20e0115f71fb17854c | /displayPFD.h | 4ffb1fb5c073b5cdbab9591c0b320565443e141e | [
"MIT"
] | permissive | mxsshao/nsb-sdd-lunar | c0022625a3b92497ac6855a20477841c95305531 | 14407a8f8d2ee9e1945285abbd5112d114020b2a | refs/heads/master | 2020-04-14T07:14:45.515172 | 2019-01-08T09:14:26 | 2019-01-08T09:14:26 | 163,707,469 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 533 | h | displayPFD.h | #pragma once
#include "interfacesimulator.h"
class CDisplayPFD
{
protected:
CDisplayPFD() {};
private:
ALLEGRO_BITMAP* render;
ALLEGRO_FONT* font;
ALLEGRO_BITMAP* bg;
ALLEGRO_BITMAP* back;
ALLEGRO_BITMAP* attitude;
ALLEGRO_BITMAP* altitude;
ALLEGRO_BITMAP* speed;
ALLEGRO_BITMAP* border;
ALLEGRO_BITMAP* off;
ALLEGRO_BITMAP* overspeed;
float y;
float width;
public:
static CDisplayPFD MDisplayPFD;
void Load();
void Init();
void Resize();
void Cleanup();
void Render();
float GetWidth() {return width;};
}; |
63ebd8a9867f070ddfb387338aaa7fcfcc9dc8c6 | 514996e39fe2129abe231503ce7f5f9688c837f7 | /src/common/ui_checkbox.h | cebb617bb0cd90aa31546ce3101f00ea14add5a3 | [] | no_license | Necrys/Fury | d39182c1e7f9bde799b0d8baec5bc8cb4f62d6c0 | 84b20613299418efb672b6ec37e41ea69aaf72b5 | refs/heads/master | 2023-04-01T18:01:13.696634 | 2021-04-07T14:25:04 | 2021-04-07T14:25:04 | 354,311,932 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 440 | h | ui_checkbox.h | #pragma once
#include "ui_panel.h"
//-----------------------------------------------------------------------------
namespace gui
{
class checkbox: public panel
{
public:
checkbox(system* controller, _base* parent = 0);
virtual ~checkbox();
bool checked;
virtual void update(){};
virtual void render();
void (*on_change)( bool cheked );
protected:
bool handle_event( uint32 msg, uint32 param1, uint32 param2 );
};
} |
f96617efdda7a733de97ce9fba8add380a6b6e03 | f69ea03fbcdca417b25d181599095ccc0b5a9a13 | /test/parser_isymtec_ai_test/CHSimulationTestCosineForce.cpp | 1002c13d0c8a20d81c210651b8069e583a1961f9 | [
"MIT",
"BSD-3-Clause"
] | permissive | IsymtecAi/isymtecai-chrono-parser | ef1e1303d2b61d326780c3dd9d659f59c967e0c2 | 348948945d8b98c12afcf9ad0477ba6ee9405219 | refs/heads/master | 2020-03-27T22:10:50.476905 | 2019-07-03T15:50:35 | 2019-07-03T15:50:35 | 147,211,069 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,842 | cpp | CHSimulationTestCosineForce.cpp | #include "gtest/gtest.h"
#include "parser_isymtec_ai/ChSimulationIsymtecAi.h"
#include "chrono/physics/ChSystemSMC.h"
#include "parser_isymtec_ai/ChIsymtecAiConstants.h"
using namespace chrono;
namespace {
class ChSimulationCosineForce : public ChSimulationIsymtecAi {
public:
mutable std::vector<double> m_CoordinateZBody;
mutable std::vector<double> m_Time;
private:
virtual void ProcessOutputTimeStep() const override final {
auto bodyList = GetSystem()->Get_bodylist();
auto body = bodyList[0];
auto bodyPos = body->GetPos();
m_CoordinateZBody.push_back(bodyPos.z());
m_Time.push_back(GetSystem()->GetChTime());
}
};
}
class ChSimulationCosineForceTest : public ::testing::Test {
protected:
// You can do set-up work for each test here.
ChSimulationCosineForceTest() {
};
// You can do clean-up work that doesn't throw exceptions here.
virtual ~ChSimulationCosineForceTest() {};
};
TEST_F(ChSimulationCosineForceTest, Test0) {
ChSimulationCosineForce simulation;
std::string filename = "isymtecAi/test_cosine_force.isym";
filename = isymtec_ai_constants::ISYMTEC_DATA_PATH + filename;
bool parseOk = simulation.Parse(filename);
EXPECT_TRUE(parseOk);
simulation.Simulate();
auto& timeVec = simulation.m_Time;
double timeRef = 2.;
double outputTimeStepRef = 0.1;
size_t countStepsRef = size_t(round(timeRef / outputTimeStepRef) + 1);
EXPECT_EQ(timeVec.size(), countStepsRef); //< = simulation time / sizeOutputstep + 1
EXPECT_NEAR(timeVec.back(), timeRef, 10E-7);
auto& coorZ = simulation.m_CoordinateZBody;
EXPECT_EQ(coorZ.size(), timeVec.size());
double minCoor = *std::min_element(coorZ.begin(), coorZ.end());
EXPECT_GE(minCoor, 0.0);
double maxCoor = *std::max_element(coorZ.begin(), coorZ.end());
EXPECT_NEAR(maxCoor, 0.2026, 0.01);
EXPECT_NEAR(coorZ.back(), 0.0, 0.015);
} |
cce727d77a360b45cede06c1677c5ba57039a590 | ffa9bada806a6330cfe6d2ab3d7decfc05626d10 | /CodeForces/CF1501/B.cpp | d9e423668ee5db4d2d914e56a5b065897649f47e | [
"MIT"
] | permissive | James3039/OhMyCodes | 064ef03d98384fd8d57c7d64ed662f51218ed08e | f25d7a5e7438afb856035cf758ab43812d5bb600 | refs/heads/master | 2023-07-15T15:52:45.419938 | 2021-08-28T03:37:27 | 2021-08-28T03:37:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | B.cpp | #include <cstdio>
#include <iostream>
#include <cstring>
const int Max=2e5+5;
int t, cream, a[Max], b[Max], n;
int main(){
// freopen("data.in", "r", stdin);
scanf("%d", &t);
for(int casenum=0; casenum<t; casenum++){
memset(b, 0, sizeof(b));
cream=0;
scanf("%d", &n);
for(int i=0; i<n; i++){
scanf("%d", &a[i]);
}
for(int i=n-1; i>=0; i--){
cream = cream>a[i]?cream:a[i];
if(cream>0){
b[i] = 1; cream--;
}
}
for(int i=0; i<n; i++){
printf("%d ", b[i]);
}
printf("\n");
}
return 0;
}
|
d1c1e31b5d90a1031c5aa2ca8d6407bedb8858ec | 7bc0e6353fada99860faf2496df3cdc65afd21a9 | /fizzbuzz/src/divisible_check.cpp | 5c3cf10bd93afa2fcb34094f9597f77b7ff406a5 | [] | no_license | markhumphrey/fizzbuzz-cpp | 89f18be659e2585c5c01e6192b0c4295e02d0c7e | 27dba8dc11c5de4df30cee6ff47256d7f9ee5457 | refs/heads/master | 2020-12-24T15:05:57.040021 | 2015-07-27T22:25:54 | 2015-07-27T22:25:54 | 39,405,487 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 727 | cpp | divisible_check.cpp | #include "divisible_check.h"
#include <iostream>
using namespace std;
DivisibleCheck::DivisibleCheck() {
}
DivisibleCheck::~DivisibleCheck() {
}
void DivisibleCheck::doCheck(int start, int end, std::ostream &stream) const {
for (int i = start; i <= end; ++i) {
bool isDiv = false;
for (size_t j = 0; j < m_divisors.size(); ++j) {
if (i % m_divisors[j].first == 0) {
stream << m_divisors[j].second;
isDiv = true;
}
}
if (!isDiv) {
stream << i;
}
stream << endl;
}
}
void DivisibleCheck::addDivisor(int divisor, const std::string &message) {
if (divisor != 0) {
m_divisors.push_back(pair<int, string>(divisor, message));
}
}
void DivisibleCheck::clearDivisors() {
m_divisors.clear();
}
|
1ce3a06b24d0f3b3c6c7be9cf6b7b6139a60970b | e827a18e7c6fa35e4b103237a9ffab7ebf69a7fa | /updated_24_overtake_angle/freicar_map_sr/include/freicar_map/planning/lane_follower.h | 252801da3408b9455bcd2e642e0b2f50c2019fba | [] | no_license | Qanadilo1/speed_racers_comp_test | 0515463e3cbe614916cf14f79504281273d0b8e0 | 6d311f091dc73151b2a0336e779724a7557b1c15 | refs/heads/master | 2023-03-27T08:35:21.419852 | 2021-03-25T08:23:22 | 2021-03-25T08:23:22 | 348,695,713 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 713 | h | lane_follower.h | #ifndef __FREICAR_LANE_FOLLOWER_H__
#define __FREICAR_LANE_FOLLOWER_H__
#include <string>
#include <vector>
#include "freicar_common/shared/planner_cmd.h"
#include "freicar_map/planning/plan.h"
namespace freicar
{
namespace planning
{
namespace lane_follower
{
freicar::planning::Plan GetPlan(const mapobjects::Point3D& current_position, enums::PlannerCommand command,
float distance, unsigned int step_count);
freicar::planning::Plan GetPlan(const std::string& lane_uuid, float req_loffset, enums::PlannerCommand command,
float distance, unsigned int step_count);
} // namespace lane_follower
} // namespace planner
} // namespace freicar
#endif |
d0e2ff0c2f79863928a2fdebd02ad3505cfef89a | 1393b088958301a6c2f6766df2864c61365e9d4b | /Code/Core/Applications/CirrusFlag/vnsAppCirrusFlag.cxx | 96d9adf178776b3733fd1f9feeb29a86b772a19f | [
"Apache-2.0"
] | permissive | alexgoussev/maja_gitlab | f6727468cb70e210d3c09453de22fee58ed9d656 | 9688780f8dd8244e60603e1f11385e1fadc90cb4 | refs/heads/develop | 2023-02-24T05:37:38.769452 | 2021-01-21T16:47:54 | 2021-01-21T16:47:54 | 332,269,078 | 0 | 0 | Apache-2.0 | 2021-01-23T18:17:25 | 2021-01-23T17:33:18 | C++ | UTF-8 | C++ | false | false | 17,335 | cxx | vnsAppCirrusFlag.cxx | /*
* Copyright (C) 2020 Centre National d'Etudes Spatiales (CNES)
*
* 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.
*
*/
/************************************************************************************************************
* *
* ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo *
* o *
* o *
* o *
* o *
* o ooooooo ooooooo o o oo *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o o o o o o o o *
* o o o oooo o o o o o o *
* o o o o o o o o o *
* o o o o o o o o o o *
* oo oooooooo o o o oooooo o oooo *
* o *
* o *
* o o *
* o o oooo o o oooo *
* o o o o o o *
* o o ooo o o ooo *
* o o o o o *
* ooooo oooo o ooooo oooo *
* o *
* *
************************************************************************************************************
* *
* Author: CS Systemes d'Information (France) *
* *
************************************************************************************************************
* HISTORIQUE *
* *
* VERSION : 1-0-0 : <TypeFT> : <NumFT> : 15 nov. 2017 : Creation
* *
* FIN-HISTORIQUE *
* *
* $Id$
* *
************************************************************************************************************/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"
#include "vnsCountCirrusPixelGenerator.h"
#include "vnsThresholdImageFunctor.h"
#include "vnsStreamingConditionalStatisticsImageFilter.h"
#include <string>
namespace vns
{
namespace Wrapper
{
using namespace otb::Wrapper;
class CirrusFlag : public Application
{
public:
/** Standard class typedefs. */
typedef CirrusFlag Self;
typedef otb::Wrapper::Application Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
/** Standard macro */
itkNewMacro(Self);
itkTypeMacro(CirrusFlag, otb::Wrapper::Application);
/** Some convenient typedefs. */
typedef DoubleImageType InputImageType;
typedef InputImageType::PixelType InputPixelType;
typedef InputImageType::InternalPixelType InputInternalPixelType;
typedef InputImageType::Pointer InputImagePointer;
typedef InputImageType::ConstPointer InputImageConstPointer;
typedef UInt8ImageType InputMaskType;
typedef InputMaskType::Pointer InputMaskPointer;
typedef InputMaskType::ConstPointer InputMaskConstPointer;
/** Filters typedefs. */
typedef CountCirrusPixelGenerator<InputImageType, InputMaskType> CountCirrusFilterType;
typedef CountCirrusFilterType::Pointer CountCirrusFilterPointerType;
typedef Functor::ThresholdImageFunctor<InputPixelType, InputPixelType> ThresholdFunctorType;
typedef itk::UnaryFunctorImageFilter<InputImageType, InputImageType, ThresholdFunctorType> ThresholdFilterType;
typedef ThresholdFilterType::Pointer ThresholdFilterPointerType;
typedef StreamingConditionalStatisticsImageFilter<InputImageType, InputImageType> StatisticsFilterType;
typedef StatisticsFilterType::Pointer StatisticsFilterPointerType;
/** Filters typedefs */
private:
void DoInit()
{
SetName("CirrusFlag");
SetDescription("CirrusFlag algo.");
Loggers::GetInstance()->Initialize(GetName());
// Documentation
SetDocLongDescription("This application computes the cirrus mask");
SetDocLimitations("None");
SetDocAuthors("MAJA-Team");
SetDocSeeAlso("MAJA Doc");
AddDocTag("Statistics");
//Input images
AddParameter(ParameterType_InputImage, "cla", "cla image");
SetParameterDescription("cla", "Cloud level altitude image");
AddParameter(ParameterType_InputImage, "edg", "EDG image");
SetParameterDescription("edg", "Image used as edge at coarse");
//algo params
AddParameter(ParameterType_Int, "altthreshold", "Altitude threshold");
SetParameterDescription("altthreshold","Threshold for altitude");
SetParameterRole("altthreshold", Role_Output);
AddParameter(ParameterType_Float, "minpercentcirrus", "Minimum percent of cirrus");
SetParameterDescription("minpercentcirrus","Minimum percent of cirrus");
SetParameterRole("minpercentcirrus", Role_Output);
AddParameter(ParameterType_Float, "minpercentcloud", "Minimum percent of cloud");
SetParameterDescription("minpercentcloud","Minimum percent of cloud");
AddParameter(ParameterType_Float, "minstdcirrus", "Minimum of cirrus standard deviation");
SetParameterDescription("minstdcirrus","Minimum of cirrus standard deviation");
SetParameterRole("minstdcirrus", Role_Output);
AddParameter(ParameterType_Float, "minpercentstdcirrus", "Minimum percent of cirrus standard deviation");
SetParameterDescription("minpercentstdcirrus","Minimum percent of cirrus standard deviation");
SetParameterRole("minpercentstdcirrus", Role_Output);
AddParameter(ParameterType_Float, "nodata","NoData for L1");
//Output flag
AddParameter(ParameterType_String, "cirrusflag", "CirrusFlag");
SetParameterDescription("cirrusflag", "Is the image cirrus enought");
SetParameterRole("cirrusflag", Role_Output);
AddParameter(ParameterType_Float, "mean", "Mean");
SetParameterRole("mean", Role_Output);
AddParameter(ParameterType_Float, "cirrusproportion", "Cirrusproportion");
SetParameterRole("cirrusproportion", Role_Output);
AddParameter(ParameterType_Float, "cirrusstd", "Cirrusstd");
SetParameterRole("cirrusstd", Role_Output);
AddParameter(ParameterType_Float, "cloudrelativestd", "Cloudrelativestd");
SetParameterRole("cloudrelativestd", Role_Output);
AddParameter(ParameterType_Float, "cloudpixelnumber", "Cloudpixelnumber");
SetParameterRole("cloudpixelnumber", Role_Output);
AddParameter(ParameterType_Float, "cirruspixelnumber", "Cirruspixelnumber");
SetParameterRole("cirruspixelnumber", Role_Output);
AddParameter(ParameterType_Float, "validpixelnumber", "Validpixelnumber");
SetParameterRole("validpixelnumber", Role_Output);
AddParameter(ParameterType_Float, "minimum", "Minimum");
SetParameterRole("minimum", Role_Output);
AddParameter(ParameterType_Float, "maximum", "Maximum");
SetParameterRole("maximum", Role_Output);
AddParameter(ParameterType_Float, "sum", "Sum");
SetParameterRole("sum", Role_Output);
AddParameter(ParameterType_Float, "variance", "Variance");
SetParameterRole("variance", Role_Output);
AddParameter(ParameterType_Float, "standardeviation", "Standardeviation");
SetParameterRole("standardeviation", Role_Output);
AddRAMParameter("ram");
SetDefaultParameterInt("ram",2048);
}
void DoUpdateParameters()
{
}
void DoExecute()
{
// Init filters
m_CountCirrusFilter = CountCirrusFilterType::New();
m_ThresholdFilter = ThresholdFilterType::New();
m_StatisticsFilter = StatisticsFilterType::New();
// Get input image pointers
InputImagePointer l_L1CLA = this->GetParameterDoubleImage("cla");
InputMaskConstPointer l_EDGSub = this->GetParameterUInt8Image("edg");
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() - Start")
std::string l_CirrusFlag = "false";
// Count all cirrus clouds
// Call the vnsCountCirrusPixelGenerator
m_CountCirrusFilter->SetInput(l_L1CLA);
m_CountCirrusFilter->SetAltitudeThreshold(this->GetParameterInt("altthreshold"));
m_CountCirrusFilter->SetL1NoData(this->GetParameterFloat("nodata"));
m_CountCirrusFilter->SetEDGSub(l_EDGSub);
//TODO Add a virtual writer
m_CountCirrusFilter->Update();
// Get the results of the vnsCountCirrusPixelGenerator
const unsigned long l_CirrusPixelNumber = m_CountCirrusFilter->GetCirrusPixelNumber();
const unsigned long l_CloudPixelNumber = m_CountCirrusFilter->GetCloudPixelNumber();
const unsigned long l_ValidPixelNumber = m_CountCirrusFilter->GetValidPixelNumber();
// Display the number of cirrus pixels in debug mode
vnsLogDebugMacro("l_CirrusPixelNumber: "<<l_CirrusPixelNumber);
vnsLogDebugMacro("l_CloudPixelNumber: "<<l_CloudPixelNumber);
vnsLogDebugMacro("l_ValidPixelNumber: "<<l_ValidPixelNumber);
if (l_ValidPixelNumber == 0)
{
vnsLogWarningMacro("CirrusFlagGenerator::GenerateData(). The number of valid pixels is null");
// Cirrus flag is set to false
this->SetParameterString( "cirrusflag", l_CirrusFlag , false);
this->SetParameterFloat( "cirrusstd", 0.0);
this->SetParameterFloat( "cloudrelativestd", 0.0);
}
else
{
// Threshold the cloud altitude (> 0) and generate a mask used to compute statistics
// Statistics are computed if the pixel of the mask is equal to 0
m_ThresholdFilter->SetInput(l_L1CLA);
m_ThresholdFilter->GetFunctor().SetThresholdValue(0);
m_ThresholdFilter->GetFunctor().SetInsideValue(1);
m_ThresholdFilter->GetFunctor().SetOutputValue(0);
// Cast the input image to a vector image
// Compute image statistics with an input mask
m_StatisticsFilter->SetInput(l_L1CLA);
m_StatisticsFilter->SetEnableVariance(true);
m_StatisticsFilter->SetMaskInput(m_ThresholdFilter->GetOutput());
//TODO add a virtual writer
m_StatisticsFilter->Update();
// Statistics used in debug mode
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() Minimum: " <<m_StatisticsFilter->GetMinimumOutput()->Get());
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() Maximum: "<< m_StatisticsFilter->GetMaximumOutput()->Get());
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() Sum: " << m_StatisticsFilter->GetSum());
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() Mean: " << m_StatisticsFilter->GetMean());
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() Variance: " << m_StatisticsFilter->GetVariance());
vnsLogDebugMacro("CirrusFlagGenerator::GenerateData() StandarDeviation: " << m_StatisticsFilter->GetStandardDeviation());
// Proportion of cirrus within the image
double l_CirrusProportion = l_CirrusPixelNumber * 100. / l_ValidPixelNumber;
double l_CloudProportion = l_CloudPixelNumber * 100. / l_ValidPixelNumber;
// Relative standard deviation for cirrus
// Get the first element of the matrix while the input image of the statistics filter
// is an otb::image and not an otb::VectorImage
const double l_CloudMean = m_StatisticsFilter->GetMean(); //[0];
double l_CloudStd = m_StatisticsFilter->GetStandardDeviation();
vnsLogDebugMacro("CirrusFlagGenerator l_CloudMean : "<<l_CloudMean);
vnsLogDebugMacro("CirrusFlagGenerator m_CloudStd : "<<l_CloudStd);
vnsLogDebugMacro("CirrusFlagGenerator m_StatisticsFilter->GetIsValid() : "<<m_StatisticsFilter->GetIsValid());
// No pixel is valid. Returns null Statistics
if (m_StatisticsFilter->GetIsValid() == false)
{
// Cirrus flag is set to false
this->SetParameterString( "cirrusflag", l_CirrusFlag , false);
this->SetParameterFloat( "cirrusstd", 0.0);
this->SetParameterFloat( "cloudrelativestd", 0.0);
}
else
{
// Check if the mean value is not null before computing the "CloudRstd" value
if(vnsIsZeroDoubleWithEpsilonMacro(l_CloudMean, CONST_EPSILON_20))
{
vnsExceptionBusinessMacro("CirrusFlagGenerator failed. The cloud statistics of L1 CLA image is null")
}
const double l_CloudRstd = l_CloudStd / l_CloudMean;
const double l_MinRstdCirrus = this->GetParameterFloat("minstdcirrus");
const double l_MinPercentCloud = this->GetParameterFloat("minpercentcloud");
const double l_MinPercentCirrus = this->GetParameterFloat("minpercentcirrus");
const double l_MinPercentStdCirrus = this->GetParameterFloat("minpercentstdcirrus");
// Parameters used to raise the cirrus flag and displayed in debug mode
vnsLogDebugMacro("m_CloudProportion: " << l_CloudProportion << " <> " << l_MinPercentCloud);
vnsLogDebugMacro("m_CirrusProportion: " << l_CirrusProportion << " <> " << l_MinPercentCirrus);
vnsLogDebugMacro("m_CloudRstd: " << l_CloudRstd << " <> " << l_MinRstdCirrus);
vnsLogDebugMacro("m_CloudStd: " << l_CloudStd << " <> " << l_MinPercentStdCirrus);
// If the proportion of cirrus within the image is too high
// or if the standart deviation is high, the cirrus flag is raised
if (l_CloudProportion > l_MinPercentCloud)
{
if ((l_CirrusProportion > l_MinPercentCirrus) || (l_CloudRstd > l_MinRstdCirrus)
|| (l_CloudStd > l_MinPercentStdCirrus))
{
l_CirrusFlag = "true";
}
}
this->SetParameterFloat( "cirrusstd", l_CloudStd);
this->SetParameterFloat( "cloudrelativestd", l_CloudRstd);
}
this->SetParameterFloat( "cirrusproportion", l_CirrusProportion);
}
// Set the output flag
this->SetParameterString( "cirrusflag", l_CirrusFlag , false);
this->SetParameterInt( "altthreshold",this->GetParameterInt("altthreshold"));
this->SetParameterFloat( "minpercentcirrus",this->GetParameterInt("minpercentcirrus"));
this->SetParameterFloat( "minstdcirrus",this->GetParameterInt("minstdcirrus"));
this->SetParameterFloat( "minpercentstdcirrus",this->GetParameterInt("minpercentstdcirrus"));
this->SetParameterFloat( "mean", m_StatisticsFilter->GetMean());
this->SetParameterFloat( "cloudpixelnumber", l_CloudPixelNumber);
this->SetParameterFloat( "cirruspixelnumber", l_CirrusPixelNumber);
this->SetParameterFloat( "validpixelnumber", l_ValidPixelNumber);
this->SetParameterFloat( "minimum", m_StatisticsFilter->GetMinimumOutput()->Get());
this->SetParameterFloat( "maximum", m_StatisticsFilter->GetMaximumOutput()->Get());
this->SetParameterFloat( "sum", m_StatisticsFilter->GetSum());
this->SetParameterFloat( "variance", m_StatisticsFilter->GetVariance());
this->SetParameterFloat( "standardeviation", m_StatisticsFilter->GetStandardDeviation());
}
/** Filters declaration */
CountCirrusFilterPointerType m_CountCirrusFilter;
ThresholdFilterPointerType m_ThresholdFilter;
StatisticsFilterPointerType m_StatisticsFilter;
};
}
}
OTB_APPLICATION_EXPORT(vns::Wrapper::CirrusFlag)
|
d0949e5f306923c21a4f52c220da80ec8c1a6554 | f3b4f013e55a0f64298dfca70e0bd13735341b32 | /biweekly-contest/biweekly-contest-18/1-rank-transform-of-an-array/sort.cpp | f6910e3c73f1a2e4d6ae69cb67a95139033b8e71 | [] | no_license | DFLovingWM/leetcode-solving | 0eb53f54a5ef5a365d6cae5ffd9e4d6a3ec4b5fb | deeb2d5ac504eaeb33cc429e2a0fcdc830e2213d | refs/heads/master | 2021-06-06T12:09:02.054056 | 2021-05-16T15:50:40 | 2021-05-16T15:50:40 | 163,033,138 | 8 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 464 | cpp | sort.cpp | class Solution {
public:
vector<int> arrayRankTransform(vector<int>& arr) {
set<int> nums(arr.begin(), arr.end()); // 去重并排序
int id = 0;
unordered_map<int, int> num2Index;
for (int num : nums) {
num2Index[num] = ++id;
}
const int n = arr.size();
vector<int> res(n);
for (int i = 0; i < n; ++i) {
res[i] = num2Index[arr[i]];
}
return res;
}
}; |
3c8327f5f682d3667ac6bf437b8b19bf5ced3880 | 35458bb054e1b53b736e54785e5d417eafee0a93 | /XDaggerMinerRuntime/CoreV2/cl_device_utils.h | 5936a2c2ff0bf7a466d5d76407e27bb4edf79865 | [] | no_license | xrdavies/XDaggerMinerWin | b17029ccd6008c56ed8d9e2ad8a576d76661b69b | 180f628b9e649db4cc89e4ec9be6673d9af3e7e5 | refs/heads/master | 2020-03-19T01:07:52.271037 | 2018-11-01T23:46:00 | 2018-11-01T23:46:00 | 135,524,862 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | h | cl_device_utils.h | #pragma once
#include <vector>
#include "Core/CL/cl2.hpp"
/*
#define OPENCL_PLATFORM_UNKNOWN 0
#define OPENCL_PLATFORM_NVIDIA 1
#define OPENCL_PLATFORM_AMD 2
#define OPENCL_PLATFORM_CLOVER 3
#define CL_USE_DEPRECATED_OPENCL_1_2_APIS true
#define CL_HPP_ENABLE_EXCEPTIONS true
#define CL_HPP_CL_1_2_DEFAULT_BUILD true
#define CL_HPP_TARGET_OPENCL_VERSION 120
#define CL_HPP_MINIMUM_OPENCL_VERSION 120
#define MAX_CL_DEVICES 16
// macOS OpenCL fix:
#ifndef CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV
#define CL_DEVICE_COMPUTE_CAPABILITY_MAJOR_NV 0x4000
#endif
#ifndef CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV
#define CL_DEVICE_COMPUTE_CAPABILITY_MINOR_NV 0x4001
#endif
*/
namespace XDaggerMinerRuntime
{
class DeviceUtils {
public:
DeviceUtils();
static std::vector<cl::Platform> GetPlatforms();
static std::vector<cl::Device> GetDevices(std::vector<cl::Platform> const& platforms, unsigned platformId, bool useAllOpenCLCompatibleDevices);
private:
};
}
|
e81f6b4785a72289714e64a139f24ccf75b0c09b | 53183072c0af943d1ff3e94e96ea7464a9114474 | /main.cpp | 284206e369b553eac35fb8f0f0c7b2770ef6606a | [] | no_license | AdiMustBeFunny/Minesweeper | 376458e236ca6e63018a96baed4b9c41b80e130b | b079db82031ebc2ba2ec8886414150be2ac072fa | refs/heads/master | 2020-05-06T13:57:03.076589 | 2019-04-08T14:29:53 | 2019-04-08T14:29:53 | 180,164,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,708 | cpp | main.cpp | #include<iostream>
#include<vector>
#include<list>
#include<cstdlib>
#include<time.h>
#include<Windows.h>
using namespace std;
enum TileType
{
Mine,
Number
};
struct Tile
{
TileType type=Number;
int x, y;
bool revealed = false;
bool demined = false;
int adjecentMineCount = 0;
};
class TileMap
{
public:
void MainLoop()
{
int choice = -1;
while (choice < 0 || choice > 2)
{
system("cls");
cout << "Welocme to the Minesweeper" << endl;
cout << "1. to start a new game" << endl;
cout << "0. to quit" << endl;
cin >> choice;
switch (choice)
{
case 0:
return;
break;
case 1:
cout << "Set width: ";
cin >> Width;
cout << "Set height: ";
cin >> Height;
cout << "Set mine count: ";
cin >> mineCount;
firstTurn = true;
playerRevealedCount = 0;
playerDeminedCount = 0;
maxPlayerDeminedCount = mineCount;
clearBoard();
//spawnMines();
GameStatus status = gameLoop();
if (status == Failure)
{
system("cls");
display();
cout << "Maybe next time." << endl;
}
else {
system("cls");
display();
cout << "Gratz mate you rock!!!" << endl; }
system("pause");
break;
}
choice = -1;
}
}
private:
int Width, Height;
int mineCount;
int playerRevealedCount = 0;
int playerDeminedCount = 0;
int maxPlayerDeminedCount = 0;
bool firstTurn = true;
vector<vector<Tile>> board;
void display()
{
for (int i = 0; i < Height; i++)
{
for (int j = 0; j < Width; j++)
{
if (board[i][j].revealed) {
if (board[i][j].type == Number)cout << board[i][j].adjecentMineCount << ' ';
else cout << 'X' << ' ';
}
else if(board[i][j].demined)
cout << 'D' << ' ';
else
cout << '#' << ' ';
}
cout << endl;
}
}
void clearBoard()
{
board.clear();
for (int i = 0; i < Height; i++)
{
board.push_back(vector<Tile>());
for (int j = 0; j < Width; j++)
{
Tile t;
t.x = j;
t.y = i;
board[i].push_back(t);
}
}
}
void spawnMines(int x,int y)
{
for (int i = 0; i < mineCount; i++)
{
int rnd_x = rand() % Width;
int rnd_y = rand() % Height;
while (board[rnd_y][rnd_x].type == Mine && (rnd_x==x && rnd_y == y))//We make sure that we dont spawn mine on top of another
{
rnd_x = rand() % Width;
rnd_y = rand() % Height;
}
board[rnd_y][rnd_x].type = Mine;
updateAdjacentNumbers(rnd_x, rnd_y);
}
}
void updateAdjacentNumbers(int x,int y)
{
if (x > 0 && y > 0)board[y - 1][x - 1].adjecentMineCount += 1;
if (x > 0 && y < Height-1)board[y + 1][x - 1].adjecentMineCount += 1;
if (x < Width-1 && y > 0)board[y - 1][x + 1].adjecentMineCount += 1;
if (x < Width - 1 && y < Height - 1)board[y + 1][x + 1].adjecentMineCount += 1;
if (x > 0)board[y][x - 1].adjecentMineCount += 1;
if (x < Width - 1)board[y][x + 1].adjecentMineCount += 1;
if (y > 0)board[y - 1][x].adjecentMineCount += 1;
if (y < Height - 1)board[y + 1][x].adjecentMineCount += 1;
}
enum GameStatus { Success, Failure} ;
void setRevealed(int from_x, int from_y)
{
if (firstTurn)
{
firstTurn = false;
spawnMines(from_x,from_y);
}
if (board[from_y][from_x].revealed == true || board[from_y][from_x].demined == true)return;
list<Tile*> revealArea;
revealArea.push_back(&board[from_y][from_x]);
while (!revealArea.empty())
{
int beginSize = revealArea.size();
list<Tile*>::iterator endd = revealArea.begin();
advance(endd, beginSize);
for (list<Tile*>::iterator tile = revealArea.begin(); tile !=endd;tile++)//auto tile : revealArea)
{
(*tile)->revealed = true;
if ((*tile)->adjecentMineCount > 0)continue;//if it is not 0 then all we do is reveal and finish
if ((*tile)->x > 0 && (*tile)->y > 0 && board[(*tile)->y - 1][(*tile)->x - 1].demined == false && board[(*tile)->y - 1][(*tile)->x - 1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y - 1][(*tile)->x - 1]) { copy = true; break; }
}
if(!copy)
revealArea.push_back(&board[(*tile)->y-1][(*tile)->x -1]);
}
if ((*tile)->x > 0 && (*tile)->y < Height-1 && board[(*tile)->y+1][(*tile)->x-1].demined == false && board[(*tile)->y+1][(*tile)->x-1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y + 1][(*tile)->x - 1]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y + 1][(*tile)->x - 1]);
}
if ((*tile)->x < Width-1 && (*tile)->y > 0 && board[(*tile)->y-1][(*tile)->x+1].demined == false && board[(*tile)->y-1][(*tile)->x+1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y - 1][(*tile)->x + 1]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y - 1][(*tile)->x + 1]);
}
if ((*tile)->x < Width-1 && (*tile)->y < Height-1 && board[(*tile)->y+1][(*tile)->x+1].demined == false && board[(*tile)->y+1][(*tile)->x+1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y + 1][(*tile)->x + 1]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y + 1][(*tile)->x + 1]);
}
if ((*tile)->x > 0 && board[(*tile)->y][(*tile)->x-1].demined == false && board[(*tile)->y][(*tile)->x-1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y][(*tile)->x - 1]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y][(*tile)->x - 1]);
}
if ((*tile)->x < Width-1 && board[(*tile)->y][(*tile)->x+1].demined == false && board[(*tile)->y][(*tile)->x+1].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y][(*tile)->x + 1]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y][(*tile)->x + 1]);
}
if ((*tile)->y > 0 && board[(*tile)->y-1][(*tile)->x].demined == false && board[(*tile)->y-1][(*tile)->x].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y - 1][(*tile)->x]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y - 1][(*tile)->x]);
}
if ((*tile)->y < Height-1 && board[(*tile)->y + 1][(*tile)->x].demined == false && board[(*tile)->y + 1][(*tile)->x].revealed == false)
{
bool copy = false;
for (list<Tile*>::iterator t = revealArea.begin(); t != endd; t++)
{
if ((*t) == &board[(*tile)->y + 1][(*tile)->x]) { copy = true; break; }
}
if (!copy)
revealArea.push_back(&board[(*tile)->y + 1][(*tile)->x]);
}
}
for (int i = 0; i < beginSize; i++)
{
playerRevealedCount += 1;
revealArea.pop_front();
}
}
}
void setDemined(int x, int y)
{
if (board[y][x].demined == true) { board[y][x].demined = false; playerDeminedCount -= 1; }
else if(playerDeminedCount<maxPlayerDeminedCount)
{
board[y][x].demined = true;
playerDeminedCount += 1;
}
}
GameStatus gameLoop()
{
int desiredRevealCount = Width * Height - mineCount;
while (playerRevealedCount != desiredRevealCount)
{
system("cls");
cout << "Revealed: " << playerRevealedCount << ". To reveal: " << desiredRevealCount << endl;
display();
cout << "Which tile to reveal? (mode,x,y) modes: 0-reveal 1- mark mine. ex.\n0 1 2- reveal mine at x=1, y=2 \n1 0 0- mark mine at x=0, y=0" << endl;
int p_x, p_y;
int mode;
cin >> mode >> p_x >> p_y;
if (mode == 0)
{
if (board[p_y][p_x].type == Mine)return Failure;//exit
else setRevealed(p_x, p_y); //board[p_y][p_x].revealed = true;
}
else//demine
{
setDemined(p_x, p_y);
}
}
return Success;
}
};
int main()
{
srand(time(NULL));
TileMap t;
t.MainLoop();
return 0;
} |
688db46b87f993686fa53f999824007a1377d249 | fd6c11973fdacec514fec2e7ab67e04895904508 | /bftengine/src/bftengine/messages/StateTransferMsg.cpp | 6093bc4d43e7ade5285f25347704d4792331b43c | [
"Apache-2.0"
] | permissive | vmware/concord-bft | 3c776e6dcf02ea524c35ecf7c74a37d12b4c4ac4 | 61c4d39e5ca71690817e341c9713e014b91a13d8 | refs/heads/master | 2023-08-25T12:23:15.164063 | 2023-05-09T08:31:27 | 2023-05-09T08:31:27 | 143,135,325 | 397 | 167 | null | 2023-09-12T05:09:38 | 2018-08-01T09:36:28 | C++ | UTF-8 | C++ | false | false | 816 | cpp | StateTransferMsg.cpp | // Concord
//
// Copyright (c) 2018 VMware, Inc. All Rights Reserved.
//
// This product is licensed to you under the Apache 2.0 license (the "License"). You may not use this product except in
// compliance with the Apache 2.0 License.
//
// This product may include a number of subcomponents with separate copyright notices and license terms. Your use of
// these subcomponents is subject to the terms and conditions of the subcomponent's license, as noted in the LICENSE
// file.
#include "StateTransferMsg.hpp"
#include "util/assertUtils.hpp"
namespace bftEngine::impl {
void StateTransferMsg::validate(const ReplicasInfo&) const {
ConcordAssert(type() == MsgCode::StateTransfer);
if (size() < sizeof(MessageBase::Header)) throw std::runtime_error(__PRETTY_FUNCTION__);
}
} // namespace bftEngine::impl
|
6015ba682f4a674881d4c3fd0327b08cea1f555e | 202306e250194e8d56cc50e9f9538e96c33cd654 | /ConvWx/src/include/ConvWx/IndexGridVal.hh | be536d9a2b9e1092212afd11f78ce587c5d8139c | [] | no_license | AdrianoPereira/ral-libs-shared | f9d34023b0994def083292cca39ec2dacc33b7fc | 9e3644604cb9c08e1bac6f45c149e22060d59170 | refs/heads/master | 2022-03-22T16:36:02.804926 | 2019-12-11T22:23:49 | 2019-12-11T22:23:49 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 2,331 | hh | IndexGridVal.hh | // *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
// © University Corporation for Atmospheric Research (UCAR) 2009-2010.
// All rights reserved. The Government's right to use this data and/or
// software (the "Work") is restricted, per the terms of Cooperative
// Agreement (ATM (AGS)-0753581 10/1/08) between UCAR and the National
// Science Foundation, to a "nonexclusive, nontransferable, irrevocable,
// royalty-free license to exercise or have exercised for or on behalf of
// the U.S. throughout the world all the exclusive rights provided by
// copyrights. Such license, however, does not include the right to sell
// copies or phonorecords of the copyrighted works to the public." The
// Work is provided "AS IS" and without warranty of any kind. UCAR
// EXPRESSLY DISCLAIMS ALL OTHER WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
// ANY IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE.
//
// *=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*=*
/**
* @file IndexGridVal.hh
* @brief IndexGridVal holds grid index and data value at the grid index.
* @class IndexGridVal
* @brief IndexGridVal holds grid index and data value at the grid index.
*/
#ifndef INDEXGRIDVAL_HH
#define INDEXGRIDVAL_HH
#include <utility>
class IndexGridVal{
public:
/**
* Constructor
* @param[in] index Array index of grid point
* @param[in] gridVal Data value at grid index
*/
inline IndexGridVal(const double index, const double gridVal)
{
pIndex = index; pGridVal = gridVal;
}
/**
* Default destructor
*/
inline virtual ~IndexGridVal(void) {}
/**
* @return pIndex Model grid array index
*/
inline double getIndex(void)const {return pIndex;}
/**
* @return pGridVal Data value at model grid index
*/
inline double getValue(void)const {return pGridVal;}
/**
* @param[in] a Reference to an IndexGridVal object
* @return true if pGridVal is less than input argument's pGridVal member.
* Else return false.
*/
inline bool operator <(const IndexGridVal& a) const
{
return pGridVal < a.pGridVal;
}
protected:
private:
/**
* Array index of grid point.
*/
double pIndex;
/**
* Data value at grid index.
*/
double pGridVal;
};
#endif
|
abcf4fb5b61949cdc7672b9f3d14bd15da8bdfd4 | 6b0a7c91a64c57e4422394eab458349822763699 | /50 trivial/Judging Moose.cpp | 2d6fe7d6f956c1ac7c0323f7d2f61bece321cdf6 | [] | no_license | DgrinderHZ/Kattis | 4e386a8ef099fc04b8b5a6f3098efc93feb9aea6 | ea9618c7bca2f89b0f0a4b873f18a50523c7c6b8 | refs/heads/master | 2020-03-27T09:18:39.676154 | 2019-10-20T13:31:42 | 2019-10-20T13:31:42 | 146,329,836 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | Judging Moose.cpp | #include <bits/stdc++.h>
using namespace std;
int main ()
{
freopen ("input.txt","r",stdin);
//freopen ("output.txt","w",stdout);
/* Code here */
int l, r;
cin>> l>> r;
if(l==0 && r==0){
cout<<"Not a moose";
}else if(l == r){
cout<<"Even "<< l+r;
}else{
cout<<"Odd "<<((l<r)?r*2:l*2);
}
fclose (stdin);
//fclose (stdout);
return 0;
}
|
b17cc45dae7a7f180d4c50451e74dce864bf9e36 | 2407ac66f106a8c0372f8bcaa82e342e06f46319 | /Baseball/Baseball/main.cpp | 8ef4c1d4736c1ce8a3e1a02a33433f9d210a625f | [] | no_license | FANOOJungjieun/exercise | 601aad0fc360220d0ea9b95d6b1a2e9ba24540bb | 3be9b69383d66c964d466411f0d0cb3fd4b344ad | refs/heads/master | 2022-06-08T22:37:25.431267 | 2022-05-16T08:34:58 | 2022-05-16T08:34:58 | 219,710,691 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 1,528 | cpp | main.cpp | #include<iostream>
#include<ctime>
using namespace std;
bool correct;
int set[4];
int number[4];
int digits[4];
int stk, ball;
void init(int ran[]) {
srand((unsigned int)time(0));
int sb1 = 0;
int sb2 = 0;
int sb3 = 0;
int sb4 = 0;
while (sb1 == sb2 || sb1 == sb3 || sb1 == sb4 || sb2 == sb3 || sb2 == sb4 || sb3 == sb4)
{
sb1 = rand() % 10;
sb2 = rand() % 10;
sb3 = rand() % 10;
sb4 = rand() % 10;
}
ran[0] = sb1;
ran[1] = sb2;
ran[2] = sb3;
ran[3] = sb4;
return;
}
void baseball() {
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 4; j++) {
if (set[i] == number[j]) {
if (i == j) {
stk++;
}
else {
ball++;
}
}
}
}
if (stk == 4) {
correct = true;
}
return;
}
int main() {
init(set);
correct = false;
int input2;
cout << "이것은 숫자가 중복되지 않는 4자릿수의 숫자 야구 게임입니다." << endl;
while (!correct) {
int input;
stk = 0;
ball = 0;
cout << "답이라고 생각되는 4자릿수의 숫자를 입력하세요. : ";
cin >> input;
input2 = input;
number[3] = input % 10;
digits[3] = number[3];
input /= 10;
number[2] = input % 10;
digits[2] = number[2];
input /= 10;
number[1] = input % 10;
digits[1] = number[1];
input /= 10;
number[0] = input % 10;
digits[0] = number[0];
input /= 10;
baseball();
cout << "스트라이크 = " << stk << endl;
cout << "볼 = " << ball << endl;
}
cout << "축하합니다. 정답은 = " << input2 << endl;
return 0;
} |
898516b8c5a674407526c217f00a7763c074c6ef | c6b828507d1550f2d3762c8fa6d6504d30758304 | /Tarea2/cache.h | 1319a4e5a0cae25f74b9ad21b2b63e3c959bc52d | [] | no_license | katyape/IE0521-Estructuras2 | 4651abeb41adb43209bf6779c728b1a849c8bc8b | ed3669ee6ba295ec96e09567a5099c9bc8506b73 | refs/heads/master | 2020-03-29T15:09:08.103516 | 2018-09-24T05:56:29 | 2018-09-24T05:56:29 | 150,047,225 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,189 | h | cache.h | // Para que no se redefina la clase
#ifndef CACHE
#define CACHE
#include<string>
#include<iostream>
using namespace std;
//Se crea una estructura llamada Bloque.
//Esta estructura poseera su tag, index, valor de dirty bit y ademas
// un atributo para verificar si esta vacio y el valor de prediccion de reuso.
typedef struct Bloque{
long tag=0;
long index=0;
int dirty_bit=0;
int vacio=1;
int RRPV=3;
}Bloque;
class Cache {
// Esta clase Cache poseera los atributos que se muestran:
// Su numero de vias, contadores para misses, hits, dirty evictions, la mascaras
// que necesitara y los metodos que se muestran para que trabaje adecuadamente.
// Todo se trabajara de manera publica por motivos de simplicidad.
public:
int contador_dirty_evictions = 0;
int store_misses = 0;
int store_hits = 0;
int load_misses = 0;
int load_hits=0;
long index_mask, tag_mask;
int bits_tag, bits_index, bits_offset;
int vias;
Bloque **Cabeza_vias;
//Metodos. Void por simplicidad.
Cache(int, int, int);
~Cache(void);
void verificar_direccion(int, int);
void reemplazar(int, int, int, int);
void modificar_RRPV(int);
void victimizar(int, int, int);
};
#endif
|
2080baede401a172e997bc02c8891cd268fbdc8b | 0b122cab77b02f30d765bb81317acb6d6af2f4d1 | /Code/Historical/Playground/Playground.ino | 572a315eeccd601002e5a039d829b3aa63a58402 | [] | no_license | keithmatthews440/DHEC_Dam_Sensor_System | 0386a96f56a555f70d650e2d96322f8c54c3b8e7 | 0b55b06d61df23119327957cb1ed1a0f697783b5 | refs/heads/main | 2023-04-24T04:10:45.775972 | 2021-05-11T14:29:19 | 2021-05-11T14:29:19 | 317,577,870 | 4 | 3 | null | 2020-12-02T17:33:04 | 2020-12-01T15:05:01 | HTML | UTF-8 | C++ | false | false | 2,044 | ino | Playground.ino | #define BLYNK_PRINT Serial
#include "ESP8266.h"
#define SSID "ITEAD"
#define PASSWORD "12345678"
ESP8266 wifi(Serial1);
void setup(void)
{
Serial.begin(9600);
Serial.print("setup begin\r\n");
Serial.print("FW Version: ");
Serial.println(wifi.getVersion().c_str());
if (wifi.setOprToStation()) {
Serial.print("to station ok\r\n");
} else {
Serial.print("to station err\r\n");
}
if (wifi.joinAP(SSID, PASSWORD)) {
Serial.print("Join AP success\r\n");
Serial.print("IP: ");
Serial.println(wifi.getLocalIP().c_str());
} else {
Serial.print("Join AP failure\r\n");
}
Serial.print("setup end\r\n");
}
void loop(void)
{
}
/*#include <ESP8266_Lib.h>
#include <BlynkSimpleShieldEsp8266.h>
#include <SoftwareSerial.h>
#define ESP8266_BAUD 9600
char auth[] = "6bae2d0e7bfa4b6096feeaffa2030e4f";
char ssid[] = "Verizon-MiFi6620L-D829"; //You can replace the wifi name to your wifi
char pass[] = "83cc19c4"; //Type password of your wifi.
SoftwareSerial EspSerial(2, 3); // RX, TX
WidgetLCD lcd(V0);
ESP8266 wifi(&EspSerial);
void setup()
{
Serial.begin(9600);
EspSerial.begin(ESP8266_BAUD);
Blynk.begin(auth, wifi, ssid, pass);
lcd.clear();
lcd.print(1, 1, "IoT");
}
void loop()
{
Blynk.run();
}
/*include <SoftwareSerial.h>
SoftwareSerial ESPserial(2, 3); // RX | TX
void setup()
{
Serial.begin(115200); // communication with the host computer
//while (!Serial) { ; }
// Start the software serial for communication with the ESP8266
ESPserial.begin(115200);
Serial.println("");
Serial.println("Remember to to set Both NL & CR in the serial monitor.");
Serial.println("Ready");
Serial.println("");
}
void loop()
{
// listen for communication from the ESP8266 and then write it to the serial monitor
if ( ESPserial.available() ) { Serial.write( ESPserial.read() ); }
// listen for user input and send it to the ESP8266
if ( Serial.available() ) { ESPserial.write( Serial.read() ); }
}*/
|
09d3efb06b35a1dd45c2aedcc409f5d31459be0f | d0693c95a4360a293aaecc2fac2398b1b8b8a92a | /include/LIP.hpp | 5b6d6449078f17ba3e2cc44f2ec7574883c597f3 | [] | no_license | deno750/LinearProgramming | eb5cf45765dabb000866c6c21d4dcd8c1a7a4787 | bf5e54200225ca685fd09a3ed1b94d9b19fde6ac | refs/heads/master | 2021-09-10T02:00:23.526825 | 2021-09-09T16:29:51 | 2021-09-09T16:29:51 | 230,082,492 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | hpp | LIP.hpp | //
// LIP.hpp
// LinearProgramming
//
// Created by Denis Deronjic on 28/12/2019.
// Copyright © 2019 Denis Deronjic. All rights reserved.
//
#ifndef LIP_HPP
#define LIP_HPP
#include <stdio.h>
#include <math.h>
#include "Matrix.hpp"
#include "Fraction.hpp"
//Includes functions for Linear Integer Programming
class LIP {
public:
/**
* Solves the Linear Integer programming problem using the cutting plane algorithm.
*
* -Param mat: The matrix tableu that defines the constraints and the costs for the problem. The algorithm works with standard form Ax = b.
*/
int solve(Matrix &mat, bool useBranchAndBound);
int solve(std::vector<double> c, Matrix &a, std::vector<double> b);
private:
/**
* This function can be easly located in Fraction class. Since the cutting plane algorithm needs the calculation of the decimal, it is useful to have this function located in LIP class because the calculation of the decimal is an important part of cutting plane algorithm.
*
* -Param val: The Fraction instance from where we want the decimal value
*
* -Returns the calculated decimal Fraction
*/
Fraction calculateDecimal(Fraction val);
void solveWithGomoryCuts(Matrix &mat, unsigned nonIntegerIndex);
void solveWithBranchAndBound(Matrix &mat, unsigned nonIntegerIndex, unsigned currentNodeIndex);
};
#endif /* LIP_hpp */
|
1c342aa53b7b46da5034b0d52fc1040ece04add4 | 8b655b94912974e05367dabb7a1e682b495c777d | /appWeather.cpp | 73e5f3b193c70a560830a1374ac78962740b752c | [
"BSD-3-Clause"
] | permissive | Mattti0/T-watch-2020 | bc209d80292d1227270c37ba5660c16498d18eb3 | 3be30c0c77c614e80b11fd3e24b28731f33ea57e | refs/heads/master | 2023-05-23T04:57:39.244140 | 2021-06-09T11:08:38 | 2021-06-09T11:08:38 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,314 | cpp | appWeather.cpp | // connect to wifi (stored in "file" acc_pts.txt (in SPIFF)), and then
// get the weather
#include "config.h"
#include "DudleyWatch.h"
#include <time.h>
#include <string.h>
// #include "esp_wifi.h"
#include <WiFi.h>
#include <Wire.h>
#include <Ethernet.h>
#include <ArduinoJson.h>
#include <AceTime.h>
#include "HTTPClient.h"
#include <OpenWeatherOneCall.h>
#include <NTPClient.h>
#include <WiFiUdp.h>
#include "my_WiFi.h"
#include "appMQTT.h"
extern WiFiClient espClient;
#include "icons.h"
#include "personal_info.h"
extern char str_latitude[];
extern char str_longitude[];
extern char get_loc_city[];
// 0 result means success
// -1 result means default to home IP
int get_lat_lon (void);
int get_city_from_lat_long(char *, char *);
float my_latitude, my_longitude;
#define DBGWEATHER 0
#define verbose true
OpenWeatherOneCall OWOC;
#define ICONSIZEFIX 0
#if ICONSIZEFIX
#define ICFIX(n) do{x+=(w-n)/2;y+=(w-n)/2;w=n;h=n;}while(0);
#else
#define ICFIX(n)
#endif
// accepts icon name ("01d", "01n", etc) and pushes that image to TFT
void putIcon(int x, int y, int w, int h, const char * iconname) {
const short unsigned int *imagefile;
tft->setSwapBytes(true);
switch(iconname[0]) {
case '0' :
switch(iconname[1]) {
case '1' :
switch(iconname[2]) {
case 'd' :
imagefile = i01d;
break;
case 'n' :
imagefile = i01n;
break;
}
break;
case '2' :
switch(iconname[2]) {
case 'd' :
imagefile = i02d;
break;
case 'n' :
imagefile = i02n;
break;
}
break;
case '3' :
switch(iconname[2]) {
case 'd' :
imagefile = i03d;
break;
case 'n' :
imagefile = i03n;
break;
}
break;
case '4' :
switch(iconname[2]) {
case 'd' :
imagefile = i04d;
break;
case 'n' :
imagefile = i04n;
break;
}
break;
case '9' :
switch(iconname[2]) {
case 'd' :
imagefile = i09d;
break;
case 'n' :
imagefile = i09n;
break;
}
break;
}
break;
case '1' :
switch(iconname[1]) {
case '0' :
switch(iconname[2]) {
case 'd' :
imagefile = i10d;
break;
case 'n' :
imagefile = i10n;
break;
}
break;
case '1' :
switch(iconname[2]) {
case 'd' :
imagefile = i11d;
break;
case 'n' :
imagefile = i11n;
break;
}
break;
case '3' :
switch(iconname[2]) {
case 'd' :
imagefile = i13d;
break;
case 'n' :
imagefile = i13n;
break;
}
break;
}
break;
case '5' :
switch(iconname[2]) {
case 'd' :
imagefile = i50d;
break;
case 'n' :
imagefile = i50n;
break;
}
break;
}
tft->pushImage(x, y, w, h, imagefile);
}
#define PAGE1 1
#define PAGE2 2
#define PAGE3 3
#define PAGE4 4
#define PAGE5 5
#define ICONTEST 27
int get_wifi_credentials_from_user (void);
void connectToWiFi(struct WiFiAp *);
void appWeather(void) {
uint32_t this_sec;
int err, ecnt, lastmode, mode, mSelect, this_wifi, alert_pages;
int last_char_index, alert_summary_length, page2sumidx[10], owcres;
int16_t x, y;
char temp_unit = (general_config.metric_units) ? 'C' : 'F';
const char *velocity_unit = (general_config.metric_units) ? "km/hr" : "mi/hr";
get_loc_city[0] = '\0';
if(connect_to_wifi(verbose, &BestAP, true, true) && verbose) {
close_WiFi();
Serial.printf("connect to wifi failed\n");
tft->setTextColor(TFT_YELLOW, TFT_BLACK);
tft->setTextSize(1);
tft->setCursor(0, 50 + (15 * 7));
tft->print(F("Connect to WiFi Failed!"));
tft->setCursor(0, 50 + (15 * 8));
tft->setTextColor(TFT_GREEN, TFT_BLACK);
tft->print(F("Opening New WiFi screen"));
tft->setCursor(0, 50 + (15 * 9));
tft->setTextColor(TFT_RED, TFT_BLACK);
tft->print(F("remember to hit the checkmark on"));
tft->setCursor(0, 50 + (15 * 10));
tft->print(F("the keyboard when finished entering"));
tft->setCursor(0, 50 + (15 * 11));
tft->print(F("the password!"));
delay(5000);
Serial.println(F("trying get wifi credentials from user"));
this_wifi = get_wifi_credentials_from_user();
if(this_wifi >= 0) {
Serial.printf("got wifi credentials, this_wifi = %d\n", this_wifi);
Serial.printf("before connectToWiFi: ssid %s, pass %s, tzone %u\n", BestAP.ssid, BestAP.pass, BestAP.tzone);
connectToWiFi(&BestAP);
}
else {
Serial.printf("didn't get wifi credentials, this_wifi = %d\n", this_wifi);
return;
}
}
ecnt = 0;
while(!connected && ecnt < 400) {
#if DBGWEATHER
Serial.println(F("waiting 0.2 seconds for wifi connection"));
#endif
ecnt++;
delay(200);
}
if(ecnt == 400) {
#if DBGWEATHER
Serial.println(F("couldn't get wifi connection in 80 seconds!"));
#endif
tft->setTextColor(TFT_YELLOW, TFT_BLACK);
tft->drawString("Connect to WiFi failed in 80 seconds!", 0, 5, 2);
delay(3000);
close_WiFi();
connected = false;
return;
}
if(verbose) {
tft->setTextColor(TFT_GREEN, TFT_BLACK);
tft->setTextSize(1);
tft->setCursor(0, 50 + (15 * 9));
tft->printf("Connected to %s channel %d", BestAP.ssid, BestAP.channel);
tft->setCursor(0, 50 + (15 * 10));
tft->print(F("Trying to connect to "));
tft->print(F("openweathermap.com"));
tft->setCursor(0, 50 + (15 * 11));
tft->print(F("my ip is: "));
tft->print(WiFi.localIP());
}
delay(1000);
#if DBGWEATHER
Serial.println(F("Trying to get latitude and longitude from IP address"));
#endif
// first, get our location:
int locr = get_lat_lon(); // populate str_latitude & str_longitude
#if DBGWEATHER
if(locr) {
Serial.printf("at home OR couldn't get latitude and longitude from IP address\n");
}
else {
Serial.printf("IP address -> str_latitude %s str_longitude %s\n", str_latitude, str_longitude);
}
#endif
if(!get_loc_city[0]) {
Serial.printf("about to call get_city(%s,%s)\n", str_latitude, str_longitude);
locr = get_city_from_lat_long(str_latitude, str_longitude);
#if DBGWEATHER
if(locr) {
Serial.printf("couldn't get cityname from latitude and longitude\n");
}
else {
Serial.printf("str_latitude %s str_longitude %s -> city %s\n", str_latitude, str_longitude, get_loc_city);
}
#endif
}
if(str_latitude[0]) {
my_latitude = atof(str_latitude);
}
if(str_longitude[0]) {
my_longitude = atof(str_longitude);
}
#define ALERT_TEST_LOCATION 0
#if ALERT_TEST_LOCATION
// my_latitude = 47.1848;
// my_longitude = -123.615;
// my_latitude = 31.8354411
// my_longitude = -93.2885038;
// my_latitude = 13.421129; // Guam
// my_longitude = 144.73972;
my_latitude = 29.9038; // India
my_longitude = -73.877190;
#endif
#if DBGWEATHER
Serial.printf("IP address -> my_latitude %f my_longitude %f\n", my_latitude, my_longitude);
Serial.println(F("Trying to connect to openweathermap.com"));
#endif
//=================================
// Get the Weather Forecast
//=================================
/* EXCLUDES ARE:
EXCL_C(urrent) EXCL_D(aily) EXCL_H(ourly) EXCL_M(inutely) EXCL_A(lerts)
In the form EXCL_C+EXCL_D+EXCL_H etc
NULL == EXCLUDE NONE (Send ALL Info)
*/
owcres = OWOC.setOpenWeatherKey(general_config.owm_api_key);
if(owcres) {
Serial.printf("OWOC error: %s\n", OWOC.getErrorMsgs(owcres));
goto ExitWeather;
}
owcres = OWOC.setLatLon(my_latitude, my_longitude);
if(owcres) {
Serial.printf("OWOC error: %s\n", OWOC.getErrorMsgs(owcres));
goto ExitWeather;
}
OWOC.setExcl(EXCL_H + EXCL_M);
OWOC.setUnits(general_config.metric_units ? METRIC : IMPERIAL);
#if OWM_LANGUAGE_FEATURE
OWOC.setLanguage(general_config.language);
#endif
my_idle();
owcres = OWOC.parseWeather();
if(owcres) {
Serial.printf("OWOC error: %s\n", OWOC.getErrorMsgs(owcres));
}
else {
memset(page2sumidx, 0, sizeof(page2sumidx)/sizeof(char));
#if ERRORTEST
#if DBGWEATHER
for(owcres = 1 ; owcres < 30 ; owcres++) {
Serial.printf("error %d -> %s\n", owcres, OWOC.getErrorMsgs(owcres));
}
#endif
#endif
mode = PAGE1;
lastmode = 0;
alert_pages = 0;
if(OWOC.alert) {
if(OWOC.alert->summary && OWOC.alert->summary[0]) {
alert_pages = (419 + strlen(OWOC.alert->summary)) / 420;
#if DBGWEATHER
Serial.printf("alert_pages = %d\n", alert_pages);
#endif
}
}
while(1) {
if(mode == PAGE1 && mode != lastmode) {
lastmode = mode;
tft->fillScreen(TFT_BLACK);
tft->setTextColor(TFT_YELLOW, TFT_BLACK);
if(get_loc_city[0]) {
sprintf(buff, "%s Weather Pg 1", get_loc_city);
}
else {
strcpy(buff, "Weather Pg 1");
}
tft->drawCentreString(buff, half_width, 0, 2);
if(OWOC.alert) {
if(OWOC.alert->summary && OWOC.alert->summary[0]) {
tft->setTextColor(TFT_RED, TFT_BLACK);
tft->drawString("Alert ->", 185, 0, 2);
}
}
tft->setTextColor(TFT_GREEN, TFT_BLACK);
tft->setTextFont(2);
if(OWOC.current->summary && OWOC.current->summary[0]) {
tft->setCursor(0, 15);
tft->printf("%s", OWOC.current->summary);
#if DBGWEATHER
Serial.printf("current summary = %s\n", OWOC.current->summary);
#endif
}
tft->setCursor(0, 30);
tft->printf("%.0f %c", OWOC.current->temperature, temp_unit);
tft->setCursor(0, 45);
tft->printf("%.0f %%RH", OWOC.current->humidity);
tft->setCursor(0, 60);
tft->printf("%.0f wind %s", OWOC.current->windSpeed, velocity_unit);
tft->setCursor(0, 75);
tft->printf("%.0f wind gust", OWOC.current->windGust);
tft->setCursor(85, 30);
tft->printf("%.0f %c dewpt", OWOC.current->dewPoint, temp_unit);
tft->setCursor(85, 45);
tft->printf("%.0f mbar", OWOC.current->pressure);
tft->setCursor(85, 60);
tft->printf("%.0f%% prob precip", 100.0 * OWOC.forecast[0].pop);
tft->setCursor(85, 75);
tft->printf("%.0f %c hi %.0f lo",
OWOC.forecast[0].temperatureHigh,
temp_unit,
OWOC.forecast[0].temperatureLow
);
if(OWOC.current->icon && OWOC.current->icon[0]) {
putIcon(191, 31, 48, 48, OWOC.current->icon);
#if DBGWEATHER
Serial.printf("current icon = %s\n", OWOC.current->icon);
#endif
}
#if DBGWEATHER
if(OWOC.current->main && OWOC.current->main[0]) {
Serial.printf("current main = %s\n", OWOC.current->main);
}
Serial.printf("current temp = %.1f\n", OWOC.current->temperature);
Serial.printf("current humidity = %.1f\n", OWOC.current->humidity);
Serial.printf("current pressure = %.1f\n", OWOC.current->pressure);
Serial.printf("current windSpeed = %.1f\n", OWOC.current->windSpeed);
Serial.printf("current windGust = %.1f\n", OWOC.current->windGust);
// Serial.printf("aW: line %d\n", __LINE__);
Serial.printf("current precipProbability = %.0f %%\n", 100.0 * OWOC.forecast[0].pop);
// Print 4 day forecast to Serial Monitor
Serial.println("");
Serial.println("4 Day Forecast:");
#endif
// for (int fo = 0; fo < (sizeof(OWOC.forecast) / sizeof(OWOC.forecast[0])) - 1; fo++)
for (int fo = 1; fo < 5 ; fo++)
{
//Date from epoch forecast[fo].dayTime
// long DoW = OWOC.forecast[fo].dayTime / 86400L;
// int day_of_week = (DoW + 4) % 7;
#if DBGWEATHER
Serial.printf("%s: high = %.0f %c, low %.0f %c\n",
OWOC.forecast[fo].weekDayName,
// OWOC.short_names[day_of_week],
OWOC.forecast[fo].temperatureHigh, temp_unit,
OWOC.forecast[fo].temperatureLow, temp_unit);
Serial.printf("%.0f %% precip probability\n", 100.0 * OWOC.forecast[fo].pop);
if(OWOC.forecast[fo].summary && OWOC.forecast[fo].summary[0]) {
Serial.printf("summary[%d] = %s\n", fo, OWOC.forecast[fo].summary);
}
if(OWOC.forecast[fo].main && OWOC.forecast[fo].main[0]) {
Serial.printf("main[%d] = %s\n", fo, OWOC.forecast[fo].main);
}
if(OWOC.forecast[fo].icon && OWOC.forecast[fo].icon[0]) {
Serial.printf("icon[%d] = %s\n", fo, OWOC.forecast[fo].icon);
}
#endif
int offset = 95;
tft->setCursor(60 * (fo-1) + 20, offset);
// tft->print(OWOC.short_names[day_of_week]);
tft->print(OWOC.forecast[fo].weekDayName);
offset += 15;
tft->setCursor(60 * (fo-1), offset);
tft->printf("%.0f %c hi", OWOC.forecast[fo].temperatureHigh, temp_unit);
offset += 15;
tft->setCursor(60 * (fo-1), offset);
tft->printf("%.0f %c lo", OWOC.forecast[fo].temperatureLow, temp_unit);
offset += 15;
tft->setCursor(60 * (fo-1), offset);
tft->printf("%.0f %%RH", OWOC.forecast[fo].humidity);
offset += 15;
tft->setCursor(60 * (fo-1), offset);
float pp = 100.0 * OWOC.forecast[fo].pop;
tft->printf("%.0f%% %s", pp, (pp < 100.0) ? "pop" : "pp");
offset += 15;
tft->setCursor(60 * (fo-1), offset);
if(OWOC.forecast[fo].main && OWOC.forecast[fo].main[0]) {
tft->printf("%s", OWOC.forecast[fo].main);
}
// ycoord = 185
if(OWOC.forecast[fo].icon && OWOC.forecast[fo].icon[0]) {
putIcon(60 * (fo-1) + 1, 191, 48, 48, OWOC.forecast[fo].icon);
}
}
}
else if(mode == PAGE2 && mode != lastmode) {
lastmode = mode;
tft->fillScreen(TFT_BLACK);
tft->setTextColor(TFT_YELLOW, TFT_BLACK);
if(get_loc_city[0]) {
sprintf(buff, "%s Weather Pg 2", get_loc_city);
}
else {
strcpy(buff, "Weather Pg 2");
}
tft->drawCentreString(buff, half_width, 0, 2);
if(OWOC.alert) {
last_char_index = 0;
if(OWOC.alert->summary && OWOC.alert->summary[0]) {
tft->setTextColor(TFT_RED, TFT_BLACK);
tft->drawString("More ->", 190, 75, 2);
alert_summary_length = strlen(OWOC.alert->summary);
}
if(OWOC.alert->event && OWOC.alert->event[0]) {
#if DBGWEATHER
Serial.printf("alert.event = %s\n", OWOC.alert->event);
#endif
tft->setCursor(0, 15);
tft->printf("%s", OWOC.alert->event);
}
if(OWOC.alert->senderName && OWOC.alert->senderName[0]) {
#if DBGWEATHER
Serial.printf("alert.senderName = %s\n", OWOC.alert->senderName);
#endif
tft->setCursor(0, 30);
tft->printf("%s", OWOC.alert->senderName);
tft->setCursor(0, 60);
tft->printf("from: %s", OWOC.alert->startInfo);
tft->setCursor(0, 75);
tft->printf("until: %s", OWOC.alert->endInfo);
}
}
tft->setTextColor(TFT_GREEN, TFT_BLACK);
tft->setTextFont(2);
// Print last 3 days forecast to Serial Monitor
#if DBGWEATHER
Serial.println("\nlast 3 Days Forecast:");
#endif
for (int fo = 5; fo < 8 ; fo++) {
#if DBGWEATHER
Serial.printf("%s: high = %.0f %c, low %.0f %c\n",
OWOC.forecast[fo].weekDayName,
OWOC.forecast[fo].temperatureHigh, temp_unit,
OWOC.forecast[fo].temperatureLow, temp_unit);
Serial.printf("%.0f %% precip probability\n", 100.0 * OWOC.forecast[fo].pop);
if(OWOC.forecast[fo].summary && OWOC.forecast[fo].summary[0]) {
Serial.printf("summary = %s\n", OWOC.forecast[fo].summary);
}
if(OWOC.forecast[fo].main && OWOC.forecast[fo].main[0]) {
Serial.printf("main = %s\n", OWOC.forecast[fo].main);
}
if(OWOC.forecast[fo].icon && OWOC.forecast[fo].icon[0]) {
Serial.printf("icon = %s\n", OWOC.forecast[fo].icon);
}
#endif
int offset = 95;
tft->setCursor(60 * (fo-5) + 20, offset);
tft->print(OWOC.forecast[fo].weekDayName);
offset += 15;
tft->setCursor(60 * (fo-5), offset);
tft->printf("%.0f %c hi", OWOC.forecast[fo].temperatureHigh, temp_unit);
offset += 15;
tft->setCursor(60 * (fo-5), offset);
tft->printf("%.0f %c lo", OWOC.forecast[fo].temperatureLow, temp_unit);
offset += 15;
tft->setCursor(60 * (fo-5), offset);
tft->printf("%.0f %%RH", OWOC.forecast[fo].humidity);
offset += 15;
tft->setCursor(60 * (fo-5), offset);
float pp = 100.0 * OWOC.forecast[fo].pop;
tft->printf("%.0f%% %s", pp, (pp < 100.0) ? "pop" : "pp");
offset += 15;
tft->setCursor(60 * (fo-5), offset);
if(OWOC.forecast[fo].main && OWOC.forecast[fo].main[0]) {
tft->printf("%s", OWOC.forecast[fo].main);
}
// ycoord = 185
if(OWOC.forecast[fo].icon && OWOC.forecast[fo].icon[0]) {
putIcon(60 * (fo-5) + 1, 191, 48, 48, OWOC.forecast[fo].icon);
}
}
}
else if(alert_pages
&& mode >= PAGE3
&& mode < ICONTEST
&& mode != lastmode) {
int sx, sy, pagelen, eop;
char oc;
lastmode = mode;
tft->fillScreen(TFT_BLACK);
tft->setTextColor(TFT_YELLOW, TFT_BLACK);
sprintf(buff, "Weather Alert Page %d", mode - 1);
tft->drawCentreString(buff, half_width, 0, 2);
tft->setTextColor(TFT_GREEN, TFT_BLACK);
tft->setTextFont(2);
pagelen = 30 * 12;
if(!page2sumidx[mode - PAGE3] && mode > PAGE3) {
page2sumidx[mode - PAGE3] = last_char_index;
}
last_char_index = page2sumidx[mode - PAGE3];
char * pp = &OWOC.alert->summary[last_char_index];
char * pe;
if(last_char_index + pagelen > strlen(OWOC.alert->summary)) {
pe = &OWOC.alert->summary[alert_summary_length - 1];
}
else {
pe = &OWOC.alert->summary[last_char_index + pagelen];
}
oc = *pe;
#if DBGWEATHER
Serial.printf("alert.summary part %d = %s\n", mode - PAGE3, pp);
#endif
if(last_char_index == 0) {
for(char *cp = pp ; *cp ; cp++) {
if((*cp == '\n' || *cp == '\r')
&& !(*(cp + 1) == '*' || *(cp + 1) == '.')
&& !(*(cp + 2) >= 'A' && *(cp + 2) <= 'Z')) {
*cp = ' ';
}
}
}
*pe = '\0';
tft->setCursor(0, 15);
tft->printf("%s", pp);
sx = tft->getCursorX();
sy = tft->getCursorY();
#if DBGWEATHER
Serial.printf("after big chunk, x = %d, y = %d\n", sx, sy);
Serial.printf("line %d, alert_summary_length = %d, last_char_index = %d\n", __LINE__, alert_summary_length, last_char_index);
#endif
last_char_index += pe - pp;
#if DBGWEATHER
Serial.printf("line %d, last_char_index = %d\n", __LINE__, last_char_index);
#endif
*pe = oc;
#if DBGWEATHER
Serial.printf("REMAINDER = %s\n", pe);
#endif
eop = 0;
if(alert_summary_length <= last_char_index) {
eop = 1;
alert_pages = mode - 2;
#if DBGWEATHER
Serial.printf("line %d, alert_summary_length = %d, last_char_index = %d, eop = %d, alert_pages = %d\n", __LINE__, alert_summary_length, last_char_index, eop, alert_pages);
#endif
}
while((sx < 180 || sy < 220) && !eop && OWOC.alert->summary[last_char_index]) {
tft->printf("%c", OWOC.alert->summary[last_char_index++]);
sx = tft->getCursorX();
sy = tft->getCursorY();
if(sy > 220 && sx > 120 && OWOC.alert->summary[last_char_index] == ' ') {
eop = 1;
#if DBGWEATHER
Serial.printf("last line break on a space, last_char_index = %d\n", last_char_index);
#endif
}
if(!OWOC.alert->summary[last_char_index]) {
eop = 1;
}
if(alert_summary_length <= last_char_index) {
eop = 1;
alert_pages = mode - 2;
#if DBGWEATHER
Serial.printf("line %d, END OF SUMMARY, alert_summary_length = %d, last_char_index = %d, eop = %d, alert_pages = %d\n", __LINE__, alert_summary_length, last_char_index, eop, alert_pages);
#endif
}
}
if(alert_summary_length > last_char_index) {
tft->setTextColor(TFT_RED, TFT_BLACK);
tft->drawString("More ->", 190, 223, 2);
tft->setTextColor(TFT_GREEN, TFT_BLACK);
}
#if DBGWEATHER
Serial.printf("line %d, after creeping to end, x = %d, y = %d\n", __LINE__, sx, sy);
Serial.printf("line %d, last_char_index = %d\n", __LINE__, last_char_index);
#endif
}
else if(mode == ICONTEST && mode != lastmode) {
lastmode = mode;
const char *iconnames[] = {
"01d", "01n", "02d", "02n", "03d", "03n", "04d", "04n", "09d",
"09n", "10d", "10n", "11d", "11n", "13d", "13n", "50d", "50n",
"01d", "01n"
};
tft->fillScreen(TFT_BLACK);
for (int r = 0 ; r < 4 ; r++) {
for (int c = 0 ; c < 5 ; c++) {
putIcon(c * 48, 12 + r * 60, 48, 48, iconnames[c + (r*5)]);
tft->drawString(iconnames[c + (r*5)], 15 + c * 48, r * 60, 2);
}
}
}
mSelect = poll_swipe_or_menu_press(16); // poll for touch or gesture
switch(mSelect) {
case LEFT :
if(mode == PAGE1) mode = PAGE2;
else if(mode < PAGE2 + alert_pages) mode++;
break;
case RIGHT :
if(mode > PAGE1 && mode < ICONTEST) mode--;
else mode = PAGE1;
break;
case UP :
break;
case DOWN :
goto ExitWeather;
case CWCIRCLE :
break;
case CCWCIRCLE :
mode = ICONTEST;
break;
}
my_idle();
}
}
ExitWeather:
while (ttgo->getTouch(x, y)) { // wait until user lifts finger to exit
my_idle();
}
connected = false;
close_WiFi();
tft->fillScreen(TFT_BLACK); // Clear screen
}
|
0986187d3c981cea2cbdb84f823a505ba590f6e3 | 3674c76452699205d34280347099dcfca38c1f01 | /ShadowPack/LocaleManager.h | 354d84f8ec2bcc513fe9f2b1ad2126cd179ef245 | [] | no_license | sTeeLM/shadowpack | c6677f02cb2c8baf87f5aad3aa3ca9a8f4df0504 | ad3a3b9a888fdb014725bbd4e6a57ffe1b08c89b | refs/heads/main | 2022-05-18T17:37:12.955042 | 2022-03-29T13:27:56 | 2022-03-29T13:27:56 | 11,245,741 | 6 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 924 | h | LocaleManager.h | #pragma once
#include "resource.h"
// CLocaleManager 命令目标
class CLocaleManager : public CObject
{
public:
CLocaleManager();
virtual ~CLocaleManager();
public:
typedef enum _LOCAL_ID_T {
LOCALE_CHINESE_SC = 0, /* default */
LOCALE_ENGLISH_US,
LOCALE_CNT
}LOCAL_ID_T;
BOOL Initialize();
BOOL SetLocale(LOCAL_ID_T Locale);
static UINT GetLocaleCount() { return (UINT)LOCALE_CNT; }
static CString GetLocalName(UINT nIndex)
{
CString strRet;
if (nIndex < LOCALE_CNT) {
strRet.LoadString(m_LocalTable[nIndex].nLocaleDesc);
}
else {
strRet.LoadString(IDS_LOCALE_UNKNOWN);
}
return strRet;
}
protected:
typedef struct _LOCAL_TABLE_T
{
LOCAL_ID_T Locale;
UINT nLocaleDesc;
DWORD dwLangureID;
DWORD dwSubLangureID;
HMODULE hResourceHandle;
LPCTSTR szResourceDll;
}LOCAL_TABLE_T;
static LOCAL_TABLE_T m_LocalTable[];
};
|
bb3196a586493607221bfbc653fbb545b7d90c8b | 69bc5e04598ef121882e85eb6bf828fda00decf8 | /src/robot_control_plugin.cpp | 1243298b12df238329611c2ce7415abb9286007d | [] | no_license | pohzhiee/ros2_control_gazebo | 2d551b2e5c2b13fc0de2e77fc890751e125c0017 | 2b576e74d4057e004e4115e37a7287767ef61741 | refs/heads/master | 2022-04-10T05:50:27.079880 | 2020-02-18T09:27:23 | 2020-02-18T09:27:23 | 208,930,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 20,518 | cpp | robot_control_plugin.cpp | #include "ros2_control_gazebo/robot_control_plugin.hpp"
#include "parameter_server_interfaces/srv/get_all_pid.hpp"
#include "py_wrappers/forward_kinematics.hpp"
#include <ament_index_cpp/get_package_share_directory.hpp>
#include <functional>
#include <string>
#include <chrono>
#include <algorithm>
namespace{
std::unique_ptr<ForwardKinematics> fk_ptr;
bool is_valid_joint_values(const std::vector<double> &joint_states){
std::string lobot_desc_share_dir = ament_index_cpp::get_package_share_directory("lobot_description");
std::string urdf_path = lobot_desc_share_dir + "/robots/arm_standalone.urdf";
if(fk_ptr == nullptr){
fk_ptr = std::make_unique<ForwardKinematics>(urdf_path);
}
auto pose = fk_ptr->calculate("world", "grip_end_point", joint_states);
return !(pose.translation.z < 0);
}
}
namespace gazebo_plugins {
constexpr double back_emf_constant = 0.8;
using namespace std::chrono_literals;
RobotControlPlugin::RobotControlPlugin()
: impl_(std::make_shared<RobotControlPluginPrivate>()) {
}
void RobotControlPlugin::Load(gazebo::physics::ModelPtr _model, sdf::ElementPtr _sdf) {
impl_->model_ = _model;
auto nodeOptions = rclcpp::NodeOptions();
nodeOptions.start_parameter_services(false);
impl_->ros_node_ = gazebo_ros::Node::CreateWithArgs(_sdf->Get<std::string>("name"), nodeOptions);
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Plugin loading...");
// Robot name is the name that is obtained from the urdf, used to query the parameter server
std::string robotName;
// Get the robot_name from the plugin sdf
if (_sdf->HasElement("robot_name")) {
sdf::ElementPtr robot_elem = _sdf->GetElement("robot_name");
robotName = robot_elem->Get<std::string>();
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Robot name from sdf: %s", robotName.c_str());
} else {
RCLCPP_FATAL(impl_->ros_node_->get_logger(),
"Robot name field not populated in sdf. Please set element robot_name");
return;
}
// Get the joints from parameter server
auto request_node = std::make_shared<rclcpp::Node>("robot_plugin_request_node");
auto joint_names = GetJoints(robotName, request_node);
auto pid_params_map = GetPidParameters(robotName, request_node);
// Register the joints, make sure the relevant vectors are empty first
impl_->pid_vec_.clear();
impl_->joints_vec_.clear();
// Some joints from the parameter server may not exist in the robot
uint8_t index = 0;
for (auto &joint_name : joint_names) {
auto joint = _model->GetJoint(joint_name);
if (!joint) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "Joint %s does not exist! Ignoring...",
joint_name.c_str());
continue;
}
impl_->joint_index_map_[joint_name] = index;
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Registering joint %s with id %lu", joint_name.c_str(), index);
auto pid = std::make_unique<gazebo::common::PID>(pid_params_map[joint_name]);
impl_->pid_vec_.emplace_back(std::move(pid));
impl_->joints_vec_.emplace_back(std::move(joint));
++index;
}
// index+1 gives the total number of registered joints, so we can initialise our vectors appropriately
impl_->goal_vec_.resize(index + 1);
impl_->command_vec_.resize(index + 1);
// Create the joint control subscription
auto qos_profile = rclcpp::QoS(20).reliable();
impl_->cmd_subscription_ = impl_->ros_node_->create_subscription<ros2_control_interfaces::msg::JointControl>(
"/" + robotName + "/control", qos_profile,
std::bind(&RobotControlPluginPrivate::CommandSubscriptionCallback, impl_, std::placeholders::_1));
// Create the set positions service
auto randomPositionsCallback = [this](std::shared_ptr<rmw_request_id_t> a,
std::shared_ptr<RandomPositions::Request> b,
std::shared_ptr<RandomPositions::Response> c) {
impl_->handle_RandomPositions(a, b, c);
};
impl_->random_positions_srv_ = impl_->ros_node_->create_service<RandomPositions>("/random_positions",
randomPositionsCallback);
SetUpdateRate(_sdf);
impl_->last_update_time_ = _model->GetWorld()->SimTime();
impl_->update_connection_ = gazebo::event::Events::ConnectWorldUpdateBegin(
std::bind(&RobotControlPluginPrivate::OnUpdate, impl_.get(), std::placeholders::_1));
}
void RobotControlPlugin::Reset() {
// RCLCPP_INFO(impl_->ros_node_->get_logger(), "Simulation reset called");
impl_->Reset();
}
void RobotControlPluginPrivate::OnUpdate(const gazebo::common::UpdateInfo &_info) {
const gazebo::common::Time ¤t_time = _info.simTime;
std::vector<double> local_goal_vec;
{
std::lock_guard<std::mutex> lock(goal_lock_);
local_goal_vec = goal_vec_;
}
if (random_position) {
random_position.store(false);
// if(joints_vec_.size() != local_goal_vec.size()){
// RCLCPP_ERROR(ros_node_->get_logger(), "Registered number of joints don't match randomised joints, "
// "joints_vec_size: %lu, goal_vec_size: %lu",
// joints_vec_.size(), local_goal_vec.size());
// }
// else{
for (unsigned long i = 0; i < joints_vec_.size(); i++) {
joints_vec_[i]->SetPosition(0, local_goal_vec[i]);
// RCLCPP_WARN(ros_node_->get_logger(),"Setting joint %s to %f", joints_vec_[i]->GetName().c_str(), local_goal_vec[i]);
}
// }
}
// If the world is reset, for example
if (current_time < last_update_time_) {
RCLCPP_INFO(ros_node_->get_logger(), "Negative sim time difference detected.");
last_update_time_ = current_time;
return;
}
// Check period
auto time_since_last_update = current_time - last_update_time_;
double seconds_since_last_update = time_since_last_update.Double();
if (seconds_since_last_update < update_period_) {
// Set the force to the previous controller command, otherwise it will default to 0
UpdateForceFromCmdBuffer();
return;
}
// Update the PID command if PID update period is reached for each joint
for (auto &pair : joint_index_map_) {
auto &joint_name = pair.first;
auto joint_index = pair.second;
auto &pid = pid_vec_[joint_index];
auto joint = model_->GetJoint(joint_name);
auto current_pos = joint->Position(0);
auto error = current_pos - local_goal_vec[joint_index];
double pid_output_command = pid->Update(error, time_since_last_update);
command_vec_[joint_index] = pid_output_command;
}
UpdateForceFromCmdBuffer();
// Update time
last_update_time_ = current_time;
}
void RobotControlPluginPrivate::CommandSubscriptionCallback(
ros2_control_interfaces::msg::JointControl::UniquePtr msg) {
// Uses map to write to buffer
{
// auto zero_time = rclcpp::Time(0, 0, RCL_ROS_TIME);
int64_t zero_time = 0;
int64_t msg_time = msg->header.stamp.sec * 1000000000 + msg->header.stamp.nanosec;
int64_t last_update_time = last_update_time_.sec * 1000000000 + last_update_time_.nsec;
// auto last_update_time = rclcpp::Time(last_update_time_.sec, last_update_time_.nsec, RCL_ROS_TIME);
if (msg_time > zero_time) {
int64_t time_buffer = 10000000;
int64_t time_diff = last_update_time - msg_time;
if (time_diff > time_buffer) {
RCLCPP_WARN(ros_node_->get_logger(),
"Ignoring outdated message, Msg time: [%u][%lu], Last update time: [%u][%lu]",
msg->header.stamp.sec, msg->header.stamp.nanosec, last_update_time / 1000000000,
last_update_time % 1000000000);
return;
}
}
auto msgNameSize = msg->joints.size();
auto msgCmdSize = msg->goals.size();
if (msgNameSize != msgCmdSize) {
RCLCPP_ERROR_ONCE(ros_node_->get_logger(), "Message number of joints don't match number of commands");
}
std::lock_guard<std::mutex> lock(goal_lock_);
for (size_t i = 0; i < msgNameSize; i++) {
auto goal = msg->goals[i];
auto name = msg->joints[i];
auto index_iter = joint_index_map_.find(name);
if (index_iter == joint_index_map_.end()) {
RCLCPP_WARN_ONCE(ros_node_->get_logger(), "Message joint [%s] not registered in the plugin",
name.c_str());
continue;
}
uint8_t index = (*index_iter).second;
goal_vec_[index] = goal;
}
}
}
void RobotControlPluginPrivate::Reset() {
for (const auto &joint : joints_vec_) {
joint->SetPosition(0, 0.0);
joint->SetVelocity(0, 0.0);
joint->SetForce(0, 0.0);
}
for (const auto &pid : pid_vec_) {
pid->Reset();
}
{
std::lock_guard<std::mutex> lock(goal_lock_);
for (auto &goal : goal_vec_) {
goal = 0;
}
}
last_update_time_ = gazebo::common::Time(0, 0);
}
void RobotControlPluginPrivate::handle_RandomPositions(const std::shared_ptr<rmw_request_id_t> &request_header,
const std::shared_ptr<RandomPositions::Request> &request,
const std::shared_ptr<RandomPositions::Response> &response) {
(void) request_header;
(void) request;
{
std::lock_guard<std::mutex> lock(goal_lock_);
bool valid = false;
do{
response->joints.clear();
response->positions.clear();
response->joints.resize(joint_index_map_.size());
response->positions.resize(joint_index_map_.size());
for (auto &pair: joint_index_map_) {
auto index = pair.second;
auto &joint = joints_vec_[index];
auto &pid = pid_vec_[index];
auto upper_limit = joint->UpperLimit(0);
auto lower_limit = joint->LowerLimit(0);
std::uniform_real_distribution<double> dist(lower_limit, upper_limit);
auto rand_angle = dist(rd_);
joint->SetPosition(0, rand_angle);
joint->SetVelocity(0, 0.0);
joint->SetForce(0, 0.0);
pid->Reset();
goal_vec_[index] = rand_angle;
response->joints[index] = (joint->GetName());
response->positions[index] = (rand_angle);
// RCLCPP_INFO(ros_node_->get_logger(), "Joint %s with val %f", joint->GetName().c_str(), rand_angle);
}
valid = is_valid_joint_values(response->positions);
} while(!valid);
random_position.store(true);
}
}
void RobotControlPluginPrivate::UpdateForceFromCmdBuffer() {
for (auto &pair : joint_index_map_) {
auto &joint_name = pair.first;
auto joint_index = pair.second;
auto command = command_vec_[joint_index];
auto joint = model_->GetJoint(joint_name);
if (joint != nullptr) {
// It seems like the GetVelocity method is subjected to a very high rounding error
// It rounds once during the current_pos - previous_pos
// It rounds another time during the division by time step
// The smaller the time step, the larger the floating point error is
// That is why the velocity seemingly never goes to a very small value
auto current_vel = joint->GetVelocity(0);
auto max_torque = joint->GetEffortLimit(0);
auto clamped_output = std::clamp(command, -max_torque, max_torque);
auto desired_output_torque = clamped_output - back_emf_constant * current_vel;
auto current_force = joint->GetForce(0);
// Gazebo is strange, even when you get a positive value for force, if you didn't call set force it wouldn't actually apply the force
// However, when you call SetForce(), it merely adds your passed force value to the existing value and apply that force instead
// Therefore, we need to reduce the entire amount of force obtained by GetForce(), such that SetForce() applies the force that we want
// instead of adding on to the old one
// This is separated into two steps because there is a clamping mechanism in set force, so we can't combine the values and set
joint->SetForce(0, -current_force);
joint->SetForce(0, desired_output_torque);
//Debugging stuff
/*
if (debug && joint_name == "arm_1_joint") {
auto current_pos = joint->Position(0);
auto force = joint->GetForce(0);
auto error = current_pos - local_goal_vec[joint_index];
const std::unique_ptr<gazebo::common::PID> &pid_ptr = pid_vec_[joint_index];
double pError, iError, dError;
pid_ptr->GetErrors(pError, iError, dError);
auto dTerm = pid_ptr->GetDGain() * dError;
auto iTerm = pid_ptr->GetIGain() * iError;
auto pTerm = pid_ptr->GetPGain() * pError;
RCLCPP_WARN(ros_node_->get_logger(),
"[%d][%09d] Command: %f\t Set Force: %f\t Desired Force: %f\t Ori Vel: %f\t Error: %f",
current_time.sec, current_time.nsec, command, force, desired_output_torque, current_vel, error);
RCLCPP_WARN(ros_node_->get_logger(),
"[%d][%09d] Command: %f\t P: %f\t I: %f\t D: %f",
current_time.sec, current_time.nsec, command, pTerm, iTerm, dTerm);
}*/
} else {
RCLCPP_WARN(ros_node_->get_logger(), "Joint [%s] not found", joint_name.c_str());
}
}
}
std::vector<std::string>
RobotControlPlugin::GetJoints(const std::string &robotName, rclcpp::Node::SharedPtr request_node) {
auto client1 = request_node->create_client<parameter_server_interfaces::srv::GetAllJoints>(
"/GetAllControlJoints");
using namespace std::chrono_literals;
client1->wait_for_service(1s);
auto retryCount = 0;
while (retryCount < 8) {
client1->wait_for_service(1s);
if (!client1->service_is_ready()) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(),
"GetAllJoints service failed to start, check that parameter server is launched");
retryCount++;
continue;
}
auto req = std::make_shared<parameter_server_interfaces::srv::GetAllJoints::Request>();
req->robot = robotName;
auto resp = client1->async_send_request(req);
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Getting joints...");
auto spin_status = rclcpp::spin_until_future_complete(request_node, resp, 1s);
if (spin_status != rclcpp::executor::FutureReturnCode::SUCCESS) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "GetAllJoints service failed to execute (spin failed)");
retryCount++;
continue;
}
auto status = resp.wait_for(1s);
if (status != std::future_status::ready) {
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "GetAllJoints service failed to execute");
retryCount++;
continue;
}
auto res = resp.get();
return res->joints;
}
RCLCPP_FATAL(impl_->ros_node_->get_logger(), "Unable to get joints for robot: %s", robotName.c_str());
return {};
}
std::unordered_map<std::string, gazebo::common::PID>
RobotControlPlugin::GetPidParameters(const std::string &robotName, rclcpp::Node::SharedPtr request_node) {
using GetAllPid = parameter_server_interfaces::srv::GetAllPid;
auto map = std::unordered_map<std::string, gazebo::common::PID>();
auto client = request_node->create_client<GetAllPid>("/GetAllPid");
unsigned int retryCount = 0;
constexpr unsigned int maxRetries = 10;
while (retryCount < maxRetries) {
client->wait_for_service(1.5s);
if (!client->service_is_ready()) {
retryCount++;
RCLCPP_ERROR(impl_->ros_node_->get_logger(),
"GetAllPid service failed to start, check that parameter server is launched, retries left: %d",
maxRetries - retryCount);
continue;
}
auto req = std::make_shared<GetAllPid::Request>();
req->robot = robotName;
auto resp = client->async_send_request(req);
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Getting PID parameters for robot %s...", robotName.c_str());
auto spin_status = rclcpp::spin_until_future_complete(request_node, resp, 1s);
if (spin_status != rclcpp::executor::FutureReturnCode::SUCCESS) {
retryCount++;
RCLCPP_ERROR(impl_->ros_node_->get_logger(),
"GetAllPid service failed to execute (spin failed), retries left: %d",
maxRetries - retryCount);
continue;
}
auto status = resp.wait_for(0.2s);
if (status != std::future_status::ready) {
retryCount++;
RCLCPP_ERROR(impl_->ros_node_->get_logger(), "GetAllPid service failed to execute, retries left: %d",
maxRetries - retryCount);
continue;
}
auto res = resp.get();
for (size_t i = 0; i < res->joints.size(); i++) {
auto joint = res->joints[i];
auto gazeboPid = gazebo::common::PID();
gazeboPid.SetPGain(res->p[i]);
gazeboPid.SetIGain(res->i[i]);
gazeboPid.SetDGain(res->d[i]);
gazeboPid.SetIMin(res->i_min[i]);
gazeboPid.SetIMax(res->i_max[i]);
map[joint] = gazeboPid;
}
return map;
}
RCLCPP_FATAL(impl_->ros_node_->get_logger(), "Unable to get pid values for joints of robot: %s",
robotName.c_str());
return {};
}
void RobotControlPlugin::SetUpdateRate(sdf::ElementPtr _sdf) {
double update_rate = 100.0;
if (!_sdf->HasElement("update_rate")) {
RCLCPP_INFO(impl_->ros_node_->get_logger(), "Missing <update_rate>, defaults to %f",
update_rate);
} else {
update_rate = _sdf->GetElement("update_rate")->Get<double>();
}
if (update_rate > 0.0) {
impl_->update_period_ = 1.0 / update_rate;
} else {
impl_->update_period_ = 0.0;
}
}
} //end namespace gazebo_plugins |
e3020acd9a46eac11d626a2d507e14ef6e8fb80e | 46ea8579c9b697127a8dbc2a59fa38a5ff97f2f5 | /RF/rfm12b/src/examples/main.ino | a914d602f40172e0ac10b627167cbbaefcda465c | [] | no_license | mihaigalos/Drivers | a50fecbb114347ab25051eb71a624ca07b16eaec | da3d653d83e54ba6e880ab87752c68b296e9986e | refs/heads/master | 2022-03-07T23:40:25.568631 | 2022-03-07T21:18:55 | 2022-03-07T21:25:25 | 72,926,966 | 11 | 2 | null | 2020-12-25T09:59:01 | 2016-11-05T13:11:45 | C | UTF-8 | C++ | false | false | 581 | ino | main.ino | #include "RFM12B.h"
//#define SEND
#define OWNID 0x12
String payload = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890~!@#$%^&*(){}[]`|<>?+=:;,.";
#define TOID 1 //the node ID we're sending to
RFM12B r;
void setup() {
r.Initialize(OWNID, RF12_868MHZ);
}
void loop() {
#ifdef SEND
r.Wakeup();
auto len = payload.length()+1;
char buf [255];
payload.toCharArray(buf, len);
r.Send(TOID, buf, len);
delay (3000);
#else
r.Wakeup();
r.ReceiveStart();
r.Sleep();
#endif
} |
d1f0510d5362d34b47cfe9473c2f3b27de304d9d | 10873fe7a5de6003ab1d0eba1763cc1b890c1b79 | /Damocles/CubeMeshComponent.cpp | aff078c44684485b4e90025c1415492c73417af7 | [] | no_license | MohammadMDSA/Damocles | 9730bb6764fd59ed5d2b24143789e66b35b36daf | 4a8e72faf59d46de81abefc7ea6f1c277e078205 | refs/heads/master | 2022-09-02T13:15:37.459661 | 2020-05-25T20:02:33 | 2020-05-25T20:02:33 | 262,283,147 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 917 | cpp | CubeMeshComponent.cpp | #include "pch.h"
#include "CubeMeshComponent.h"
using namespace DirectX::SimpleMath;
std::unique_ptr<DirectX::GeometricPrimitive> CubeMeshComponent::cube = std::unique_ptr<DirectX::GeometricPrimitive>();
CubeMeshComponent* CubeMeshComponent::instance = nullptr;
CubeMeshComponent::CubeMeshComponent()
{
}
CubeMeshComponent::~CubeMeshComponent()
{
}
void CubeMeshComponent::Render(Matrix const& view, Matrix const& proj)
{
cube->Draw(gameObject->GetTransform()->GetWorld(), view, proj);
}
void CubeMeshComponent::Setup()
{
}
void CubeMeshComponent::Update(DX::StepTimer const& timer)
{
}
void CubeMeshComponent::SetupDevice(ID3D11DeviceContext2* context)
{
cube = DirectX::GeometricPrimitive::CreateCube(context, 1.f);
}
void CubeMeshComponent::DeviceLost()
{
cube.reset();
}
CubeMeshComponent* CubeMeshComponent::GetInstance()
{
if (!instance)
instance = new CubeMeshComponent();
return instance;
}
|
9b685b23ce25274eda00f1e215e4da2f644a302f | e2f3148365870b414b1f958e51a47e9b2dd9f28f | /liblargo/core/media/video/video_frame_converter.h | 134f0638be24b1720d95d863ce0ec40616d4b571 | [] | no_license | vkurbatov/mcu_remake | 2987d780a51fb155b702790b7cf586b964a95105 | 5e8be35f00e43568dd4ca0261dc5fec5deeb4e54 | refs/heads/master | 2021-06-24T07:09:10.160934 | 2020-12-07T11:43:40 | 2020-12-07T11:43:40 | 170,029,545 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,791 | h | video_frame_converter.h | #ifndef VIDEO_FRAME_CONVERTER_H
#define VIDEO_FRAME_CONVERTER_H
#include "media/common/i_media_frame_converter.h"
#include "media/common/ffmpeg/libav_converter.h"
#include "video_frame_rect.h"
namespace core
{
namespace media
{
namespace video
{
typedef ffmpeg::scaling_method_t scaling_method_t;
enum class aspect_ratio_mode_t
{
scale,
crop,
fill
};
class video_frame_converter : virtual public i_media_frame_converter
{
ffmpeg::libav_converter m_ffmpeg_converter;
aspect_ratio_mode_t m_aspect_ratio_mode;
frame_rect_t m_input_area;
frame_rect_t m_output_area;
public:
video_frame_converter(scaling_method_t scaling_method = scaling_method_t::default_method
, aspect_ratio_mode_t aspect_ratio_mode = aspect_ratio_mode_t::scale
, const frame_rect_t& input_area = frame_rect_t()
, const frame_rect_t& output_area = frame_rect_t());
const frame_rect_t& input_area() const;
const frame_rect_t& output_area() const;
scaling_method_t scaling_method() const;
aspect_ratio_mode_t aspect_ratio_mode() const;
void set_input_area(const frame_rect_t& input_area);
void set_output_area(const frame_rect_t& output_area);
void set_scaling_method(scaling_method_t scaling_method);
void set_aspect_ratio_mode(aspect_ratio_mode_t aspect_ratio_mode);
void reset();
// i_media_frame_converter interface
public:
bool convert(const i_media_frame &input_frame
, i_media_frame &output_frame) override;
media_frame_ptr_t convert(const i_media_frame &input_frame
, media_format_t &output_format) override;
};
}
}
}
#endif // VIDEO_FRAME_CONVERTER_H
|
20c3fd0d2d80575f475dcd06a568bd65117a91d6 | afa15ca111ec2b73a5a8fd9c4edfae540c36fb33 | /src/include/camera.hpp | 0740b6bffe066bdaeeb306b47815ffefa3229345 | [
"Apache-2.0"
] | permissive | andeluvian/micromachines | ac2056f0118c6bc84c43c78f11fbe37b6c8f943e | 566e51a7555c0b3ab974e0fb87e3387a3427f655 | refs/heads/main | 2023-01-24T07:07:41.531057 | 2020-11-30T17:04:29 | 2020-11-30T17:04:29 | 317,291,272 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,046 | hpp | camera.hpp | #ifndef CAMERA_HH
#define CAMERA_HH
#include <SFML/Graphics.hpp>
#include "vehicle.hpp"
/*
* @Author: Miika Karsimus
*
* This class is for controlling 2D camera
*
* Features to be implemented:
*
* - Camera follows car
* - You can manually control the camera with keyboard (at least while developing the project)
* e.g. zooming, moving
* - Introduce the whole track by moving the camera around the track at the beginning of the race
* (if track is large)
*
* --------------- VIEW CONTROL BUTTONS --------------------
*
* Up (keyboard button): move up
* Down: move down
* Right: move right
* Left: move left
* M: Zoom in
* N: Zoom out
*
*/
class Camera
{
public:
enum Views {
DEFAULT = 0,
LEFT = 1,
RIGHT = 2,
STATIC = 3
};
// Pass window width and height as parameter
Camera(const int& width, const int& height);
// Call this in every loop
// Param. type is an enum value, e.g. Views::LEFT
void setViewToWindow(sf::RenderWindow& window, Views type);
/// Control view with keyboard
void handleEvents(sf::Event& event);
// Set the center point of the view to correspond the position of the car
void followVehicle(Vehicle& vehicle, Views type);
inline const sf::Vector2f getCenter() const { return view.getCenter(); }
/// Zoom in num %.
void zoomIn(int num);
/// Zoom out num %.
void zoomOut(int num);
private:
sf::View view; // Basic view which follows the vehicle in non-split-screen mode.
sf::View staticView; // This view will never be moved. Draw static objects in this view.
// The following two view are for split screen.
sf::View leftView;
sf::View rightView;
structures::Point defaultCenterPoint;
/// Set original view.
void setDefaultView();
/// Tell if the camera is following a car.
bool isFollowing = false;
/// Tell if the view is in its default position.
//bool isDefaultView = true;
};
#endif
|
e04ff959722401f194e378a8df0a75c838246dc3 | 546bcce85ce208fe2d93a49da4131da113b95067 | /Game_Of_Live.cpp | 38a7ff168f59fcfaba9d6d1bd732c68909056540 | [] | no_license | kanchan1910/December-Leetcoding-Challenge-2020 | 552b0eb32ec63c645a976014896bd694c2ece18e | c16c580fd3195efd60225a84986e1e0818e438a7 | refs/heads/master | 2023-04-10T05:43:12.950963 | 2021-04-16T06:10:25 | 2021-04-16T06:10:25 | 358,494,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,414 | cpp | Game_Of_Live.cpp | class Solution {
public:
bool valid(int x,int y,vector<vector<int>>&board){
return (x>=0&&x<board.size()&&y>=0&&y<board[0].size());
}
void gameOfLife(vector<vector<int>>& board) {
vector<int> ways_row = {0, 0, 1, 1, 1, -1, -1, -1};
vector<int> ways_col = {1, -1, 1, -1, 0, 0, 1, -1};
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
int live=0;
for(int k=0;k<8;k++){
int cur_row=i+ways_row[k];
int cur_col=j+ways_col[k];
if(valid(cur_row,cur_col,board)==true&&abs(board[cur_row][cur_col])==1){
live++;
}
}
//indicates a cell that was live but now is dead.
if(board[i][j]==1&&(live<2||live>3)){
board[i][j]=-1;
}
//indicates a cell that was dead but now is live.
if(board[i][j]==0&&live==3){
board[i][j]=2;
}
}
}
for(int i=0;i<board.size();i++){
for(int j=0;j<board[0].size();j++){
if(board[i][j]>=1){
board[i][j]=1;
}
else{
board[i][j]=0;
}
}
}
}
};
|
991726a368e6659da959adb683dcdc1f6b86d069 | dd6907b3f719baad6be0b51ce13625d7b5bb3d13 | /source/Pila.hpp | a4f994a4d070505dd10228b3d3cd28ed4a6ec436 | [] | no_license | norman-ipn/Exp.Reg.a.AFD | 5539038570e3ddbc25f7d7c6756d0741ac76197d | f003606b0bf829f07dd5089d8875c0ea3b1b69e6 | refs/heads/master | 2021-01-01T15:40:21.246388 | 2014-06-02T05:32:42 | 2014-06-02T05:32:42 | 19,504,784 | 0 | 2 | null | 2014-06-01T23:10:16 | 2014-05-06T18:01:26 | C++ | UTF-8 | C++ | false | false | 738 | hpp | Pila.hpp | #ifndef __PILA_HPP__
#define __PILA_HPP__
#include <iostream>
#include "Nodo.hpp"
class Pila{
private:
// El elemento básico de la pila son los nodos,
// que se irán apilando o eliminando de la pila.
Nodo *ultimo;
public:
// El constructor Pila incializa la pila en NULL.
Pila();
// La función push() inserta un elemento del tipo char,
// creando un nodo y apilandolo sobre la misma.
void push(char);
// La función pop() elimina el último elemento insertado en la pila,
// siempre y cuando la pila no se encuentre vacía.
void pop();
// Consulta el último caracter insertado en la pila.
char top();
// Consulata si la está vacía, devolviendo true si lo está y false si no está vacia.
bool esVacia();
};
#endif |
d6d64c6903e20af54cee4a9537dc3d3090730b29 | da2f1ded78038ab7db38929ef5376c9804a8ff6c | /src/sigset2.cpp | 881b77039a0e5ff7ab8c8d728893744cdcb2aac2 | [] | no_license | fusky/linux_study | e67ecc8cceaed482745e84502436066339ec7fb4 | add98c83ec4b7ab2c0ed23f5ea3683a9553f0483 | refs/heads/master | 2020-03-29T20:07:38.827553 | 2014-09-24T10:59:39 | 2014-09-24T10:59:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | cpp | sigset2.cpp | //解决信号不可靠问题,和sigset.cpp比较
//设置信号屏蔽
#include <io.h>
int *heap;
int array[10];
static int flags = 0;
void set(int n)
{
int i = 0;
int stack[10];
for(i = 0; i < 10; i++){
stack[i] = n;
heap[i] = n;
array[i] = n;
sleep(1);
}
cout << "heap: ";
for(i = 0; i < 10; i++){
cout << heap[i] << ",";
}
cout << endl;
cout << "stack: ";
for(i = 0; i < 10; i++){
cout << stack[i] << ",";
}
cout << endl;
cout << "data: ";
for(i = 0; i < 10; i++){
cout << array[i] << ",";
}
cout << endl;
}
void sighandler(int sig)
{
cout << "in sighandler: " << endl;
set(20);
cout << "signal finished!" << endl;
flags = 1;
}
int main(int argc, char** argv)
{
signal(SIGINT, sighandler);
heap = new int[10];
//set运行时,屏蔽SIGINT信号
sigset_t oset;
sigemptyset(&oset);
sigaddset(&oset, SIGINT);
sigprocmask(SIG_BLOCK, &oset, NULL);
set(10);
//sigdelset(&set, SIGINT);
sigprocmask(SIG_UNBLOCK, &oset, NULL);
while(!flags) pause();
delete[] heap;
return 0;
}
|
0d125db5f3cb516212c27545f5bd3e5ac7e477ec | eb10d421252568464bf17d0552bb5e811e1ff300 | /Leetcod_way/Leetcod_way/dft.h | 038e34911bde7c9dfd4f89220e1da0b0acc8c136 | [] | no_license | Meveral/Leetcode | 213d697489e5f5b723c8e45c13bbf68f142b4bcd | 674f4e4858d63a5c209d77924cbbd22b24ee9cfd | refs/heads/master | 2023-02-13T13:03:05.070954 | 2021-01-15T02:00:10 | 2021-01-15T02:00:10 | 270,582,300 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 180 | h | dft.h | #pragma once
#include<iostream>
#include<string>
#include<vector>
#include<set>
#include<map>
#include<algorithm>
#include<queue>
#include<stack>
//#include<>
using namespace std;
|
89aad42b398bd7a11075055c6b271a41db8101a3 | e68c1f9134b44ddea144f7efa7523076f3f12d3a | /FinalCode/PlayerCamera.h | bc57903f5bc0e62cf32f54a059925f241238041a | [] | no_license | iso5930/Direct-3D-Team-Portfolio | 4ac710ede0c9176702595cba5579af42887611cf | 84e64eb4e91c7e5b4aed77212cd08cfee038fcd3 | refs/heads/master | 2021-08-23T08:15:00.128591 | 2017-12-04T06:14:39 | 2017-12-04T06:14:39 | 112,998,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | h | PlayerCamera.h | #pragma once
#include "Camera.h"
class CPlayerCamera : public CCamera
{
private:
// Dist
float m_fDist;
// Mode
int m_iMode;
// Time
float m_fTime;
public:
virtual void Initialize();
virtual int Update();
virtual void Render();
virtual void Release();
public:
explicit CPlayerCamera(TCHAR* _tszObjKey, OBJ_TYPE _eObjType, DWORD _dwIndex);
virtual ~CPlayerCamera();
};
|
389d1db32dfc19eb59cf194bf4f6e14a7df2d9ca | 1b0ff9800e667d18363be7a5bfb424e61c2aea6e | /Q22_Primenumberslist.cpp | 729b46d9afd091e10398546ed67f5bdecf79eeba | [] | no_license | AastikM/Hacktoberfest2020-9 | 0a7efb78844b3417ffba42cee49bec19b2fc0aed | b54c68db99b640cf066a4bea3e334ce146f0b15c | refs/heads/main | 2023-01-01T22:32:28.073146 | 2020-10-31T15:13:32 | 2020-10-31T15:13:32 | 308,908,890 | 1 | 0 | null | 2020-10-31T15:12:48 | 2020-10-31T15:12:47 | null | UTF-8 | C++ | false | false | 977 | cpp | Q22_Primenumberslist.cpp | // C++ program to find the prime numbers between a given interval
#include<iostream>
using namespace std;
// Function to print prime number in given range
void primeInRange(int L, int U)
{
int flag;
// Traverse each number in the interval with the help of for loop
for (int i=L;i<=U;i++) {
// Skip 0 and 1 as they are neither prime nor composite
if (i == 1 || i == 0)
continue;
// flag variable to tell if i is prime or not
flag = 1;
for (int j=2;j<=i/2;j++) {
if (i % j == 0) {
flag=0;
break;
}
}
// flag = 1 means i is prime
// and flag = 0 means i is not prime
if (flag == 1)
cout << i << " ";
}
}
// Driver Code
int main()
{
// Given Range
int L,U;
cout<<"Enter the Range:";
cin>>L>>U;
cout<<"The list of prime numbers in given range:";
// Function Call
primeInRange(L,U);
}
|
64e914c1ef8868d6a4a43a35a9e9172a5c726931 | 0edcf706d41b506cb1dc754b7bdfae263823793f | /source/CAT/cluster.h | b425cedc3be9a2e6eac005768c410003c76f6e5f | [] | no_license | xgarrido/LCAT | 3638a823d08ee3669273b3f258eecf60defef1a4 | b7ec4cb77d01fcfbdbd555a206adcb949fce39fc | refs/heads/master | 2020-01-27T09:59:52.519598 | 2016-10-13T14:41:16 | 2016-10-13T14:41:16 | 67,502,818 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,211 | h | cluster.h | // -*- mode: c++ -*-
#ifndef FALAISE_CAT_CLUSTER_H
#define FALAISE_CAT_CLUSTER_H 1
// Standard library:
#include <iostream>
#include <cmath>
#include <vector>
// This project:
#include <CAT/experimental_point.h>
#include <CAT/experimental_vector.h>
#include <CAT/cell.h>
#include <CAT/line.h>
#include <CAT/cell_couplet.h>
#include <CAT/cell_triplet.h>
#include <CAT/node.h>
#include <CAT/broken_line.h>
namespace CAT {
/// \brief A cluster is composed of a list of nodes
class cluster
{
public:
// list of nodes
std::vector<node> nodes_;
// status of cluster
bool free_;
//!Default constructor
cluster();
//!Default destructor
virtual ~cluster();
//! constructor from std::vector of nodes
cluster(const std::vector<node> &nodes);
//! constructor from single node
cluster(node &a_node);
/*** dump ***/
virtual void dump (std::ostream & a_out = std::clog,
const std::string & a_title = "",
const std::string & a_indent = "",
bool a_inherit = false) const ;
//! set nodes
void set_nodes(const std::vector<node> &nodes);
//! set free level
void set_free(bool free);
//! get nodes
const std::vector<node> & nodes()const;
//! get free level
bool Free()const;
public:
bool has_cell(const cell & c)const;
node node_of_cell(const cell & c);
void solve_ambiguities(std::vector< std::vector<broken_line> > * sets_of_bl_alternatives);
bool start_ambiguity(size_t i);
bool end_ambiguity(size_t i);
std::vector<broken_line> solve_ambiguities_with_ends(size_t ifirst, size_t ilast);
std::vector<broken_line> solve_ambiguities_with_ends__1_node(size_t ifirst, size_t ilast, bool first_ambiguous_is_after_gap, bool first_ambiguous_is_second, bool last_ambiguous_is_begore_gap, bool last_ambiguous_is_last_but_one);
std::vector<broken_line> solve_ambiguities_with_ends__2_nodes(size_t ifirst, size_t ilast, bool first_ambiguous_is_after_gap, bool first_ambiguous_is_second, bool last_ambiguous_is_begore_gap, bool last_ambiguous_is_last_but_one);
std::vector<broken_line> solve_ambiguities_with_ends__3_nodes(size_t ifirst, size_t ilast, bool first_ambiguous_is_after_gap, bool first_ambiguous_is_second, bool last_ambiguous_is_begore_gap, bool last_ambiguous_is_last_but_one);
std::vector<broken_line> solve_ambiguities_with_ends__4_nodes(size_t ifirst, size_t ilast, bool first_ambiguous_is_after_gap, bool first_ambiguous_is_second, bool last_ambiguous_is_begore_gap, bool last_ambiguous_is_last_but_one);
void solve_ambiguities_with_ends__more_than_4_nodes(broken_line ACD[2][2][2], size_t ifirst, size_t ilast, bool first_ambiguous_is_after_gap, bool first_ambiguous_is_second);
void solve_ambiguities_with_ends__more_than_4_nodes(broken_line aACD[2][2][2][2], size_t ifirst, size_t ilast);
void merge__more_than_4_nodes(broken_line ACD[2][2][2], broken_line aACD[2][2][2][2]);
std::vector<broken_line> finish__more_than_4_nodes(broken_line ACD[2][2][2], size_t ipivot, size_t n_residuals);
};
} // namespace CAT
#endif // FALAISE_CAT_CLUSTER_H
|
62014d3baf21f746a8e6df857d75d500a766526e | 11a044d1328c54a1f1a3df967de8b569cce307a9 | /MyList/MyList.h | 167dca798350a407b3a5ee85fbc423245fee447d | [] | no_license | dnsmoly/MyList | 0d11fbe140e911ca948281ac7a0c31615d7013fe | 9192d0a8e651ba158a28b4aed0d999aa7d24ead1 | refs/heads/master | 2023-01-15T03:57:28.240668 | 2020-11-19T10:30:50 | 2020-11-19T10:30:50 | 314,209,915 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 655 | h | MyList.h | #pragma once
#include "Node.h"
template <typename T>
class MyList
{
public:
MyList(int capacity = 10);
~MyList();
void remove(); // remove last added item
void remove(const T&); // remove an element and all it`s copies
void removeBack(); // remove last element
void append(const T&); // add an element
void pushBack(const T&); // add an element to the end of the list
T front(); // returns the head element
T back(); // returns the last element
//void clear();
void print(); // prints the list
int size(); // returns the size of the list
private:
int capacity;
bool search(const T& item);
Node<T>* head; // link to the head element
}; |
1c96ea313a141f105eac788511dd575b257dff12 | d0f2bb18c39ff5dac5d9d2cec8cc98e96a642d8a | /Examples/Cpp/source/Outlook/AddVotingButtonToExistingMessage.cpp | 6d26045ed6872a584ba39c307cb9ce68b6a66e09 | [
"MIT"
] | permissive | kashifiqb/Aspose.Email-for-C | d1e26c1eb6cb1467cee6a050ed5b52baaf186816 | 96684cb6ed9f4e321a00c74ca219440baaef8ba8 | refs/heads/master | 2023-03-24T22:44:20.264193 | 2021-02-10T14:07:51 | 2021-02-10T14:07:51 | 105,030,475 | 0 | 0 | null | 2017-09-27T14:43:20 | 2017-09-27T14:43:20 | null | UTF-8 | C++ | false | false | 1,194 | cpp | AddVotingButtonToExistingMessage.cpp | /*
This project uses Automatic Package Restore feature of NuGet to resolve Aspose.Email for .NET API reference
when the project is build. Please check https://Docs.nuget.org/consume/nuget-faq for more information.
If you do not wish to use NuGet, you can manually download Aspose.Email for .NET API from https://www.nuget.org/packages/Aspose.Email/,
install it and then add its reference to this project. For any issues, questions or suggestions
please feel free to contact us using https://forum.aspose.com/c/email
*/
#include <system/string.h>
#include <system/shared_ptr.h>
#include <Mapi/MapiMessage.h>
#include <Mapi/FollowUpManager.h>
#include "Examples.h"
using namespace Aspose::Email;
using namespace Aspose::Email::Mapi;
void AddVotingButtonToExistingMessage()
{
// ExStart:AddVotingButtonToExistingMessage
// The path to the File directory.
System::String dataDir = GetDataDir_Outlook();
System::SharedPtr<MapiMessage> mapi = MapiMessage::FromFile(dataDir + u"message.msg");
FollowUpManager::AddVotingButton(mapi, u"Indeed!");
mapi->Save(dataDir + u"AddVotingButtonToExistingMessage_out.msg");
// ExEnd:AddVotingButtonToExistingMessage
}
|
ffcb8cd77016a909e4ee1d0733a05aea7c917c2b | 328d8619f839541ec00938979070c56015c07d98 | /srcs/utils.cpp | 64b94e16cc0c8bc2a4dfc7aecf7a3699de1f214b | [] | no_license | KITKATJN/ft_containers | c6a6bbe3bfccacb32cb493f61e68a41f1cd67879 | e6153e5972004167dcecdd38ac7a74b2513bc1a4 | refs/heads/master | 2023-08-31T10:19:39.424571 | 2021-10-16T18:21:22 | 2021-10-16T18:21:22 | 395,973,601 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,438 | cpp | utils.cpp | #include "vector_test.hpp"
#include <cstdlib>
#include <ctime>
#include <iostream>
void time(int start, int end) {
std::cout << "[" << GREEN << end - start << RESET << "] ticks && "
<< "[" << GREEN << ((float)end - start) / CLOCKS_PER_SEC
<< RESET << "]"
<< " sec.\n";
}
void percentage_compare(int std_ticks, int ft_ticks) {
double per;
if (ft_ticks > std_ticks) {
std::cout << "FT SLOWER BY ";
per = ((float)std_ticks / ft_ticks) * 100;
std::cout << YELLOW "[" << 100 - per << "%]\n" << RESET;
} else {
std::cout << "FT FASTER BY ";
per = ((float)ft_ticks / std_ticks) * 100;
std::cout << BOLDCYAN << "[" << 100 - per << "%]\n" << RESET;
}
}
void checker(bool equal) {
if (equal)
std::cout << GREEN << "[OK]" << RESET << " ";
else
std::cout << BOLDRED << "[ERROR]" << RESET << " ";
std::cout << "\n";
}
void test_title(std::string str) {
std::cout << YELLOW << str << RESET << ":\n";
}
Test::Test() {
srand(time(0));
bool r = rand() % 2;
storage = new int(10);
size = 10;
if (r)
throw 1;
}
Test::Test(const Test &other) {
storage = new int(10);
size = other.size;
}
Test::~Test() {
delete storage;
}
Test& Test::operator=(const Test &other) {
if (this == &other)
return *this;
if (storage != NULL) {
}
return *this;
}
|
3c21eea76cd837582cdfdac190fd1c8f1e527d95 | c61b09d0a3e36cf2976625699c812410be9e823b | /common/CompositeModels/CompositeModelReader.h | b35743f0c6d024b194cbfd69ce3742172c9a3843 | [] | no_license | OpenModelica/OMTLMSimulator | f66b976c0cabe40dcfa9e67c1f085f42aedee6cb | e0693c46327b47c94ad5ce8294fad7ef1463b5cd | refs/heads/master | 2023-07-24T18:24:17.313677 | 2023-07-15T10:59:36 | 2023-07-18T11:58:55 | 88,967,835 | 4 | 15 | null | 2023-07-18T11:58:56 | 2017-04-21T09:36:23 | C | UTF-8 | C++ | false | false | 4,595 | h | CompositeModelReader.h | //! \file: CompositeModelReader.h
//!
//! Defines the CompositeModelReader class which provides an interface
//! for reading in the meta-model information from xml file
//!
#ifndef CompositeModelReader_h
#define CompositeModelReader_h
#include <cstdio>
#include <string>
#include <fstream>
#include <iostream>
#include "CompositeModels/CompositeModel.h"
#include <libxml/parser.h>
#include <libxml/tree.h>
//! Class CompositeModelReader is responsible for reading meta model definition from
//! an XML file and passing the information to the CompositeModel classes
//! to create the internal representation of the model.
class CompositeModelReader {
//! The model object to be filled in during reading
omtlm_CompositeModel& TheModel;
//! ReadComponents method reads in Components (SubModels) definition from
//! the XML file starting from the given xml node that should be "SubModels".
//! Input: \param node - pointer to the "SubModels" element node
//! - parent to all the SubModels
//! Input/Output: TheModel - structure is updated in the model representation
void ReadComponents(xmlNode *node, bool skipInterfaces, std::string singleModel);
//! ReadTLMInterfaceNodes method reads in TLM interface definitions for a
//! given SubModel XML node and its ID (ComponentID).
void ReadTLMInterfaceNodes(xmlNode* node, int ComponentID);
void ReadComponentParameters(xmlNode* node, int ComponentID);
//! ReadSimParams method reads in simulation parameters (Port, StartTime, StopTime)
//! from XML-element node for a TLMConnection
void ReadSimParams(xmlNode* node);
//! ReadVectorAttribute method reads a nodes 3D vector attribute, if applicable.
//! For instance, reads a position vector "x,y,z", that is, Position="0.0,1.0,-0.3".
//! \param node The current XML node that might have an attribute of the given name "attribute"
//! \param attribute The name of the attribute, for instance, "Position"
//! \param pos The 3D vector that contains the result, that is, the 3D vector read from the XML node.
//! This field will be unchanged if the attribute is not found.
void ReadVectorAttribute(xmlNode* node, const char* attribute, double pos[3]);
//! ReadDoubleAttribute method reads a double value attribute, if applicable.
//! \param node The current XML node that might have an attribute of the given name "attribute"
//! \param attribute The name of the attribute, for instance, "Position"
//! \return The result, that is, the double value read from the XML node.
//! Returns 0.0 if the attribute is not found.
double ReadDoubleAttribute(xmlNode* node, const char *attribute);
//! ReadPositionAndOrientation method reads position and orientation (phi angles) from the meta-model XML file.
//! Orientation 3x3 matrix A is created from the phi angles.
//! \param node The current XML node that contains the location and orientation attributes.
//! \param R The position vector, output.
//! \param A The 3x3 orientation matrix, output.
void ReadPositionAndOrientation(xmlNode* node, double R[3], double A[9]);
//! FindChildByName is an utility function used for finding child elements by name
//! for a given XML node. Used for looking up required sections in the XML document.
//! Returns: xmlNode* giving address of the found node or NULL if an optional node
//! is not found.
xmlNode* FindChildByName(xmlNode* node, const char* name, bool required = true);
//! FindAttributeByName is an utility function for finding node attributes by name
//! for a given XML element node. Used for looking up required attributes while
//! building the Model structure.
//! Returns: xmlNode* providing address of the found attribute or NULL
xmlNode* FindAttributeByName(xmlNode* node, const char* name, bool required = true);
//! ReadTLMConnectionNode method processes an TLM connection definition in XML file.
//! The definition is submitted as xmlNode* and is registered in TheModel as a
//! result of the method.
void ReadTLMConnectionNode(xmlNode* node);
public:
//! Constructor
CompositeModelReader(omtlm_CompositeModel& model) : TheModel(model) {}
//! ReadModel method processes input XML file and creates CompositeModel definition.
//! Input: InputFile - input XML file name
//! Input/Output: TheModel - model structure to be build.
void ReadModel(std::string& InputFile, bool SkipConnections=false, std::string singleModel="");
};
#endif
|
82743939a51085d8bdfc87a6bb4097675817c956 | 602a895c5835d59934385710910c98c17610b5f5 | /src/calc/engine/proc/base/ElementInteger.cpp | 9e0462cb9ca64b62f97f0f6c687a8359dc1c458e | [
"MIT"
] | permissive | yuishin-kikuchi/eckert | ebb73dc960ec07e2ecb83a02898e69d15c70e9ab | bb7ac85173dc7f3d895764a5df51adbdbfd76024 | refs/heads/master | 2022-11-27T04:30:34.313614 | 2022-11-05T12:13:33 | 2022-11-05T12:13:33 | 76,098,919 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 803 | cpp | ElementInteger.cpp | #include "ElementInteger.h"
namespace engine {
////==--------------------------------------------------------------------====//
// ECKERT ELEMENT - INTEGER / Constructor
// [ description ]
// Constructor using integer_t.
// [ Update ]
// Nov 13, 2016
//====--------------------------------------------------------------------==////
Integer::Integer(const integer_t &num) {
_data = num;
}
////==--------------------------------------------------------------------====//
// ECKERT ELEMENT - INTEGER / Clone
// [ description ]
// Generate its clone and return the shared pointer that points.
// [ Update ]
// Nov 13, 2016
//====--------------------------------------------------------------------==////
SpElement Integer::clone() const {
return SpElement(new Integer(_data));
}
} // namespace engine
|
4b9b1d4cfd007d63f3757dbb3cc32d37fe883513 | 49be3d76cc9b8ffad3f2196e1de5e1bc4ee68e58 | /include/CEstimator.h | e6ec940874370b689e8c447ee3eef44ef6deac74 | [] | no_license | tectronics/zestim | ac97aee13abffdec88307b03232447fbe0c0d7c6 | 05a5c21f56d23cdba3fc39b9923d3488cfec12dc | refs/heads/master | 2018-01-11T14:58:07.976757 | 2012-10-16T13:15:16 | 2012-10-16T13:15:16 | 49,482,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 733 | h | CEstimator.h | #pragma once
#include <CGraph.h>
#include <CIniFile.h>
#include <string>
#include <CParameters.h>
#include <CLikelihood.h>
class CEstimator {
public:
CGraph dataTemplate, dataTemplateOrg, dataAbsorption;
CGraph absorptionLines;
vector<CGraph> data;
bool use_absorption_lines;
int cutoff_mode_start, cutoff_mode_end;
int cutoff_start_smallscale;
string basename; // data base name
CParameters params;
CIniFile ini;
void Setup(string filename);
void Run();
void CalculateChisq2D(string file, CGraph& g);
void CalculateChisq1D(CGraph& g, double zfrom, double zto, double steps);
void CalculateChisq1D();
void CalculateChisq2D();
private:
void setupAbsorption();
void CalculateSmooth();
};
|
74183395e68a576f2b477cc72da0436b4015124f | 5c012c7f308da27b8e66725ea118d09ba4515c7b | /code/src/nearest_neighbor.hpp | c56d658194d6fd185f99d480d0a14e755bb4e490 | [
"MIT"
] | permissive | Team-NNZ-Algorithms/tsp | 0fcbd302e8173c51104086fce68fa2dd7d868d8b | e3cc07acd6b7c087cc44d2da8d986f659e113264 | refs/heads/master | 2020-03-19T05:24:38.273808 | 2018-06-09T06:09:04 | 2018-06-09T06:09:04 | 135,927,902 | 0 | 1 | MIT | 2018-06-09T06:09:05 | 2018-06-03T18:00:09 | C++ | UTF-8 | C++ | false | false | 151 | hpp | nearest_neighbor.hpp | #ifndef NEAREST_NEIGHBOR_HPP
#define NEAREST_NEIGHBOR_HPP
#include "utils.hpp"
struct tour tsp_nearest_neighbor(struct tsp_problem &problem);
#endif |
26872849354ad26ef1d9c72a72f2f3584f03790b | 67f865009c64a37261e85e6e6b44009c3883f20f | /c++/part1/amduong.cpp | 4b3814fdac23cfb0cc6f3447358e26cc6a20d642 | [] | no_license | tabvn/ued | 762a25ff68042ff8b77b6f307f3182f3713e5f31 | 005b07c4f9924247b819d9611f84a80c8938fb21 | refs/heads/master | 2021-07-10T06:49:21.535462 | 2020-06-28T07:53:57 | 2020-06-28T07:53:57 | 153,631,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 282 | cpp | amduong.cpp | #include <iostream>
using namespace std;
int main(){
long int n;
cin >> n;
long int value = n;
bool notFound = true;
for (int i = 2; i < n; ++i){
while(value % i == 0){
notFound = false;
cout << i;
value /= i;
}
}
if(notFound){
cout << -1;
}
return 0;
} |
af5bee98d6b3041e7ae87f71ed6ab69c0482400c | 60a915754fbe66071ac67d06aab9293a1218e268 | /src/lib/logical_query_plan/mock_node.cpp | 4af853facc2a238c812dd8f2039915ade379b253 | [
"MIT"
] | permissive | b-xiang/hyrise-1 | ec86fa25350b4d4ae8938afcdcca3f00f22cfe9a | 47ed4dc235c5b9f347a74efdfdcec6480a3a448d | refs/heads/master | 2020-03-27T12:25:55.828018 | 2018-08-28T13:11:53 | 2018-08-28T13:11:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,736 | cpp | mock_node.cpp | #include "mock_node.hpp"
#include <memory>
#include <string>
#include <vector>
#include "expression/lqp_column_expression.hpp"
#include "statistics/table_statistics.hpp"
#include "utils/assert.hpp"
using namespace std::string_literals; // NOLINT
namespace opossum {
MockNode::MockNode(const ColumnDefinitions& column_definitions, const std::optional<std::string>& name)
: AbstractLQPNode(LQPNodeType::Mock), _name(name), _constructor_arguments(column_definitions) {}
MockNode::MockNode(const std::shared_ptr<TableStatistics>& statistics)
: AbstractLQPNode(LQPNodeType::Mock), _constructor_arguments(statistics) {}
LQPColumnReference MockNode::get_column(const std::string& name) const {
const auto& column_definitions = this->column_definitions();
for (auto column_id = ColumnID{0}; column_id < column_definitions.size(); ++column_id) {
if (column_definitions[column_id].second == name) return LQPColumnReference{shared_from_this(), column_id};
}
Fail("Couldn't find column named '"s + name + "' in MockNode");
}
const MockNode::ColumnDefinitions& MockNode::column_definitions() const {
Assert(_constructor_arguments.type() == typeid(ColumnDefinitions), "Unexpected type");
return boost::get<ColumnDefinitions>(_constructor_arguments);
}
const boost::variant<MockNode::ColumnDefinitions, std::shared_ptr<TableStatistics>>& MockNode::constructor_arguments()
const {
return _constructor_arguments;
}
const std::vector<std::shared_ptr<AbstractExpression>>& MockNode::column_expressions() const {
if (!_column_expressions) {
_column_expressions.emplace();
auto column_count = size_t{0};
if (_constructor_arguments.type() == typeid(ColumnDefinitions)) {
column_count = boost::get<ColumnDefinitions>(_constructor_arguments).size();
} else {
column_count = boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments)->column_statistics().size();
}
for (auto column_id = ColumnID{0}; column_id < column_count; ++column_id) {
const auto column_reference = LQPColumnReference(shared_from_this(), column_id);
_column_expressions->emplace_back(std::make_shared<LQPColumnExpression>(column_reference));
}
}
return *_column_expressions;
}
std::string MockNode::description() const { return "[MockNode '"s + _name.value_or("Unnamed") + "']"; }
std::shared_ptr<TableStatistics> MockNode::derive_statistics_from(
const std::shared_ptr<AbstractLQPNode>& left_input, const std::shared_ptr<AbstractLQPNode>& right_input) const {
Assert(_constructor_arguments.type() == typeid(std::shared_ptr<TableStatistics>),
"Can only return statistics from statistics mock node");
return boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments);
}
std::shared_ptr<AbstractLQPNode> MockNode::_on_shallow_copy(LQPNodeMapping& node_mapping) const {
if (_constructor_arguments.type() == typeid(std::shared_ptr<TableStatistics>)) {
return MockNode::make(boost::get<std::shared_ptr<TableStatistics>>(_constructor_arguments));
} else {
return MockNode::make(boost::get<ColumnDefinitions>(_constructor_arguments));
}
}
bool MockNode::_on_shallow_equals(const AbstractLQPNode& rhs, const LQPNodeMapping& node_mapping) const {
const auto& mock_node = static_cast<const MockNode&>(rhs);
if (_constructor_arguments.which() != mock_node._constructor_arguments.which()) return false;
if (_constructor_arguments.type() == typeid(ColumnDefinitions)) {
return boost::get<ColumnDefinitions>(_constructor_arguments) ==
boost::get<ColumnDefinitions>(mock_node._constructor_arguments);
} else {
Fail("Comparison of statistics not implemented, because this is painful");
}
}
} // namespace opossum
|
4edc2e292c435b7d49dad276e136c810c1192605 | 01bc302c699a9796b9a2f0d99316fc038b1991ea | /Yar2019/G/G.cpp | 8f46f660a0448bf0ce05041ee0e0c418411e0c1f | [] | no_license | palich12/acm | 0b4918ad49d77f43ff2551ae168b3194cae516b8 | f05afd5113e679e346dbdc290d44d3d4ad4df95e | refs/heads/master | 2020-03-29T13:48:10.318837 | 2020-03-22T17:31:32 | 2020-03-22T17:31:32 | 149,983,000 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,510 | cpp | G.cpp | #include <iostream>
#include <vector>
#include <bitset>
#include <map>
#include <queue>
#define MAX_STEP_LENGHT 900
#define MAX_RECURSION_CALL 100000
//one action about reverse hourglasses
struct Action {
int time;
int glassMap;
};
//combination of actions that open posibility to count time of some lenght
struct Step {
int length;
std::vector<Action> actions;
};
//specific order of selection reverse combinations of hourglasses for reverse simple combination first
int sort[4][16] = {
{0b0001, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000},
{0b0001, 0b0010, 0b0011, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000},
{0b0001, 0b0010, 0b0100, 0b0011, 0b0110, 0b0101, 0b0111, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000, 0b0000},
{0b0001, 0b0010, 0b0100, 0b1000, 0b0011, 0b0110, 0b1010, 0b0101, 0b1100, 0b1001, 0b1110, 0b1101, 0b1011, 0b0111, 0b1111, 0b0000}
};
int N = 0;
int K = 0;
int glasses[4] = { 0,0,0,0 };
std::bitset<MAX_STEP_LENGHT * 21 * 21 * 21 * 21> visitedPoints = { false };
std::vector<Step> timeLine (1450);
int recursionCount = 0;
//find new avalible time points by using new finding step
bool useNewStep(Step step) {
for (int i = 0; i < K; i++) {
int newIndex = i + step.length;
if ((timeLine[i].length > 0 || i == 0)
&& newIndex <= K
&& timeLine[newIndex].length == 0) {
timeLine[newIndex] = step;
if (newIndex == K) {
return true;
}
}
}
return false;
}
//find all avilable combination of actions while we have time for it ;)
bool findPosibleSteps(int time, std::vector<int> state, std::vector<Action> actions) {
if (time >= MAX_STEP_LENGHT || time > K || recursionCount > MAX_RECURSION_CALL) {
return false;
}
recursionCount++;
int index = time;
int m = MAX_STEP_LENGHT;
for (int i = 0; i < N; i++) {
index += state[i] * m;
m *= 21;
}
if (visitedPoints[index]) {
return false;
}
visitedPoints[index] = true;
//generate all posible combination of action
for (int i = 0; i < (1 << N)-1; i++) {
std::vector<int> newState;
int timeToNextAction = 0;
//generate new state after action
for (int j = 0; j < N; j++) {
int newStateValue;
if ((sort[N-1][i] & (1 << j)) > 0) {
newStateValue = glasses[j] - state[j];
}
else {
newStateValue = state[j];
}
newState.push_back(newStateValue);
if (newStateValue > 0 && newStateValue < timeToNextAction || timeToNextAction == 0) {
timeToNextAction = newStateValue;
}
}
if (timeToNextAction == 0) {
continue;
}
//create next action
Action nextAction;
nextAction.glassMap = sort[N - 1][i];
nextAction.time = time;
std::vector<Action> nextActions = actions;
nextActions.push_back(nextAction);
int nextTime = time + timeToNextAction;
//define state after action
bool stopFlag = true;
for (int j = 0; j < N; j++) {
if (newState[j] > 0) {
newState[j] = newState[j] - timeToNextAction;
}
if (newState[j] > 0) {
stopFlag = false;
}
}
if (stopFlag) {
Step step;
step.actions = nextActions;
step.length = nextTime;
if (useNewStep(step)) {
return true;
}
continue;
}
if (findPosibleSteps(nextTime, newState, nextActions)) {
return true;
}
}
return false;
}
int main()
{
std::vector<int> startState;
std::vector<Action> startActions;
scanf_s("%d", &N);
for (int i = 0; i < N; i++) {
int g;
scanf_s("%d", &g);
glasses[i] = g;
startState.push_back(0);
}
scanf_s("%d", &K);
//start reqursion
if (!findPosibleSteps(0, startState, startActions)) {
printf_s("-1\n");
return 0;
}
//generate result
std::vector<Action> result;
int time = K;
while (time > 0) {
int actionSize = timeLine[time].actions.size();
int nextTime = time - timeLine[time].length;
for (int i = actionSize-1; i >=0; i--) {
timeLine[time].actions[i].time += nextTime;
result.push_back(timeLine[time].actions[i]);
}
time = nextTime;
}
printf_s("%d\n", result.size() + 1);
for (int i = result.size() - 1; i >= 0; i--) {
int g = result[i].glassMap;
int j = 1;
std::vector<int> answer;
answer.clear();
while (g > 0) {
if ((g & 1) > 0) {
answer.push_back(j);
}
g = g >> 1;
j++;
}
printf_s("%d %d", result[i].time, answer.size());
for (int j = 0; j < answer.size(); j++) {
int n = answer[j];
printf_s(" %d", n);
}
printf_s("\n");
}
printf_s("%d 0\n", K);
return 0;
} |
5a101af106e2a3951d3adc808d359732a941f785 | 6013a919c2820cc1c9d71a9be785633674b1891e | /apps/myApps/exampleOutput/src/Individuo.cpp | 2d3a043922d0f15b22372a459d1874e5cbad8061 | [] | no_license | fbarretto/Zer0 | d4e839cbfc96f98e30344cd837fba0682b3e8688 | 84d88ed87bb4e9dd6f0539931d84a9f77ef42977 | refs/heads/master | 2020-12-24T15:32:33.881780 | 2018-10-04T11:10:30 | 2018-10-04T11:10:30 | 15,858,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,883 | cpp | Individuo.cpp | //
// Individuo.cpp
// Pulso
//
// Created by barretto on 12/01/14.
//
//
#include "Individuo.h"
Individuo::Individuo() {
radius = 0;
radiusLimit = ofRandom(5,25);
radiusOffset=10;
position = ofPoint(ofRandomWidth(),ofRandomHeight());
//offset;
baseTime = 10;
lifespan = ofRandom(700,1200);
color = ofRandom(0,255);
circleResolution = int(ofRandom(2,15));
score = 0;
midiNote = ofRandom(0,127);
isActive = true;
framecountOffset=ofRandom(-100,100);
for (int i=0; i<8; i++) {
pattern[i] = int(ofRandom(50, 150));
}
pulseCountdown = pattern[0];
patternIndex=0;
// destination=ofPoint(ofRandomWidth(), ofRandomHeight());
destination.x=position.x+ofRandom(-100,100);
destination.y=position.y+ofRandom(-100,100);
}
void Individuo::draw(){
//std::cout << lifespan<<endl;
if(isActive) {
if (pulsos.size()>0) {
for(int i = pulsos.size()-1 ; i >=0; i--){
pulsos[i].draw();
//std::cout << "draw pulse"<<endl;
}
}
ofEnableAlphaBlending(); // turn on alpha blending
ofColor c = ofColor::fromHsb(color,255,255,int(255*(lifespan/1000)));
ofSetColor(c);
ofFill();
ofSetCircleResolution(circleResolution);
ofCircle(position, radius+radiusOffset); // draw circle with radius offset
ofDisableAlphaBlending();
}
}
bool Individuo::update(){
if(isActive) {
// std::cout << "is active"<<endl;
radius -= (lifespan/10000);
if (radius < radiusLimit) {
radius +=0.5;
}
isActive = !(lifespan < 0);
//position.x += (ofRandomWidth() - position.x)*0.1;
//position.y += (ofRandomHeight() - position.y)*0.1;
pulseCountdown--;
//std::cout << "countdown " << pulseCountdown<<endl;
//std::cout << "pulses " << pulsos.size()<<endl;
if (pulsos.size()>0) {
for(int i = pulsos.size()-1 ; i >=0; i--){
if (pulsos[i].kill()) {
pulsos.erase(pulsos.begin()+i);
//std::cout << "dead pulse " << pulsos.size()<<endl;
} else {
pulsos[i].update(position);
// std::cout << "update pulse " << pulsos.size()<<endl;
}
}
}
if (pulseCountdown==0) {
Pulso p = Pulso(position,1, radius*4);
// p.start(position,1);
pulsos.push_back(p);
//std::cout << "added pulse " << pulsos.size()<<endl;
patternIndex++;
if (patternIndex>7) {
patternIndex=0;
}
pulseCountdown=pattern[patternIndex];
}
move();
lifespan--;
//if (lifespan<0)
//std::cout << "dead!" <<endl;
}
return isActive;
}
void Individuo::start(ofPoint _position){
if(!isActive){
position = _position;
isActive = true;
//std::cout << "started @ " << position.x << "\t" << position.y << "\t" << speed << std::endl;
}
}
void Individuo::move(){
if(isActive){
if ((ofGetFrameNum()+framecountOffset)%100==0) {
destination.x=position.x+ofRandom(-100,100);
destination.y=position.y+ofRandom(-100,100);
}
position.x += (destination.x - position.x)*0.01;
position.y += (destination.y - position.y)*0.01;
}
}
void Individuo::reset(){
radius = 0; //reset radius here
}
void Individuo::playNote() {
//cout<<"play note, dude!"<<endl;
}
bool Individuo::kill(){
//cout<<isActive<<endl;
return (!isActive); // verify if the radius exceedes the limit and is not active
} |
ddf2bbec4e1dcba875ba27dc4bb7e3cab359a1a2 | 333b58a211c39f7142959040c2d60b69e6b20b47 | /Include/Oos/Semaphore.h | 8665082d62d3ec97a815589bc8ff08860e8365da | [] | no_license | JoeAltmaier/Odyssey | d6ef505ade8be3adafa3740f81ed8d03fba3dc1a | 121ea748881526b7787f9106133589c7bd4a9b6d | refs/heads/master | 2020-04-11T08:05:34.474250 | 2015-09-09T20:03:29 | 2015-09-09T20:03:29 | 42,187,845 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,965 | h | Semaphore.h | /* Semaphore.h -- Encapsulates Kernel Semaphores
*
* Copyright (C) ConvergeNet Technologies, 1999
*
* This material is a confidential trade secret and proprietary
* information of ConvergeNet Technologies, Inc. which may not be
* reproduced, used, sold or transferred to any third party without the
* prior written consent of ConvergeNet Technologies, Inc. This material
* is also copyrighted as an unpublished work under sections 104 and 408
* of Title 17 of the United States Code. Law prohibits unauthorized
* use, copying or reproduction.
*
* Description:
* This class encapsulates the underlying Kernel semaphores.
*
**/
// Revision History:
// 3/15/99 Tom Nelson: Created
//
#ifndef __Semaphore_h
#define __Semaphore_h
#include "Kernel.h"
#include "Critical.h"
//***
//*** Semaphore (Standard)
//***
class Semaphore {
private:
CT_Semaphore ctSemaphore;
public:
Semaphore(UNSIGNED cInitial = 0) {
Kernel::Create_Semaphore(&ctSemaphore, "Semaphr", cInitial);
}
~Semaphore() {
Kernel::Delete_Semaphore(&ctSemaphore);
}
STATUS Wait() {
return Kernel::Obtain_Semaphore(&ctSemaphore,CT_SUSPEND);
}
STATUS Signal() {
return Kernel::Release_Semaphore(&ctSemaphore);
}
};
//***
//*** Semaphore (Mutex)
//***
class Mutex {
private:
Semaphore semaphore;
public:
Mutex() : semaphore(1) {}
STATUS Enter() {
return semaphore.Wait();
}
STATUS Leave() {
return semaphore.Signal();
}
};
//***
//*** Semaphore (Pulse)
//***
class Pulse {
private:
U32 nWait;
Semaphore semaphore;
public:
Pulse() : semaphore(0) {}
// Wait for event
STATUS Wait() {
Critical section;
++nWait;
semaphore.Wait();
return OK;
}
// Signal only if task is waiting
STATUS Signal() {
Critical section;
if (nWait > 0) {
--nWait;
semaphore.Signal();
}
return OK;
}
};
#endif // __Semaphore_h
|
5b1ddfc8222dda36041951698a18b2a3d5235236 | 756f58f3844cbb426bf6f8b5deceeeaa55c2fcb6 | /src/Helpers/include/hvector.h | 4730fb7c5b90a5f97715ae302b2c8e69ffed097b | [] | no_license | JiaquanLi/Algorithm-Server | 7e4345f5a7ef7c847bb516b45348a01006c23a25 | 7b10f19120b72638984b4d30f4650931643340cc | refs/heads/master | 2020-03-28T22:31:09.376675 | 2018-10-16T03:20:21 | 2018-10-16T03:20:21 | 149,238,793 | 2 | 2 | null | 2018-10-12T04:18:17 | 2018-09-18T06:23:37 | C++ | UTF-8 | C++ | false | false | 10,059 | h | hvector.h | //---------------------------------------------------------------------------
// Copyright (C) Honeywell International, Inc. 2017
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
// This template class is disigned to mimic the STL vector as much as
// practical. When we can't/don't meet ISO vector spec are noted in
// each method's documentation. These notes will be labelled
// "ISO Note:".
//
// ISO Note: no methods will throw an exception and there is no true
// iterator support (we return a pointer instead of an iterator).
//
// ISO Note: this container requires a default constructor for the
// class T. This also affects how push_back() and clear() work. We
// can change this, but there's a fair amount of time to code and test.
// The more proper implementation would use a local copy of a memory
// pool allocated on the heap, per the capacity needs(placement new).
// Then we use that pool of memory and the class' copy contstructor
// for creating the objects. We would call the classe' destructor
// explicitly when we remove them.
//
// Limitations: There are many methods not implemented.
//---------------------------------------------------------------------------
#ifndef _hvector_h_
#define _hvector_h_
#include <stdlib.h>
template <class T> class hvector
{
public:
hvector(size_t size = 0);
hvector(const hvector<T> & TheVector);
~hvector(void)
{
delete [] m_pArray;
}
T * begin() {return m_pArray;} // ISO Note: returns a T pointer, not an iterator
const T * begin() const {return m_pArray;} // ISO Note: returns a T pointer, not an iterator
size_t size(void) const {return m_Size;}
size_t capacity(void) const {return m_Capacity;}
T & operator[](size_t index);
const T & operator[](size_t index) const;
hvector<T> & operator=(const hvector<T> & rhs);
bool reserve(size_t NewCapacity);
bool push_back(const T & item);
void erase(size_t index);
void clear(void);
protected:
T * m_pArray;
size_t m_Size;
size_t m_Capacity;
};
/*----------------------------------------------------------------------------------------
hvector
Constructor. Will construct a vector with the optional size.
ISO Note: since we can't throw an exception, if we can't allocate the memory, we create
an empty vector.
Parameters:
size[in]: size of vector
Returns: nothing
----------------------------------------------------------------------------------------*/
template <class T> hvector<T>::hvector(size_t size /*= 0*/)
{
m_pArray = new T[size]; // ISO C++ says we'll get a pointer if size is 0. This is handy because we don't have to check for NULL everywhere.
if ( m_pArray )
{
m_Size = size;
m_Capacity = size;
}
else
{ // we're out of ram. Gracefully handle this by creating an empty array
m_Size = 0;
m_Capacity = 0;
m_pArray = new T[m_Size]; // if we're so low on memory that THIS fails, we have bigger issues, so don't bother checking
}
}
/*----------------------------------------------------------------------------------------
hvector
Copy constructor. Will construct a vector with the same size and values of the one
passed.
Parameters:
TheVector[in]: the vector we will be set to
Returns: nothing
----------------------------------------------------------------------------------------*/
template <class T> hvector<T>::hvector(const hvector<T> & TheVector)
{
m_pArray = new T[TheVector.size()];
if ( m_pArray )
{
m_Size = TheVector.size();
m_Capacity = m_Size;
const T * pRhs = TheVector.begin();
T * pArray = m_pArray;
for (size_t i = 0; i < m_Size; i++)
{
*pArray = *pRhs;
pArray++;
pRhs++;
}
}
else
{ // we're out of ram. Gracefully handle this by creating an empty array
m_Size = 0;
m_Capacity = 0;
m_pArray = new T[m_Size]; // if we're so low on memory that THIS fails, we have bigger issues, so don't bother checking
}
}
/*----------------------------------------------------------------------------------------
reserve
Ensures vector can hold the number of bytes passed in.
ISO Note: since we can't throw an exception, if we can't allocate the memory, we leave
things unchanged and return false.
Parameters:
NewCapacity[in]: minimum size of new vector
Returns: true if OK, false otherwise.
----------------------------------------------------------------------------------------*/
template <class T> bool hvector<T>::reserve(size_t NewCapacity)
{
if ( NewCapacity > m_Capacity )
{ // We need to re-allocate. Keep member variables intact untill we safely allocated space for new array
T * pNewArray;
pNewArray = new T[NewCapacity];
if ( pNewArray == NULL )
{ // Failed allocation.
return false;
}
// It's now safe to modify member variables
T * pOldArrayBytes = m_pArray;
T * pNewArrayBytes = pNewArray;
// memcpy(pNewArray, m_pArray, m_Size * sizeof(T)); //this won't work with objects with destructors as they will get called twice (1st time when we delete m_pArray below)
for (size_t i = 0; i < m_Size; i++ )
{
*pNewArrayBytes = *pOldArrayBytes;
pNewArrayBytes++;
pOldArrayBytes++;
}
delete [] m_pArray;
m_pArray = pNewArray;
m_Capacity = NewCapacity;
}
return true;
}
/*----------------------------------------------------------------------------------------
operator[]
Allows you to set an item at a particular offset.
ISO Note: since we can't throw an exception, if the index is out of range, we use the
the last index.
Parameters:
index[in]: offset of item in the vector
Returns: the item at that index.
----------------------------------------------------------------------------------------*/
template <class T> T & hvector<T>::operator[](size_t index)
{
if ( index >= m_Size ) index = m_Size - 1; // size_t is an unsigned variable
return *(m_pArray + index);
}
/*----------------------------------------------------------------------------------------
operator[]
Allows you to read an item at a particular offset.
ISO Note: since we can't throw an exception, if the index is out of range, we use the
the last index.
Parameters:
index[in]: offset of item in the vector
Returns: the item at that index.
----------------------------------------------------------------------------------------*/
template <class T> const T & hvector<T>::operator[](size_t index) const
{
if ( index >= m_Size ) index = m_Size - 1; // size_t is an unsigned variable
return *(m_pArray + index);
}
/*----------------------------------------------------------------------------------------
operator=
Allows you to set one vector to another.
ISO Note: since we can't throw an exception, if we can't expand, we don't and we don't
bother copying the data over. It's up to the caller to check size() to ensure the
assignment went OK.
Parameters:
rhs[in]: the vector we will be set to
Returns: this vector.
----------------------------------------------------------------------------------------*/
template <class T> hvector<T> & hvector<T>::operator=(const hvector<T> & rhs)
{
if ( this == &rhs ) return *this; // someone is assigning me to me
if ( rhs.size() > m_Capacity )
{ // we need more space to hold the larger vector
T * pNewArray;
pNewArray = new T[rhs.size()];
if ( pNewArray == NULL )
{ // Failed allocation.
return *this;
}
delete [] m_pArray;
m_pArray = pNewArray;
m_Capacity = rhs.size();
}
m_Size = rhs.size();
// now do the copying
const T * pRhs = rhs.begin();
T * pArray = m_pArray;
for (size_t i = 0; i < m_Size; i++)
{
*pArray = *pRhs;
pArray++;
pRhs++;
}
return *this;
}
/*----------------------------------------------------------------------------------------
push_back
Appends an item at the end of the vector.
ISO Note: since we can't throw an exception, if we need to grow the vector and can't,
we return false.
Parameters:
item[in]: item to add to the vector
Returns: true if OK, false otherwise.
----------------------------------------------------------------------------------------*/
template <class T> bool hvector<T>::push_back(const T & item)
{
if ( m_Size == m_Capacity )
{
size_t extra = m_Capacity/4;
if ( ! extra ) extra = 4;
size_t NewCapacity = m_Capacity + extra; // increase by 25% to keep re-allocations down
if ( ! reserve(NewCapacity) ) return false;
}
*(m_pArray + m_Size) = item; // m_Size right now is the index of the new last item in the array
m_Size++;
return true;
}
/*----------------------------------------------------------------------------------------
erase
Erases an item.
ISO Note: This returns void instead of an iterator. There is no overload to allow
removing a range of items.
Parameters:
index[in]: index of item to remove
Returns: nothing.
----------------------------------------------------------------------------------------*/
template <class T> void hvector<T>::erase(size_t index)
{
if ( index >= m_Size ) return;
T * pFirstVal = (m_pArray + index);
T * pNextVal = (m_pArray + index + 1);
size_t NumToMove = m_Size - index - 1;
for (size_t i = 0; i < NumToMove; i++)
{
*pFirstVal = *pNextVal;
pFirstVal++;
pNextVal++;
}
m_Size--;
}
/*----------------------------------------------------------------------------------------
clear
Removes all items from the list, but keeps the capacity.
Parameters: none
Returns: nothing.
----------------------------------------------------------------------------------------*/
template <class T> void hvector<T>::clear(void)
{
m_Size = 0;
}
#endif
|
b65407441b3c229b59eeb190922cba9e21e8facc | 5a4604ad5bdf3cadb07b2837f25641521c5c609b | /subpartcontroller.h | 9b5dd7019147cbc2d2dd894eac674185333d8b4b | [] | no_license | littletophe2/mycanvas1 | 1b6326746fd45764590f0b1dbfd08844c2f1da92 | 3ae5ac9fd996b717b0c3ebb64a1c63eea237bb95 | refs/heads/master | 2020-06-19T21:31:38.593511 | 2016-11-29T20:58:53 | 2016-11-29T20:58:53 | 74,831,266 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 562 | h | subpartcontroller.h | #ifndef SUBPARTCONTROLLER_H
#define SUBPARTCONTROLLER_H
#include "viewer3d.h"
#include "controlpanel.h"
/**
* @brief The SubpartController class
* A controller
*/
class SubpartController
{
private:
QString subpartName;
QWidget * widgetForSubpart;
public:
SubpartController(QString subpartName);
virtual ~SubpartController();
virtual void install(Viewer3d * viewer, ControlPanel * controlPanel)=0;
/**
* @brief getWidgetForSubpart
* @return
*/
QWidget * getWidgetForSubpart();
};
#endif // SUBPARTCONTROLLER_H
|
871589ed37b8f049298b50a173bd318dc7f291fa | f2cbdee1dfdcad7b77c597e1af5f40ad83bad4aa | /MyJava/JRex/src/native/JRexPrintEventWrapper.cpp | c9566927845ebcac28ef29c9ff3ae6ed4265c411 | [] | no_license | jdouglas71/Examples | d03d9effc414965991ca5b46fbcf808a9dd6fe6d | b7829b131581ea3a62cebb2ae35571ec8263fd61 | refs/heads/master | 2021-01-18T14:23:56.900005 | 2011-04-07T19:34:04 | 2011-04-07T19:34:04 | 1,578,581 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 17,705 | cpp | JRexPrintEventWrapper.cpp | /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public
* License Version 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* Contributor(s):
* C.N Medappa <jrex_moz@yahoo.com><>
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the NPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the NPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#include "JRexWindow.h"
nsresult JRexWindow::PrintInternal(PRBool prompt, PRBool showProgress){
JREX_LOGLN("PrintInternal()--> **** prompt<"<<prompt<<"> showProgress<"<<showProgress<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"PrintInternal()--> **** do_GetInterface nsIWebBrowserPrint")
nsCOMPtr<nsIPrintSettings> printSettings;
rv = browserAsPrint->GetGlobalPrintSettings(getter_AddRefs(printSettings));
JREX_RETURN_IF_FAILED(rv,"PrintInternal()--> **** GetGlobalPrintSettings nsIPrintSettings")
printSettings->SetPrintSilent(!prompt);
printSettings->SetShowPrintProgress(showProgress);
rv = browserAsPrint->Print(printSettings, nsnull);
JREX_LOGLN("PrintInternal()--> **** Print rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::Print(PRBool prompt, PRBool showProgress){
JREX_LOGLN("Print()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
if(IS_EQT)
return PrintInternal(prompt, showProgress);
PRBool *temp=new PRBool[2];
temp[0]=prompt;
temp[1]=showProgress;
rv=ExecInEventQ(this, JREX_PRINT,temp, PR_FALSE, HandlePrintEvent,DestroyPrintEvent,nsnull);
if (NS_FAILED(rv) && temp)
delete temp;
JREX_LOGLN("Print()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::CancelPrintInternal(){
if(mBrowCreated==PR_FALSE)return NS_OK;
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"CancelPrintInternal()--> **** do_GetInterface nsIWebBrowserPrint")
PRBool printing=PR_FALSE;
browserAsPrint->GetDoingPrint(&printing);
if(printing==PR_TRUE){
rv = browserAsPrint->Cancel();
JREX_LOGLN("CancelPrintInternal()--> **** Cancel rv<"<<rv<<"> ****")
}
return rv;
}
nsresult JRexWindow::CancelPrint(){
JREX_LOGLN("CancelPrint()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
if(IS_EQT)
return CancelPrintInternal();
rv=ExecInEventQ(this, JREX_CANCEL_PRINT,nsnull, PR_FALSE, HandlePrintEvent,DestroyPrintEvent,nsnull);
JREX_LOGLN("CancelPrint()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::PrintPreviewInternal(PRBool shrinkToFit, PRBool isLandScape){
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> print(do_GetInterface(mWebBrowser,&rv));
JREX_RETURN_IF_FAILED(rv,"PrintPreviewInternal()--> **** do_GetInterface nsIWebBrowserPrint")
nsCOMPtr<nsIPrintSettings> printSettings;
rv = print->GetGlobalPrintSettings(getter_AddRefs(printSettings));
JREX_RETURN_IF_FAILED(rv,"PrintPreviewInternal()--> **** GetGlobalPrintSettings nsIPrintSettings")
rv=printSettings->SetShrinkToFit(shrinkToFit);
JREX_LOGLN("PrintPreviewInternal()--> **** SetShrinkToFit rv<"<<rv<<"> ****")
PRInt32 land=nsIPrintSettings::kLandscapeOrientation;
PRInt32 port=nsIPrintSettings::kPortraitOrientation;
rv=printSettings->SetOrientation(isLandScape?land:port);
JREX_LOGLN("PrintPreviewInternal()--> **** SetOrientation rv<"<<rv<<"> ****")
print->PrintPreview(printSettings, nsnull, nsnull);
JREX_LOGLN("PrintPreviewInternal()--> **** PrintPreview rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::PrintPreview(PRBool shrinkToFit, PRBool isLandScape){
JREX_LOGLN("PrintPreview()--> **** mBrowCreated<"<<mBrowCreated<<"> shrinkToFit<"<<shrinkToFit<<"> isLandScape<"<<isLandScape<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
if(IS_EQT)
return PrintPreviewInternal(shrinkToFit,isLandScape);
PRBool *temp=new PRBool[2];
temp[0]=shrinkToFit;
temp[1]=isLandScape;
rv=ExecInEventQ(this, JREX_PRINT_PREVIEW,temp, PR_FALSE, HandlePrintEvent,DestroyPrintEvent,nsnull);
if (NS_FAILED(rv) && temp)
delete temp;
JREX_LOGLN("PrintPreview()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::CancelPrintPreviewInternal(){
if(mBrowCreated==PR_FALSE)return NS_OK;
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"CancelPrintPreviewInternal()--> **** do_GetInterface nsIWebBrowserPrint")
PRBool printPreviewing=PR_FALSE;
rv=browserAsPrint->GetDoingPrintPreview(&printPreviewing);
JREX_LOGLN("CancelPrintPreviewInternal()--> **** GetDoingPrintPreview rv<"<<rv<<"> printPreviewing<"<<printPreviewing<<"> ****")
if(printPreviewing==PR_TRUE){
try{
rv = browserAsPrint->ExitPrintPreview();
JREX_LOGLN("CancelPrintPreviewInternal()--> **** ExitPrintPreview rv<"<<rv<<"> ****")
}catch(...){
JREX_LOGLN("CancelPrintPreviewInternal()--> **** UGLY F**KN BUG ****")
}
}
return rv;
}
nsresult JRexWindow::CancelPrintPreview(){
JREX_LOGLN("CancelPrintPreview()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
if(IS_EQT)
return CancelPrintPreviewInternal();
rv=ExecInEventQ(this, JREX_CANCEL_PREVIEW,nsnull, PR_FALSE, HandlePrintEvent,DestroyPrintEvent,nsnull);
JREX_LOGLN("CancelPrintPreview()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::GetPrintPreviewNumPagesInternal(PRInt32 *aPrintPreviewNumPages){
NS_ENSURE_ARG_POINTER(aPrintPreviewNumPages);
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"GetPrintPreviewNumPagesInternal()--> **** do_GetInterface nsIWebBrowserPrint")
rv=browserAsPrint->GetPrintPreviewNumPages(aPrintPreviewNumPages);
JREX_LOGLN("GetPrintPreviewNumPagesInternal()--> **** GetPrintPreviewNumPages rv<"<<rv<<"> aPrintPreviewNumPages<"<<*aPrintPreviewNumPages<<"> ****")
return rv;
}
nsresult JRexWindow::GetPrintPreviewNumPages(PRInt32 *aPrintPreviewNumPages){
NS_ENSURE_ARG_POINTER(aPrintPreviewNumPages);
JREX_LOGLN("GetPrintPreviewNumPages()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_ERROR_NOT_INITIALIZED;
nsresult rv;
if(IS_EQT)
return GetPrintPreviewNumPagesInternal(aPrintPreviewNumPages);
PRInt32 printPreviewNumPages=0;
rv=ExecInEventQ(this, JREX_PREVIEW_PAGES,nsnull, PR_TRUE, HandlePrintEvent,DestroyPrintEvent, (void**)&printPreviewNumPages);
JREX_LOGLN("GetPrintPreviewNumPages()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
if(NS_SUCCEEDED(rv))
*aPrintPreviewNumPages=printPreviewNumPages;
JREX_LOGLN("GetPrintPreviewNumPages()--> **** pages <"<<printPreviewNumPages<<"> ****")
return rv;
}
nsresult JRexWindow::PrintPreviewNavigateInternal(PRInt16 aNavType, PRInt32 aPageNum){
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"PrintPreviewNavigateInternal()--> **** do_GetInterface nsIWebBrowserPrint")
PRBool printPreviewing=PR_FALSE;
rv=browserAsPrint->GetDoingPrintPreview(&printPreviewing);
JREX_LOGLN("PrintPreviewNavigateInternal()--> **** GetDoingPrintPreview rv<"<<rv<<"> printPreviewing<"<<printPreviewing<<"> ****")
if(printPreviewing==PR_TRUE){
rv = browserAsPrint->PrintPreviewNavigate(aNavType, aPageNum);
JREX_LOGLN("PrintPreviewNavigateInternal()--> **** PrintPreviewNavigate rv<"<<rv<<"> ****")
}
return rv;
}
nsresult JRexWindow::PrintPreviewNavigate(PRInt16 aNavType, PRInt32 aPageNum){
JREX_LOGLN("PrintPreviewNavigate()--> **** mBrowCreated<"<<mBrowCreated<<"> aNavType<"<<aNavType<<"> aPageNum<"<<aPageNum<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
if(IS_EQT)
return PrintPreviewNavigateInternal(aNavType, aPageNum);
PRInt32 *temp=new PRInt32[2];
temp[0]=aNavType;
temp[1]=aPageNum;
nsresult rv=ExecInEventQ(this, JREX_NAV_PREVIEW,temp, PR_FALSE, HandlePrintEvent,DestroyPrintEvent,nsnull);
if (NS_FAILED(rv) && temp)
delete temp;
JREX_LOGLN("PrintPreviewNavigate()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::PageSetupInternal(){
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"PageSetupInternal()--> **** do_GetInterface nsIWebBrowserPrint")
nsCOMPtr<nsIDOMWindow> domWindow;
rv=mWebBrowser->GetContentDOMWindow(getter_AddRefs(domWindow));
JREX_RETURN_IF_FAILED(rv,"PageSetupInternal()--> **** GetContentDOMWindow")
nsCOMPtr<nsIPrintSettings> printSettings;
rv = browserAsPrint->GetGlobalPrintSettings(getter_AddRefs(printSettings));
JREX_RETURN_IF_FAILED(rv,"PageSetupInternal()--> **** GetGlobalPrintSettings")
nsCOMPtr<nsIPrintingPromptService> printingPromptService =do_GetService("@mozilla.org/embedcomp/printingprompt-service;1",&rv);
JREX_RETURN_IF_FAILED(rv,"PageSetupInternal()--> **** do_GetService nsIPrintingPromptService")
rv=printingPromptService->ShowPageSetup(domWindow, printSettings, nsnull);
JREX_LOGLN("PageSetupInternal()--> **** ShowPageSetup rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::PageSetup(){
JREX_LOGLN("PageSetup()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_OK;
nsresult rv;
if(IS_EQT)
return PageSetupInternal();
rv=ExecInEventQ(this, JREX_PAGE_SETUP,nsnull, PR_FALSE, HandlePrintEvent,DestroyPrintEvent, nsnull);
JREX_LOGLN("PageSetup()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
return rv;
}
nsresult JRexWindow::IsPrintingInternal(PRBool *isPrinting){
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"IsPrintingInternal()--> **** do_GetInterface nsIWebBrowserPrint")
PRBool printing=PR_FALSE;
browserAsPrint->GetDoingPrint(&printing);
*isPrinting=printing;
JREX_LOGLN("IsPrintingInternal()--> **** printing <"<<printing<<"> ****")
return rv;
}
nsresult JRexWindow::IsPrinting(PRBool *isPrinting){
NS_ENSURE_ARG_POINTER(isPrinting);
JREX_LOGLN("IsPrinting()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_ERROR_NOT_INITIALIZED;
nsresult rv;
if(IS_EQT)
return IsPrintingInternal(isPrinting);
PRBool printing=PR_FALSE;
rv=ExecInEventQ(this, JREX_DOING_PRINT,nsnull, PR_TRUE, HandlePrintEvent,DestroyPrintEvent, (void**)&printing);
JREX_LOGLN("IsPrinting()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
if(NS_SUCCEEDED(rv))
*isPrinting=printing;
JREX_LOGLN("IsPrinting()--> **** printing <"<<printing<<"> ****")
return rv;
}
nsresult JRexWindow::IsPrintPreviewingInternal(PRBool *isPrintPreviewing){
nsresult rv;
nsCOMPtr<nsIWebBrowserPrint> browserAsPrint=do_GetInterface(mWebBrowser,&rv);
JREX_RETURN_IF_FAILED(rv,"IsPrintPreviewingInternal()--> **** do_GetInterface nsIWebBrowserPrint")
PRBool printPreviewing=PR_FALSE;
browserAsPrint->GetDoingPrintPreview(&printPreviewing);
*isPrintPreviewing=printPreviewing;
JREX_LOGLN("IsPrintPreviewingInternal()--> **** printPreviewing <"<<printPreviewing<<"> ****")
return rv;
}
nsresult JRexWindow::IsPrintPreviewing(PRBool *isPrintPreviewing){
NS_ENSURE_ARG_POINTER(isPrintPreviewing);
JREX_LOGLN("IsPrintPreviewing()--> **** mBrowCreated<"<<mBrowCreated<<"> ****")
if(WINDOW_NOT_VALID)return NS_ERROR_NOT_INITIALIZED;
nsresult rv;
if(IS_EQT)
return IsPrintPreviewingInternal(isPrintPreviewing);
PRBool printPreviewing=PR_FALSE;
rv=ExecInEventQ(this, JREX_DOING_PREVIEW,nsnull, PR_TRUE, HandlePrintEvent, DestroyPrintEvent, (void**)&printPreviewing);
JREX_LOGLN("IsPrintPreviewing()--> **** ExecPrintEvent rv<"<<rv<<"> ****")
if(NS_SUCCEEDED(rv))
*isPrintPreviewing=printPreviewing;
JREX_LOGLN("IsPrintPreviewing()--> **** printPreviewing <"<<printPreviewing<<"> ****")
return rv;
}
void* PR_CALLBACK JRexWindow::HandlePrintEvent(PLEvent* aEvent){
JRexEventRV* rVal=nsnull;
if(!gXpcomRunning || !(rVal=new JRexEventRV))return nsnull;
JRexBasicEvent* event = NS_REINTERPRET_CAST(JRexBasicEvent*, aEvent);
JRexWindow* window = NS_STATIC_CAST(JRexWindow*, event->target);
//Assign this so that it can be deleted in proper place.
event->eRV=rVal;
rVal->rv=NS_OK;
JREX_LOGLN("HandlePrintEvent()--> **** JRexWindow <"<<window<<"> ****")
if(JRexWindow::IsWindowAvailable(window)==PR_FALSE)
return rVal;
switch(event->eventType){
case JREX_PRINT:
{
PRBool *temp=(PRBool *)event->eventData;
JREX_LOGLN("HandlePrintEvent()--> **** PrintInternal prompt<"<<temp[0]<<"> showProgress<"<<temp[1]<<"> ****")
rVal->rv=window->PrintInternal(temp[0], temp[1]);
JREX_LOGLN("HandlePrintEvent()--> **** PrintInternal rv<"<<rVal->rv<<"> ****")
break;
}
case JREX_PRINT_PREVIEW:
{
PRBool *temp=(PRBool *)event->eventData;
JREX_LOGLN("HandlePrintEvent()--> **** PrintPreviewInternal prompt<"<<temp[0]<<"> showProgress<"<<temp[1]<<"> ****")
rVal->rv=window->PrintPreviewInternal(temp[0], temp[1]);
JREX_LOGLN("HandlePrintEvent()--> **** PrintInternal rv<"<<rVal->rv<<"> ****")
break;
}
case JREX_PREVIEW_PAGES:
{
PRInt32 printPreviewNumPages=0;
rVal->rv=window->GetPrintPreviewNumPagesInternal(&printPreviewNumPages);
JREX_LOGLN("HandlePrintEvent()--> **** GetPrintPreviewNumPagesInternal rv<"<<rVal->rv<<"> printPreviewNumPages<"<<printPreviewNumPages<<"> ****")
rVal->rData=(void*)printPreviewNumPages;
break;
}
case JREX_DOING_PRINT:
{
PRBool isPrinting=PR_FALSE;
rVal->rv=window->IsPrintingInternal(&isPrinting);
JREX_LOGLN("HandlePrintEvent()--> **** IsPrintingInternal rv<"<<rVal->rv<<"> isPrinting<"<<isPrinting<<"> ****")
rVal->rData=(void*)isPrinting;
break;
}
case JREX_DOING_PREVIEW:
{
PRBool isPreviewing=PR_FALSE;
rVal->rv=window->IsPrintPreviewingInternal(&isPreviewing);
JREX_LOGLN("HandlePrintEvent()--> **** IsPrintPreviewingInternal rv<"<<rVal->rv<<"> isPreviewing<"<<isPreviewing<<"> ****")
rVal->rData=(void*)isPreviewing;
break;
}
case JREX_CANCEL_PRINT:
{
rVal->rv=window->CancelPrintInternal();
JREX_LOGLN("HandlePrintEvent()--> **** CancelPrintInternal rv<"<<rVal->rv<<"> ****")
break;
}
case JREX_CANCEL_PREVIEW:
{
rVal->rv=window->CancelPrintPreviewInternal();
JREX_LOGLN("HandlePrintEvent()--> **** CancelPrintPreviewInternal rv<"<<rVal->rv<<"> ****")
break;
}
case JREX_NAV_PREVIEW:
{
PRInt32 *temp=(PRInt32 *)event->eventData;
JREX_LOGLN("HandlePrintEvent()--> **** PrintPreviewNavigate NavType<"<<temp[0]<<"> pageNum<"<<temp[1]<<"> ****")
rVal->rv=window->PrintPreviewNavigateInternal(temp[0], temp[1]);
JREX_LOGLN("HandlePrintEvent()--> **** PrintPreviewNavigateInternal rv<"<<rVal->rv<<"> ****")
break;
}
case JREX_PAGE_SETUP:
{
rVal->rv=window->PageSetupInternal();
JREX_LOGLN("HandlePrintEvent()--> **** PageSetupInternal rv<"<<rVal->rv<<"> ****")
break;
}
default:
{
JREX_LOGLN("HandlePrintEvent()--> **** EVENT TYPE<"<<event->eventType<<"> not handled!!! ****")
}
}
JREX_LOGLN("HandlePrintEvent()--> **** returning rVal<"<<rVal<<"> ****")
return rVal;
}
void PR_CALLBACK JRexWindow::DestroyPrintEvent(PLEvent* aEvent){
JRexBasicEvent* event = NS_REINTERPRET_CAST(JRexBasicEvent*, aEvent);
JREX_LOGLN("DestroyPrintEvent()--> **** event <"<<event<<"> ****")
if(event->eventData){
if(event->eventType==JREX_PRINT || event->eventType==JREX_PRINT_PREVIEW){
PRBool *temp=(PRBool *)event->eventData;
delete temp;
}else
if(event->eventType==JREX_NAV_PREVIEW){
PRInt32 *temp=(PRInt32 *)event->eventData;
delete temp;
}
}
if((event->isSync==PR_FALSE) && event->eRV)//Delete eRV of Non-Sync Event Here
delete event->eRV;
delete event;
}
|
fc544fc0ce49a53d34d75503b0b7863398201887 | 01fa15aad6918d6904ee917642a3385dd5848cfa | /Game/TriggerTestScript.cpp | 1d1acefed8a3632a37255aa58e7cc2b6ad4d9c95 | [] | no_license | SybrenVP/2D_GameEngine | a62e30780e0ab3144c7f5e16892cac7c2940c140 | c590bf2c08a8c52ee9f5ba16f7ecb3309ffc04fe | refs/heads/master | 2020-05-24T17:02:45.217348 | 2019-05-26T19:49:40 | 2019-05-26T19:49:40 | 187,373,373 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 689 | cpp | TriggerTestScript.cpp | #include "pch.h"
#include "TriggerTestScript.h"
TriggerTestScript::TriggerTestScript(svp::GameObject* const pGameObject)
: BaseComponent(pGameObject)
{
m_Layer = LayerFlag::Trigger;
}
void TriggerTestScript::OnTriggerEnter(svp::TriggerComponent * pOther)
{
svp::Logger::GetInstance().Log(svp::Logger::LogType::Debug, "Own script ENTER");
UNREFERENCED_PARAMETER(pOther);
}
void TriggerTestScript::OnTriggerLeave(svp::TriggerComponent * pOther)
{
svp::Logger::GetInstance().Log(svp::Logger::LogType::Debug, "Own script LEAVE");
UNREFERENCED_PARAMETER(pOther);
}
void TriggerTestScript::Update()
{
}
void TriggerTestScript::Render()
{
}
void TriggerTestScript::FixedUpdate()
{
}
|
63191d6ce61cb6e643110e1ae448941baeec8c3a | 3bca8bdbbf6cbd503d50c3d8053f748bf2eaf9cd | /Template_outside_class.cpp | ceb8a4e0984862386e4d4facf19b64026ad55518 | [] | no_license | PolyglotFormalCoder/Cpp_Practice | 228dd0d5adf7292168d055a9c6ca6f3774f67852 | b19cda698d088fbe4c2166c0110c56736b2cdf26 | refs/heads/master | 2022-11-30T21:52:21.068831 | 2020-08-11T14:35:41 | 2020-08-11T14:35:41 | 285,615,356 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 466 | cpp | Template_outside_class.cpp | //simple template
#include<iostream>
#include<vector>
#include <cstddef>
#include <concepts>
#include <functional>
using namespace std;
template <typename T, int N>
class C
{
public:
C(T temp):a(temp){}
T operator()(){
std::cout<<"generic: "<<N<<std::endl;
return a;}
T getData();
private:
T a;
};
template <typename T, int N>
T C<T, N>::getData()
{
return a;
}
int main()
{
C<int,100> c(2000);
std::cout<<c()<<std::endl;
return 0;
} |
f1025e16b4190f0e0ba123902f5abe79b5e23804 | 5dadf128a55f5d1fc5a1d9b9f655ca3053657676 | /src/KendallTau.cpp | a61965a0e829ae306db1dbc6ea5e513a2f9becb1 | [] | no_license | projeto-de-algoritmos/D-C_KendallTau | 13808f6c4dbf3216d7a625077258fde3df298b5b | 6d3058f1b31af25389d27936b0cb2c8c085567c2 | refs/heads/master | 2023-01-23T03:01:53.341923 | 2020-11-14T01:59:25 | 2020-11-14T01:59:25 | 310,756,210 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,923 | cpp | KendallTau.cpp | #include "KendallTau.hpp"
#include <iostream>
#include <iomanip>
bool KendallTau::adicionarElemento(int elemento) {
if(temElemento(elemento, lista))
return false;
lista.push_back(elemento);
return true;
}
bool KendallTau::temElemento(int elemento, vector <int> listaX) {
for(int i = 0; i < (int)listaX.size(); i++) {
if(listaX[i] == elemento)
return true;
}
return false;
}
bool KendallTau::adicionarPosicao(int elemento) {
for(int i = 0; i < (int)lista.size(); i++) {
if(lista[i] == elemento) {
if(temElemento(elemento, lista2))
return false;
posicoes.push_back(i);
lista2.push_back(elemento);
return true;
}
}
return false;
}
void KendallTau::imprimirListas(){
if(lista.empty()){
cout << "Lista vazia" << endl << endl;
return;
}
vector <bool> adicionarEspaco(lista.size(), false);
vector <int> espacos;
gerarEspacos(espacos, adicionarEspaco);
cout << "Lista 1: ";
for(int i = 0; i< (int)lista.size(); i++){
if(adicionarEspaco[i])
cout << setw(espacos[i] + to_string(lista[i]).length());
cout << lista[i] << " ";
}
cout << endl << endl << "Lista 2: ";
for(int i = 0; i< (int)lista.size(); i++){
if(!adicionarEspaco[i])
cout << setw(espacos[i] + to_string(lista2[i]).length());
cout << lista2[i] << " ";
}
cout << endl << endl;
}
void KendallTau::gerarEspacos(vector <int> &espacos, vector <bool> &adicionarEspaco){
for(int i = 0; i< (int)lista.size(); i++){
int tam1 = to_string(lista[i]).length();
int tam2 = to_string(lista2[i]).length();
if(tam2 > tam1){
adicionarEspaco[i] = true;
espacos.push_back((tam2-tam1));
}
else
espacos.push_back(tam1 - tam2);
}
}
void KendallTau::limparDados() {
lista.clear();
lista2.clear();
posicoes.clear();
}
int KendallTau::obterDistancia() {
qtDeInversoes = 0;
listaOrdenada = lista;
posicoesOrdenadas = posicoes;
mergesort(0, listaOrdenada.size() - 1);
return qtDeInversoes;
}
void KendallTau::mergesort(int inicio, int fim) {
if(fim > inicio) {
mergesort(inicio, (fim + inicio) / 2);
mergesort((fim + inicio) / 2 + 1, fim);
mergeCount(inicio, (fim + inicio) / 2, (fim + inicio) / 2 + 1, fim);
}
}
void KendallTau::mergeCount(int inicioA, int fimA, int inicioB, int fimB) {
vector <int> listaOrdenada;
vector <int> posicoesOrdenadas;
int indiceA = inicioA, indiceB = inicioB;
int total = fimB - inicioA + 1;
for(int i = 0; i < total; i++) {
if(indiceA > fimA) {
listaOrdenada.push_back(this->listaOrdenada[indiceB]);
posicoesOrdenadas.push_back(this->posicoesOrdenadas[indiceB]);
indiceB++;
} else if(indiceB > fimB) {
listaOrdenada.push_back(this->listaOrdenada[indiceA]);
posicoesOrdenadas.push_back(this->posicoesOrdenadas[indiceA]);
indiceA++;
} else if(this->posicoesOrdenadas[indiceA] < this->posicoesOrdenadas[indiceB]) {
listaOrdenada.push_back(this->listaOrdenada[indiceA]);
posicoesOrdenadas.push_back(this->posicoesOrdenadas[indiceA]);
indiceA++;
} else {
listaOrdenada.push_back(this->listaOrdenada[indiceB]);
posicoesOrdenadas.push_back(this->posicoesOrdenadas[indiceB]);
indiceB++;
qtDeInversoes += fimA - indiceA + 1;
}
}
int indice = inicioA;
for(int i = 0; i < (int)listaOrdenada.size(); i++) {
this->listaOrdenada[indice] = listaOrdenada[i];
this->posicoesOrdenadas[indice] = posicoesOrdenadas[i];
indice++;
}
}
int KendallTau::getElemento(int i){
return lista[i];
}
|
ae1f46587ee7d574f90c3a0368758047b6cef705 | af8ff98454a03ef8cd96cbd8057d76385a376251 | /mlmodel/src/ResultReason.hpp | 7b6b676eea1586764cf08357365ee48d18a1e59a | [
"BSD-3-Clause"
] | permissive | prakriti07/coremltools | 4c697773ff6f54b48dd780b3f91da10cf5ba6242 | 82c916d4925ac4dc380e20a595011abb44a35335 | refs/heads/master | 2022-11-08T07:08:33.651727 | 2020-06-29T04:32:19 | 2020-06-29T04:32:19 | 275,730,143 | 0 | 0 | BSD-3-Clause | 2020-06-29T04:28:46 | 2020-06-29T04:28:45 | null | UTF-8 | C++ | false | false | 2,098 | hpp | ResultReason.hpp | //
// ResultReason.hpp
// CoreML
//
// Created by Jeff Kilpatrick on 12/16/19.
// Copyright © 2019 Apple Inc. All rights reserved.
//
#pragma once
namespace CoreML {
/**
Super specific reasons for non-good Results.
*/
enum class ResultReason {
UNKNOWN,
// -----------------------------------------
// Model validation
MODEL_INPUT_TYPE_INVALID,
MODEL_OUTPUT_TYPE_INVALID,
// -----------------------------------------
// Program validation
BLOCK_INPUT_COUNT_MISMATCHED,
BLOCK_OUTPUT_NAME_EMPTY,
BLOCK_OUTPUT_COUNT_MISMATCHED,
BLOCK_OUTPUT_TYPE_MISMATCHED,
BLOCK_OUTPUT_VALUE_UNDEFINED,
BLOCK_PARAM_NAME_EMPTY,
BLOCK_PARAM_NAME_SHADOWS,
FUNCTION_BLOCK_RETURN_COUNT_MISMATCHED,
FUNCTION_BLOCK_RETURN_TYPE_MISMATCHED,
FUNCTION_NAME_EMPTY,
FUNCTION_PARAM_NAME_EMPTY,
FUNCTION_PARAM_NAME_SHADOWS,
FUNCTION_PARAM_TYPE_NULL,
MODEL_MAIN_IMAGE_INPUT_SIZE_BAD,
MODEL_MAIN_IMAGE_INPUT_TYPE_BAD,
MODEL_MAIN_IMAGE_OUTPUT_SIZE_BAD,
MODEL_MAIN_IMAGE_OUTPUT_TYPE_BAD,
MODEL_MAIN_INPUT_COUNT_MISMATCHED,
MODEL_MAIN_INPUT_OUTPUT_MISSING,
MODEL_MAIN_INPUT_OUTPUT_TYPE_INVALID,
MODEL_MAIN_INPUT_RANK_MISMATCHED,
MODEL_MAIN_INPUT_SHAPE_MISMATCHED,
MODEL_MAIN_INPUT_TYPE_MISMATCHED,
MODEL_MAIN_OUTPUT_COUNT_MISMATCHED,
MODEL_MAIN_OUTPUT_RANK_MISMATCHED,
MODEL_MAIN_OUTPUT_SHAPE_MISMATCHED,
MODEL_MAIN_OUTPUT_TYPE_MISMATCHED,
OP_ARG_COUNT_MISMATCH,
OP_ARG_NAME_EMPTY,
OP_ARG_OUTPUT_CIRCULAR_DEFINITION,
OP_ARG_TYPE_MISMATCH,
OP_ARG_VALUE_UNDEFINED,
OP_ATTRIBUTE_NAME_EMPTY,
OP_ATTRIBUTE_VALUE_UNDEFINED,
OP_BLOCK_COUNT_INVALID,
OP_INVALID_IN_CONTEXT,
OP_NAME_EMPTY,
OP_OUTPUT_COUNT_MISMATCHED,
OP_OUTPUT_NAME_EMPTY,
OP_OUTPUT_NAME_SHADOWS,
OP_OUTPUT_TYPE_INVALID,
OP_PARAM_COUNT_MISMATCHED,
OP_PARAM_INVALID,
OP_PARAM_NAME_EMPTY,
OP_REQUIRED_ARG_NOT_FOUND,
PARAMETER_NAME_EMPTY,
PARAMETER_VALUE_UNDEFINED,
PROGRAM_MAIN_FUNCTION_MISSING,
PROGRAM_NULL,
PROGRAM_PARSE_THREW,
};
}
|
778834ddd7f5778b2261155ce6297eeb6c29fd5e | 7d7301514d34006d19b2775ae4f967a299299ed6 | /leetcode/string/712.minimumDeleteSum.cpp | 9d64dc3d56999ee8b30b878927b10228b201b4ef | [] | no_license | xmlb88/algorithm | ae83ff0e478ea01f37bc686de14f7d009d45731b | cf02d9099569e2638e60029b89fd7b384f3c1a68 | refs/heads/master | 2023-06-16T00:21:27.922428 | 2021-07-17T03:46:50 | 2021-07-17T03:46:50 | 293,984,271 | 1 | 0 | null | 2020-12-02T09:08:28 | 2020-09-09T02:44:20 | C++ | WINDOWS-1252 | C++ | false | false | 1,605 | cpp | 712.minimumDeleteSum.cpp | #include <iostream>
#include <string>
#include <vector>
using namespace std;
// µÝ¹é
vector<vector<int>> memo;
int minimumDeleteSum(string s1, string s2) {
int m = s1.size(), n = s2.size();
memo.resize(m, vector<int> (n, -1));
return dp(s1, 0, s2, 0);
}
int dp(string s1, int i, string s2, int j) {
int m = s1.length(), n = s2.length();
if (i == m) {
int rest = 0;
while (j < n) {
rest += s2[j];
j++;
}
return rest;
}
if (j == n) {
int rest = 0;
while (i < m) {
rest += s1[i];
i++;
}
return rest;
}
if (memo[i][j] != -1) return memo[i][j];
if (s1[i] == s2[j]) {
memo[i][j] = dp(s1, i + 1, s2, j + 1);
} else {
memo[i][j] = min((int)s1[i] + dp(s1, i + 1, s2, j), (int)s2[j] + dp(s1, i, s2, j + 1));
}
return memo[i][j];
}
// µü´ú
int minimumDeleteSum(string s1, string s2) {
int m = s1.length(), n = s2.length();
vector<vector<int>> dp(m + 1, vector<int> (n + 1, 0));
// ³õʼ»¯[...,0]ºÍ[0, ...]
for (int i = 1; i <= n; i++) {
dp[0][i] = dp[0][i - 1] + (int)s2[i - 1];
}
for (int i = 1; i <= m; i++) {
dp[i][0] = dp[i - 1][0] + (int)s1[i - 1];
}
for (int i = 1; i <= m; i++) {
for (int j = 1; j <= n; j++) {
if (s1[i - 1] == s2[j - 1]) dp[i][j] = dp[i - 1][j - 1];
else {
dp[i][j] = min((int)s1[i - 1] + dp[i - 1][j], (int)s2[j - 1] + dp[i][j - 1]);
}
}
}
return dp[m][n];
} |
a16cdc4548a4b464d839390fc1769a5262150238 | 294d5e5fd0f176c27fb94391d117690f10e6b9a2 | /12555_babyMe.cpp | fa623e0f7fab70802eb574058b634c8dcb15373c | [] | no_license | matrix01/Uva-Solve | 6b60002344e9b5ac9c5c3fea9085e26abe6e8bd2 | 4a321527bcf90e725348964378d6c4c953619617 | refs/heads/master | 2021-04-09T17:14:59.589768 | 2015-04-23T23:56:50 | 2015-04-23T23:56:50 | 34,484,846 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 306 | cpp | 12555_babyMe.cpp | #include<iostream>
#include<cstdio>
#include<string>
using namespace std;
int main(){
int a, b, t, sq=1;
cin>>t;
string num;
while(t--){
a=0;
b=0;
cin>>a;
cin>>num;
if(num.size()>3){
b=(int)(num[3]-'0');
}
cout << "Case " << sq++ << ": " << a * 0.5 + b * 0.05 << endl;
}
return 0;
} |
705102ad35ac25a423df90de75ea61670b96d016 | 09e897e40fb9e32e33bc5a146aeb9faded607bf5 | /Source/math_utils.cpp | 752f443cef57f1080c559b8f07eca37e7769423b | [
"MIT"
] | permissive | JuanDiegoMontoya/EngineBase | b919acad0bc1e2b5acf77d29bd821739a61bc18e | e9b3f35d1a49e24a23c322c554176da55272e680 | refs/heads/master | 2021-02-08T04:57:19.543337 | 2020-11-14T23:44:58 | 2020-11-14T23:44:58 | 244,111,711 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,995 | cpp | math_utils.cpp | #include "../../stdafx.h"
#include <cmath>
#include <random>
#include "utilities.h"
namespace Utils
{
float lerp(float a, float b, float t)
{
return (a + ((b - a) * t));
}
// 1 - t is the AMOUNT COMPLETED after one second (lower is faster)
float lerp_t(float a, float b, float t)
{
float dt = 0; //= ...
return (a + ((b - a) * (1 - pow(t, dt))));
}
float align(float value, float size)
{
//return std::floor(value / size) * size;
//round is way better than floor
return std::round(value / size) * size;
}
//sets a value to zero if it falls within a given range
void epsilon(float *val, float min, float max)
{
if (*val > min && *val < max)
*val = 0.0f;
}
float inverse_lerp(float a, float b, float t)
{
return ((t - a) / (b - a));
}
float smoothstep(float edge0, float edge1, float x)
{
x = std::clamp((x - edge0) / (edge1 - edge0), 0.0f, 1.0f);
return x * x * (3 - 2 * x);
}
float distPointToRect(glm::vec2 p, glm::vec2 rc, glm::vec2 rs)
{
float dx = glm::max(glm::abs(p.x - rc.x) - rs.x / 2.0f, 0.0f);
float dy = glm::max(glm::abs(p.y - rc.y) - rs.y / 2.0f, 0.0f);
return dx * dx + dy * dy;
}
float distPointToPoint(glm::vec2 p1, glm::vec2 p2)
{
float dx = glm::max(glm::abs(p1.x - p2.x), 0.0f);
float dy = glm::max(glm::abs(p1.y - p2.y), 0.0f);
return dx * dx + dy * dy;
}
float get_random(float low, float high)
{
// super fast and super random
static std::random_device rd;
static std::mt19937 rng(rd());
std::uniform_real_distribution<float> dist(low, high);
return (float)dist(rng);
}
float get_random_r(float low, float high)
{
static thread_local std::mt19937 generator;
std::uniform_real_distribution<float> distribution(low, high);
return distribution(generator);
}
float get_random_s(unsigned seed, float low, float high)
{
static std::random_device rd;
static std::mt19937 rng(rd());
rng.seed(seed);
std::uniform_real_distribution<float> dist(low, high);
return (float)dist(rng);
}
// seeded with vector
float get_random_svr(glm::vec3 seed, float low, float high)
{
//static thread_local std::random_device rd;
//static std::mt19937 rng(rd());
//rng.seed(ivec3Hash()(seed));
//std::uniform_real_distribution<float> dist(low, high);
//return (float)dist(rng);
static thread_local std::mt19937 generator;
generator.seed(ivec3Hash()(seed));
std::uniform_real_distribution<float> distribution(low, high);
return distribution(generator);
}
glm::vec3 get_random_vec3_r(float low, float high)
{
static thread_local std::mt19937 generator;
std::uniform_real_distribution<float> distribution1(low, high);
std::uniform_real_distribution<float> distribution2(low, high);
std::uniform_real_distribution<float> distribution3(low, high);
return glm::vec3(distribution1(generator), distribution2(generator), distribution3(generator));
}
} |
058cb2ac3a131b893dbfbb27572f6f41d9bd2700 | 6934698255bccce965723be83684c2757e74750c | /src/mongo-cxx-driver/mongo/client/distlock.cpp | 9ec98eaed187348c77f4f0f935f515d82c8a5916 | [
"Apache-2.0"
] | permissive | tpisto/rmongo | 5beffa02e7e3b12e07d5c47e16cd7e32878047f5 | dc34be98ad509b9636d7a1968e8f12669666ae2f | refs/heads/master | 2016-09-06T10:28:03.445079 | 2011-02-28T17:45:13 | 2011-02-28T17:45:13 | 1,416,232 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 12,451 | cpp | distlock.cpp | // @file distlock.h
/* Copyright 2009 10gen Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "pch.h"
#include "dbclient.h"
#include "distlock.h"
namespace mongo {
static string lockPingNS = "config.lockpings";
static string locksNS = "config.locks";
ThreadLocalValue<string> distLockIds("");
/* ==================
* Module initialization
*/
boost::once_flag _init = BOOST_ONCE_INIT;
static string* _cachedProcessString = NULL;
static void initModule() {
// cache process string
stringstream ss;
ss << getHostName() << ":" << time(0) << ":" << rand();
_cachedProcessString = new string( ss.str() );
}
/* =================== */
string getDistLockProcess() {
boost::call_once( initModule, _init );
assert( _cachedProcessString );
return *_cachedProcessString;
}
string getDistLockId() {
string s = distLockIds.get();
if ( s.empty() ) {
stringstream ss;
ss << getDistLockProcess() << ":" << getThreadName() << ":" << rand();
s = ss.str();
distLockIds.set( s );
}
return s;
}
void _distLockPingThread( ConnectionString addr ) {
setThreadName( "LockPinger" );
log() << "creating dist lock ping thread for: " << addr << endl;
static int loops = 0;
while( ! inShutdown() ) {
string process = getDistLockProcess();
log(4) << "dist_lock about to ping for: " << process << endl;
try {
ScopedDbConnection conn( addr );
// refresh the entry corresponding to this process in the lockpings collection
conn->update( lockPingNS ,
BSON( "_id" << process ) ,
BSON( "$set" << BSON( "ping" << DATENOW ) ) ,
true );
string err = conn->getLastError();
if ( ! err.empty() ) {
warning() << "dist_lock process: " << process << " pinging: " << addr << " failed: "
<< err << endl;
conn.done();
sleepsecs(30);
continue;
}
// remove really old entries from the lockpings collection if they're not holding a lock
// (this may happen if an instance of a process was taken down and no new instance came up to
// replace it for a quite a while)
// if the lock is taken, the take-over mechanism should handle the situation
auto_ptr<DBClientCursor> c = conn->query( locksNS , BSONObj() );
vector<string> pids;
while ( c->more() ) {
BSONObj lock = c->next();
if ( ! lock["process"].eoo() ) {
pids.push_back( lock["process"].valuestrsafe() );
}
}
Date_t fourDays = jsTime() - ( 4 * 86400 * 1000 ); // 4 days
conn->remove( lockPingNS , BSON( "_id" << BSON( "$nin" << pids ) << "ping" << LT << fourDays ) );
err = conn->getLastError();
if ( ! err.empty() ) {
warning() << "dist_lock cleanup request from process: " << process << " to: " << addr
<< " failed: " << err << endl;
conn.done();
sleepsecs(30);
continue;
}
// create index so remove is fast even with a lot of servers
if ( loops++ == 0 ) {
conn->ensureIndex( lockPingNS , BSON( "ping" << 1 ) );
}
conn.done();
}
catch ( std::exception& e ) {
warning() << "dist_lock exception during ping: " << e.what() << endl;
}
log( loops % 10 == 0 ? 0 : 1) << "dist_lock pinged successfully for: " << process << endl;
sleepsecs(30);
}
}
void distLockPingThread( ConnectionString addr ) {
try {
_distLockPingThread( addr );
}
catch ( std::exception& e ) {
error() << "unexpected error in distLockPingThread: " << e.what() << endl;
}
catch ( ... ) {
error() << "unexpected unknown error in distLockPingThread" << endl;
}
}
class DistributedLockPinger {
public:
DistributedLockPinger()
: _mutex( "DistributedLockPinger" ) {
}
void got( const ConnectionString& conn ) {
string s = conn.toString();
scoped_lock lk( _mutex );
if ( _seen.count( s ) > 0 )
return;
boost::thread t( boost::bind( &distLockPingThread , conn ) );
_seen.insert( s );
}
set<string> _seen;
mongo::mutex _mutex;
} distLockPinger;
DistributedLock::DistributedLock( const ConnectionString& conn , const string& name , unsigned takeoverMinutes )
: _conn(conn),_name(name),_takeoverMinutes(takeoverMinutes) {
_id = BSON( "_id" << name );
_ns = "config.locks";
distLockPinger.got( conn );
}
bool DistributedLock::lock_try( string why , BSONObj * other ) {
// write to dummy if 'other' is null
BSONObj dummyOther;
if ( other == NULL )
other = &dummyOther;
ScopedDbConnection conn( _conn );
BSONObjBuilder queryBuilder;
queryBuilder.appendElements( _id );
queryBuilder.append( "state" , 0 );
{
// make sure its there so we can use simple update logic below
BSONObj o = conn->findOne( _ns , _id ).getOwned();
if ( o.isEmpty() ) {
try {
log(4) << "dist_lock inserting initial doc in " << _ns << " for lock " << _name << endl;
conn->insert( _ns , BSON( "_id" << _name << "state" << 0 << "who" << "" ) );
}
catch ( UserException& e ) {
log() << "dist_lock could not insert initial doc: " << e << endl;
}
}
else if ( o["state"].numberInt() > 0 ) {
BSONObj lastPing = conn->findOne( lockPingNS , o["process"].wrap( "_id" ) );
if ( lastPing.isEmpty() ) {
// if a lock is taken but there's no ping for it, we're in an inconsistent situation
// if the lock holder (mongos or d) does not exist anymore, the lock could safely be removed
// but we'd require analysis of the situation before a manual intervention
error() << "config.locks: " << _name << " lock is taken by old process? "
<< "remove the following lock if the process is not active anymore: " << o << endl;
*other = o;
conn.done();
return false;
}
unsigned long long now = jsTime();
unsigned long long pingTime = lastPing["ping"].Date();
if ( now < pingTime ) {
// clock skew
warning() << "dist_lock has detected clock skew of " << ( pingTime - now ) << "ms" << endl;
*other = o;
conn.done();
return false;
}
unsigned long long elapsed = now - pingTime;
elapsed = elapsed / ( 1000 * 60 ); // convert to minutes
if ( elapsed > ( 60 * 24 * 365 * 100 ) /* 100 years */ ) {
warning() << "distlock elapsed time seems impossible: " << lastPing << endl;
}
if ( elapsed <= _takeoverMinutes ) {
log(1) << "dist_lock lock failed because taken by: " << o << " elapsed minutes: " << elapsed << endl;
*other = o;
conn.done();
return false;
}
log() << "dist_lock forcefully taking over from: " << o << " elapsed minutes: " << elapsed << endl;
conn->update( _ns , _id , BSON( "$set" << BSON( "state" << 0 ) ) );
string err = conn->getLastError();
if ( ! err.empty() ) {
warning() << "dist_lock take over from: " << o << " failed: " << err << endl;
*other = o.getOwned();
other->getOwned();
conn.done();
return false;
}
}
else if ( o["ts"].type() ) {
queryBuilder.append( o["ts"] );
}
}
OID ts;
ts.init();
bool gotLock = false;
BSONObj now;
BSONObj lockDetails = BSON( "state" << 1 << "who" << getDistLockId() << "process" << getDistLockProcess() <<
"when" << DATENOW << "why" << why << "ts" << ts );
BSONObj whatIWant = BSON( "$set" << lockDetails );
try {
log(4) << "dist_lock about to aquire lock: " << lockDetails << endl;
conn->update( _ns , queryBuilder.obj() , whatIWant );
BSONObj o = conn->getLastErrorDetailed();
now = conn->findOne( _ns , _id );
if ( o["n"].numberInt() == 0 ) {
*other = now;
other->getOwned();
log() << "dist_lock error trying to aquire lock: " << lockDetails << " error: " << o << endl;
gotLock = false;
}
else {
gotLock = true;
}
}
catch ( UpdateNotTheSame& up ) {
// this means our update got through on some, but not others
log(4) << "dist_lock lock did not propagate properly" << endl;
for ( unsigned i=0; i<up.size(); i++ ) {
ScopedDbConnection temp( up[i].first );
BSONObj temp2 = temp->findOne( _ns , _id );
if ( now.isEmpty() || now["ts"] < temp2["ts"] ) {
now = temp2.getOwned();
}
temp.done();
}
if ( now["ts"].OID() == ts ) {
log(4) << "dist_lock completed lock propagation" << endl;
gotLock = true;
conn->update( _ns , _id , whatIWant );
}
else {
log() << "dist_lock error trying to complete propagation" << endl;
gotLock = false;
}
}
conn.done();
log(2) << "dist_lock lock gotLock: " << gotLock << " now: " << now << endl;
return gotLock;
}
void DistributedLock::unlock() {
const int maxAttempts = 3;
int attempted = 0;
while ( ++attempted <= maxAttempts ) {
try {
ScopedDbConnection conn( _conn );
conn->update( _ns , _id, BSON( "$set" << BSON( "state" << 0 ) ) );
log(2) << "dist_lock unlock: " << conn->findOne( _ns , _id ) << endl;
conn.done();
return;
}
catch ( std::exception& e) {
log( LL_WARNING ) << "dist_lock " << _name << " failed to contact config server in unlock attempt "
<< attempted << ": " << e.what() << endl;
sleepsecs(1 << attempted);
}
}
log( LL_WARNING ) << "dist_lock couldn't consumate unlock request. " << "Lock " << _name
<< " will be taken over after " << _takeoverMinutes << " minutes timeout" << endl;
}
}
|
f43f3d1ffbf9cc2121d09e04bf97dc7cc2404a18 | a92d745464fe87a9be5a3b3a7f22c894d4a56399 | /cc/file_system_model.cc | 7054b76ffa329d137e98e924981940b367f1817f | [] | no_license | 20496e76696e6369626c65/qt_file_manager | 225360702b1af7a177814814683ac1c0687dc683 | e2d8762c299c8bc0a7354b7abd4e36213c342803 | refs/heads/master | 2020-04-23T15:33:55.727851 | 2019-02-18T11:17:44 | 2019-02-18T11:17:44 | 171,270,177 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,142 | cc | file_system_model.cc | #include "h/file_system_model.h"
#include <QDir>
#include <QFileInfo>
QVector<QString> FileSystemModel::all_columns_;
bool FileSystemModel::created_ = false;
FileSystemModel::FileSystemModel(QObject *parent): QAbstractItemModel (parent)
{
columns_.reserve(HeaderInfo::COUNT);
columns_.push_back(HeaderInfo::NAME);
columns_.push_back(HeaderInfo::EXT);
columns_.push_back(HeaderInfo::SIZE);
columns_.push_back(HeaderInfo::DATE);
columns_.push_back(HeaderInfo::RWX);
if(!created_)
{
created_ = true;
all_columns_.push_back("Name");
all_columns_.push_back("Ext");
all_columns_.push_back("Size");
all_columns_.push_back("Date");
all_columns_.push_back("rwx");
}
}
QModelIndex FileSystemModel::index(int row, int column, const QModelIndex &parent) const
{
if(!parent.isValid())
{
return createIndex(0, 0, const_cast<FileSystemNode*>(file_system_.DefaultNode()));
}
if(row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent))
{
return QModelIndex();
}
const FileSystemNode* parent_node = Index2Node(parent);
const FileSystemNode* child_node = parent_node->Child(row);
Q_ASSERT(child_node);
if(child_node == nullptr)
{
child_node = file_system_.DefaultNode();
}
return createIndex(row, column, const_cast<FileSystemNode*>(child_node));
}
int FileSystemModel::rowCount(const QModelIndex &parent) const
{
if(parent.column() > 0)
{
return 0;
}
return Index2Node(parent)->ChildrenCount();
}
int FileSystemModel::columnCount(const QModelIndex &parent) const
{
if(parent.column() > 0)
{
return 0;
}
return columns_.size();
}
QModelIndex FileSystemModel::parent(const QModelIndex &child) const
{
if(!child.isValid())
return QModelIndex();
const FileSystemNode* node = Index2Node(child);
if(node == nullptr || !node->IsValide())
{
return QModelIndex();
}
const FileSystemNode* parent = node->Parent();
if(parent == nullptr || !parent->IsValide())
{
return QModelIndex();
}
int row = 0;
const FileSystemNode* grand_parent = parent->Parent();
if(grand_parent != nullptr && grand_parent->IsValide())
{
row = grand_parent->Index(parent->Path());
}
if(row == -1)
{
return QModelIndex();
}
return createIndex(row, 0, const_cast<FileSystemNode*>(node->Parent()));
}
QVariant FileSystemModel::data(const QModelIndex &index, int role = Qt::DisplayRole ) const
{
if(index.column() > columns_.size())
{
return QVariant::Invalid;
}
switch (role)
{
case Qt::DisplayRole:
return DisplayRole(index);
case Qt::DecorationRole:
return DecorationRole(index);
default:
return QVariant::Invalid;
}
}
QVariant FileSystemModel::headerData(int selection, Qt::Orientation orient, int role) const
{
if(role != Qt::DisplayRole)
{
return QVariant::Invalid;
}
if(orient == Qt::Vertical)
{
return "";
}
if(columns_.size() < selection)
{
return QVariant::Invalid;
}
return all_columns_[columns_[selection]];
}
QModelIndex FileSystemModel::SetDir(const QString& path)
{
emit layoutAboutToBeChanged();
file_system_.SetDir(path);
const FileSystemNode* node = file_system_.DefaultNode();
const FileSystemNode* parent_node = node->Parent();
int row = 0;
if(parent_node)
{
row = parent_node->Index(node->Path());
}
emit layoutChanged();
return createIndex(row, 0, const_cast<FileSystemNode*>(node));
}
void FileSystemModel::OpenRow(int row)
{
const FileSystemNode* root = file_system_.DefaultNode();
if(root == nullptr)
{
return;
}
const FileSystemNode* node = root->Child(row);
if(node == nullptr)
{
return;
}
if(!node->IsDir())
{
}
QString name = node->FileName();
QString path = node->Path();
if(name=="..")
{
QDir dir(path);
path = dir.absolutePath();
}
SetDir(path);
}
void FileSystemModel::CdUp()
{
const FileSystemNode* root = file_system_.DefaultNode();
if(root == nullptr)
{
return;
}
const FileSystemNode* node = root->Child("..");
if(node == nullptr)
{
return;
}
if(!node->IsDir())
{
return;
}
SetDir(QDir(node->Path()).absolutePath());
}
QString FileSystemModel::Path() const
{
return file_system_.RootNode()->Path();
}
QVector<HeaderInfo> FileSystemModel::Headers() const
{
return columns_;
}
const FileSystemNode *FileSystemModel::Index2Node(const QModelIndex &index) const
{
if(index.isValid())
{
return static_cast<const FileSystemNode*>(index.internalPointer());
}
return file_system_.DefaultNode();
}
QVariant FileSystemModel::DisplayRole(const QModelIndex &index) const
{
const FileSystemNode* node = Index2Node(index);
if(node == nullptr || !node->IsValide())
return QVariant::Invalid;
switch(columns_[index.column()])
{
case HeaderInfo::NAME:
return node->FileName();
case HeaderInfo::EXT:
return node->FileExt();
case HeaderInfo::SIZE:
return node->FileSize();
case HeaderInfo::DATE:
return node->FileDate();
case HeaderInfo::RWX:
return node->FilePermExt();
case HeaderInfo::COUNT:
default:
return QVariant::Invalid;
}
}
QVariant FileSystemModel::DecorationRole(const QModelIndex &index) const
{
if(columns_.size() < index.column() || columns_.size() < 0 || columns_[index.column()] != HeaderInfo::NAME)
return QVariant::Invalid;
const FileSystemNode* node = Index2Node(index);
QString n = QVariant(index).toString();
QFileInfo info(n);
if(node == nullptr || !node->IsValide())
return QVariant::Invalid;
if(node->IsDir())
return icon_provider_.icon(QFileIconProvider::Folder);
return icon_provider_.icon(QFileIconProvider::File);
}
|
47290fa07269862c1be20780bf0bf07644f9c6f2 | 1fd648182ba26a1ade511843d44f5e4e1f7d9be7 | /polly/lib/Analysis/ScopPass.cpp | dfdf31396d9fbe353db5ef68c09b61f1c9d5af3e | [
"NCSA"
] | permissive | fortanix/llvm-project | 027520a1fe1654b619252556680aeb4998f90704 | 6ea8f0c412376c1df942d7a77a292675489ebb37 | refs/heads/release/5.x | 2022-11-13T17:47:22.927605 | 2020-03-27T11:03:08 | 2020-03-27T11:03:08 | 165,190,717 | 1 | 3 | null | 2022-11-06T10:31:35 | 2019-01-11T06:22:04 | C++ | UTF-8 | C++ | false | false | 4,373 | cpp | ScopPass.cpp | //===- ScopPass.cpp - The base class of Passes that operate on Polly IR ---===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file contains the definitions of the ScopPass members.
//
//===----------------------------------------------------------------------===//
#include "polly/ScopPass.h"
#include "polly/ScopInfo.h"
#include "llvm/Analysis/AssumptionCache.h"
using namespace llvm;
using namespace polly;
bool ScopPass::runOnRegion(Region *R, RGPassManager &RGM) {
S = nullptr;
if (skipRegion(*R))
return false;
if ((S = getAnalysis<ScopInfoRegionPass>().getScop()))
return runOnScop(*S);
return false;
}
void ScopPass::print(raw_ostream &OS, const Module *M) const {
if (S)
printScop(OS, *S);
}
void ScopPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<ScopInfoRegionPass>();
AU.setPreservesAll();
}
namespace llvm {
template class PassManager<Scop, ScopAnalysisManager,
ScopStandardAnalysisResults &, SPMUpdater &>;
template class InnerAnalysisManagerProxy<ScopAnalysisManager, Function>;
template class OuterAnalysisManagerProxy<FunctionAnalysisManager, Scop,
ScopStandardAnalysisResults &>;
template <>
PreservedAnalyses
PassManager<Scop, ScopAnalysisManager, ScopStandardAnalysisResults &,
SPMUpdater &>::run(Scop &S, ScopAnalysisManager &AM,
ScopStandardAnalysisResults &AR, SPMUpdater &U) {
auto PA = PreservedAnalyses::all();
for (auto &Pass : Passes) {
auto PassPA = Pass->run(S, AM, AR, U);
AM.invalidate(S, PassPA);
PA.intersect(std::move(PassPA));
}
// All analyses for 'this' Scop have been invalidated above.
// If ScopPasses affect break other scops they have to propagate this
// information through the updater
PA.preserveSet<AllAnalysesOn<Scop>>();
return PA;
}
bool ScopAnalysisManagerFunctionProxy::Result::invalidate(
Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv) {
// First, check whether our ScopInfo is about to be invalidated
auto PAC = PA.getChecker<ScopAnalysisManagerFunctionProxy>();
if (!(PAC.preserved() || PAC.preservedSet<AllAnalysesOn<Function>>() ||
Inv.invalidate<ScopAnalysis>(F, PA) ||
Inv.invalidate<ScalarEvolutionAnalysis>(F, PA) ||
Inv.invalidate<LoopAnalysis>(F, PA) ||
Inv.invalidate<AAManager>(F, PA) ||
Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
Inv.invalidate<AssumptionAnalysis>(F, PA))) {
// As everything depends on ScopInfo, we must drop all existing results
for (auto &S : *SI)
if (auto *scop = S.second.get())
if (InnerAM)
InnerAM->clear(*scop);
InnerAM = nullptr;
return true; // Invalidate the proxy result as well.
}
bool allPreserved = PA.allAnalysesInSetPreserved<AllAnalysesOn<Scop>>();
// Invalidate all non-preserved analyses
// Even if all analyses were preserved, we still need to run deferred
// invalidation
for (auto &S : *SI) {
Optional<PreservedAnalyses> InnerPA;
auto *scop = S.second.get();
if (!scop)
continue;
if (auto *OuterProxy =
InnerAM->getCachedResult<FunctionAnalysisManagerScopProxy>(*scop)) {
for (const auto &InvPair : OuterProxy->getOuterInvalidations()) {
auto *OuterAnalysisID = InvPair.first;
const auto &InnerAnalysisIDs = InvPair.second;
if (Inv.invalidate(OuterAnalysisID, F, PA)) {
if (!InnerPA)
InnerPA = PA;
for (auto *InnerAnalysisID : InnerAnalysisIDs)
InnerPA->abandon(InnerAnalysisID);
}
}
if (InnerPA) {
InnerAM->invalidate(*scop, *InnerPA);
continue;
}
}
if (!allPreserved)
InnerAM->invalidate(*scop, PA);
}
return false; // This proxy is still valid
}
template <>
ScopAnalysisManagerFunctionProxy::Result
ScopAnalysisManagerFunctionProxy::run(Function &F,
FunctionAnalysisManager &FAM) {
return Result(*InnerAM, FAM.getResult<ScopInfoAnalysis>(F));
}
} // namespace llvm
|
d468492225e4f97e96cfe71cf4208ed7069fd1ba | 7fbbae05d8d4d6b3eaeb9d771b6470f26c84c286 | /core/mm.cc | f758e84c0e94959bc128376bdfcdc4d3ee8272c3 | [
"MIT"
] | permissive | baileyforrest/chipix | 4e663712db41c5498cf1ecc7a0c1fbc59ac1be99 | 35ed48293411cc36d9a44e524c1189134e7dff18 | refs/heads/main | 2023-06-24T10:08:21.694081 | 2021-07-19T07:04:36 | 2021-07-19T07:04:52 | 384,381,148 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,026 | cc | mm.cc | #include "core/mm.h"
#include <arch.h>
#include <assert.h>
#include <stdbool.h>
#include <stddef.h>
#include <algorithm>
#include <utility>
#include "core/addr-mgr.h"
#include "core/cleanup.h"
#include "core/macros.h"
#include "libc/macros.h"
#include "libc/malloc.h"
namespace mm {
namespace {
AddrMgr g_kernel_va_mgr;
AddrMgr g_pa_mgr;
// Page allocation requires requires heap allocation.
// Heap allocation requires page allocation.
//
// To solve chicken/egg problem use a single static page.
struct DefaultPage {
char data[PAGE_SIZE];
};
alignas(PAGE_SIZE) DefaultPage g_default_page;
bool g_default_page_used = false;
PhysAddr AllocAndMapPhysPages(const VirtAddr virt_begin, const size_t count) {
const PhysAddr phys_begin = AllocPagesPa(count);
if (phys_begin == kInvalidPa) {
return kInvalidPa;
}
auto clean_pa = MakeCleanup([&] { FreePagesPa(phys_begin, count); });
if (arch::MapAddr(arch::cur_page_table, virt_begin, phys_begin, count) < 0) {
return kInvalidPa;
}
std::move(clean_pa).Cancel();
return phys_begin;
}
} // namespace
void Init(multiboot_info_t* mbd) {
if (!((mbd->flags >> 6) & 1)) {
PANIC("invalid memory map given by GRUB bootloader");
}
uintptr_t num_heap_pages = (0 - PAGE_SIZE - KERNEL_HEAP_VA) / PAGE_SIZE;
int err = g_kernel_va_mgr.AddVas(KERNEL_HEAP_VA, num_heap_pages);
PANIC_IF(err != 0, "Registering virtual addresses failed");
const uintptr_t kernel_begin = arch::KernelBegin();
const uintptr_t kernel_end = arch::KernelEnd();
printf("kernel_pa: [%x, %x)\n", kernel_begin, kernel_end);
for (int i = 0; i < mbd->mmap_length; i += sizeof(multiboot_memory_map_t)) {
auto* mmmt = reinterpret_cast<multiboot_memory_map_t*>(mbd->mmap_addr + i);
if (mmmt->type != MULTIBOOT_MEMORY_AVAILABLE) {
continue;
}
uintptr_t begin = mmmt->addr;
uintptr_t end = begin + mmmt->len;
auto register_pa = [](uintptr_t begin, uintptr_t end) {
if (begin == end) {
return;
}
printf("Registering PAs: [%x, %x)\n", begin, end);
int err = g_pa_mgr.AddVas(begin, (end - begin) / PAGE_SIZE);
PANIC_IF(err != 0, "Registering physical addresses failed");
};
if (kernel_begin >= begin && kernel_end <= end) {
register_pa(begin, kernel_begin);
begin = kernel_end;
end = std::max(begin, end);
}
if (kernel_end >= begin && kernel_end <= end) {
begin = kernel_end;
}
register_pa(begin, end);
}
}
PagesRef AllocPages(const size_t count) {
if (count <= 0) {
return {};
}
PagesRef ret(new Pages());
if (!ret) {
return {};
}
ret->count = count;
ret->va = AllocPagesVa(count);
if (ret->va == kInvalidVa) {
return {};
}
auto clean_va = MakeCleanup([&] { FreePagesVa(ret->va, count); });
ret->pa = AllocAndMapPhysPages(ret->va, count);
if (ret->pa == kInvalidPa) {
return {};
}
std::move(clean_va).Cancel();
return ret;
}
void FreePages(Pages* pages) {
assert(pages->RefCnt() == 0);
UnmapAddr(arch::cur_page_table, pages->va, pages->count);
FreePagesPa(pages->pa, pages->count);
FreePagesVa(pages->va, pages->count);
delete pages;
}
VirtAddr AllocPagesVa(size_t num_pages) {
return VirtAddr(g_kernel_va_mgr.Alloc(num_pages));
}
void FreePagesVa(VirtAddr addr, size_t num_pages) {
g_kernel_va_mgr.Free(addr.val(), num_pages);
}
PhysAddr AllocPagesPa(size_t num_pages) {
return PhysAddr(g_pa_mgr.Alloc(num_pages));
}
void FreePagesPa(PhysAddr addr, size_t num_pages) {
g_pa_mgr.Free(addr.val(), num_pages);
}
} // namespace mm
void* __malloc_alloc_pages(const size_t count) {
if (count <= 0) {
return nullptr;
}
if (!mm::g_default_page_used) {
assert(count == 1);
mm::g_default_page_used = true;
return &mm::g_default_page;
}
const VirtAddr virt_begin = mm::AllocPagesVa(count);
if (virt_begin == kInvalidVa) {
return nullptr;
}
// Malloc doesn't need contiguous physical pages.
size_t i = 0;
for (; i < count; ++i) {
VirtAddr va = virt_begin + i * PAGE_SIZE;
PhysAddr pa = mm::AllocAndMapPhysPages(va, 1);
if (pa == kInvalidPa) {
goto error;
}
}
return reinterpret_cast<void*>(virt_begin.val());
error:
arch::UnmapAddr(arch::cur_page_table, virt_begin, i);
for (size_t j = 0; j < i; ++j) {
VirtAddr va = virt_begin + j * PAGE_SIZE;
PhysAddr pa = LookupPa(arch::cur_page_table, va);
mm::FreePagesPa(pa, 1);
}
mm::FreePagesVa(virt_begin, count);
return nullptr;
}
void __malloc_free_page(void* addr, size_t num_pages) {
if (addr == &mm::g_default_page) {
mm::g_default_page_used = false;
return;
}
VirtAddr virt_begin(reinterpret_cast<uintptr_t>(addr));
for (size_t i = 0; i < num_pages; ++i) {
PhysAddr pa =
arch::LookupPa(arch::cur_page_table, virt_begin + i * PAGE_SIZE);
assert(pa != kInvalidPa);
mm::FreePagesPa(pa, 1);
}
arch::UnmapAddr(arch::cur_page_table, virt_begin, num_pages);
mm::FreePagesVa(virt_begin, num_pages);
}
|
dd604e8501fa2306aaa73326c3bc483917221a99 | 2d361696ad060b82065ee116685aa4bb93d0b701 | /src/gui/packages/pkg_sequence/gff_load_manager.cpp | ae29d227fda4c985840883555f4c004791861f07 | [
"LicenseRef-scancode-public-domain"
] | permissive | AaronNGray/GenomeWorkbench | 5151714257ce73bdfb57aec47ea3c02f941602e0 | 7156b83ec589e0de8f7b0a85699d2a657f3e1c47 | refs/heads/master | 2022-11-16T12:45:40.377330 | 2020-07-10T00:54:19 | 2020-07-10T00:54:19 | 278,501,064 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,350 | cpp | gff_load_manager.cpp | /* $Id: gff_load_manager.cpp 38477 2017-05-15 21:10:59Z evgeniev $
* ===========================================================================
*
* PUBLIC DOMAIN NOTICE
* National Center for Biotechnology Information
*
* This software/database is a "United States Government Work" under the
* terms of the United States Copyright Act. It was written as part of
* the author's official duties as a United States Government employee and
* thus cannot be copyrighted. This software/database is freely available
* to the public for use. The National Library of Medicine and the U.S.
* Government have not placed any restriction on its use or reproduction.
*
* Although all reasonable efforts have been taken to ensure the accuracy
* and reliability of the software and data, the NLM and the U.S.
* Government do not and cannot warrant the performance or results that
* may be obtained by using this software or data. The NLM and the U.S.
* Government disclaim all warranties, express or implied, including
* warranties of performance, merchantability or fitness for any particular
* purpose.
*
* Please cite the author in any work or product based on this material.
*
* ===========================================================================
*
* Authors: Roman Katargin
*
*/
#include <ncbi_pch.hpp>
#include "gff_load_manager.hpp"
#include <gui/widgets/loaders/gff_params_panel.hpp>
#include <gui/widgets/loaders/gff_object_loader.hpp>
#include <gui/widgets/wx/wx_utils.hpp>
#include <gui/widgets/wx/file_extensions.hpp>
#include <wx/filename.h>
BEGIN_NCBI_SCOPE
wxPanel* CGffLoadManager::CPage::GetPanel()
{
return m_Manager.x_GetParamsPanel();
}
///////////////////////////////////////////////////////////////////////////////
/// CGffLoadManager
CGffLoadManager::CGffLoadManager()
: m_SrvLocator(NULL)
, m_ParentWindow(NULL)
, m_State(eInvalid)
, m_ParamsPanel(NULL)
, m_Descr("", "")
, m_OptionsPage(*this)
{
m_Descr.Init(ToStdString(CFileExtensions::GetLabel(CFileExtensions::kGFF)), "");
m_Descr.SetLogEvent("loaders");
}
//
// IFileLoadPanelClient implementation
//
string CGffLoadManager::GetLabel() const
{
return m_Descr.GetLabel();
}
wxString CGffLoadManager::GetFormatWildcard() const
{
return CFileExtensions::GetDialogFilter(CFileExtensions::kGFF) + wxT("|") +
CFileExtensions::GetDialogFilter(CFileExtensions::kGTF) + wxT("|") +
CFileExtensions::GetDialogFilter(CFileExtensions::kAllFiles);
}
//
// IUILoadManager implementation
//
void CGffLoadManager::SetServiceLocator(IServiceLocator* srv_locator)
{
m_SrvLocator = srv_locator;
}
void CGffLoadManager::SetParentWindow(wxWindow* parent)
{
m_ParentWindow = parent;
}
const IUIObject& CGffLoadManager::GetDescriptor() const
{
return m_Descr;
}
void CGffLoadManager::InitUI()
{
m_State = eParams;
}
void CGffLoadManager::CleanUI()
{
m_State = eInvalid;
m_ParamsPanel = NULL; // window is destroyed by the system
}
wxPanel* CGffLoadManager::GetCurrentPanel()
{
return (m_State == eParams) ? x_GetParamsPanel() : NULL;
}
CGffParamsPanel* CGffLoadManager::x_GetParamsPanel()
{
if (m_ParamsPanel == NULL) {
m_ParamsPanel = new CGffParamsPanel(m_ParentWindow);
m_ParamsPanel->SetData(m_Params);
m_ParamsPanel->TransferDataToWindow();
}
return m_ParamsPanel;
}
bool CGffLoadManager::CanDo(EAction action)
{
switch(m_State) {
case eParams:
return action == eNext;
case eCompleted:
return action == eBack;
default:
_ASSERT(false);
return false;
}
}
bool CGffLoadManager::IsFinalState()
{
return m_State == eParams;
}
bool CGffLoadManager::IsCompletedState()
{
return m_State == eCompleted; // does not matter
}
bool CGffLoadManager::DoTransition(EAction action)
{
if(m_State == eParams && action == eNext) {
if(m_ParamsPanel->TransferDataFromWindow()) {
//TODO validate
m_Params = m_ParamsPanel->GetData();
m_State = eCompleted;
return true;
}
return false;
} else if(m_State == eCompleted && action == eBack) {
m_State = eParams;
return true;
}
_ASSERT(false);
return false;
}
IAppTask* CGffLoadManager::GetTask()
{
return nullptr;
}
IExecuteUnit* CGffLoadManager::GetExecuteUnit()
{
return new CGffObjectLoader(m_Params, m_FileNames);
}
wxString CGffLoadManager::GetFormatWildcard()
{
return CFileExtensions::GetDialogFilter(CFileExtensions::kGFF) + wxT("|") +
CFileExtensions::GetDialogFilter(CFileExtensions::kGTF) + wxT("|") +
CFileExtensions::GetDialogFilter(CFileExtensions::kAllFiles);
}
bool CGffLoadManager::ValidateFilenames(const vector<wxString>& /*filenames*/)
{
// not implemented
return true;
}
void CGffLoadManager::SetFilenames(const vector<wxString>& filenames)
{
m_FileNames = filenames;
}
void CGffLoadManager::GetFilenames(vector<wxString>& filenames) const
{
filenames = m_FileNames;
}
bool CGffLoadManager::IsInitialState()
{
return m_State == eParams;
}
bool CGffLoadManager::RecognizeFormat(const wxString& filename)
{
wxString ext;
wxFileName::SplitPath(filename, 0, 0, &ext);
return CFileExtensions::RecognizeExtension(CFileExtensions::kGFF, ext) ||
CFileExtensions::RecognizeExtension(CFileExtensions::kGTF, ext);
}
bool CGffLoadManager::RecognizeFormat(CFormatGuess::EFormat fmt)
{
switch (fmt) {
case CFormatGuess::eGff2 :
case CFormatGuess::eGff3 :
case CFormatGuess::eGtf :
case CFormatGuess::eGvf :
case CFormatGuess::eGtf_POISENED :
return true;
default :
return false;
}
}
string CGffLoadManager::GetExtensionIdentifier() const
{
return "gff_format_load_manager";
}
string CGffLoadManager::GetExtensionLabel() const
{
static string slabel("GFF/GTF/GFV Format Load Manager");
return slabel;
}
void CGffLoadManager::SetRegistryPath(const string& path)
{
m_RegPath = path; // store for later use
m_Params.SetRegistryPath(m_RegPath + ".GffParams");
}
void CGffLoadManager::SaveSettings() const
{
m_Params.SaveSettings();
}
void CGffLoadManager::LoadSettings()
{
m_Params.LoadSettings();
}
END_NCBI_SCOPE
|
aeba1b59497ff4d27e335a38701eccf45fc9575a | 88fe22e8898aa55db979ddf56153a0aaaa0b6216 | /EnchantmentItemHelper.h | 7d17e2388c13fa97b85f4ae291ed154ad01fccd2 | [] | no_license | GarrixWong/SmartHarvestSE | 6e32edbaea6ae07f0362a2cef1b06bd225efd58b | 3eabb00056017e5fe2245bb6fc6322d96981890c | refs/heads/master | 2022-11-11T12:09:43.212104 | 2020-07-01T09:28:18 | 2020-07-01T09:28:18 | 276,326,476 | 0 | 0 | null | 2020-07-01T08:52:00 | 2020-07-01T08:51:59 | null | UTF-8 | C++ | false | false | 190 | h | EnchantmentItemHelper.h | #pragma once
class EnchantmentItemHelper
{
public:
EnchantmentItemHelper(RE::EnchantmentItem* item) : m_item(item) {}
UInt32 GetGoldValue(void);
private:
RE::EnchantmentItem* m_item;
};
|
5af74877327feafb58d63ad54b05f4082ce29096 | 03727fc0a8c6356c7816af11abe96b0534d54ba9 | /INTEGRATE-Vis.1.0.0/src/BedpeAnnotator/src/main.cpp | 06596e9e00b7e3b66d384a4929131804276196bf | [] | no_license | ChrisMaherLab/INTEGRATE-Vis | 6f765f39ea4734eb2b696545b2cdd92450c6864d | 1e96a2d1b088135dda0338c30c000f6d71574eb7 | refs/heads/master | 2023-05-26T12:11:53.726899 | 2023-05-08T19:50:13 | 2023-05-08T19:50:13 | 98,339,013 | 12 | 9 | null | 2023-05-08T15:41:43 | 2017-07-25T18:44:40 | Python | UTF-8 | C++ | false | false | 4,096 | cpp | main.cpp | /*
* main.cpp
*
* Created on: Jun 16, 2016
* Author: Jin Zhang
*/
#include "Bedpe.h"
#include "Reference.h"
#include "Gene2.h"
#include "Annotate.h"
#include "Dinucleo.h"
#include "AnnotateDi.h"
#include <iostream>
#include <getopt.h>
#include <iostream>
#include <string>
#include <cstring>
#include <cstdlib>
using namespace std;
map<int,char> intChar;
map<char,char> charChar;
map<string,char> tableAmino;
string version("0.2.2");
int usage()
{
cerr<<endl;
cerr<<"fusionBedpeAnnotator version "+version<<endl;
cerr<<endl;
cerr<<"Usage:"<<endl;
cerr<<"fusionBedpeAnnotator --reference-file reference-file --gene-annotation-file annot-file --di-file di-file ";
cerr<<"--input-file input-bedpe-file --output-file output-bedpe-file"<<endl;
cerr<<endl;
cerr<<"Required parameters:"<<endl;
cerr<<" -r/--reference-file"<<endl;
cerr<<" -g/--gene-annotation-file"<<endl;
cerr<<" -d/--di-file"<<endl;
cerr<<" -i/--input-file"<<endl;
cerr<<" -o/--output-file"<<endl;
cerr<<endl;
cerr<<"Options:"<<endl;
cerr<<" -r/--reference-file <string> [ fasta ]"<<endl;
cerr<<" -g/--gene-annotation-file <string> [ 11 columns refer to INTEGRATE 0.2.5 ]"<<endl;
cerr<<" -i/--input-file <string [ bedpe refer to SMC-RNA ]"<<endl;
cerr<<" -d/--di-file <string> [ 2 columns dinucleo canonical splice ]"<<endl;
cerr<<" -o/--output-file <string> [ bedpe ]"<<endl;
cerr<<endl;
return 0;
}
int main(int argc, char * argv[])
{
InitialIntChar();
int c;
int option_index = 0;
string input_file="";
string output_file="";
string gene_file="";
string reference_file="";
string di_file="";
static struct option long_options[] = {
{"input-file", required_argument, 0, 'i' },
{"output-file", required_argument, 0, 'o' },
{"gene-annotation-file", required_argument, 0, 'g' },
{"reference-file", required_argument, 0, 'r' },
{"di-file", required_argument, 0, 'd' },
{"help", no_argument, 0, 'h' },
{0, 0, 0, 0}
};
while(1)
{
c = getopt_long(argc, argv, "i:o:g:d:r:h",
long_options, &option_index);
if (c==-1)
{
break;
}
switch(c)
{
case 'h':
usage();
exit(0);
case 'r':
reference_file=optarg;
break;
case 'g':
gene_file=optarg;
break;
case 'd':
di_file=optarg;
break;
case 'o':
output_file=optarg;
break;
case 'i':
input_file=optarg;
break;
default:
break;
}
}
if (reference_file.compare("")==0 || gene_file.compare("")==0 || output_file.compare("")==0 || input_file.compare("")==0 || di_file.compare("")==0 )
{
usage();
exit(1);
}
cerr<<"loading gene annotation file..."<<endl;
Gene g;
g.loadGenesFromFile((char*)gene_file.c_str());
g.setGene();
cout<<"loading reference..."<<endl;
Reference ref;
ref.setIsInt(0);
ref.test((char*)reference_file.c_str());
cerr<<"loading bedpe file..."<<endl;
Bedpe bpe;
bpe.loadFromFile((char*)input_file.c_str());
cerr<<"annotate..."<<endl;
Annotate annot;
annot.assignJunctions(g,ref,bpe);
annot.getJunctionType(g,ref,bpe);
annot.getJunctionPeptide(g,ref);
annot.annotate(bpe,g,ref);
Dinucleo di;
di.loadFromFile((char*)di_file.c_str());
AnnotateDi annotDi;
annotDi.annotateDi(bpe,di,ref);
bpe.printBedpe((char*)output_file.c_str());
return 0;
}
|
f604b2cd3018e290b129ec95a9d1d42abb06509a | 27738731ef7fcba49dc0c13ea6fda9eea7ee6740 | /SPOJ/101. Fishmonger/main.cpp | 9d31041006cb29f39f475edd2e73d2f83dd536ea | [] | no_license | BranimirE/Workspace | 7d72d2d5a3e041c9cc2d7d452d084484a9e1b2fb | c0c2248f575b6106662a91f84da0717ffe69ef57 | refs/heads/master | 2020-04-25T23:17:33.310034 | 2015-08-19T05:42:57 | 2015-08-19T05:42:57 | 11,217,839 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,353 | cpp | main.cpp | #include <cstdio>
#include <iostream>
#include <algorithm>
#include <fstream>
#define MAX 52
#define INF (1<<29)
using namespace std;
int n;
int tiempo[MAX][MAX], peaje[MAX][MAX];
pair<int,int> dp[MAX][1002], nocalculado = make_pair(-1, -1);
pair<int,int> solve(int actual, int disponible){ // return costo, tiempo
if(disponible < 0)
return make_pair(INF,INF);
pair<int,int> &ans = dp[actual][disponible];
if(ans != nocalculado)
return ans;
if(actual == n-1)
return ans = make_pair(0, 0);
ans = make_pair(INF,INF);
for(int X = 0; X < n; X++)if(X != actual){
pair<int,int> tmp = solve(X, disponible - tiempo[actual][X]);
if(peaje[actual][X] + tmp.first < ans.first){
ans.first = peaje[actual][X] + tmp.first;
ans.second = tiempo[actual][X] + tmp.second;
}
}
return ans;
}
int main(){
freopen("in", "r",stdin);
int tdisp;
while(scanf("%d%d", &n, &tdisp) and !(!n && !tdisp)){
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
scanf("%d", &tiempo[i][j]);
for(int i = 0; i < n; i++)
for(int j = 0; j < n; j++)
scanf("%d", &peaje[i][j]);
// 0 a n-1
for(int i = 0; i < n; i++)
for(int j = 0; j <= tdisp; j++)
dp[i][j] = nocalculado;
pair<int,int> sol = solve(0, tdisp);
printf("%d %d\n", sol.first, sol.second);
}
return 0;
}
|
85444647a8973ebf52fd5128558466e145ad951f | 325483686eb27365fa08e39c543747d659a69099 | /cpp/LargestRectangleinHistogram.cpp | ae0b490e64c3e87125c981457f93b2ef927e35c3 | [
"Apache-2.0"
] | permissive | thinksource/code_interview | 11bff53199cd47e9df3c7bc3034f0670209231d2 | 08be992240508b73894eaf6b8c025168fd19df19 | refs/heads/master | 2020-04-11T02:36:38.858986 | 2016-09-13T22:13:31 | 2016-09-13T22:13:31 | 68,151,728 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,004 | cpp | LargestRectangleinHistogram.cpp | class Solution {
public:
int largestRectangleArea(vector<int> &height) {
int maxArea = 0;
stack<int> heights;
stack<int> indexes;
for(int i=0;i<(int)height.size();i++) {
if(heights.empty() || heights.top() < height[i]) {
heights.push(height[i]);
indexes.push(i);
} else {
int recStart = -1;
while(!heights.empty() && heights.top() >= height[i]) {
maxArea = max(maxArea, heights.top()*(i-indexes.top()));
recStart = indexes.top();
heights.pop();
indexes.pop();
}
heights.push(height[i]);
indexes.push(recStart);
}
}
while(!heights.empty()) {
maxArea = max(maxArea, heights.top()*((int)height.size()-indexes.top()));
heights.pop();
indexes.pop();
}
return maxArea;
}
};
|
03da1762e4410c13cbb52d3ec8f76985ff349839 | 635c344550534c100e0a86ab318905734c95390d | /ntcore/src/main/native/include/networktables/NetworkTableListener.inc | 5453d87584c6d3534b9c84ddd2f8077c16c9b8ce | [
"BSD-3-Clause"
] | permissive | wpilibsuite/allwpilib | 2435cd2f5c16fb5431afe158a5b8fd84da62da24 | 8f3d6a1d4b1713693abc888ded06023cab3cab3a | refs/heads/main | 2023-08-23T21:04:26.896972 | 2023-08-23T17:47:32 | 2023-08-23T17:47:32 | 24,655,143 | 986 | 769 | NOASSERTION | 2023-09-14T03:51:22 | 2014-09-30T20:51:33 | C++ | UTF-8 | C++ | false | false | 6,138 | inc | NetworkTableListener.inc | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include <span>
#include <string_view>
#include <utility>
#include <vector>
#include "networktables/MultiSubscriber.h"
#include "networktables/NetworkTableEntry.h"
#include "networktables/NetworkTableInstance.h"
#include "networktables/NetworkTableListener.h"
#include "networktables/Topic.h"
#include "ntcore_cpp.h"
namespace nt {
inline NetworkTableListener NetworkTableListener::CreateListener(
NetworkTableInstance inst, std::span<const std::string_view> prefixes,
unsigned int mask, ListenerCallback listener) {
return NetworkTableListener{
::nt::AddListener(inst.GetHandle(), prefixes, mask, std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateListener(
Topic topic, unsigned int mask, ListenerCallback listener) {
return NetworkTableListener{
nt::AddListener(topic.GetHandle(), mask, std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateListener(
Subscriber& subscriber, unsigned int mask, ListenerCallback listener) {
return NetworkTableListener{
::nt::AddListener(subscriber.GetHandle(), mask, std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateListener(
MultiSubscriber& subscriber, unsigned int mask, ListenerCallback listener) {
return NetworkTableListener{
::nt::AddListener(subscriber.GetHandle(), mask, std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateListener(
NetworkTableEntry& entry, unsigned int mask, ListenerCallback listener) {
return NetworkTableListener{
::nt::AddListener(entry.GetHandle(), mask, std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateConnectionListener(
NetworkTableInstance inst, bool immediate_notify,
ListenerCallback listener) {
return NetworkTableListener{::nt::AddListener(
inst.GetHandle(),
NT_EVENT_CONNECTION | (immediate_notify ? NT_EVENT_IMMEDIATE : 0),
std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateTimeSyncListener(
NetworkTableInstance inst, bool immediate_notify,
ListenerCallback listener) {
return NetworkTableListener{::nt::AddListener(
inst.GetHandle(),
NT_EVENT_TIMESYNC | (immediate_notify ? NT_EVENT_IMMEDIATE : 0),
std::move(listener))};
}
inline NetworkTableListener NetworkTableListener::CreateLogger(
NetworkTableInstance inst, unsigned int minLevel, unsigned int maxLevel,
ListenerCallback listener) {
return NetworkTableListener{::nt::AddLogger(inst.GetHandle(), minLevel,
maxLevel, std::move(listener))};
}
inline NetworkTableListener::NetworkTableListener(NetworkTableListener&& rhs)
: m_handle(rhs.m_handle) {
rhs.m_handle = 0;
}
inline NetworkTableListener& NetworkTableListener::operator=(
NetworkTableListener&& rhs) {
if (m_handle != 0) {
nt::RemoveListener(m_handle);
}
m_handle = rhs.m_handle;
rhs.m_handle = 0;
return *this;
}
inline NetworkTableListener::~NetworkTableListener() {
if (m_handle != 0) {
nt::RemoveListener(m_handle);
}
}
inline bool NetworkTableListener::WaitForQueue(double timeout) {
if (m_handle != 0) {
return nt::WaitForListenerQueue(m_handle, timeout);
} else {
return false;
}
}
inline NetworkTableListenerPoller::NetworkTableListenerPoller(
NetworkTableInstance inst)
: m_handle(nt::CreateListenerPoller(inst.GetHandle())) {}
inline NetworkTableListenerPoller::NetworkTableListenerPoller(
NetworkTableListenerPoller&& rhs)
: m_handle(rhs.m_handle) {
rhs.m_handle = 0;
}
inline NetworkTableListenerPoller& NetworkTableListenerPoller::operator=(
NetworkTableListenerPoller&& rhs) {
if (m_handle != 0) {
nt::DestroyListenerPoller(m_handle);
}
m_handle = rhs.m_handle;
rhs.m_handle = 0;
return *this;
}
inline NetworkTableListenerPoller::~NetworkTableListenerPoller() {
if (m_handle != 0) {
nt::DestroyListenerPoller(m_handle);
}
}
inline NT_Listener NetworkTableListenerPoller::AddListener(
std::span<const std::string_view> prefixes, unsigned int mask) {
return nt::AddPolledListener(m_handle, prefixes, mask);
}
inline NT_Listener NetworkTableListenerPoller::AddListener(Topic topic,
unsigned int mask) {
return ::nt::AddPolledListener(m_handle, topic.GetHandle(), mask);
}
inline NT_Listener NetworkTableListenerPoller::AddListener(
Subscriber& subscriber, unsigned int mask) {
return ::nt::AddPolledListener(m_handle, subscriber.GetHandle(), mask);
}
inline NT_Listener NetworkTableListenerPoller::AddListener(
MultiSubscriber& subscriber, unsigned int mask) {
return ::nt::AddPolledListener(m_handle, subscriber.GetHandle(), mask);
}
inline NT_Listener NetworkTableListenerPoller::AddListener(
NetworkTableEntry& entry, unsigned int mask) {
return ::nt::AddPolledListener(m_handle, entry.GetHandle(), mask);
}
inline NT_Listener NetworkTableListenerPoller::AddConnectionListener(
bool immediate_notify) {
return ::nt::AddPolledListener(
m_handle, ::nt::GetInstanceFromHandle(m_handle),
NT_EVENT_CONNECTION | (immediate_notify ? NT_EVENT_IMMEDIATE : 0));
}
inline NT_Listener NetworkTableListenerPoller::AddTimeSyncListener(
bool immediate_notify) {
return ::nt::AddPolledListener(
m_handle, ::nt::GetInstanceFromHandle(m_handle),
NT_EVENT_TIMESYNC | (immediate_notify ? NT_EVENT_IMMEDIATE : 0));
}
inline NT_Listener NetworkTableListenerPoller::AddLogger(
unsigned int minLevel, unsigned int maxLevel) {
return ::nt::AddPolledLogger(m_handle, minLevel, maxLevel);
}
inline void NetworkTableListenerPoller::RemoveListener(NT_Listener listener) {
::nt::RemoveListener(listener);
}
inline std::vector<Event> NetworkTableListenerPoller::ReadQueue() {
return ::nt::ReadListenerQueue(m_handle);
}
} // namespace nt
|
0a393ac4a83ef08d8dcb894340b3b13e58f99c75 | e8a42b2a3d43c1d514633de5bb54120cc1c534a1 | /TOV_Solver.cc | 671799b4b1eee775f31713e9e7f4c83aebc0dba7 | [
"BSD-2-Clause"
] | permissive | leowerneck/TOV_Solver | 47f6afb6c572a97b24860963831e7c044bef02bc | 1bc3d6b98d32a987d78ba2f1f53ec5d73d3e58bf | refs/heads/master | 2023-08-09T05:06:55.350121 | 2023-07-27T16:01:30 | 2023-07-27T16:01:30 | 222,497,476 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,014 | cc | TOV_Solver.cc | /* .-----------------------------------------.
* | Copyright (c) 2019, Leonardo Werneck |
* | Licensed under the BSD 2-Clause License |
* .-----------------------------------------.
*/
/* Program : TOV Solver
* File : TOV_Solver.C
* Author : Leo Werneck (werneck@if.usp.br)
* Date : October 29, 2019
*
* Description : This file implements the RHSs of the Tolman–Oppenheimer–Volkoff
* equations
*
* Dependencies: stdio.h, stdlib.h, math.h, tov_headers.h, RK4.C, TOV_RHSs.C, Polytropic_EOS__struct_initialization.C, & Polytropic_EOS__lowlevel_functions.C
*
* Reference(s): Read et al., PRD 79, 124032 (2009) | (https://arxiv.org/pdf/0812.2163.pdf)
* https://en.wikipedia.org/wiki/Tolman%E2%80%93Oppenheimer%E2%80%93Volkoff_equation
*
*/
/* TOV_Solver files */
#include "tov_headers.h"
/* Function : main()
* Author : Leo Werneck (werneck@if.usp.br)
* Date : October 29, 2019
*
* Description: TOV Solver - main driver function
*
* Input(s) : argc - Number of command line input parameters (expected: EOSname)
* : argv - Array containing the command line input parameters
*
* Outputs(s) : return value:
* 0 - Program finished with no errors
* 1 - Input error, wrong usage of the program
* 2 - Input error, invalid EOS name
*
* : output file:
* name - EOSname-TOV_Solver_Output.dat
* Column 1 - Iteration number
* Column 2 - Step size (Geometrized units)
* Column 3 - Radius (Geometrized units)
* Column 4 - Mass (Geometrized units)
* Column 5 - rho_baryon (Geometrized units)
* Column 6 - Pressure (Geometrized units)
* Column 7 - Mass (Solar masses)
* Column 8 - Radius (Kilometers)
*/
int main (int argc, char *argv[]) {
print_TOV_logo();
/* .--------------------.
* | Reading user input |
* .--------------------.
*
* Verify correct usage of the program */
if(argc != 3) {
printf("Error! Incorrect usage. Run the program as: ./TOV_Solver EOSname CentralDensity\n");
exit(1);
}
/* Read in the EOSname */
string EOSname = argv[1];
printf("Input EOS: %s\n",EOSname.c_str());
printf("Initializing EOS parameters...\n");
/* .----------------.
* | EOS Parameters |
* .----------------.
*
* Declare and initialize the EOS struct */
eos_struct eos;
initialize_EOS_struct( EOSname, eos );
print_EOS_table( eos );
/* .----------------------.
* | Variable declaration |
* .----------------------.
*
* Gridfunctions */
REAL gfs_at_rr[NGFS], gfs_at_rr_plus_dr[NGFS];
/* Radial variable */
REAL rr = 0.0;
/* RK4 initial step size */
REAL dr = 1.0e-5;
/* RK4 integration limiter */
int max_integration_steps = (int)(1.0/dr+0.5);
/* .---------------------------.
* | Output initial parameters |
* .---------------------------.
*
* Declare outputfile name */
string outfile_name = EOSname+"TOV_Solver_Output.dat";
/* Declare output checkpoint */
int output_checkpoint = 1e6;
/* Output initial data to file */
output_current_data_to_file(outfile_name,eos, 0,rr,dr,gfs_at_rr);
/* Print integration related information to the user */
printf("(TOV_Solver INFO) Iteration: %5d/%5d | Radius = %9.6lf | Mass = %9.6lf | Compactness = %9.6lf\n",
0,max_integration_steps,rr,gfs_at_rr_plus_dr[MASS],gfs_at_rr_plus_dr[MASS] == 0 ? 0.0 : gfs_at_rr_plus_dr[MASS]/rr);
/* .----------------------.
* | Mass vs. Radius data |
* .----------------------.
* We now start the algorithm which loops over central densities, solving
* the TOV equations for a given EOS. For each value of the central density,
* the algorithm below finds the maximum value of the mass and its respective
* radius. The algorithm continues until Mass(rho_c + drho_c) < Mass(rho_c),
* where rho_c is the central density and drho_c how much we increment it in
* between iterations.
*
* Start by setting the initial central density */
REAL rho_b_central = atof(argv[2]);
/* Then set the increment in the central density
* Experimental: setting to *fixed*, 1% of the initial
* central density.
*/
REAL drho_b_central = 0.05 * rho_b_central;
/* Set up variabless to store the outputs */
REAL Mass_in_solar_masses = 0.0;
REAL Radius_in_kilometers = 0.0;
REAL Mass, Radius;
for(int k=0; k<500; k++) {
/* Print integration related information to the user */
printf("(TOV_Solver INFO) EOSname: %s | Interation: %3d | rho_b_central = %6.4lf\n",EOSname.c_str(),k+1,rho_b_central);
/* .-------------.
* | Integration |
* .-------------.
*
* Set up initial conditions */
/* Pressure associated with central density: this is
* the initial condition for our RK4 integration method
*/
REAL Press_central = compute_P_from_rhob( eos, rho_b_central );
/* Mass associated with central density: because the
* central density corresponds to the density at r=0,
* this means that m(r=0) = 0.
*/
REAL mass_central = 0.0;
/* To complete the set of initial conditions, we also
* set nu(r=0) = 0.
*/
REAL nu_central = 0.0;
/* Set the initial conditions */
gfs_at_rr[PRESSURE] = Press_central;
gfs_at_rr[MASS] = mass_central;
gfs_at_rr[NU] = nu_central;
/* Perform the first RK4 step manually */
RK4_method( eos, rr, dr, gfs_at_rr, gfs_at_rr_plus_dr );
rr += dr;
/* Begin the integration loop */
for(int n=2; n < max_integration_steps; n++) {
/* Update the gridfunctions */
for(int GF=PRESSURE; GF < NGFS; GF++) {
gfs_at_rr[GF] = gfs_at_rr_plus_dr[GF];
}
/* Call upon the adaptive step size routine */
recompute_step_size(eos,rr,gfs_at_rr, dr);
/* Perform an RK4 integration step */
RK4_method( eos, rr, dr, gfs_at_rr, gfs_at_rr_plus_dr );
rr += dr;
/* Output to file, if we have reached the checkpoint */
if( n%output_checkpoint == 0 ) {
/* Print integration related information to the user */
printf("(TOV_Solver INFO) Iteration: %5d/%5d | Radius = %9.6lf | Mass = %9.6lf | Compactness = %9.6lf\n",
n,max_integration_steps,rr,gfs_at_rr_plus_dr[MASS],gfs_at_rr_plus_dr[MASS]/rr);
/* Output to the current file */
output_current_data_to_file(outfile_name,eos, n,rr,dr,gfs_at_rr_plus_dr);
}
if( gfs_at_rr_plus_dr[MASS] <= gfs_at_rr[MASS] ) {
output_current_data_to_file(outfile_name,eos, n,rr,dr,gfs_at_rr_plus_dr);
Mass = convert_mass_to_solar_masses( gfs_at_rr[MASS] );
Radius = convert_radius_to_kilometers( rr );
printf("(TOV_Solver INFO) EOS: %s | Results: Mass = %.5e Solar masses | Radius = %.5e km\n",EOSname.c_str(),Mass,Radius);
break;
}
else{
Mass = 0.0;
Radius = 0.0;
}
}
if( Mass > Mass_in_solar_masses ) {
Mass_in_solar_masses = Mass;
Radius_in_kilometers = Radius;
//output_rhob_mass_radius_to_file( EOSname, k, rho_b_central, gfs_at_rr[MASS], rr );
output_rhob_mass_radius_to_file( EOSname, k, rho_b_central, Mass_in_solar_masses, Radius_in_kilometers );
rho_b_central += drho_b_central;
rr = 0.0;
dr = 1.0e-5;
continue;
}
else{
printf("(TOV_Solver INFO) Maximum mass found for EOS: %s | Mass_max = %6.4lf Solar masses | Radius(Mass_max) = %7.4lf km\n",
EOSname.c_str(),Mass_in_solar_masses,Radius_in_kilometers);
//output_rhob_mass_radius_to_file( EOSname, k, rho_b_central, gfs_at_rr[MASS], rr );
output_rhob_mass_radius_to_file( EOSname, k, rho_b_central, Mass_in_solar_masses, Radius_in_kilometers );
break;
}
}
return 0;
}
|
278df51562ee9fa56842032d233873c976329dd2 | f0efafb3f01a21dd3ad8c19508eb01f34c86afb1 | /DnfTest/Common/ErrorReport.h | c9de8d135804d924ff852e2f6bce8ee3a55a76eb | [] | no_license | liuxiaowei/DnfTest | 7fa7274b69801f1684d2a643da651e97803fa83f | 681cab7085ff92e90f062af3e4ea439e40286911 | refs/heads/master | 2020-04-30T15:20:03.267851 | 2019-04-09T08:46:26 | 2019-04-09T08:46:26 | 176,917,741 | 0 | 0 | null | 2019-04-09T08:46:27 | 2019-03-21T09:58:57 | C++ | GB18030 | C++ | false | false | 2,015 | h | ErrorReport.h | //-------------------------------------------------------------------------
// 文件: ErrorReport.h
// 时间: 2005-12-19 10:43
// 作者: 游戏行业很多兄弟奋斗的积累
// 名称: 错误报告与发送
// 版本:
// [v1.0]2005-12-19 10:43:初始版本
// [v1.1]2005-12-20 14:09:添加了一个主对话框
// [v1.2]2005-12-23 15:01:参照UE的显示,添加了二进制显示功能
// [v1.3]2006-01-04 20:23:更改了Win9X的文件兼容性问题
// [v1.4]2006-01-12 18:23:添加了文件预览的UTF8支持
// [v1.5]2006-03-07 16:31:更改了部分界面显示
//-------------------------------------------------------------------------
#pragma once
#ifndef ErrorReport_h_
#define ErrorReport_h_
namespace ErrorReport {
//-------------------------------------------------------------------------
// 函数: void RegisterLogFiles( LPCTSTR szLogFile )
// 说明: 注册日志文件,将日志添加在发送列表,以便在错误发生时发送
// 参数: szLogFile 日志文件名
// 返回: 无
//-------------------------------------------------------------------------
void RegisterLogFiles( LPCTSTR szLogFile );
//-------------------------------------------------------------------------
// 函数: void UnRegisterLogFiles( LPCTSTR szLogFile )
// 说明: 取消对某个日志文件的注册
// 参数: szLogFile 日志文件名
// 返回: 无
//-------------------------------------------------------------------------
void UnRegisterLogFiles( LPCTSTR szLogFile );
//-------------------------------------------------------------------------
// 函数: BOOL DisplayErrorDlg( IN PEXCEPTION_POINTERS pException )
// 说明: 显示错误对话框,这个函数中的文件列表取自RegisterLogFiles
// 参数: pException 异常指针(如果为空则不自动生成dmp和md文件)
// 返回: 是否用户选择了发送
//-------------------------------------------------------------------------
BOOL DisplayErrorDlg( IN PEXCEPTION_POINTERS pException );
};
#endif//ErrorReport_h_
|
5bfbea792c0523af0a100a6ab5fd71fdf25e53ba | 5a96ec7e5d4417b155887353b9f249eba0e82fd1 | /app/src/main/cpp/ChaoResample.h | 67db5b83de8d13cd1af4050bfdbd3dcc246eb00e | [] | no_license | lichao3140/ChaoPlayer | 6201a400dc0dd084c6a1fa724b11440cc801d25d | 00ecb03ad5e8005a5431958a997d15eb6ee2dd38 | refs/heads/master | 2020-03-14T23:26:57.886050 | 2018-05-19T13:29:14 | 2018-05-19T13:29:14 | 131,845,231 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 489 | h | ChaoResample.h | //
// Created by Administrator on 2018/5/5 0005.
//
#ifndef CHAOPLAYER_CHAORESAMPLE_H
#define CHAOPLAYER_CHAORESAMPLE_H
#include "ChaoObserver.h"
#include "ChaoParameter.h"
class ChaoResample: public ChaoObserver {
public:
virtual bool Open(ChaoParameter in, ChaoParameter out = ChaoParameter()) = 0;
virtual ChaoData Resample(ChaoData indata) = 0;
virtual void Update(ChaoData data);
int outChannels = 2;
int outFormat = 1;
};
#endif //CHAOPLAYER_CHAORESAMPLE_H
|
60eedf74a817b14c7a13a3363576be9f1e4107c4 | bca2bde27beb974e1ba6d55d295af145dad45f77 | /Codeforces/1392D. Omkar and Bed Wars.cpp | b696c14b0a0e8672b2ce291fe7d9b060c3be016c | [] | no_license | nasif-raihan/Solved-Problems-of-Online-Judges | 35a4bec8e96bc231890a04748c25253fcd26ac87 | 5c7d77e1189745851ee7e15333f44a4623073d11 | refs/heads/main | 2023-01-07T15:42:38.485717 | 2020-10-21T06:54:24 | 2020-10-21T06:54:24 | 301,312,908 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | 1392D. Omkar and Bed Wars.cpp | #include <bits/stdc++.h>
using namespace std;
string s;
int main()
{
int i, j, n, t, l, r, ans;
cin >> t;
while(t--)
{
cin >> n >> s;
j = 0;
for(i=1; i<n; i++)
{
if(s[i] != s[i-1])
{
j = i;
break;
}
}
if(j == 0)
{
cout << ceil(n/3.0) << endl;
continue;
}
rotate(s.begin(), s.begin()+j, s.end());
l = r = ans = 0;
for(i=0; i<n; i++)
{
if(s[i] == 'L')
{
l++, r = 0;
if(l == 3)
ans++, l = 0;
}
else
{
r++, l = 0;
if(r == 3)
ans++, r = 0;
}
}
cout << ans << endl;
}
return 0;
}
|
29f6305eb732a4984dfd778e46e83eb3a024f52f | 8d6277108164d60cc323191900d2700c42ce83c5 | /cpp/src/gandiva/precompiled/decimal_wrapper.cc | d5c919e8af11a762046ce5e8c12b3386dfc4cd1b | [
"Apache-2.0",
"CC0-1.0",
"BSD-3-Clause",
"MIT",
"ZPL-2.1",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | SeppPenner/arrow | 0fa703c696a4570485d3ba34ed2c83c8ce65185f | 1df8806c61ace322a72bd44e73e7060af53d4b82 | refs/heads/master | 2020-05-05T02:07:38.921743 | 2019-11-25T08:22:31 | 2019-11-25T08:22:31 | 179,625,814 | 1 | 0 | Apache-2.0 | 2019-11-25T08:22:32 | 2019-04-05T05:45:41 | C++ | UTF-8 | C++ | false | false | 4,153 | cc | decimal_wrapper.cc | // 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 "gandiva/precompiled/decimal_ops.h"
#include "gandiva/precompiled/types.h"
extern "C" {
FORCE_INLINE
void add_large_decimal128_decimal128(int64_t x_high, uint64_t x_low, int32_t x_precision,
int32_t x_scale, int64_t y_high, uint64_t y_low,
int32_t y_precision, int32_t y_scale,
int32_t out_precision, int32_t out_scale,
int64_t* out_high, uint64_t* out_low) {
gandiva::BasicDecimalScalar128 x(x_high, x_low, x_precision, x_scale);
gandiva::BasicDecimalScalar128 y(y_high, y_low, y_precision, y_scale);
arrow::BasicDecimal128 out = gandiva::decimalops::Add(x, y, out_precision, out_scale);
*out_high = out.high_bits();
*out_low = out.low_bits();
}
FORCE_INLINE
void multiply_internal_decimal128_decimal128(int64_t x_high, uint64_t x_low,
int32_t x_precision, int32_t x_scale,
int64_t y_high, uint64_t y_low,
int32_t y_precision, int32_t y_scale,
int32_t out_precision, int32_t out_scale,
int64_t* out_high, uint64_t* out_low) {
gandiva::BasicDecimalScalar128 x(x_high, x_low, x_precision, x_scale);
gandiva::BasicDecimalScalar128 y(y_high, y_low, y_precision, y_scale);
bool overflow;
// TODO ravindra: generate error on overflows (ARROW-4570).
arrow::BasicDecimal128 out =
gandiva::decimalops::Multiply(x, y, out_precision, out_scale, &overflow);
*out_high = out.high_bits();
*out_low = out.low_bits();
}
FORCE_INLINE
void divide_internal_decimal128_decimal128(
int64_t context, int64_t x_high, uint64_t x_low, int32_t x_precision, int32_t x_scale,
int64_t y_high, uint64_t y_low, int32_t y_precision, int32_t y_scale,
int32_t out_precision, int32_t out_scale, int64_t* out_high, uint64_t* out_low) {
gandiva::BasicDecimalScalar128 x(x_high, x_low, x_precision, x_scale);
gandiva::BasicDecimalScalar128 y(y_high, y_low, y_precision, y_scale);
bool overflow;
// TODO ravindra: generate error on overflows (ARROW-4570).
arrow::BasicDecimal128 out =
gandiva::decimalops::Divide(context, x, y, out_precision, out_scale, &overflow);
*out_high = out.high_bits();
*out_low = out.low_bits();
}
FORCE_INLINE
void mod_internal_decimal128_decimal128(int64_t context, int64_t x_high, uint64_t x_low,
int32_t x_precision, int32_t x_scale,
int64_t y_high, uint64_t y_low,
int32_t y_precision, int32_t y_scale,
int32_t out_precision, int32_t out_scale,
int64_t* out_high, uint64_t* out_low) {
gandiva::BasicDecimalScalar128 x(x_high, x_low, x_precision, x_scale);
gandiva::BasicDecimalScalar128 y(y_high, y_low, y_precision, y_scale);
bool overflow;
// TODO ravindra: generate error on overflows (ARROW-4570).
arrow::BasicDecimal128 out =
gandiva::decimalops::Mod(context, x, y, out_precision, out_scale, &overflow);
*out_high = out.high_bits();
*out_low = out.low_bits();
}
} // extern "C"
|
dac064969a32f38f857920a514e7d686009f6b0d | 260b9dcbfa93804704cd88bfd5ddb3bf987027a7 | /TrafficGenerator/exp_distribution.cpp | 9a72b8d18ece3538a922091c2849da29933d86b6 | [] | no_license | simonjoylet/magna | 916bf806249e9b46db85be194de2daf71ecda4f6 | 918655ff9c6a6f6bfe0f9c7aab8d3da0aafdfca6 | refs/heads/master | 2018-07-20T04:29:47.773532 | 2018-06-02T01:47:58 | 2018-06-02T01:47:58 | 110,985,385 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 303 | cpp | exp_distribution.cpp | #include <iostream>
#include <random>
#include <stdio.h>
#include <time.h>
using namespace std;
int main()
{
time_t t;
time(&t);
srand(t);
int lamda = 1000;
for (int i = 0; i < 100; ++i)
{
double rst = (log(lamda) - log(rand() % lamda)) / lamda;
cout << rst * 1000 << endl;
}
getchar();
} |
196a7b738d253e8671907d88b8168b5fdd5eb967 | 511872278bea465e58c64d96c9dbe58bc726e1a6 | /7_trees/8_levelOrderSpiral1.cpp | 813aee81535ad81b94874b09a1ece9752894e3fe | [] | no_license | SubashChandra/placements-Mtech | d0bca826e4342635138e330f5ec23e1119cbc57e | 85c8b09b0400243d3db5af5db6578ba70fad8058 | refs/heads/master | 2021-01-20T11:23:46.143637 | 2016-11-02T17:08:56 | 2016-11-02T17:08:56 | 59,268,656 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,941 | cpp | 8_levelOrderSpiral1.cpp | //binary search tree
#include<cstdio>
#include<iostream>
#include<map>
#include<stack>
#include<queue>
using namespace std;
struct tree
{
int data;
struct tree *left;
struct tree *right;
};
typedef struct tree Tree;
typedef Tree *Treeptr;
Treeptr getNew(int data)
{
Treeptr newnode=(Treeptr)malloc(sizeof(Tree));
newnode->data=data;
newnode->left=newnode->right=NULL;
return newnode;
}
Treeptr insert(Treeptr root, int data)
{
if(root==NULL)
return getNew(data);
if(data<root->data)
root->left=insert(root->left,data);
else if(data>root->data)
root->right=insert(root->right,data);
return root;
}
void preOrder(Treeptr root)
{
if(root)
{
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
}
void inOrder(Treeptr root)
{
if(root)
{
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
}
void postOrder(Treeptr root)
{
if(root)
{
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
}
void auxFunc1(Treeptr root, vector<vector<int> > &vec, int depth)
{
if(root==NULL)
return;
if(vec.size()<=depth)
{
vector<int> temp;
temp.push_back(root->data);
vec.push_back(temp);
}
else
{
vec[depth].push_back(root->data);
}
auxFunc1(root->left,vec,depth+1);
auxFunc1(root->right, vec, depth+1);
}
void auxFunc(Treeptr root)
{
if(root==NULL)
return;
vector<vector<int> > vec;
int depth=0;
auxFunc1(root,vec,depth);
for(int i=0;i<vec.size();i++)
{
if(i%2==0)
{
reverse(vec[i].begin(),vec[i].end());
}
for(int j=0;j<vec[i].size();j++)
cout<<vec[i][j]<<" ";
}
cout<<endl;
}
int main()
{
int n;
Treeptr root=NULL;
cin>>n;
while(n>0)
{
int data;
cin>>data;
root=insert(root,data);
n--;
}
cout<<"preorder:"<<endl;
preOrder(root);
cout<<endl;
cout<<"inorder:"<<endl;
inOrder(root);
cout<<endl;
cout<<"postorder:"<<endl;
postOrder(root);
cout<<endl;
auxFunc(root);
return 0;
}
|
48721b17a27e8ec8cf2cf9186c1c6c933f3af982 | 027836e14779ecc9ac036c39b622bf5d6a31c71b | /addons/breathing/ACE_Medical_Actions.hpp | d249f5c3593079663492265d45b54a0eb2ec1939 | [
"MIT"
] | permissive | kellerkompanie/kellerkompanie-medical | 33d5cf8b5c1532e309ff2c8f4cee0ca16fa37781 | b66076217c1c08b6464ec19c15eef72c91bb5cfb | refs/heads/master | 2022-02-16T18:13:01.188420 | 2022-01-28T20:00:41 | 2022-01-28T20:00:41 | 177,442,305 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,819 | hpp | ACE_Medical_Actions.hpp | class ACE_Medical_Actions {
class Advanced {
class Pulseoximeter {
displayName = CSTRING(Pulseoximeter_Display);
displayNameProgress = CSTRING(placing);
category = "examine";
treatmentLocations[] = {"All"};
allowedSelections[] = {"hand_l", "hand_r"};
allowSelfTreatment = 0;
requiredMedic = 1;
treatmentTime = 2;
items[] = {"keko_pulseOximeter"};
condition = QGVAR(enable);
patientStateCondition = 0;
callbackSuccess = QUOTE([ARR_2(_player, _target)] call FUNC(treatmentAdvanced_pulseoximeter));
callbackFailure = "";
callbackProgress = "";
itemConsumed = 1;
animationPatient = "";
animationPatientUnconscious = "AinjPpneMstpSnonWrflDnon_rolltoback";
animationPatientUnconsciousExcludeOn[] = {"ainjppnemstpsnonwrfldnon"};
animationCaller = "AinvPknlMstpSlayWrflDnon_medicOther";
animationCallerProne = "AinvPpneMstpSlayW[wpn]Dnon_medicOther";
animationCallerSelf = "AinvPknlMstpSlayW[wpn]Dnon_medic";
animationCallerSelfProne = "AinvPpneMstpSlayW[wpn]Dnon_medic";
litter[] = {};
};
class RemovePulseoximeter {
displayName = CSTRING(Pulseoximeter_Display_Remove);
displayNameProgress = CSTRING(remove);
category = "examine";
treatmentLocations[] = {"All"};
allowedSelections[] = {"hand_l", "hand_r"};
allowSelfTreatment = 0;
requiredMedic = 1;
treatmentTime = 2;
items[] = {};
condition = QUOTE(_target getVariable [ARR_2(QQGVAR(pulseoximeter), false)]);
patientStateCondition = 0;
callbackSuccess = QUOTE([ARR_2(_player, _target)] call FUNC(treatmentAdvanced_removePulseoximeter));
callbackFailure = "";
callbackProgress = "";
itemConsumed = 0;
animationPatient = "";
animationPatientUnconscious = "AinjPpneMstpSnonWrflDnon_rolltoback";
animationPatientUnconsciousExcludeOn[] = {"ainjppnemstpsnonwrfldnon"};
animationCaller = "AinvPknlMstpSlayWrflDnon_medicOther";
animationCallerProne = "AinvPpneMstpSlayW[wpn]Dnon_medicOther";
animationCallerSelf = "AinvPknlMstpSlayW[wpn]Dnon_medic";
animationCallerSelfProne = "AinvPpneMstpSlayW[wpn]Dnon_medic";
litter[] = {};
};
class ChestSeal {
displayName = CSTRING(pneumothorax_display);
displayNameProgress = CSTRING(treating);
category = "advanced";
treatmentLocations[] = {"All"};
allowedSelections[] = {"body"};
allowSelfTreatment = 0;
requiredMedic = 2;
treatmentTime = 7;
items[] = {"keko_chestSeal"};
condition = "_target getVariable ['ace_medical_airwayCollapsed', false]";
patientStateCondition = 0;
callbackSuccess = QUOTE([ARR_2(_player, _target)] call FUNC(treatmentAdvanced_chestSeal));
callbackFailure = "";
callbackProgress = "";
itemConsumed = 1;
animationPatient = "";
animationPatientUnconscious = "AinjPpneMstpSnonWrflDnon_rolltoback";
animationPatientUnconsciousExcludeOn[] = {"ainjppnemstpsnonwrfldnon"};
animationCaller = "AinvPknlMstpSlayWrflDnon_medicOther";
animationCallerProne = "AinvPpneMstpSlayW[wpn]Dnon_medicOther";
animationCallerSelf = "AinvPknlMstpSlayW[wpn]Dnon_medic";
animationCallerSelfProne = "AinvPpneMstpSlayW[wpn]Dnon_medic";
litter[] = {};
};
};
};
|
de49328a7d7af966144781138087151902401648 | 7cd9751c057fcb36b91f67e515aaab0a3e74a709 | /src/mip/MIP_Kappa_Calculator.cc | 967cdaebd097deb5151521185a54fb80b28ec75f | [
"MIT"
] | permissive | pgmaginot/DARK_ARTS | 5ce49db05f711835e47780677f0bf02c09e0f655 | f04b0a30dcac911ef06fe0916921020826f5c42b | refs/heads/master | 2016-09-06T18:30:25.652859 | 2015-06-12T19:00:40 | 2015-06-12T19:00:40 | 20,808,459 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,066 | cc | MIP_Kappa_Calculator.cc | /** @file Local_MIP_Assembler.cc
* @author pmaginot
* @brief Implement the (partially) virtual Diffusion_Matrix_Cretator class,
* The goal of this clas is to construct MIP diffusion operator matrices in a generic format
* concrete instantiations of this class will evaluate the following :
* \f$ \mathbf{R}_{\widetilde{\Sigma}_a} \f$, \f$ \mathbf{R}_{\widetilde{\Sigma}_s} \f$,
* and $\widetilde{D}$ at cell edges and quadratureintegration points
*/
#include "MIP_Kappa_Calculator.h"
MIP_Kappa_Calculator::MIP_Kappa_Calculator(const int p_ord , const double z_mip)
:
m_ord( double( p_ord ) ),
m_z_mip( z_mip )
{
}
double MIP_Kappa_Calculator::calculate_interior_edge_kappa(const double dx_l, const double dx_r , const double d_l , const double d_r) const
{
return std::max(0.25, m_z_mip/2.*(m_ord*(m_ord+1.))*(d_l/dx_l + d_r/dx_r) );
}
double MIP_Kappa_Calculator::calculate_boundary_kappa(const double dx , const double d) const
{
return std::max(0.25, m_z_mip*(m_ord*(m_ord+1.))*(d/dx) );
}
|
eb06d3da25a05cc80b43a201bcc2834ccf88a8ae | bf8ef95132764c84262f60ab27e873364e3a3c78 | /affineTransform.cpp | 40c8cee82b6906cc8e094edb9f6a6f682627d02c | [] | no_license | catherinetaylor2/Markers | 939cb1ead7778855df058de67b7de82cb05da689 | 675af50e383077e599a2000463f7fadd26dcd4ba | refs/heads/master | 2021-05-05T04:48:10.373787 | 2018-04-10T13:27:41 | 2018-04-10T13:27:41 | 118,628,503 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,054 | cpp | affineTransform.cpp | #include <iostream>
#include <cmath>
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "affineTransform.hpp"
float degToRad(float angleDegrees){
return angleDegrees*PI/180.0f;
}
float randomNumber0to1(){
return (float)rand()/RAND_MAX ;
}
float randomNumber0tox(float x){
return randomNumber0to1() * x ;
}
float randomNumberatob(float a, float b){
return (b-a)*randomNumber0to1() + a ;
}
cv::Mat getXRotation(float angle){
cv::Mat R = cv::Mat::zeros(3, 3, CV_32F);
float angleRad = degToRad(angle);
R.at<float>(0,0) = 1.0f;
R.at<float>(1,1) = std::cos(angleRad);
R.at<float>(1,2) = -std::sin(angleRad);
R.at<float>(2,1) = std::sin(angleRad);
R.at<float>(2,2) = std::cos(angleRad);
return R;
}
cv::Mat getZRotation(float angle){
cv::Mat R = cv::Mat::zeros(3, 3, CV_32F);
float angleRad = degToRad(angle);
R.at<float>(2,2) = 1.0f;
R.at<float>(0,0) = std::cos(angleRad);
R.at<float>(0,1) = -std::sin(angleRad);
R.at<float>(1,0) = std::sin(angleRad);
R.at<float>(1,1) = std::cos(angleRad);
return R;
}
cv::Mat getYRotation(float angle){
cv::Mat R = cv::Mat::zeros(3, 3, CV_32F);
float angleRad = degToRad(angle);
R.at<float>(1,1) = 1.0f;
R.at<float>(0,0) = std::cos(angleRad);
R.at<float>(2,0) = -std::sin(angleRad);
R.at<float>(0,2) = std::sin(angleRad);
R.at<float>(2,2) = std::cos(angleRad);
return R;
}
cv::Mat getScale(float sx, float sy, float sz){
cv::Mat S = cv::Mat::zeros(3,3,CV_32F);
if(sx == 0) sx = 1; //prevents blank image
if(sy == 0) sy = 1;
if(sz == 0) sz = 1;
S.at<float>(0,0) = sx;
S.at<float>(1,1) = sy;
S.at<float>(2,2) = sz;
return S;
}
cv::Mat getShear(float sxy, float sxz, float syx, float syz, float szx, float szy){
cv::Mat S = cv::Mat::ones(3,3, CV_32F);
S.at<float>(0,1) = sxy;
S.at<float>(0,2) = sxz;
S.at<float>(1,0) = syx;
S.at<float>(1,2) = syz;
S.at<float>(2,0) = szx;
S.at<float>(2,1) = szy;
return S;
}
|
f59c124ecf8a84fd2c8f51d7540352444aaed1c8 | 949714310a640856b524724fbda04493636de60e | /M8_classes/M1_classes/p1/class_members.cpp | 5fcdde3117a65a85c22d11d6a4331e779f9c0f10 | [] | no_license | jcwalmsley/CourseNotes_Cpp | 0fc5fbf5a7f66a681952d88537009e4c3b992c8b | f7c15f065a01f14c0bc58c8ba1135ba70f157c36 | refs/heads/master | 2022-03-27T08:36:20.601483 | 2019-12-28T13:56:50 | 2019-12-28T13:56:50 | 178,411,629 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,321 | cpp | class_members.cpp | /*
Create a function that can modify values witin the student class created
before.
Standard method for inputing data items is to use setDataName to change data inside a class.
Include the these 3 items of data:
name
id
gradDate
*/
//
void setName(std::string nameIn)
//
/*
Add a function that can input each item type of data.
*/
//
class Student
{
string name;
int id;
int gradDate;
public:
void setName(string nameIn);
void setId(int idIn);
void setGradDate(int dateIn);
};
//
/*
In order to return the data we'll need another function that can access and return
it as output.
To retrieve data items from within a class we a get function with the form
getDataValue
Get functions return data, therefore they have the variable type as a return value.
In order to access name, the function declaration is:
string getName();
Student class with a function for each data member shown below:
*/
//
class Student
{
string name;
int id;
int gradDate;
public:
void setName(string nameIn);
void setId(int idIn);
void setGradDate(int dateIn);
string getName();
int getId();
int getGradDate();
void print();
};
|
c685f3a27f2d483b97141ddb2d67bdce28887907 | 6b8fff0eeb75ad266af0ec2b9e9aaf28462c2a73 | /GCJ_Dataset/Data/Alexander86/1835486_1481492_Alexander86.cpp | 1ebd57ce8ee58bec31898c2d5cb5f53cb8703105 | [] | no_license | kotunde/SourceFileAnalyzer_featureSearch_and_classification | 030ab8e39dd79bcc029b38d68760c6366d425df5 | 9a3467e6aae5455142bc7a5805787f9b17112d17 | refs/heads/master | 2020-09-22T04:04:41.722623 | 2019-12-07T11:59:06 | 2019-12-07T11:59:06 | 225,040,703 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,295 | cpp | 1835486_1481492_Alexander86.cpp |
#include <list>
#include <map>
#include <set>
#include <stack>
#include <queue>
#include <algorithm>
#include <sstream>
#include <iostream>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <climits>
#include <cfloat>
#include <numeric>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vi;
typedef vector<string> vs;
typedef pair<int, int> pii;
const int oo = 0x3f3f3f3f;
const double eps = 1e-9;
#define sz(c) int((c).size())
#define all(c) (c).begin(), (c).end()
#define FOR(i,a,b) for (int i = (a); i < (b); i++)
#define FORD(i,a,b) for (int i = int(b)-1; i >= (a); i--)
#define FORIT(i,c) for (__typeof__((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define mp(a,b) make_pair(a,b)
#define pb(a) push_back(a)
const int MAXN = 1000;
pair<ll,ll> meals[MAXN];
int main() {
int tc;
cin >> tc;
FOR(tcc,1,tc+1){
ll M,F;
int N;
cin >> M >> F >> N;
// cout << M << " "<< F << " "<< N << endl;
FOR(i,0,N)cin >> meals[i].first >> meals[i].second;
sort(meals,meals+N);
int ne = 1;
FOR(i,1,N){
if(meals[i].second > meals[ne-1].second)meals[ne++] = meals[i];
}
FOR(i,0,N)meals[i].second++;
ll res = 0;
N = ne;
ll last = 0;
ll co = F;
// if(tcc == 7)cout << M << endl;
FOR(i,0,N){
if(co > M)break;
ll mnext = min(meals[i].second - last, (M - co) / meals[i].first);
ll nco = co + mnext * meals[i].first;
// if(tcc == 7)cout << "i= " << i << ": " << co << " " << nco << endl;
if(mnext == 0)break;
ll maxTurns = M / co;
ll minTurns = (M + nco - 1) / nco;
ll cres = 0;
// if(tcc == 7) cout << maxTurns << " "<< minTurns << endl;
if(maxTurns < minTurns){
co = nco;
last += mnext;
continue;
}
int ST = 1000;
while(ST-->0 && maxTurns >= minTurns){
// cout <<"("<< minTurns << " " << maxTurns << ")" << endl;
cres = max(cres,max(maxTurns * last + (M - maxTurns * co) / meals[i].first,minTurns * last + (M - minTurns * co) / meals[i].first));
// cout << "cres = " << cres << endl;
--maxTurns;
++minTurns;
}
res = max(cres,res);
co = nco;
last += mnext;
}
// cout << "FINAL " << last << " " << co << endl;
res = max(res, last * (M / co));
cout << "Case #" << tcc << ": " << res << endl;
}
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.