blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0c77acb83313bf8f84ec2976f48a91c1e35ac25e | 79a88c724679b27081533d37c2eed171ca525fd9 | /Qt/QDialog/dialog.cpp | 073addb07e97dc7f67e291c7e6e808323b4ebf79 | [] | no_license | wurtzg/StackOverflow | 2e66b77921b7a23e1e50628863a388a4706deded | bbf1a1eb6d70586e73dc23f26df3a7d486ba71ba | refs/heads/master | 2021-01-16T19:19:21.890620 | 2014-08-20T06:33:47 | 2014-08-20T06:33:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 681 | cpp | /**
* This work is licensed under the Creative Commons Attribution 3.0 Unported
* License. To view a copy of this license, visit
* http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative
* Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.
*/
/* StackOverflow reference:
* http://stackoverflow.com/questions/13116863/qt-show-modal-dialog-ui-on-menu-item-click/13117278#13117278
*/
#include <QApplication>
#include <QDialog>
#include "ui_dialog.h"
int main(int argc, char ** argv) {
QApplication app( argc, argv );
QDialog* about = new QDialog(0,0);
Ui_Dialog myUi;
myUi.setupUi(about);
about->exec();
return 0;
}
| [
"[email protected]"
] | |
67212cf3d244e4a583be4ae0ac22beb0e9773a8b | 31734a7e654260efc71c506ea353535a88e8b604 | /helloworld/NCVehicle.hpp | 0bf7642e5da0868cbffed36b1e91df60746bf6b5 | [] | no_license | kemperrr/rage-ralu | 76d7cc397660c68937c603393aaf4f08002cb1fd | c3a332d1880e041d612f57cd0b1a441f15ed631d | refs/heads/master | 2023-05-05T10:30:24.057003 | 2021-05-28T13:18:50 | 2021-05-28T13:18:50 | 371,706,466 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,987 | hpp | #pragma once
#include "RaluCore.hpp"
#include "NCEntity.hpp"
#include "NCPlayer.hpp"
class NCPlayer;
class NCVehicle : public NCEntity {
public:
NCVehicle(rage::IEntity* entryEntity);
void Destroy();
bool IsSirenActive() const;
void SetSirenActive(bool toggle);
bool IsHornActive() const;
bool AreHighbeamsActive() const;
void SetHighbeamsActive(bool toggle);
bool AreLightsActive() const;
void SetLightsActive(bool toggle);
bool IsEngineActive() const;
void SetEngineActive(bool toggle);
bool IsRocketBoostActive() const;
bool IsBrakeActive() const;
float GetSteerAngle() const;
float GetGasPedalState() const;
float GetEngineHealth() const;
float GetBodyHealth() const;
NCPlayer* GetOccupant(uint8_t seat) const;
int GetOccupants(lua_State* state);
void SetOccupant(uint8_t seat, NCPlayer* player);
bool IsLocked() const;
void Lock(bool toggle);
bool IsDead() const;
void Explode();
void Spawn(NCVector3* pos, float heading);
uint8_t GetMod(uint8_t id) const;
void SetMod(uint8_t id, uint8_t mod);
bool AreNeonsEnabled() const;
void EnableNeons(bool toggle);
void SetNeonsColour(uint8_t r, uint8_t g, uint8_t b);
int GetNeonsColour(lua_State* state);
void Repair();
int GetColourRGB(lua_State* state);
uint8_t GetColour(uint8_t id) const;
uint8_t GetPaint(uint8_t id) const;
void SetColourRGB(uint8_t r1, uint8_t g1, uint8_t b1, uint8_t r2, uint8_t g2, uint8_t b2);
void SetColour(uint8_t primary, uint8_t secondary);
void SetPaint(uint8_t type1, uint8_t colour1, uint8_t type2, uint8_t colour2);
uint8_t GetMaterialType() const;
std::string GetNumberPlate() const;
void SetNumberPlate(const std::string numberPlate);
bool operator==(NCVehicle* vehicle) const;
static void Register(LuaVM* rVM);
private:
static int CreateVehicle(lua_State* state);
static int GetAtVehicle(lua_State* state);
static bool Exists(NCVehicle* vehicle);
static int ForEach(lua_State* state);
static int ToArray(lua_State* state);
static int GetSize();
}; | [
"[email protected]"
] | |
b3614b2a512f890064cf94e6f3eb74165cc2065c | e31bf7bb85a47153cfc3aa8c65b8a231c0316aa6 | /Castlevania/Dog.h | f840ec3419dfc1ded2524ebeba476cb7760fb847 | [] | no_license | hcminh/Castlevania | 8a158f8fa0397a0b591a4373754afca2ee96086a | d3ff913646c5a0805d2030d0c5a5102ac3c6c65a | refs/heads/master | 2020-07-22T12:37:11.572203 | 2020-01-05T07:11:29 | 2020-01-05T07:11:29 | 207,204,476 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 929 | h | #pragma once
#include "Enemy.h"
// Dog
#define DOG_BBOX_WIDTH 65
#define DOG_BBOX_HEIGHT 28
#define DOG_WALKING_SPEED 0.3f
#define DOG_JUMPING_SPEED 0.4f
#define DOG_GRAVITY 0.002f
#define DOG_STATE_DEAD 0
#define DOG_STATE_RESPAWN 1
#define DOG_STATE_JUMP 2
#define DOG_ANI_SIT_RIGHT 0 //chó NGỒI R
#define DOG_ANI_SIT_LEFT 1 //chó NGỒI L
#define DOG_ANI_WALK_RIGHT 2 //chó đi phải
#define DOG_ANI_WALK_LEFT 3 //chó đi trái
#define DOG_ANI_JUMP_RIGHT 4 //chó nhảy phải
#define DOG_ANI_JUMP_LEFT 5 //chó nhảy trái
#define DOG_ANI_BURNING 6 //chó chết
class CDog : public CEnemy
{
public:
bool isJumping = false;
bool isSitting = false;
CDog(float x, float y);
virtual void Update(DWORD dt, vector<LPGAMEOBJECT>* coObject = NULL);
virtual void Render();
virtual void respawn();
virtual void dead();
virtual void active();
virtual void SetState(int state);
};
| [
"[email protected]"
] | |
e4ce105adcd2f7a680b1c834d591515240e728a1 | 9ec67e83200f643f9f55ed90e0b2cae4581ebcb6 | /JavaParserLib/JavaTokenBoolean.h | 707163379c160d3ca56d2dcfe9ad74bc69e6e043 | [] | no_license | andrewpaterson/Codaphela.Library | 465770eaf2839589fc305660725abb38033f8aa2 | 2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5 | refs/heads/master | 2023-05-25T13:01:45.587888 | 2023-05-14T11:46:36 | 2023-05-14T11:46:36 | 3,248,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 464 | h | #ifndef __JAVA_BOOLEAN_H__
#define __JAVA_BOOLEAN_H__
#include "BaseLib/Chars.h"
#include "JavaTokenLiteral.h"
class CJavaTokenBoolean : public CJavaTokenLiteral
{
CONSTRUCTABLE(CJavaTokenBoolean);
protected:
bool mbValue;
public:
void Init(STextPosition* psPosition, bool bValue);
void Kill(void);
char* GetType(void);
bool Is(bool b);
void Print(CChars* pszDest);
bool IsBoolean(void);
};
#endif // !__JAVA_BOOLEAN_H__
| [
"[email protected]"
] | |
c01043c0b0fee9c020f0cc114b44450fcc980a1b | 7e68c3e0e86d1a1327026d189a613297b769c411 | /Lib/Src/BigReal/BigInt.cpp | 87044b7f5b63218631587b936fe41732916d8886 | [] | no_license | staticlibs/Big-Numbers | bc08092e36c7c640dcf43d863448cd066abaebed | adbfa38cc2e3b8ef706a3ac8bbd3e398f741baf3 | refs/heads/master | 2023-03-16T20:25:08.699789 | 2020-12-20T20:50:25 | 2020-12-20T20:50:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,236 | cpp | #include "pch.h"
#include <Math/BigReal/BigInt.h>
BigInt::BigInt(const BigReal &x, DigitPool *digitPool) : BigReal(digitPool ? digitPool : x.getDigitPool()) {
digitPool = getDigitPool();
clrInitDone();
if(!x._isnormal()) {
setToNonNormal(x.m_low, x.isNegative());
} else if(x.m_expo < 0) { // |x| < 1
*this = x.isNegative() ? -digitPool->_1() : digitPool->_0();
} else if(x.getLow() >= 0) { // x is an integer
copyAllDigits(x);
copyNonPointerFields(x);
} else { // |x| > 1 and x is not an integer
copyDigits(x, (m_expo = x.m_expo)+1);
m_low = 0;
if(copySign(x).trimZeroes().isNegative()) {
--(*this);
}
}
setInitDone();
}
BigInt::BigInt(const BigInt &x, DigitPool *digitPool) : BigReal(digitPool ? digitPool : x.getDigitPool()) {
clrInitDone();
if(!x._isnormal()) {
setToNonNormal(x.m_low, x.isNegative());
} else {
copyAllDigits(x);
copyNonPointerFields(x);
}
setInitDone();
}
BigInt::BigInt(const String &s, DigitPool *digitPool) : BigReal(digitPool) {
clrInitDone();
init(s, false);
setInitDone();
}
BigInt::BigInt(const char *s, DigitPool *digitPool) : BigReal(digitPool) {
clrInitDone();
init(s, false);
setInitDone();
}
BigInt::BigInt(const wchar_t *s, DigitPool *digitPool) : BigReal(digitPool) {
clrInitDone();
init(s, false);
setInitDone();
}
BigInt quot(const BigInt &x, const BigInt &y, DigitPool *digitPool) {
_SELECTDIGITPOOL(x);
BigInt result(pool);
result.clrInitDone();
quotRemainder(x, y, &result, nullptr);
result.setSignByProductRule(x, y).setInitDone();
return result;
}
BigInt rem(const BigInt &x, const BigInt &y, DigitPool *digitPool) {
_SELECTDIGITPOOL(x);
BigInt result(pool);
result.clrInitDone();
quotRemainder(x, y, nullptr, &result);
result.setInitDone();
return result;
}
#define _BR2 (BIGREALBASE / 2)
BigInt &BigInt::divide2() {
CHECKISMUTABLE(*this);
bool borrow = false;
if(_isnormal()) {
for(Digit *d = m_first; d; d = d->next) {
const bool nb = (d->n & 1) != 0;
d->n /= 2;
if(borrow) d->n += _BR2;
borrow = nb;
}
if(borrow && (m_low > 0)) {
appendDigit(_BR2);
} else {
trimZeroes();
}
}
return *this;
}
| [
"[email protected]"
] | |
2033c7cc290f3bb3890ea3b3aaf50d4554c12501 | efeda21c44f8703c408b0e9b2a33f7c8742ad258 | /tests/locale/locale_fwd.hpp | f0c54d4af4d6f66aa1671ad64507071bf6ead022 | [
"MIT"
] | permissive | olegpublicprofile/stdfwd | 9d6987a49e57f73e3b625552c43c65818f91d041 | 19671bcc8e53bd4c008f07656eaf25a22495e093 | refs/heads/master | 2023-08-15T00:32:13.591955 | 2021-09-18T17:36:29 | 2021-09-18T17:36:29 | 347,794,330 | 18 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,147 | hpp | #pragma once
#include <stdfwd/locale>
#include <cwchar>
#include <codecvt>
#include <string>
//------------------------------------------------------------------------------
#ifdef STDFWD_IS_CPP11
#define STDFWD_IS_WSTRING_CONVERT
#define STDFWD_IS_WBUFFER_CONVERT
#endif
#ifdef STDFWD_IS_CPP17
#undef STDFWD_IS_WSTRING_CONVERT
#undef STDFWD_IS_WBUFFER_CONVERT
#endif
//------------------------------------------------------------------------------
namespace locale_tests {
//------------------------------------------------------------------------------
class TestClass
{
public:
int getInt();
std::locale getLocate();
#ifdef STDFWD_IS_WSTRING_CONVERT
stdfwd::wstring_convert<std::codecvt_utf8<wchar_t>> & getWstringConvert();
#endif
#ifdef STDFWD_IS_WBUFFER_CONVERT
stdfwd::wbuffer_convert<std::codecvt_utf8<wchar_t>> & getWbufferConvert();
#endif
std::ctype_base & getCtypeBase();
std::codecvt_base & getCodecvtBase();
std::time_base & getTimeBase();
std::money_base & getMoneyBase();
std::messages_base & getMessagesBase();
};
//------------------------------------------------------------------------------
}
| [
"[email protected]"
] | |
59a907500af8b669c9ecef4ec1fe9695a39a90d8 | a72d9357c5b43c5ae6b5b82ca16d548ac1fdd853 | /ref_app/src/util/STL/impl/ptr_traits.h | eeac466134c1a3eeb0e622b24172acee2d1e914f | [
"BSL-1.0",
"LicenseRef-scancode-unknown-license-reference",
"LGPL-3.0-only"
] | permissive | ckormanyos/real-time-cpp | d61e90e79b47d41349ba4f34633a14ea35f36d70 | 1741e058cac3b0e865602be5f747d1fe828b7f6f | refs/heads/master | 2023-08-29T02:58:32.175068 | 2023-08-28T11:48:04 | 2023-08-28T11:48:04 | 5,922,310 | 484 | 160 | BSL-1.0 | 2023-08-28T11:48:05 | 2012-09-23T13:31:08 | C++ | UTF-8 | C++ | false | false | 6,328 | h | ///////////////////////////////////////////////////////////////////////////////
// Copyright Christopher Kormanyos 2021 - 2022.
// Distributed under the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt
// or copy at http://www.boost.org/LICENSE_1_0.txt)
//
// Pointer Traits -*- C++ -*-
// Copyright (C) 2011-2019 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library 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, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
#ifndef PTR_TRAITS_2021_01_26_H_
#define PTR_TRAITS_2021_01_26_H_
namespace std
{
template<typename...>
using __void_t = void;
// Implementation of the detection idiom (negative case).
template<typename _Default, typename _AlwaysVoid,
template<typename...> class _Op, typename... _Args>
struct __detector
{
using value_t = false_type;
using type = _Default;
};
// Implementation of the detection idiom (positive case).
template<typename _Default,
template<typename...> class _Op,
typename... _Args>
struct __detector<_Default, __void_t<_Op<_Args...>>, _Op, _Args...>
{
using value_t = true_type;
using type = _Op<_Args...>;
};
// Detect whether _Op<_Args...> is a valid type, use _Default if not.
template<typename _Default, template<typename...> class _Op, typename... _Args>
using __detected_or = __detector<_Default, void, _Op, _Args...>;
// _Op<_Args...> if that is a valid type, otherwise _Default.
template<typename _Default, template<typename...> class _Op, typename... _Args>
using __detected_or_t = typename __detected_or<_Default, _Op, _Args...>::type;
class __undefined;
// Given Template<T, ...> return T, otherwise invalid.
template<typename _Tp>
struct __get_first_arg
{ using type = __undefined; };
template<template<typename, typename...> class _Template,
typename _Tp,
typename... _Types>
struct __get_first_arg<_Template<_Tp, _Types...>>
{ using type = _Tp; };
template<typename _Tp>
using __get_first_arg_t = typename __get_first_arg<_Tp>::type;
// Given Template<T, ...> and U return Template<U, ...>, otherwise invalid.
template<typename _Tp, typename _Up>
struct __replace_first_arg { };
template<template<typename, typename...> class _Template,
typename _Up,
typename _Tp, typename... _Types>
struct __replace_first_arg<_Template<_Tp, _Types...>, _Up>
{ using type = _Template<_Up, _Types...>; };
template<typename _Tp, typename _Up>
using __replace_first_arg_t = typename __replace_first_arg<_Tp, _Up>::type;
template<typename _Tp>
using __make_not_void = typename conditional<is_void<_Tp>::value, __undefined, _Tp>::type;
template<typename _Ptr>
struct pointer_traits
{
private:
template<typename _Tp>
using __element_type = typename _Tp::element_type;
template<typename _Tp>
using __difference_type = typename _Tp::difference_type;
template<typename _Tp, typename _Up, typename = void>
struct __rebind : __replace_first_arg<_Tp, _Up> { };
template<typename _Tp, typename _Up>
struct __rebind<_Tp, _Up, __void_t<typename _Tp::template rebind<_Up>>>
{ using type = typename _Tp::template rebind<_Up>; };
public:
using pointer = _Ptr;
using element_type = __detected_or_t<__get_first_arg_t<_Ptr>, __element_type, _Ptr>;
using difference_type = __detected_or_t<ptrdiff_t, __difference_type, _Ptr>;
template<typename _Up>
using rebind = typename __rebind<_Ptr, _Up>::type;
static _Ptr pointer_to(__make_not_void<element_type>& __e)
{ return _Ptr::pointer_to(__e); }
static_assert(!is_same<element_type, __undefined>::value,
"pointer type defines element_type or is like SomePointer<T, Args>");
};
template<typename _Tp>
struct pointer_traits<_Tp*>
{
typedef _Tp* pointer;
typedef _Tp element_type;
typedef ptrdiff_t difference_type;
template<typename _Up>
using rebind = _Up*;
static constexpr pointer pointer_to(__make_not_void<element_type>& __r)
{ return std::addressof(__r); }
};
// Convenience alias for rebinding pointers.
template<typename _Ptr, typename _Tp>
using __ptr_rebind = typename pointer_traits<_Ptr>::template rebind<_Tp>;
template<typename _Tp>
constexpr _Tp* __to_address(_Tp* __ptr)
{
return __ptr;
}
#if __cplusplus <= 201703L
template<typename _Ptr>
constexpr typename std::pointer_traits<_Ptr>::element_type* __to_address(const _Ptr& __ptr)
{ return std::__to_address(__ptr.operator->()); }
#else
template<typename _Ptr>
constexpr auto __to_address(const _Ptr& __ptr) -> decltype(std::pointer_traits<_Ptr>::to_address(__ptr))
{ return std::pointer_traits<_Ptr>::to_address(__ptr); }
template<typename _Ptr, typename... _None>
constexpr auto __to_address(const _Ptr& __ptr, _None...)
{
return std::__to_address(__ptr.operator->());
}
template<typename _Tp>
constexpr _Tp*
to_address(_Tp* __ptr)
{ return std::__to_address(__ptr); }
template<typename _Ptr>
constexpr auto
to_address(const _Ptr& __ptr)
{ return std::__to_address(__ptr); }
#endif // C++2a
}
#endif // PTR_TRAITS_2021_01_26_H_
| [
"[email protected]"
] | |
a48438d294a13c5f552d79c9ad40621256b82767 | 904cab3675e143883a38f1799a9b1c5619915efa | /Flame1.0/src/physics/ParticleMPMWater.cpp | b8a0437b5bbb98266258dbe8ef08d77d5cc5fd08 | [
"MIT"
] | permissive | fengjixuchui/Flame | 49f165ffc15630f8b4744dcae87b80ba32d09681 | a0553b935d33ce84674b5e348b85ab2eafd661ea | refs/heads/master | 2022-10-15T20:37:04.113210 | 2020-06-14T04:20:39 | 2020-06-14T04:20:39 | 271,991,447 | 0 | 0 | MIT | 2020-06-14T04:20:41 | 2020-06-13T10:58:22 | null | UTF-8 | C++ | false | false | 1,417 | cpp | #include"../../include/physics/ParticleMPMWater.h"
#include"../../include/math/Function.h"
ParticleMPMWater::ParticleMPMWater()
{
}
ParticleMPMWater::~ParticleMPMWater()
{
}
ParticleMPMWater::ParticleMPMWater(Vector2d pos, Vector2d vel, double mass, int num, double gama, double hardness)
{
position = pos;
velocity = vel;
this->mass = mass;
index = num;
Gama = gama;
Hardness = hardness;
J = 1;
color = Vector3d(0, 0.8, 1.0);
p_type = WATER;
}
ParticleMPMWater::ParticleMPMWater(Vector2d pos, Vector2d vel, int num, WaterParameters p, Vector3d PColor)
{
position = pos;
velocity = vel;
index = num;
this->mass = p.mass;
Gama = p.Gama;
Hardness = p.Hardness;
J = 1;
float dc = RandomNumber(0, 0.2);
if (PColor[0] < 0) color = Vector3d(dc, -dc, 0.0) + Vector3d(0.3, 0.8, 1.0);
else color = Vector3d(dc, -dc, 0.0) + PColor;
p_type = WATER;
}
void ParticleMPMWater::UpdatePos()
{
position += DT*velocity;
}
void ParticleMPMWater::UpdateGradient()
{
double trace;
trace = velocity_gradient.trace();
trace *= DT;
trace = trace + 1;
J = trace * J;
}
Matrix2d ParticleMPMWater::EnergyDerivative()
{
double Je = def_elastic.determinant();
Matrix2d out;
double P = Hardness*(1 / pow(J, Gama) - 1);
Matrix2d temp = Matrix2d::Identity();
out = -P*temp;
return volume * out;
}
void ParticleMPMWater::MPMUpdate()
{
UpdatePos();
UpdateGradient();
}
void ParticleMPMWater::DeltaForce()
{
} | [
"[email protected]"
] | |
c91333b9efc637b26efb581b661c5c93a76bab14 | 2b4a6f5ab327f7cc9b8eb6abe7c64f8ae50a3f97 | /Source/Cargo/CargoPlayerController.h | f275b620992c5be1b27e301147138d9d5970f03a | [] | no_license | martinezpierre/Cargo | 8289cc0422775ba35e79f76d177b8259904b9055 | ee6535f3816150030c02b3c17c81b4a6c79b51f8 | refs/heads/master | 2021-01-01T05:19:28.463994 | 2016-05-24T13:43:26 | 2016-05-24T13:43:26 | 58,642,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 296 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "GameFramework/PlayerController.h"
#include "CargoPlayerController.generated.h"
/**
*
*/
UCLASS()
class CARGO_API ACargoPlayerController : public APlayerController
{
GENERATED_BODY()
};
| [
"[email protected]"
] | |
237160add29914b46a6d195b3d791ceb524b10a2 | e8ce6d40f69b614e7420c64edce4ef0cce79893d | /1553.cpp | bfc1df5251f5f6c7800634bf974c78efd0d08918 | [] | no_license | Eberty/CodigosURI | 1a23af25454bc059f9cfabce1678c7d2b053aec9 | 65a43c59a8594940312cc4526fe63536b2ca31f2 | refs/heads/master | 2020-05-14T02:04:55.348762 | 2019-08-05T03:00:45 | 2019-08-05T03:00:45 | 181,687,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 454 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() {
int n, k, p, resp;
while ((cin >> n >> k) && n && k) {
map<int, int> perguntas;
resp = 0;
for (int i=0; i< n; i++) {
cin >> p;
perguntas[p]++;
}
for (map<int, int>::iterator p=perguntas.begin(); p!=perguntas.end(); ++p){
if (((*p).second) >= k)
resp++;
}
cout << resp << endl;
}
return 0;
}
| [
"[email protected]"
] | |
8fd108bc968b2001e0647bceeaa5afe52bf94910 | 15a7060159f10832aa6df747ff0f7cabe0110c13 | /1303_Spurs_Rocks/1303_Spurs_Rocks.cpp | 96b36f2eb2a4ff42c4e554cb8ce4bc9ea0683794 | [] | no_license | guidesanti/URI | cca9c20fc462324763947c98041c5eb4379f5c2c | 243231b187a877c964d1b709e104b190c84d5da2 | refs/heads/master | 2021-06-06T00:57:57.224672 | 2017-08-30T16:00:29 | 2017-08-30T16:00:29 | 41,391,678 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,035 | cpp | #include <stdio.h>
// Constraints
#define MAX_NUMBER_OF_TEAMS (100) // MAximum number of teams
// Data structures
typedef struct Team Team;
struct Team {
int number;
int pointsScored;
int pointsReceived;
int points;
double averageBasket;
Team* next;
};
// Data
int numberOfTeams = 0; // The number of teams
int numberOfMatches = 0; // The number of matches
int instanceNumber = 0; // The instance number
Team teams[MAX_NUMBER_OF_TEAMS]; // The teams of the league
Team* rank = NULL; // The rank of the teams
int i = 0; // Loop control
// Functions
int Compare(Team* t1, Team* t2) {
if (t1->points > t2->points) {
return 1;
} else if (t1->points < t2->points) {
return 2;
} else {
if (t1->averageBasket > t2->averageBasket) {
return 1;
} else if (t1->averageBasket < t2->averageBasket) {
return 2;
} else {
if (t1->pointsScored > t2->pointsScored) {
return 1;
} else if (t1->pointsScored < t2->pointsScored) {
return 2;
} else{
if (t1->number < t2->number) {
return 1;
}
else {
return 2;
}
}
}
}
}
int main() {
while (1) {
// Read the number of teams
scanf("%d", &numberOfTeams);
// Check stop condition
if (!numberOfTeams) {
break;
}
// Reset
for (i = 0; i < numberOfTeams; i++) {
teams[i].number = (i + 1);
teams[i].pointsScored = 0;
teams[i].pointsReceived = 0;
teams[i].points = 0;
teams[i].averageBasket = 0.0;
teams[i].next = NULL;
}
// Read the match results
numberOfMatches = ((numberOfTeams * (numberOfTeams - 1)) / 2);
for (i = 0; i < numberOfMatches; i++) {
int x;
int y;
int z;
int w;
scanf("%d %d %d %d", &x, &y, &z, &w);
x--;
z--;
teams[x].pointsScored += y;
teams[x].pointsReceived += w;
teams[z].pointsScored += w;
teams[z].pointsReceived += y;
if (y > w) {
teams[x].points += 2;
teams[z].points += 1;
} else if (y < w) {
teams[x].points += 1;
teams[z].points += 2;
} else {
// It shall not reach here
}
}
// Calculate the average basket for each team
for (i = 0; i < numberOfTeams; i++) {
teams[i].averageBasket = (double)(teams[i].pointsScored);
if (teams[i].pointsReceived > 0) {
teams[i].averageBasket /= (double)(teams[i].pointsReceived);
}
}
// Rank the teams
rank = &teams[0];
for (i = 1; i < numberOfTeams; i++) {
if (Compare(&teams[i], rank) == 1) {
teams[i].next = rank;
rank = &teams[i];
} else {
Team* team = rank;
while (team->next) {
if (Compare(&teams[i], team->next) == 1) {
teams[i].next = team->next;
team->next = &teams[i];
break;
}
team = team->next;
}
if (!team->next) {
team->next = &teams[i];
}
}
}
// Print the result
if (instanceNumber) {
printf("\n");
}
printf("Instancia %d\n", ++instanceNumber);
while (rank) {
if (rank->next) {
printf("%d ", rank->number);
} else {
printf("%d\n", rank->number);
}
rank = rank->next;
}
}
return 0;
} | [
"[email protected]"
] | |
cd3b964f219edd4b35bddf73ec4a718bf348c01b | 8a815610a3d9ee31098cf50459d58f7f5bcc419c | /2. window_programming/ch09/p05-Colordialog/p05-ColordialogView.cpp | dd2a3da4c1b5cdc6b97442259872a257b37cb23d | [] | no_license | hackerlank/2015_second_semester | 8ce7735bab02c6ba0c9ab70afae6642a9a31045f | 7b756b5961b3f9fce982513830f1781d2cec8207 | refs/heads/master | 2021-01-12T05:43:51.565908 | 2016-01-06T04:19:15 | 2016-01-06T04:19:15 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 3,344 | cpp |
// p05-ColordialogView.cpp : Cp05ColordialogView 클래스의 구현
//
#include "stdafx.h"
// SHARED_HANDLERS는 미리 보기, 축소판 그림 및 검색 필터 처리기를 구현하는 ATL 프로젝트에서 정의할 수 있으며
// 해당 프로젝트와 문서 코드를 공유하도록 해 줍니다.
#ifndef SHARED_HANDLERS
#include "p05-Colordialog.h"
#endif
#include "p05-ColordialogDoc.h"
#include "p05-ColordialogView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#endif
// Cp05ColordialogView
IMPLEMENT_DYNCREATE(Cp05ColordialogView, CView)
BEGIN_MESSAGE_MAP(Cp05ColordialogView, CView)
// 표준 인쇄 명령입니다.
ON_COMMAND(ID_FILE_PRINT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_DIRECT, &CView::OnFilePrint)
ON_COMMAND(ID_FILE_PRINT_PREVIEW, &Cp05ColordialogView::OnFilePrintPreview)
ON_WM_CONTEXTMENU()
ON_WM_RBUTTONUP()
ON_WM_LBUTTONDOWN()
END_MESSAGE_MAP()
// Cp05ColordialogView 생성/소멸
Cp05ColordialogView::Cp05ColordialogView()
{
// TODO: 여기에 생성 코드를 추가합니다.
str = "jmleeeeeeeeeeee";
color = RGB(255, 0, 0);
}
Cp05ColordialogView::~Cp05ColordialogView()
{
}
BOOL Cp05ColordialogView::PreCreateWindow(CREATESTRUCT& cs)
{
// TODO: CREATESTRUCT cs를 수정하여 여기에서
// Window 클래스 또는 스타일을 수정합니다.
return CView::PreCreateWindow(cs);
}
// Cp05ColordialogView 그리기
void Cp05ColordialogView::OnDraw(CDC* pDC)
{
Cp05ColordialogDoc* pDoc = GetDocument();
ASSERT_VALID(pDoc);
if (!pDoc)
return;
// TODO: 여기에 원시 데이터에 대한 그리기 코드를 추가합니다.
pDC->SetTextColor(color);
pDC->TextOutA(100, 100, str);
}
// Cp05ColordialogView 인쇄
void Cp05ColordialogView::OnFilePrintPreview()
{
#ifndef SHARED_HANDLERS
AFXPrintPreview(this);
#endif
}
BOOL Cp05ColordialogView::OnPreparePrinting(CPrintInfo* pInfo)
{
// 기본적인 준비
return DoPreparePrinting(pInfo);
}
void Cp05ColordialogView::OnBeginPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄하기 전에 추가 초기화 작업을 추가합니다.
}
void Cp05ColordialogView::OnEndPrinting(CDC* /*pDC*/, CPrintInfo* /*pInfo*/)
{
// TODO: 인쇄 후 정리 작업을 추가합니다.
}
void Cp05ColordialogView::OnRButtonUp(UINT /* nFlags */, CPoint point)
{
ClientToScreen(&point);
OnContextMenu(this, point);
}
void Cp05ColordialogView::OnContextMenu(CWnd* /* pWnd */, CPoint point)
{
#ifndef SHARED_HANDLERS
theApp.GetContextMenuManager()->ShowPopupMenu(IDR_POPUP_EDIT, point.x, point.y, this, TRUE);
#endif
}
// Cp05ColordialogView 진단
#ifdef _DEBUG
void Cp05ColordialogView::AssertValid() const
{
CView::AssertValid();
}
void Cp05ColordialogView::Dump(CDumpContext& dc) const
{
CView::Dump(dc);
}
Cp05ColordialogDoc* Cp05ColordialogView::GetDocument() const // 디버그되지 않은 버전은 인라인으로 지정됩니다.
{
ASSERT(m_pDocument->IsKindOf(RUNTIME_CLASS(Cp05ColordialogDoc)));
return (Cp05ColordialogDoc*)m_pDocument;
}
#endif //_DEBUG
// Cp05ColordialogView 메시지 처리기
//쓰여진 cstring을 dlg를 열어서 색깔을 바꾸어 보자
void Cp05ColordialogView::OnLButtonDown(UINT nFlags, CPoint point)
{
CColorDialog dlg(color);
//CDialog dlg;
dlg.DoModal();
color = dlg.GetColor();
this->Invalidate();
CView::OnLButtonDown(nFlags, point);
}
| [
"[email protected]"
] | |
7be80511e3726093fe0891a0a22a2d2e85fd82c2 | 65b7dfe3f086ad5f71901e8c49b12993a7f00d9e | /SensAble/GHOST/v4.0/include/gstConstraintEffect.h | ff2315891df51a7a1e4e0a60c7736dc7a11b1519 | [] | no_license | oliriley/PhantomController | 0e7c24494a32dd75206d398e7aff402f5538bd3a | 28e6468abab235c60b3132f934b5e0de190a49ac | refs/heads/master | 2020-04-05T23:11:29.017105 | 2015-12-03T23:56:43 | 2015-12-03T23:56:43 | 38,007,748 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,833 | h | //=============================================================================
// Filename : gstConstraintEffect.h
// Project : GHOST library v3.0
// Authors : Chris Tarr
// Revised : W. A. Aviles
// ----------------------------------------------------------------------------
// Description: An effect to constrain the PHANToM to a point, line or plane
//
// Send your questions, comments or bugs to:
// [email protected]
// http://www.sensable.com
//
// Copyright (c) 1996-1999 SensAble Technologies, Inc. All rights reserved.
//=============================================================================
#ifndef GST_CONSTRAINT_EFFECT
#define GST_CONSTRAINT_EFFECT
#define GST_POINT_CONSTRAINT 0
#define GST_LINE_CONSTRAINT 1
#define GST_PLANE_CONSTRAINT 2
#include <math.h>
#include <gstDllExport.h>
#include <gstBasic.h>
#include <gstPlane.h>
#include <gstEffect.h>
#include <gstErrorHandler.h>
// Constraint effect for PHANToM.
// This effect constrains the PHANToM to a point,
// line or plane using a spring/damper system. When
// this effect is started, its force effects
// ramp up over three seconds so that no significant
// forces are immediately generated.
class GHOST_DLL_IMPORT_EXPORT gstConstraintEffect :public gstEffect
{
public:
// Constructor.
gstConstraintEffect():gstEffect(){
constraint = GST_POINT_CONSTRAINT;
springStiffness = 0.6;
damping = 0.0;
useAttenuation = TRUE;
}
// Destructor.
~gstConstraintEffect() {}
// Set damping coefficient.
void setDamping(double newDamping) {
if (newDamping <= 0) {
gstErrorHandler(GST_BOUNDS_ERROR,
"gstInertiaEffect:setDamping Invalid < 0",newDamping);
return;
}
damping = newDamping;
}
// Get damping coefficient.
double getDamping()const { return damping; }
// Set spring constant (stiffness) [Kg/(1000.0*sec^2)].
void setSpringStiffness(double newStiffness) {
if (newStiffness <= 0) {
gstErrorHandler(GST_BOUNDS_ERROR,
"gstInertiaEffect:setSpringStiffness Invalid <= 0",newStiffness);
return;
}
springStiffness = newStiffness;
}
// Get spring constant (stiffness) [Kg/(1000.0*sec^2)].
double getSpringStiffness()const { return springStiffness; }
// Set a point constraint.
void setPoint(gstPoint newPoint) {
stop();
pointConstraint = newPoint;
constraint = GST_POINT_CONSTRAINT;
}
// Set a line constraint given a point on the line and
// a vector.
void setLine(gstPoint newPointOnLine, gstVector newLineDir) {
stop();
pointOnLine = newPointOnLine;
lineDirection = newLineDir;
constraint = GST_LINE_CONSTRAINT;
}
// Set a planar constraint.
void setPlane(gstPlane newPlane) {
stop();
planeConstraint = newPlane;
constraint = GST_PLANE_CONSTRAINT;
}
void setAttenuation(gstBoolean flag) {
useAttenuation = flag;
}
// FOR_GHOST_EXTENSION:
// Caculate the force. Force is returned in parent
// reference frame of phantom. When subclassing, the first
// parameter should be cast to gstPHANToM to retrieve
// any information about the state of the PHANToM that
// is needed to calculate the forces. deltaT should
// be used to update the time. Also, if the effect is
// not active, the zero vector should be returned.
// ACTUNG!
// WARNING!: Never call PHANToM->setForce or
// PHANToM->setForce_WC from this function.
// It will cause an infinite recursion.
virtual gstVector calcEffectForce(void *phantom);
virtual gstVector calcEffectForce(void *phantom, gstVector &torques) {
torques.init(0.0, 0.0, 0.0);
return calcEffectForce(phantom);
}
protected:
double springStiffness, damping;
int constraint;
gstPoint pointConstraint;
gstPoint pointOnLine;
gstVector lineDirection;
gstPlane planeConstraint;
double attenuation;
gstBoolean useAttenuation;
};
#endif // GST_CONSTRAINT_EFFECT
| [
"[email protected]"
] | |
e05ee8a49c305061610277ff7376a622a2a425ae | 46744eb2977c904cb112bd09af59711fd71ee267 | /src/Yasg.h | 6a4990b4e85fc20b3c84d4130f1012f896a77dc2 | [] | no_license | geckoxx/yasg-sdl | 8144040cef708a2a4cad24d9b51dce4bc90c68f9 | 2cf41d50fa98ac27ad435d70c48fcfe9ec2d331c | refs/heads/master | 2016-09-03T02:15:47.735424 | 2013-05-09T22:12:43 | 2013-05-09T22:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,298 | h | /*
* <one line to give the program's name and a brief idea of what it does.>
* Copyright (C) 2013 Johannes Hackel
*
* 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/>.
*
*/
#ifndef YASG_YASG_H
#define YASG_YASG_H
#include "Engine.h"
#include "MouseEvent.h"
#include "WindowEvent.h"
#include "Menu.h"
#include "Playground.h"
namespace yasg {
class Yasg : public MouseEventHandler
{
private:
Engine* engine;
Menu* menu;
Playground* playground;
enum Status {
MENU, SCORES, INGAME, NEWRESULT
} status;
public:
Yasg();
~Yasg();
void run();
void renderFunction();
virtual void updateME(MouseEvent mouseEvent);
};
}
#endif // YASG_YASG_H
| [
"[email protected]"
] | |
88f98d4710cb2da14e9267af4127333fee425f84 | 82a3e40b75d0cc4250998702c2bff873590d92db | /src/data/data_error.h | 4cbacbf663fa345890ae59bd5397642a2a3cc814 | [] | no_license | PavelAmialiushka/Aera.demo | 12c7981d0883e8b832c2f3e72fee14234cdeb3b0 | 4beeb315a99da6f90a87ba0bb5b3dffa6c52bd2d | refs/heads/master | 2021-10-11T14:41:00.180456 | 2019-01-27T13:38:21 | 2019-01-27T13:38:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 329 | h | /////////////////////////////////////////////////////////////////////////////
//
// data library
//
// Written by Pavel Amialiushka
// No commercial use permited.
//
//////////////////////////////////////////////////////////////////////////
#pragma once
namespace data
{
DEFINE_NERROR(format_error, "data::format_error");
}
| [
"[email protected]"
] | |
8e8cac104a58678bed12664447af040d71f32f28 | 59bf634aac81fa248a31190f28c108d720360be7 | /Line2D.h | 886011f67b05cf57d8ad3d930fd5908202f589ea | [] | no_license | zprimal/Assgn3 | 4c089f7a4b31008345cbe082e5c1e799d52c1d6e | a265f9644f63bf29e1c048e825a45fc5c4dd7093 | refs/heads/master | 2020-03-17T09:27:48.761000 | 2018-05-19T13:46:26 | 2018-05-19T13:46:26 | 133,476,062 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 934 | h | //Line2D.h
//Superclass to Line3D
#ifndef Line2D_H
#define Line2D_H
#include <iostream>
#include <iomanip>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <cmath>
#include "Point2D.h"
using namespace std;
class Line2D{
private:
Point2D pt1;
Point2D pt2;
protected:
double length;
virtual int setLength();
public:
Line2D();
Line2D(Point2D, Point2D);
~Line2D();
int setPt1(Point2D);
int setPt2(Point2D);
Point2D getPt1();
Point2D getPt2();
virtual double getScalarValue();
friend ostream& operator <<(ostream&, Line2D&);
friend Line2D operator +(const Line2D&, const Line2D&);
friend Line2D operator -(const Line2D&, const Line2D&);
friend bool operator ==(const Line2D&, const Line2D&);
friend bool operator <(const Line2D&, const Line2D&);
};
bool sortltL2DPt1(Line2D, Line2D);
bool sortltL2DPt2(Line2D, Line2D);
bool sortltL2DLength(Line2D, Line2D);
#endif
| [
"[email protected]"
] | |
3991d997198552a4b20e991b8ee16ae52b844bf3 | b6827ba9b5bf3d438123e6b8b787cb242df5eed3 | /project/topcoder/d1/cpp/HowEasy.h | fc01720c8a18ecb64ad801811e33507f20353ec6 | [] | no_license | fpzh2011/technotes | a9dd762e7e0d866204ccd22c99738d41c18f48d5 | d95532f8306dc1716fd764ef74438d9b16f1ad00 | refs/heads/master | 2021-06-10T10:32:42.940997 | 2021-02-23T03:26:00 | 2021-02-23T03:26:00 | 60,340,086 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 256 | h | /* 162.html */
#include <string>
class HowEasy {
public:
std::string::size_type pointVal (const std::string &s);
private:
auto wordlen (const std::string &s) -> decltype(s.size());
std::string::size_type getPointByLen (std::string::size_type len);
};
| [
"[email protected]"
] | |
8605c5d50712be4782037237c465d9eae0b0be34 | 464d6cb42fb8981595cbf7260069cd1e6a67fe2f | /Linked List/Standard Important/CDC Design Linked List.cpp | a905b9847e1c54b5fdcaaa6c7f48bb4f2bdefec3 | [] | no_license | rahul799/leetcode_problems | fd42276f85dc881b869072b74654f5811c6618ea | cc7f086eb9ac9bbd20ea004c46d89aa84df10d36 | refs/heads/main | 2023-04-14T05:09:31.016878 | 2021-04-20T19:46:52 | 2021-04-20T19:46:52 | 359,933,382 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,047 | cpp |
707. Design Linked List
Medium
807
855
Add to List
Share
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and next is a pointer/reference to the next node.
If you want to use the doubly linked list, you will need one more attribute prev to indicate the previous node in the linked list. Assume all nodes in the linked list are 0-indexed.
Implement the MyLinkedList class:
MyLinkedList() Initializes the MyLinkedList object.
int get(int index) Get the value of the indexth node in the linked list. If the index is invalid, return -1.
void addAtHead(int val) Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list.
void addAtTail(int val) Append a node of value val as the last element of the linked list.
void addAtIndex(int index, int val) Add a node of value val before the indexth node in the linked list. If index equals the length of the linked list, the node will be appended to the end of the linked list. If index is greater than the length, the node will not be inserted.
void deleteAtIndex(int index) Delete the indexth node in the linked list, if the index is valid.
Example 1:
Input
["MyLinkedList", "addAtHead", "addAtTail", "addAtIndex", "get", "deleteAtIndex", "get"]
[[], [1], [3], [1, 2], [1], [1], [1]]
Output
[null, null, null, null, 2, null, 3]
Explanation
MyLinkedList myLinkedList = new MyLinkedList();
myLinkedList.addAtHead(1);
myLinkedList.addAtTail(3);
myLinkedList.addAtIndex(1, 2); // linked list becomes 1->2->3
myLinkedList.get(1); // return 2
myLinkedList.deleteAtIndex(1); // now the linked list is 1->3
myLinkedList.get(1); // return 3
Constraints:
0 <= index, val <= 1000
Please do not use the built-in LinkedList library.
At most 2000 calls will be made to get, addAtHead, addAtTail, addAtIndex and deleteAtIndex.
class Node {
public:
int val;
Node* next;
Node(int val) {
this->val=val;
next=NULL;
}
};
class MyLinkedList {
public:
/** Initialize your data structure here. */
int size=0;
Node* head=new Node(0);
MyLinkedList() {
}
/** Get the value of the index-th node in the linked list. If the index is invalid, return -1. */
int get(int index) {
if(index>=size) return -1;
Node* temp=head->next;
for(int i=0;i<index;i++) temp=temp->next;
return temp->val;
}
/** Add a node of value val before the first element of the linked list. After the insertion, the new node will be the first node of the linked list. */
void addAtHead(int val) {
Node* temp=head->next;
head->next=new Node(val);
head->next->next=temp;
size++;
}
/** Append a node of value val to the last element of the linked list. */
void addAtTail(int val) {
Node* temp=head;
while(temp->next!=NULL) temp=temp->next;
temp->next=new Node(val);
size++;
}
/** Add a node of value val before the index-th node in the linked list. If index equals to the length of linked list, the node will be appended to the end of linked list. If index is greater than the length, the node will not be inserted. */
void addAtIndex(int index, int val) {
if(index>size) return;
Node* temp=head;
for(int i=0;i<index;i++) temp=temp->next;
Node* temp1=temp->next;
temp->next=new Node(val);
temp->next->next=temp1;
size++;
}
/** Delete the index-th node in the linked list, if the index is valid. */
void deleteAtIndex(int index) {
if(index>=size) return;
Node* temp=head;
for(int i=0;i<index;i++) temp=temp->next;
Node* temp1=temp->next;
temp->next=temp1->next;
temp1->next=NULL;
size--;
delete temp1;
}
};
| [
"[email protected]"
] | |
c71cca88f268ba57098fe798f29145112c92e472 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14186/function14186_schedule_18/function14186_schedule_18.cpp | 7edff7a08fae38e9b565a906291b70ccbb3ad7a1 | [] | no_license | IsraMekki/tiramisu_code_generator | 8b3f1d63cff62ba9f5242c019058d5a3119184a3 | 5a259d8e244af452e5301126683fa4320c2047a3 | refs/heads/master | 2020-04-29T17:27:57.987172 | 2019-04-23T16:50:32 | 2019-04-23T16:50:32 | 176,297,755 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,223 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14186_schedule_18");
constant c0("c0", 64), c1("c1", 64), c2("c2", 128), c3("c3", 128);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i3("i3", 0, c3), i01("i01"), i02("i02"), i03("i03"), i04("i04");
input input00("input00", {i0, i3}, p_int32);
input input01("input01", {i0, i2, i3}, p_int32);
input input02("input02", {i0, i1, i2}, p_int32);
computation comp0("comp0", {i0, i1, i2, i3}, input00(i0, i3) - input01(i0, i2, i3) + input02(i0, i1, i2));
comp0.tile(i2, i3, 128, 128, i01, i02, i03, i04);
comp0.parallelize(i0);
buffer buf00("buf00", {64, 128}, p_int32, a_input);
buffer buf01("buf01", {64, 128, 128}, p_int32, a_input);
buffer buf02("buf02", {64, 64, 128}, p_int32, a_input);
buffer buf0("buf0", {64, 64, 128, 128}, p_int32, a_output);
input00.store_in(&buf00);
input01.store_in(&buf01);
input02.store_in(&buf02);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf01, &buf02, &buf0}, "../data/programs/function14186/function14186_schedule_18/function14186_schedule_18.o");
return 0;
} | [
"[email protected]"
] | |
4cb11ea5f7fcf66c6200010390deae3fb77be0ac | a4344b32439a01e4ef67c521f97dc13e3600c642 | /1937/1937/소스.cpp | cd5852ebd29c086f68280d6a2ba7b697d763794c | [] | no_license | jjunCoder/ProblemSolving | 419ed6ded9ac46fcc52ec14fcfe626055462cfcc | ed150d186d2b02e514239f5d585bc068d426f4dd | refs/heads/master | 2022-09-03T14:10:32.086545 | 2020-05-30T04:15:59 | 2020-05-30T04:15:59 | 66,230,023 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,008 | cpp | /*
2016.9.2
BaekJoon Online Judge
Problem Solving
Seong Joon Seo (ID: jjunCoder)
Problem
#1937
욕심쟁이 판다
*/
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<vector<int> > table, dp;
int n;
int solve(int y, int x, int cost) {
if (x < 0 || y < 0 || x >= n || y >= n) return 0;
if (table[y][x] <= cost) return 0;
int& ret = dp[y][x];
if (ret != -1) return ret;
int temp = table[y][x];
ret = max(ret, solve(y + 1, x, temp)+1);
ret = max(ret, solve(y, x + 1, temp)+1);
ret = max(ret, solve(y - 1, x, temp)+1);
return ret = max(ret, solve(y, x - 1, temp)+1);
}
int main() {
cin.sync_with_stdio(false);
cin >> n;
dp.assign(n, vector<int>(n, -1));
table.assign(n, vector<int>(n, -1));
int cost,maxi=-1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> cost;
table[i][j] = cost;
}
}
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
maxi = max(maxi,solve(i, j, -1));
}
}
cout << maxi;
return 0;
} | [
"[email protected]"
] | |
36473ed90d52034b67ac4d4854675527e888c7dd | b92e95cfa8410fcc5b0b001ab9416806ed4c6d05 | /src/planning/parking_planner_node/include/parking_planner_node/parking_planner_node.hpp | ee561d51c8fc95271185cb1a546147c052fe32e1 | [
"Apache-2.0"
] | permissive | jiangtaojiang/AutowareAuto | 515535d6efa9333ea94e0579c125bf94acbfeeff | 579bd5cec65859779d215c28c468b06de809749b | refs/heads/master | 2023-02-05T12:00:30.009286 | 2020-12-23T02:20:15 | 2020-12-23T02:20:15 | 325,235,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,543 | hpp | // Copyright 2020 Embotech AG, Zurich, Switzerland, inspired by Christopher Ho's mpc code
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef PARKING_PLANNER_NODE__PARKING_PLANNER_NODE_HPP_
#define PARKING_PLANNER_NODE__PARKING_PLANNER_NODE_HPP_
#include <tf2_ros/transform_listener.h>
#include <tf2_ros/buffer.h>
#include <parking_planner_node/visibility_control.hpp>
#include <parking_planner/parking_planner.hpp>
#include <trajectory_planner_node_base/trajectory_planner_node_base.hpp>
#include <visualization_msgs/msg/marker.hpp>
#include <visualization_msgs/msg/marker_array.hpp>
#include <autoware_auto_msgs/srv/had_map_service.hpp>
#include <autoware_auto_msgs/action/plan_trajectory.hpp>
#include <autoware_auto_msgs/msg/vehicle_kinematic_state.hpp>
#include <autoware_auto_msgs/msg/trajectory.hpp>
#include <autoware_auto_msgs/msg/bounding_box_array.hpp>
#include <autoware_auto_msgs/msg/bounding_box.hpp>
#include <geometry_msgs/msg/transform_stamped.hpp>
#include <lanelet2_core/LaneletMap.h>
#include <motion_common/motion_common.hpp>
#include <motion_common/config.hpp>
#include <common/types.hpp>
#include <rclcpp_action/rclcpp_action.hpp>
#include <rclcpp/rclcpp.hpp>
#include <string>
#include <memory>
#include <vector>
#include <thread>
#include <future>
using autoware::common::types::float64_t;
using motion::motion_common::VehicleConfig;
using motion::motion_common::Real;
namespace autoware
{
namespace motion
{
namespace planning
{
namespace parking_planner_node
{
using PlannerPtr = std::unique_ptr<autoware::motion::planning::parking_planner::ParkingPlanner>;
using HADMapService = autoware_auto_msgs::srv::HADMapService;
using Route = autoware_auto_msgs::msg::Route;
using State = autoware_auto_msgs::msg::VehicleKinematicState;
using ParkerNLPCostWeights = autoware::motion::planning::parking_planner::NLPCostWeights<float64_t>;
using ParkerVehicleState = autoware::motion::planning::parking_planner::VehicleState<float64_t>;
using ParkerVehicleCommand = autoware::motion::planning::parking_planner::VehicleCommand<float64_t>;
using ParkingPolytope = autoware::motion::planning::parking_planner::Polytope2D<float64_t>;
using ParkingPlanner = autoware::motion::planning::parking_planner::ParkingPlanner;
using autoware_auto_msgs::msg::TrajectoryPoint;
using AutowareTrajectory = autoware_auto_msgs::msg::Trajectory;
class PARKING_PLANNER_NODE_PUBLIC ParkingPlannerNode : public
autoware::trajectory_planner_node_base::TrajectoryPlannerNodeBase
{
public:
explicit ParkingPlannerNode(const rclcpp::NodeOptions & options);
protected:
HADMapService::Request create_map_request(const Route & route);
AutowareTrajectory plan_trajectory(
const Route & route,
const lanelet::LaneletMapPtr & lanelet_map_ptr);
PlannerPtr m_planner{nullptr};
// Debug topics
rclcpp::Publisher<visualization_msgs::msg::MarkerArray>::SharedPtr m_debug_obstacles_publisher;
rclcpp::Publisher<autoware_auto_msgs::msg::Trajectory>::SharedPtr m_debug_trajectory_publisher;
rclcpp::Publisher<autoware_auto_msgs::msg::BoundingBoxArray>::SharedPtr
m_debug_start_end_publisher;
private:
PARKING_PLANNER_NODE_LOCAL void init(
const VehicleConfig & vehicle_param,
const ParkerNLPCostWeights & optimization_weights,
const ParkerVehicleState & lower_state_bounds,
const ParkerVehicleState & upper_state_bounds,
const ParkerVehicleCommand & lower_command_bounds,
const ParkerVehicleCommand & upper_command_bounds
);
PARKING_PLANNER_NODE_LOCAL void debug_publish_obstacles(
const std::vector<ParkingPolytope> & obstacles);
PARKING_PLANNER_NODE_LOCAL void debug_publish_start_and_end(
const ParkerVehicleState & start,
const ParkerVehicleState & end);
PARKING_PLANNER_NODE_LOCAL void debug_publish_trajectory(
const AutowareTrajectory & trajectory);
}; // class parkingPlannerNode
} // namespace parking_planner_node
} // namespace planning
} // namespace motion
} // namespace autoware
#endif // PARKING_PLANNER_NODE__PARKING_PLANNER_NODE_HPP_
| [
"[email protected]"
] | |
968eb35cf8b76e233ff7210daa5c72cd76588090 | 198806ccd0b5a7d476c701be5943e9a7afacb7d0 | /xdaq/include/tts/fmm/FMMOpenInputsTest.hh | 97ee21b30d459814824a7f7f13fb93f0ea5e26ee | [] | no_license | marcomuzio/EMULib_CLCT_Timing | df5999b5f1187725d7f5b6196ba566045ba60f55 | 04e930d46cadaa0c73b94a0c22e4478f55fac844 | refs/heads/master | 2021-01-16T13:47:26.141865 | 2014-08-14T12:04:33 | 2014-08-14T12:04:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,394 | hh | #ifndef _FMMOPENINPUTSTEST_H
#define _FMMOPENINPUTSTEST_H
/**
* @class FMMOpenInputsTest
*
* @short Test the FMM with open inputs.
*
* This test tests that all inputs of the FMM go to disconnected state,
* when no caabled are connected.
*
*
* @see ---
* @author Hannes Sakulin
* $Revision: 1.1 $
* $Date: 2007/03/27 07:53:27 $
*
*
**/
#include "tts/fmm/FMMBasicTest.hh"
#include "tts/fmm/FMMCard.hh"
#include <iostream>
#include <stdint.h>
namespace tts {
class FMMOpenInputsTest : public tts::FMMBasicTest {
public:
/// c-tor
///
/// @param card is the FMMCard to use
/// @param os is an std::ostream to which output is directed.
/// @param vlevel is the verbosity level
FMMOpenInputsTest( tts::FMMCard& card,
std::ostream& os = std::cout,
tts::FMMBasicTest::VerbosityLevel vlevel = tts::FMMBasicTest::V_ERR)
: tts::FMMBasicTest(os, vlevel), _card(card) {};
/// d-tor
virtual ~FMMOpenInputsTest() {};
/// return name
virtual std::string getName() const { return "FMMOpenInputsTest"; };
/// get the version of the test
virtual std::string getVersion() const;
protected:
/// run the test
///
/// returns true if successful, false if not
virtual bool _run(uint32_t nloops);
tts::FMMCard& _card;
};
}
#endif
| [
"[email protected]"
] | |
aee146b41c1fb54652ad8ae7293c548c59ab8619 | a2099530de430ab5bc91ce610e9548028ab71dfd | /Intensifier-AU/dependencies/DunneAudioKit/StereoDelay.h | ec11dc17f9871ce6ea62ab049de6089c8f369d0b | [
"MIT"
] | permissive | emurray2/Intensifier-AU | b79bfe4da4a324478aac19d4a4692881965735f7 | b3de8d28459145f4c7226b629b7e612783338abe | refs/heads/main | 2023-05-29T23:16:30.561434 | 2021-06-05T01:35:36 | 2021-06-05T01:35:36 | 373,341,783 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 902 | h | // Copyright AudioKit. All Rights Reserved.
#pragma once
#include "AdjustableDelayLine.h"
namespace DunneCore
{
class StereoDelay {
float feedbackFraction;
float dryWetMixFraction;
bool pingPongMode;
AdjustableDelayLine delayLine1, delayLine2;
public:
StereoDelay() : feedbackFraction(0.0f), dryWetMixFraction(0.5f), pingPongMode(false) {}
~StereoDelay() { deinit(); }
void init(double sampleRate, double maxDelayMs);
void deinit();
void clear();
void setPingPongMode(bool pingPong);
void setDelayMs(double delayMs);
void setFeedback(float fraction);
void setDryWetMix(float fraction);
bool getPingPongMode() { return pingPongMode; }
void render(int sampleCount, const float *inBuffers[], float *outBuffers[]);
};
}
| [
"[email protected]"
] | |
3ce36b6b794542049780d952a417a98dd0b64e32 | c681508bf3ad18a832389c402a5029acf6e8c72f | /testing/testing_ztranspose.cpp | 68d8268319f0408a324fd183775077738d9d148e | [] | no_license | xulunfan/magma | 6f058ed0e288ecfc88a4ecc3711ad17faf74cb18 | b4e228e14cc1046861c8f38803743d784b06b9bf | refs/heads/master | 2021-01-21T15:50:21.484822 | 2016-02-10T15:08:42 | 2016-02-10T15:08:42 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,915 | cpp | /*
-- MAGMA (version 2.0.0) --
Univ. of Tennessee, Knoxville
Univ. of California, Berkeley
Univ. of Colorado, Denver
@date February 2016
@precisions normal z -> s d c
@author Mark Gates
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
// includes, project
#include "magma.h"
#include "magma_lapack.h"
#include "magma_operators.h" // conj
#include "testings.h"
#define COMPLEX
/* ////////////////////////////////////////////////////////////////////////////
-- Testing ztranspose
Code is very similar to testing_zsymmetrize.cpp
*/
int main( int argc, char** argv)
{
TESTING_INIT();
// OpenCL use: cl_mem , offset (two arguments);
// else use: pointer + offset (one argument).
#ifdef HAVE_clBLAS
#define d_A(i_, j_) d_A, ((i_) + (j_)*ldda)
#define d_B(i_, j_) d_B, ((i_) + (j_)*lddb)
#else
#define d_A(i_, j_) (d_A + (i_) + (j_)*ldda)
#define d_B(i_, j_) (d_B + (i_) + (j_)*lddb)
#endif
real_Double_t gbytes, gpu_perf, gpu_time, gpu_perf2=0, gpu_time2=0, cpu_perf, cpu_time;
double error, error2, work[1];
magmaDoubleComplex c_neg_one = MAGMA_Z_NEG_ONE;
magmaDoubleComplex *h_A, *h_B, *h_R;
magmaDoubleComplex_ptr d_A, d_B;
magma_int_t M, N, size, lda, ldda, ldb, lddb;
magma_int_t ione = 1;
magma_int_t status = 0;
magma_opts opts;
opts.parse_opts( argc, argv );
#ifdef COMPLEX
magma_int_t ntrans = 2;
magma_trans_t trans[] = { Magma_ConjTrans, MagmaTrans };
#else
magma_int_t ntrans = 1;
magma_trans_t trans[] = { MagmaTrans };
#endif
printf("%% Inplace transpose requires M == N.\n");
printf("%% Trans M N CPU GByte/s (ms) GPU GByte/s (ms) check Inplace GB/s (ms) check\n");
printf("%%=========================================================================================\n");
for( int itest = 0; itest < opts.ntest; ++itest ) {
for( int itran = 0; itran < ntrans; ++itran ) {
for( int iter = 0; iter < opts.niter; ++iter ) {
M = opts.msize[itest];
N = opts.nsize[itest];
lda = M;
ldda = magma_roundup( M, opts.align ); // multiple of 32 by default
ldb = N;
lddb = magma_roundup( N, opts.align ); // multiple of 32 by default
// load entire matrix, save entire matrix
gbytes = sizeof(magmaDoubleComplex) * 2.*M*N / 1e9;
TESTING_MALLOC_CPU( h_A, magmaDoubleComplex, lda*N ); // input: M x N
TESTING_MALLOC_CPU( h_B, magmaDoubleComplex, ldb*M ); // output: N x M
TESTING_MALLOC_CPU( h_R, magmaDoubleComplex, ldb*M ); // output: N x M
TESTING_MALLOC_DEV( d_A, magmaDoubleComplex, ldda*N ); // input: M x N
TESTING_MALLOC_DEV( d_B, magmaDoubleComplex, lddb*M ); // output: N x M
/* Initialize the matrix */
for( int j = 0; j < N; ++j ) {
for( int i = 0; i < M; ++i ) {
h_A[i + j*lda] = MAGMA_Z_MAKE( i + j/10000., j );
}
}
for( int j = 0; j < M; ++j ) {
for( int i = 0; i < N; ++i ) {
h_B[i + j*ldb] = MAGMA_Z_MAKE( i + j/10000., j );
}
}
magma_zsetmatrix( N, M, h_B, ldb, d_B(0,0), lddb );
/* =====================================================================
Performs operation using naive out-of-place algorithm
(LAPACK doesn't implement transpose)
=================================================================== */
cpu_time = magma_wtime();
//for( int j = 1; j < N-1; ++j ) { // inset by 1 row & col
// for( int i = 1; i < M-1; ++i ) { // inset by 1 row & col
if ( trans[itran] == MagmaTrans ) {
for( int j = 0; j < N; ++j ) {
for( int i = 0; i < M; ++i ) {
h_B[j + i*ldb] = h_A[i + j*lda];
}
}
}
else {
for( int j = 0; j < N; ++j ) {
for( int i = 0; i < M; ++i ) {
h_B[j + i*ldb] = conj( h_A[i + j*lda] );
}
}
}
cpu_time = magma_wtime() - cpu_time;
cpu_perf = gbytes / cpu_time;
/* ====================================================================
Performs operation using MAGMA, out-of-place
=================================================================== */
magma_zsetmatrix( M, N, h_A, lda, d_A(0,0), ldda );
magma_zsetmatrix( N, M, h_B, ldb, d_B(0,0), lddb );
magmablasSetKernelStream( opts.queue );
gpu_time = magma_sync_wtime( opts.queue );
if ( trans[itran] == MagmaTrans ) {
//magmablas_ztranspose( M-2, N-2, d_A(1,1), ldda, d_B(1,1), lddb ); // inset by 1 row & col
magmablas_ztranspose( M, N, d_A(0,0), ldda, d_B(0,0), lddb );
}
#ifdef HAVE_CUBLAS
else {
//magmablas_ztranspose_conj( M-2, N-2, d_A(1,1), ldda, d_B(1,1), lddb ); // inset by 1 row & col
magmablas_ztranspose_conj( M, N, d_A(0,0), ldda, d_B(0,0), lddb );
}
#endif
gpu_time = magma_sync_wtime( opts.queue ) - gpu_time;
gpu_perf = gbytes / gpu_time;
/* ====================================================================
Performs operation using MAGMA, in-place
=================================================================== */
if ( M == N ) {
magma_zsetmatrix( M, N, h_A, lda, d_A(0,0), ldda );
gpu_time2 = magma_sync_wtime( opts.queue );
if ( trans[itran] == MagmaTrans ) {
//magmablas_ztranspose_inplace( N-2, d_A(1,1), ldda ); // inset by 1 row & col
magmablas_ztranspose_inplace( N, d_A(0,0), ldda );
}
#ifdef HAVE_CUBLAS
else {
//magmablas_ztranspose_conj_inplace( N-2, d_A(1,1), ldda ); // inset by 1 row & col
magmablas_ztranspose_conj_inplace( N, d_A(0,0), ldda );
}
#endif
gpu_time2 = magma_sync_wtime( opts.queue ) - gpu_time2;
gpu_perf2 = gbytes / gpu_time2;
}
/* =====================================================================
Check the result
=================================================================== */
// check out-of-place transpose (d_B)
size = ldb*M;
magma_zgetmatrix( N, M, d_B(0,0), lddb, h_R, ldb );
blasf77_zaxpy( &size, &c_neg_one, h_B, &ione, h_R, &ione );
error = lapackf77_zlange("f", &N, &M, h_R, &ldb, work );
if ( M == N ) {
// also check in-place tranpose (d_A)
magma_zgetmatrix( N, M, d_A(0,0), ldda, h_R, ldb );
blasf77_zaxpy( &size, &c_neg_one, h_B, &ione, h_R, &ione );
error2 = lapackf77_zlange("f", &N, &M, h_R, &ldb, work );
printf("%5c %5d %5d %7.2f (%7.2f) %7.2f (%7.2f) %6s %7.2f (%7.2f) %s\n",
lapacke_trans_const( trans[itran] ),
(int) M, (int) N,
cpu_perf, cpu_time*1000., gpu_perf, gpu_time*1000.,
(error == 0. ? "ok" : "failed"),
gpu_perf2, gpu_time2,
(error2 == 0. ? "ok" : "failed") );
status += ! (error == 0. && error2 == 0.);
}
else {
printf("%5c %5d %5d %7.2f (%7.2f) %7.2f (%7.2f) %6s --- ( --- )\n",
lapacke_trans_const( trans[itran] ),
(int) M, (int) N,
cpu_perf, cpu_time*1000., gpu_perf, gpu_time*1000.,
(error == 0. ? "ok" : "failed") );
status += ! (error == 0.);
}
TESTING_FREE_CPU( h_A );
TESTING_FREE_CPU( h_B );
TESTING_FREE_CPU( h_R );
TESTING_FREE_DEV( d_A );
TESTING_FREE_DEV( d_B );
fflush( stdout );
}
if ( opts.niter > 1 ) {
printf( "\n" );
}
}
}
opts.cleanup();
TESTING_FINALIZE();
return status;
}
| [
"[email protected]"
] | |
76b56cb1f66f37a2be5f3690bfbf9eac9ff19db4 | 2891a607848b80209db7a8e260fb63c5dac018c6 | /Assignment/Ray.cpp | 4a269776c9860598839e1ab20c22c5602b0b38c1 | [] | no_license | zeynepakkalyoncu/RayTracer | fd2a6c05c9f62585f76916bfd49d337f97aabcbf | f006bddd0c7a470c91b1feba0232b4a0870047ef | refs/heads/master | 2021-06-07T18:04:35.297096 | 2016-11-22T20:23:47 | 2016-11-22T20:23:47 | 71,885,153 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 483 | cpp | //
// Created by Fatih on 10/27/15.
//
#include "Ray.h"
Ray::Ray(const Vector3 &origin, const Vector3 &direction)
: _origin(origin), _direction(direction)
{
}
void Ray::Direction(const Vector3 &dir)
{
_direction = dir;
_inv_direction.X(1 / dir.X());
_inv_direction.Y(1 / dir.Y());
_inv_direction.Z(1 / dir.Z());
}
std::ostream &operator<<(std::ostream &out, const Ray &ray)
{
out << "(" << ray.Origin() << ", " << ray.Direction() << ")";
return out;
}
| [
"[email protected]"
] | |
2312944b1afccd8e4aca30a221176ecce272a9ca | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5686313294495744_0/C++/anhhungcolao7/A.cpp | 67b78f6b16eeac960377e8fbd763cce32e3a1d2c | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 8,811 | cpp |
#include <bits/stdc++.h>
#define fi "a.inp"
#define fo "a.out"
#define For(i,a,b) for(int i=a;i<=b;i++)
#define Ford(i,a,b) for(int i=a;i>=b;i--)
#define All(x) x.begin(),x.end()
#define st first
#define nd second
#define It interator
#define sl_int(x) __builtin_popcount(x)
#define el endl
#define in cin
#define out cout
#define sz size()
#define in_vt(x) For(i,0,(int) x.sz - 1) printf("%d ",x[i]);puts("");
using namespace std;
typedef pair<int,int> II;
typedef pair<int,II> III;
typedef long long ll;
typedef pair<ll,ll> LL;
typedef map<int,int> mii;
typedef map<ll,int> mli;
typedef map<ll,ll> mll;
typedef vector <int> vti;
typedef vector <ll> vtl;
typedef queue <int> qi;
typedef deque <int> dqi;
typedef set <int> si;
typedef multiset <int> msi;
typedef queue <ll> ql;
typedef deque <ll> dql;
typedef set <ll> sl;
typedef multiset <ll> msl;
struct Point
{
int x,y;
bool operator <(const Point &T) const {
if (x==T.x) return (y<T.y);
return (x<T.x);
}
};
struct Matrix{
ll d[4][4];
int mod;
Matrix operator *(const Matrix &A) const{
Matrix ans;
ans.mod = mod;
For(i,0,3) For(j,0,3) ans.d[i][j] = 0;
For(i,0,3) {
For(j,0,3) {
For(k,0,3) {
ans.d[i][j] += (A.d[i][k] * d[k][j]);
ans.d[i][j]%=mod;
}
}
}
return ans;
}
Matrix operator ^(const int n) const{
Matrix ans;
ans.mod = mod;
For(i,0,3) For(j,0,3) ans.d[i][j] = d[i][j];
if (n==1) return ans;
Matrix t = ans ^ (n/2);
if (n%2==0) return (t*t);
return (t*t*ans);
}
};
double INF = 1e100;
double EPS = 1e-7;
struct PT {
double x, y;
PT (){}
PT (double x, double y) : x(x), y(y){}
PT (const PT &p) : x(p.x), y(p.y){}
PT operator - (const PT &p){ return PT(x - p.x, y - p.y);}
PT operator + (const PT &p){ return PT(x + p.x, y + p.y);}
PT operator * (double c){ return PT(x * c, y * c); }
PT operator / (double c){ return PT(x/c, y/c); }
bool operator == (const PT &p) {return x == p.x && y == p.y; }
bool operator != (const PT &p) {return x != p.x || y != p.y; }
};
double dot(PT p, PT q){ return p.x*q.x+p.y*q.y; }
double dist2(PT p, PT q){ return dot(p-q,p-q); }
double cross(PT p, PT q){ return p.x*q.y-p.y*q.x; }
ostream &operator<< (ostream &os, const PT &p){
os << "("<< p.x << ","<< p.y << ")";
}
// rotate a point CCW or CW around the origin
PT RotateCCW90(PT p){ return PT(-p.y,p.x); } //+90
PT RotateCW90(PT p){ return PT(p.y, -p.x); } // -90
PT RotateCCW(PT p, double t){
return PT(p.x * cos(t) - p.y * sin(t), p.x*sin(t)+p.y*cos(t));
}
PT RotateCCW90(PT origin, PT pt){
pt = pt - origin; pt = RotateCCW90(pt);
pt = pt + origin; return pt;
}
bool isSquare(PT pt1, PT pt2, PT pt3, PT pt4){
PT center = pt1 + pt2 + pt3 + pt4;
center = center * 0.25;
if(center == pt1) return false;
PT pt = RotateCCW90(center, pt1); if(pt != pt2 && pt != pt3 && pt != pt4) return false;
pt = RotateCCW90(center, pt); if(pt != pt2 && pt != pt3 && pt != pt4) return false;
pt = RotateCCW90(center, pt); if(pt != pt2 && pt != pt3 && pt != pt4) return false;
return true;
}
bool isRectangle(PT pt1, PT pt2, PT pt3, PT pt4){
PT center = pt1 + pt2 + pt3 + pt4;
center = center * 0.25;
if(center == pt1) return false;
if(pt1 + pt2 == (center * 2.0) && pt3 + pt4 == (center * 2.0) && dist2(pt1, pt2) == dist2(pt3, pt4)) return true;
if(pt1 + pt3 == (center * 2.0) && pt2 + pt4 == (center * 2.0) && dist2(pt1, pt3) == dist2(pt2, pt4)) return true;
if(pt1 + pt4 == (center * 2.0) && pt2 + pt3 == (center * 2.0) && dist2(pt1, pt4) == dist2(pt3, pt2)) return true;
return false;
}
double area(PT a, PT b, PT c){
PT ab = b - a, ac = c - a;
return 0.5 * (abs(cross(ab, ac)));
}
// project point c onto line through a and b
// assuming a != b
PT ProjectPointLine(PT a, PT b, PT c){
return a + (b-a) * dot(c-a,b-a)/dot(b-a,b-a);
}
// project point c onto line segment through a and b
PT ProjectPointSegment(PT a, PT b, PT c){
double r = dot(b-a,b-a);
if(fabs(r) < EPS) return a;
r = dot(c-a,b-a)/r;
if(r < 0) return a;
if(r > 1) return b;
return a + (b-a)*r;
}
// compute distance between point (x,y,z) and plane ax+by+cz=d
double DistancePointPlane(double x, double y, double z, double a, double b, double c, double d){
return fabs(a*x+b*y+c*z-d)/sqrt(a*a+b*b+c*c);
}
// determine if two lines are parallel or collinear
bool LinesParallel(PT a, PT b, PT c, PT d){
return fabs(cross(b-a,c-d)) < EPS;
}
bool LinesCollinear(PT a, PT b, PT c, PT d){
return LinesParallel(a,b,c,d) && fabs(cross(a-c,d-c)) < EPS;
}
// determine if line segment from a to b intersects with
// line segment from c to d
bool SegmentsIntersect(PT a, PT b, PT c, PT d){
if(cross(d-a,b-a) * cross(c-a,b-a) > 0) return false;
if(cross(a-c,d-c) * cross(b-c,d-c) > 0) return false;
return true;
}
// compute intersection of line passing through a and b
// with line passing through c and d, assuming that unique
// intersection exists
PT ComputeLineIntersection(PT a, PT b, PT c, PT d){
b=b-a; d=c-d; c=c-a;
if(dot(b,b) < EPS) return a;
if(dot(d,d) < EPS) return c;
return a + b*cross(c,d)/cross(b,d);
}
// compute center of circle given three points
PT ComputeCircleCenter(PT a, PT b, PT c){
b=(a+b)/2;
c=(a+c)/2;
return ComputeLineIntersection (b,b + RotateCW90(a-b), c, c + RotateCW90(a-c));
}
// determine if point is in a possibly non-convex polygon
// (by William Randolph Franklin); returns 1 for strictly
// interior points, 0 for strictly exterior points, and
// 0 or 1 for the remaining points
// note that it is possible to convert this into an *exact*
// test using integer arithmetic by taking care of the
// division appropriately (making sure to deal with signs
// properly) and then by writing exact tests for checking
// point on polygon boundary
bool PointInPolygon(const vector<PT> &p, PT q){
bool c = 0;
for(int i = 0; i < p.size(); i++){
int j = (i+1) % p.size();
if((p[i].y <= q.y && q.y < p[j].y || p[j].y <= q.y && q.y < p[i].y) &&
q.x < p[i].x + (p[j].x - p[i].x) * (q.y - p[i].y) / (p[j].y - p[i].y)) c = !c;
}
return c;
}
// determine if point is on the boundary of a polygon
bool PointOnPolygon(const vector<PT> &p, PT q){
for(int i = 0; i < p.size(); i++)
if(dist2(ProjectPointSegment (p[i], p[(i+1)%p.size()], q), q) < EPS) return true;
return false;
}
// compute intersection of line through points a and b with
// circle centered at c with radius r > 0
vector<PT> CircleLineIntersection (PT a, PT b, PT c, double r){
vector<PT> ret;
PT d = b-a;
double D = cross(a-c,b-c);
double e = r*r*dot(d,d)-D*D;
if(e < 0) return ret;
e = sqrt(e);
ret.push_back (c+PT(D*d.y+(d.y>=0?1:-1)*d.x*e,-D*d.x+fabs(d.y)*e)/dot(d,d));
if(e > 0)
ret.push_back (c+PT(D*d.y-(d.y>=0?1:-1)*d.x*e,-D*d.x-fabs(d.y)*e)/dot(d,d));
return ret;
}
// compute intersection of circle centered at a with radius r
// with circle centered at b with radius R
// Khong xet truong hop a == b && r == R
vector<PT> CircleCircleIntersection (PT a, PT b, double r, double R){
vector<PT> ret;
double d = sqrt(dist2(a,b));
if(d > r+R || d+min(r,R) < max(r,R)) return ret;
double x = (d*d-R*R+r*r)/(2*d);
double y = sqrt(r*r-x*x);
PT v = (b-a)/d;
ret.push_back (a+v*x + RotateCCW90(v)*y);
if(y > 0)
ret.push_back (a+v*x - RotateCCW90(v)*y);
return ret;
}
double dist(double xa, double ya, double xb, double yb) {
xa -= xb; ya -= yb;
return sqrt(xa * xa + ya * ya);
}
double angle(double ox, double oy, double ax, double ay, double bx, double by){ // goc AOB
double a, b, c, alpha;
a = dist(ax, ay, bx, by);
b = dist(ox, oy, ax, ay);
c = dist(ox, oy, bx, by);
alpha = acos((a * a - b * b - c * c) / (-2.0 * b * c));
return alpha;
}
int getbit(int n,int k) {
return (n>>(k-1))&1;
}
set <string> m,m1;
string s[20],s1[20];
int test,n;
int main()
{
freopen (fi, "r", stdin);
freopen (fo, "w", stdout);
scanf("%d", &test);
For(Test,1,test) {
scanf("%d", &n);
For(i,1,n) {
cin>>s[i];cin>>s1[i];
}
int ans = 0;
For(i,0,(1<<n)-1) {
m.clear();
m1.clear();
For(j,1,n)
if (getbit(i,j)) {
m.insert(s[j]);
m1.insert(s1[j]);
}
bool ok = 1;
int sl = 0;
For(j,1,n) if (!getbit(i,j)) {
if (m.find(s[j])!=m.end()&&m1.find(s1[j])!=m1.end()) {
sl++;
} else {
ok = 0; break;
}
}
if (ok) ans = max(ans,sl);
}
printf("Case #%d: ",Test);
cout<<ans<<endl;
}
return 0;
}
| [
"[email protected]"
] | |
342165b632257024cea569ad1a6d9f0c478cf0b6 | 874aa59e5b3ed5b6c0307467c53a6a61ede5d969 | /WinSpy/WindowsView.h | 153406058a3baf5c63057d846478c282ca9dd62e | [
"MIT"
] | permissive | rajendra1185/WinSpy | da1ec45074ccb88c65c716f3835b442ce82772f5 | 03f28735c593ec6a5dc8436efe7f3456f985919d | refs/heads/master | 2023-06-12T03:49:39.994658 | 2021-06-26T18:14:08 | 2021-06-26T18:14:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,369 | h | // View.h : interface of the CView class
//
/////////////////////////////////////////////////////////////////////////////
#pragma once
#include "VirtualListView.h"
#include "TreeViewManager.h"
#include "ViewBase.h"
class CWindowsView :
public CViewBase<CWindowsView>,
public CVirtualListView<CWindowsView>,
public CCustomDraw<CWindowsView>,
public CTreeViewManager<CWindowsView> {
public:
CWindowsView(IMainFrame* frame) : CViewBase(frame) {}
BOOL PreTranslateMessage(MSG* pMsg);
CString GetColumnText(HWND, int row, int col) const;
int GetRowImage(HWND, int row) const;
void OnActivate(bool activate);
void DoSort(const SortInfo* si);
bool IsSortable(int col) const;
DWORD OnPrePaint(int, LPNMCUSTOMDRAW cd);
DWORD OnItemPrePaint(int, LPNMCUSTOMDRAW cd);
virtual void OnFinalMessage(HWND /*hWnd*/);
enum { IDC_TREE = 123 };
BEGIN_MSG_MAP(CWindowsView)
MESSAGE_HANDLER(WM_TIMER, OnTimer)
MESSAGE_HANDLER(WM_CREATE, OnCreate)
NOTIFY_CODE_HANDLER(TVN_ITEMEXPANDING, OnNodeExpanding)
NOTIFY_CODE_HANDLER(TVN_DELETEITEM, OnNodeDeleted)
NOTIFY_CODE_HANDLER(TVN_SELCHANGED, OnNodeSelected)
NOTIFY_HANDLER(IDC_TREE, NM_RCLICK, OnTreeNodeRightClick)
COMMAND_ID_HANDLER(ID_VIEW_REFRESH, OnRefresh)
COMMAND_ID_HANDLER(ID_WINDOW_SHOW, OnWindowShow)
COMMAND_ID_HANDLER(ID_WINDOW_HIDE, OnWindowHide)
COMMAND_ID_HANDLER(ID_WINDOW_BRINGTOFRONT, OnWindowBringToFront)
COMMAND_ID_HANDLER(ID_WINDOW_MINIMIZE, OnWindowMinimize)
COMMAND_ID_HANDLER(ID_WINDOW_MAXIMIZE, OnWindowMaximize)
COMMAND_ID_HANDLER(ID_STATE_FLASH, OnWindowFlash)
COMMAND_ID_HANDLER(ID_WINDOW_RESTORE, OnWindowRestore)
COMMAND_ID_HANDLER(ID_VIEW_HIDDENWINDOWS, OnToggleHiddenWindows)
COMMAND_ID_HANDLER(ID_VIEW_EMPTYTITLEWINDOWS, OnToggleEmptyTitleWindows)
COMMAND_ID_HANDLER(ID_VIEW_CHILDWINDOWS, OnToggleChildWindows)
CHAIN_MSG_MAP(CVirtualListView<CWindowsView>)
CHAIN_MSG_MAP(CCustomDraw<CWindowsView>)
CHAIN_MSG_MAP(CTreeViewManager<CWindowsView>)
CHAIN_MSG_MAP(CViewBase<CWindowsView>)
END_MSG_MAP()
private:
enum class WindowListType {
Parent = 1,
AllChildren = 2,
DirectChildren = 4,
};
enum class DataItemType {
Handle, ClassName, Text, Style, ExtendedStyle, ProcessName,
ProcessId, ThreadId, ParentWindow, FirstChildWindow, NextWindow, PrevWindow, OwnerWindow,
WindowProc, UserData, ID, Rectangle,
ClassAtom, ClassStyle, ClassExtra, WindowExtra,
};
struct DataItem {
CString Property;
DataItemType Type;
};
void UpdateUI();
void Refresh();
void InitTree();
void AddChildWindows(HTREEITEM hParent);
CTreeItem AddNode(HWND hWnd, HTREEITEM hParent);
BOOL AddChildNode(HWND hChild);
void AddChildWindows(std::vector<HWND>& v, HWND hParent, bool directOnly = false);
void UpdateList();
CString GetDetails(const DataItem& item) const;
static CString GetWindowClassAndTitle(HWND);
// Handler prototypes (uncomment arguments if needed):
// LRESULT MessageHandler(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/)
// LRESULT CommandHandler(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
// LRESULT NotifyHandler(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/)
LRESULT OnCreate(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnTimer(UINT /*uMsg*/, WPARAM /*wParam*/, LPARAM /*lParam*/, BOOL& /*bHandled*/);
LRESULT OnNodeExpanding(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
LRESULT OnNodeDeleted(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
LRESULT OnNodeSelected(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
LRESULT OnWindowShow(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowHide(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowMinimize(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowMaximize(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowRestore(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleHiddenWindows(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnRefresh(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleEmptyTitleWindows(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnToggleChildWindows(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnTreeNodeRightClick(int /*idCtrl*/, LPNMHDR /*pnmh*/, BOOL& /*bHandled*/);
LRESULT OnWindowFlash(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
LRESULT OnWindowBringToFront(WORD /*wNotifyCode*/, WORD /*wID*/, HWND /*hWndCtl*/, BOOL& /*bHandled*/);
CSplitterWindow m_Splitter;
CListViewCtrl m_List;
CTreeViewCtrlEx m_Tree;
inline static CImageList s_Images;
CTreeItem m_hCurrentNode;
CTreeItem m_DesktopNode;
CTreeItem m_Selected;
CWindow m_SelectedHwnd;
std::unordered_map<HWND, HTREEITEM> m_WindowMap;
inline static std::unordered_map<HWND, int> s_IconMap;
std::vector<HWND> m_Items;
DWORD m_TotalWindows, m_TotalVisibleWindows, m_TopLevelWindows;
bool m_ShowHiddenWindows : 1 { false };
bool m_ShowNoTitleWindows : 1 { true };
bool m_ShowChildWindows : 1 { true };
bool m_Deleting{ false };
};
| [
"[email protected]"
] | |
9bc2a438c4749a35c11f7f2b940a1d9af058673d | dd6147bf9433298a64bbceb7fdccaa4cc477fba6 | /8381/Maria_Lisok/lr2/game_oop 4/Base/base.cpp | 40c1db8054dc6b89f9ce77119738d43a366851ed | [] | no_license | moevm/oop | 64a89677879341a3e8e91ba6d719ab598dcabb49 | faffa7e14003b13c658ccf8853d6189b51ee30e6 | refs/heads/master | 2023-03-16T15:48:35.226647 | 2020-06-08T16:16:31 | 2020-06-08T16:16:31 | 85,785,460 | 42 | 304 | null | 2023-03-06T23:46:08 | 2017-03-22T04:37:01 | C++ | UTF-8 | C++ | false | false | 1,712 | cpp | #include "base.h"
Base::Base(int maxUnitsCount, int health, int xx, int yy, int baseNumb) : baseNumb(baseNumb),
unitCount(0), maxCount(maxUnitsCount),
unitCurr(0),health(health), x(xx), y(yy)
{
units = new CompositeUnit();
}
int Base::getBaseNumb() const
{
return baseNumb;
}
int Base::getX() const
{
return x;
}
int Base::getY() const
{
return y;
}
int Base::getUnitCount() const
{
return unitCount;
}
int Base::getMaxCount() const
{
return maxCount;
}
int Base::getHealth() const
{
return health;
}
Unit *Base::createUnit(string unitName)
{
AbstractArmy* humanityArmy = new HumanityArmy();
AbstractArmy* creaturesArmy = new CreaturesArmy();
Unit* unit = nullptr;
if (unitName == "Archer"){
unit = humanityArmy->createArrow();
}
else if (unitName == "Shaman"){
unit = creaturesArmy->createArrow();
}
else if (unitName == "Knigth"){
unit = humanityArmy->createCavelry();
}
else if (unitName == "Rider"){
unit = creaturesArmy->createCavelry();
}
else if (unitName == "Swardman"){
unit = humanityArmy->createInfantry();
}
else if (unitName == "Ork"){
unit = creaturesArmy->createInfantry();
}
units->addUnit(unit);
unitCount++;
return unit;
}
void Base::addUnit(Unit *u)
{
units->addUnit(u);
unitCount++;
}
void Base::deleteUnit(Subject * unit)
{
if (units->delUnit(unit)){
unitCount--;
}
}
Unit *Base::getCurrUnit()
{
return units->getUnit(unitCurr);
}
bool Base::getDamage(int numb)
{
this->health -= numb;
if (this->health <= 0){
this->health = 0;
return true;
}
return false;
}
| [
"[email protected]"
] | |
3cf68fc72c88b7b3cf752697dd486969d25d17d5 | 5945d6e644a25dcc1b1552205b6f96fffe159f5f | /src/lib/lists/listsmemberships.h | bce0f8ea8c43617b85f702bfd32805a2b3eb4c68 | [
"BSD-3-Clause"
] | permissive | yuntan/twitter4qml | 5cba11e7f10eb53b547484ce680b115f3511d9c9 | 67a7ea7c5467293f6b288435e73bc9db18639985 | refs/heads/master | 2016-09-08T01:20:37.275268 | 2014-02-18T09:03:39 | 2014-02-18T09:03:39 | 16,941,630 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,389 | h | /* Copyright (c) 2012-2013 Twitter4QML Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the Twitter4QML nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL TWITTER4QML BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef LISTSMEMBERSHIPS_H
#define LISTSMEMBERSHIPS_H
#include "abstractlistsmodel.h"
class TWITTER4QML_EXPORT ListsMemberships : public AbstractListsModel
{
Q_OBJECT
Q_PROPERTY(QString user_id READ user_id WRITE user_id NOTIFY user_idChanged)
Q_PROPERTY(QString screen_name READ screen_name WRITE screen_name NOTIFY screen_nameChanged)
Q_PROPERTY(QString cursor READ cursor WRITE cursor NOTIFY cursorChanged)
Q_PROPERTY(bool filter_to_owned_lists READ filter_to_owned_lists WRITE filter_to_owned_lists NOTIFY filter_to_owned_listsChanged)
Q_PROPERTY(int next_cursor READ next_cursor NOTIFY next_cursorChanged DESIGNABLE false)
Q_PROPERTY(QString next_cursor_str READ next_cursor_str NOTIFY next_cursor_strChanged DESIGNABLE false)
Q_PROPERTY(int previous_cursor READ previous_cursor NOTIFY previous_cursorChanged DESIGNABLE false)
Q_PROPERTY(QString previous_cursor_str READ previous_cursor_str NOTIFY previous_cursor_strChanged DESIGNABLE false)
Q_DISABLE_COPY(ListsMemberships)
public:
explicit ListsMemberships(QObject *parent = 0);
signals:
void user_idChanged(const QString &user_id);
void screen_nameChanged(const QString &screen_name);
void cursorChanged(const QString &cursor);
void filter_to_owned_listsChanged(bool filter_to_owned_lists);
void next_cursorChanged(int next_cursor) const;
void next_cursor_strChanged(const QString &next_cursor_str) const;
void previous_cursorChanged(int previous_cursor) const;
void previous_cursor_strChanged(const QString &previous_cursor_str) const;
protected:
QUrl api() const { return QUrl("https://api.twitter.com/1.1/lists/memberships.json"); }
void parseDone(const QVariant &result);
ADD_PROPERTY(bool, filter_to_owned_lists, bool)
};
#endif // LISTSMEMBERSHIPS_H
| [
"[email protected]"
] | |
4af1ed6edd07555eef66652823c55126bf7a1604 | f99ee67eda1ec1aee36fc2fec30962c59554fd83 | /c/局部最大值.cpp | 3a424d7e5a668315c2df3dd2f659a27542d43953 | [] | no_license | embarce/css | ae2572d18d887e82529ef35de50ae2e826ec3212 | a4a12d9afaaaa54e40a538ecd8aee59d02a0eacb | refs/heads/master | 2021-04-09T13:47:31.928460 | 2018-03-19T04:55:31 | 2018-03-19T04:55:31 | 125,518,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | #include<stdio.h>
int main()
{
int i, j, m, n, t;
scanf("%d%d", &m, &n);
int a[m][n];
for(i = 0; i < m; i++)
for(j = 0; j < n; j++)
scanf("%d", &a[i][j]);
t = 0;
for(i=1;i<m-1;i++)
{
for(j=1;j<n-1; j++)
{
if(a[i][j]>a[i-1][j]&&a[i][j]>a[i+1][j]&&a[i][j]>a[i][j-1]&&a[i][j] > a[i][j + 1])
{
t = 1;
printf("%d %d %d\n", a[i][j],i+1,j+1);
}
}
}
if(t==0)
printf("None %d %d\n", m, n);
return 0;
}
| [
"[email protected]"
] | |
a48e15deeeb6e751d69440e6c98f429ee8b894db | dc18985fd56873aae1cfb78cd7e70a0e8a2f471c | /Classes/scene/MainScene.h | 722387a1f5310d7a32e92e9256317cd5e7fefdac | [] | no_license | lonag/ChinesePoker | f614a498fb724dbe2a73370dabae26dd8dd629cb | 232ab14c0b0379087a96ee52a976dd99ad635cfb | refs/heads/master | 2021-01-21T11:15:21.069228 | 2017-03-10T15:03:16 | 2017-03-10T15:03:16 | 83,538,708 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 415 | h | #ifndef _main_scene_h_
#define _main_scene_h_
#include "cocos2d.h"
#include "ui/CocosGUI.h"
#include "cocostudio/CocoStudio.h"
USING_NS_CC;
using namespace ui;
using namespace cocostudio;
class MainScene:public Layer
{
public:
static Scene* scene();
bool init();
void createview();
CREATE_FUNC(MainScene);
public:
Layout* main_ui;
void onClick(Ref *sender, TouchEventType type);
};
#endif | [
"[email protected]"
] | |
cba9abc8c76a5f1d60eed8f759e55ff45a030ce5 | 2db52bea4847d6a3e4cd806ac466142dbfde7fa2 | /src/MS5611.h | 5a49f1537dc68a745d2ca7fc5f0523c96024efea | [
"MIT"
] | permissive | pec1985/SimpleVario-Arduino | 0b55bdc28a550aaa5c1df7d51ab1d377a34830ce | a189230cd9711ded4808282fb44bca35adf34cf3 | refs/heads/main | 2023-01-12T14:46:35.284228 | 2020-11-18T23:20:55 | 2020-11-18T23:20:55 | 314,074,647 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | h | /*
ms5611.h
Library for barometric pressure sensor MS5611-01BA on I2C with arduino
by Petr Gronat@2014
*/
// Include guard token - prevents to include header file twice
#ifndef MS5611_h
#define MS5611_h //create token
// Include Arduino libraries
#include <Arduino.h>
#include "i2c_t3.h"
#define N_PROM_PARAMS 6
// address of the device MS5611
#define ADD_MS5611 0x77 // can be 0x76 if CSB pin is connected to GND
class MS5611{
public:
MS5611(); //constructor
void begin();
uint32_t getRawTemperature();
int32_t getTemperature();
uint32_t getRawPressure();
int32_t getPressure();
void readCalibration();
void getCalibration(uint16_t *);
void sendCommand(uint8_t);
uint32_t readnBytes(uint8_t);
private:
void reset();
//variables
int32_t m_P;
int32_t m_T;
int32_t m_dT;
uint16_t m_C[N_PROM_PARAMS];
uint32_t m_lastTime;
};
#endif
| [
"[email protected]"
] | |
662406b8eb85225e58d1a027cae1f18a74dbc890 | 88fb624f1b61a3f789f46e45aea58bcf9f04824b | /Test/D3D12Cube.cpp | 6feeb49ee2a504aa2f43622c21aabc65ad69272d | [
"MIT"
] | permissive | jianyuyanyu/Panda | 74d36ad42a6c3c0f115dcbee4951e438bd620d6a | 4c19e328d03749eea60a6fc9755621c5fa58dbd1 | refs/heads/master | 2020-07-12T04:19:09.625966 | 2019-07-03T13:13:39 | 2019-07-03T13:13:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 52,660 | cpp | #include <windows.h>
#include <windowsx.h>
#include <stdio.h>
#include <tchar.h>
#include <stdint.h>
#include <array>
#include <vector>
#include <xstring>
#include <DirectXMath.h>
#include <DirectXPackedVector.h>
#include <DirectXColors.h>
#include <DirectXCollision.h>
#include <d3d12.h>
#include <DXGI1_4.h>
#include <d3dcompiler.h>
#include <wrl/client.h>
#include <exception>
#include "Utility.hpp"
#include "PandaMath.hpp"
#include "d3dx12.h"
using namespace DirectX;
using namespace DirectX::PackedVector;
namespace Panda
{
Handness g_ViewHandness = Handness::kHandnessRight;
DepthClipSpace g_DepthClipSpace = DepthClipSpace::kDepthClipZeroToOne;
}
using namespace Panda;
const uint32_t nScreenWidth = 960;
const uint32_t nScreenHeight = 480;
const uint32_t nFrameCount = 2;
HWND g_hWnd; // window handle
IDXGIFactory4* g_pFactory = nullptr; // factory
ID3D12Device* g_pDevice = nullptr; // Device
IDXGISwapChain* g_pSwapChain = nullptr; // swap chain
/// Heaps
ID3D12DescriptorHeap* g_pRtvHeap = nullptr; // render target heap
ID3D12DescriptorHeap* g_pDsvHeap = nullptr; // depth / stencil heap
ID3D12DescriptorHeap* g_pCbvHeap = nullptr; // const buffer heap
/// resources
ID3D12Resource* g_pRenderTargets[nFrameCount] = {nullptr, nullptr}; // render target view
ID3D12Resource* g_pDefaultVertexBuffer = nullptr; // vertex buffer
ID3D12Resource* g_pUploadVertexBuffer = nullptr; // vertex buffer
ID3D12Resource* g_pDefaultIndexBuffer = nullptr; // index buffer
ID3D12Resource* g_pUploadIndexBuffer = nullptr; // index buffer
ID3D12Resource* g_pDepthStencilBuffer = nullptr; // depth stencil buffer
ID3D12Resource* g_pConstantBuffer = nullptr; // constant buffer (upload)
/// views
D3D12_VERTEX_BUFFER_VIEW g_VertexBufferView;
D3D12_INDEX_BUFFER_VIEW g_IndexBufferView;
/// commands
ID3D12CommandQueue* g_pCommandQueue = nullptr; // command queue
ID3D12CommandAllocator* g_pCommandAllocator = nullptr; // command allocator
ID3D12GraphicsCommandList* g_pCommandList = nullptr; // command list
/// root signature
ID3D12RootSignature* g_pRootSignature = nullptr; // root signature
/// pso
ID3D12PipelineState* g_pPso; // pipeline state object
/// sizes
uint32_t g_nRtvDescriptorSize;
uint32_t g_nCbvDescriptorSize;
uint32_t g_nConstantBufferSize;
/// synchronization object
uint32_t g_nFrameIndex = 0;
ID3D12Fence* g_pFence = nullptr;
uint32_t g_nFenceValue = 0;
/// screen
D3D12_VIEWPORT g_ViewPort = {0.0f, 0.0f, static_cast<float>(nScreenWidth), static_cast<float>(nScreenHeight)};
D3D12_RECT g_ScissorPort = {0, 0, nScreenWidth, nScreenHeight};
// vertex struct
struct Vertex
{
Vector3Df Pos;
Vector4Df Color;
};
struct ObjectConstants
{
Matrix4f WorldViewProj;
ObjectConstants()
{
WorldViewProj.SetIdentity();
}
};
std::array<Vertex, 8> vertices =
{
Vertex({Vector3Df({-1.0f, -1.0f, -1.0f}), Vector4Df({1.000000000f, 1.000000000f, 1.000000000f, 1.000000000f})}),
Vertex({Vector3Df({-1.0f, +1.0f, -1.0f}), Vector4Df({0.000000000f, 0.000000000f, 0.000000000f, 1.000000000f})}),
Vertex({Vector3Df({+1.0f, +1.0f, -1.0f}), Vector4Df({1.000000000f, 0.000000000f, 0.000000000f, 1.000000000f})}),
Vertex({Vector3Df({+1.0f, -1.0f, -1.0f}), Vector4Df({0.000000000f, 0.501960814f, 0.000000000f, 1.000000000f})}),
Vertex({Vector3Df({-1.0f, -1.0f, +1.0f}), Vector4Df({0.000000000f, 0.000000000f, 1.000000000f, 1.000000000f})}),
Vertex({Vector3Df({-1.0f, +1.0f, +1.0f}), Vector4Df({1.000000000f, 1.000000000f, 0.000000000f, 1.000000000f})}),
Vertex({Vector3Df({+1.0f, +1.0f, +1.0f}), Vector4Df({0.000000000f, 1.000000000f, 1.000000000f, 1.000000000f})}),
Vertex({Vector3Df({+1.0f, -1.0f, +1.0f}), Vector4Df({1.000000000f, 0.000000000f, 1.000000000f, 1.000000000f})})
};
std::array<uint16_t, 36> indices =
{
// front face
0, 1, 2,
0, 2, 3,
// back face
4, 6, 5,
4, 7, 6,
// left face
4, 5, 1,
4, 1, 0,
// right face
3, 2, 6,
3, 6, 7,
// top face
1, 5, 6,
1, 6, 2,
// bottom face
4, 0, 3,
4, 3, 7
};
// input layout
D3D12_INPUT_ELEMENT_DESC g_ieds[2] =
{
{"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
{"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0}
};
// shaders
D3D12_SHADER_BYTECODE g_VertexShaderByteCode;
D3D12_SHADER_BYTECODE g_PixelShaderByteCode;
// D3D initialization
void CreateDevice();
void CreateCommandObjects();
void CreateSwapChain();
void CreateDescriptorHeaps();
void CreateRenderTarget();
void CreateDepthStencilBuffer();
void CreateConstantBuffer();
void CreateVertexBuffer();
void CreateIndexBuffer();
void CreateRootSignature();
void InitializeShaders();
void CreatePSOs();
void PopulateCommandList();
void Update();
void Draw();
void FlushCommandQueue();
void InitDirect3D();
ID3DBlob* CompileShader(const std::wstring& filename,
const D3D_SHADER_MACRO* defines,
const std::string& entrypoint,
const std::string& target);
// The Main window
// the WindowProc function prototype
LRESULT CALLBACK WindowProc(HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam);
// the entry point for any Windows program
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow)
{
// this struct holds information for the window class
WNDCLASSEX wc;
// clear out the window class for use
ZeroMemory(&wc, sizeof(WNDCLASSEX));
// fill in the struct with the needed information
wc.cbSize = sizeof(WNDCLASSEX);
wc.style = CS_HREDRAW | CS_VREDRAW;
wc.lpfnWndProc = WindowProc;
wc.hInstance = hInstance;
wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
wc.lpszClassName = _T("WindowClass1");
// register the window class
RegisterClassEx(&wc);
// create the window and use the result as the handle
g_hWnd = CreateWindowEx(0,
_T("WindowClass1"), // name of the window class
_T("Hello, Engine![Direct 3D]"), // title of the window
WS_OVERLAPPEDWINDOW, // window style
100, // x-position of the window
100, // y-position of the window
nScreenWidth, // width of the window
nScreenHeight, // height of the window
NULL, // we have no parent window, NULL
NULL, // we aren't using menus, NULL
hInstance, // application handle
NULL); // used with multiple windows, NULL
// display the window on the screen
ShowWindow(g_hWnd, nCmdShow);
UpdateWindow(g_hWnd);
// Do the D3D initialization here
InitDirect3D();
// this struct holds Windows event messages
MSG msg = {0};
// wait for the next message in the queue, store the result in 'msg'
while(msg.message != WM_QUIT)
{
// If there are Window messages then process them.
if(PeekMessage( &msg, 0, 0, 0, PM_REMOVE ))
{
TranslateMessage( &msg );
DispatchMessage( &msg );
}
// Otherwise, do animation/game stuff.
else
{
Update();
PopulateCommandList();
Draw();
FlushCommandQueue();
}
}
// return this part of the WM_QUIT message to Windows
return msg.wParam;
}
// this is the main message handler for the program
LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
LRESULT result = 0;
bool wasHandled = false;
// sort through and find what code to run for the message given
switch(message)
{
case WM_DESTROY:
PostQuitMessage(0);
wasHandled = true;
break;
case WM_DISPLAYCHANGE:
InvalidateRect(hWnd, nullptr, false);
wasHandled = true;
break;
}
// Handle any messages the switch statement didn't
return DefWindowProc (hWnd, message, wParam, lParam);
}
void CreateDevice()
{
if (g_pSwapChain == nullptr)
{
// 1、the factory
if (FAILED(CreateDXGIFactory1(IID_PPV_ARGS(&g_pFactory))))
{
return;
}
// 2、the device
HRESULT hardwareResult = D3D12CreateDevice(
nullptr, // default adapter
D3D_FEATURE_LEVEL_11_0,
IID_PPV_ARGS(&g_pDevice)
);
if (FAILED(hardwareResult))
{
IDXGIAdapter* pAdapter;
g_pFactory->EnumWarpAdapter(IID_PPV_ARGS(&pAdapter));
if (FAILED(D3D12CreateDevice(
pAdapter,
D3D_FEATURE_LEVEL_11_0,
IID_PPV_ARGS(&g_pDevice)
)))
{
return;
}
}
g_pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_pFence));
}
return;
}
void CreateCommandObjects()
{
// Command Queue
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
g_pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&g_pCommandQueue));
g_pDevice->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&g_pCommandAllocator));
// Command List
g_pDevice->CreateCommandList(
0,
D3D12_COMMAND_LIST_TYPE_DIRECT,
g_pCommandAllocator,
nullptr,
IID_PPV_ARGS(&g_pCommandList)
);
// We must close the command list.
g_pCommandList->Close();
}
void CreateSwapChain()
{
DXGI_SWAP_CHAIN_DESC sd;
sd.BufferDesc.Width = nScreenWidth;
sd.BufferDesc.Height = nScreenHeight;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = nFrameCount;
sd.OutputWindow = g_hWnd;
sd.Windowed = true;
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
// Create swap chain
// Note: Swap chain uses queue to perform flush
g_pFactory->CreateSwapChain(
g_pCommandQueue,
&sd,
&g_pSwapChain);
}
void CreateDescriptorHeaps()
{
// create renter target view descriptor heap
D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc = {};
rtvHeapDesc.NumDescriptors = nFrameCount;
rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
rtvHeapDesc.NodeMask = 0;
g_pDevice->CreateDescriptorHeap(&rtvHeapDesc, IID_PPV_ARGS(&g_pRtvHeap));
g_nRtvDescriptorSize = g_pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
// create depth stencil view descriptor heap
D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc = {};
dsvHeapDesc.NumDescriptors = 1;
dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
dsvHeapDesc.NodeMask = 0;
g_pDevice->CreateDescriptorHeap(&dsvHeapDesc, IID_PPV_ARGS(&g_pDsvHeap));
// create const buffer view descriptor heap
D3D12_DESCRIPTOR_HEAP_DESC cbvHeapDesc = {};
cbvHeapDesc.NumDescriptors = 1;
cbvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV;
cbvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; // we want shaders to access the buffer
cbvHeapDesc.NodeMask = 0;
g_pDevice->CreateDescriptorHeap(&cbvHeapDesc, IID_PPV_ARGS(&g_pCbvHeap));
g_nCbvDescriptorSize = g_pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV);
}
void CreateRenderTarget()
{
D3D12_CPU_DESCRIPTOR_HANDLE rtvHandle = g_pRtvHeap->GetCPUDescriptorHandleForHeapStart();
// Create a RTV for each frame
for (size_t i = 0; i < nFrameCount; ++i)
{
if (FAILED(g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&g_pRenderTargets[i])))){
return;
}
g_pDevice->CreateRenderTargetView(g_pRenderTargets[i], nullptr, rtvHandle);
rtvHandle.ptr += g_nRtvDescriptorSize;
}
return;
}
void CreateDepthStencilBuffer()
{
D3D12_RESOURCE_DESC depthStencilDesc;
depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
depthStencilDesc.Alignment = 0;
depthStencilDesc.Width = nScreenWidth;
depthStencilDesc.Height = nScreenHeight;
depthStencilDesc.DepthOrArraySize = 1;
depthStencilDesc.MipLevels = 1;
depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
depthStencilDesc.SampleDesc.Count = 1;
depthStencilDesc.SampleDesc.Quality = 0;
depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
D3D12_CLEAR_VALUE optClear;
optClear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
optClear.DepthStencil.Depth = 1.0f;
optClear.DepthStencil.Stencil = 0;
g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&depthStencilDesc,
D3D12_RESOURCE_STATE_COMMON,
&optClear,
IID_PPV_ARGS(&g_pDepthStencilBuffer));
// Create descriptor to mip level 0 of entire resource using the format of the resource.
D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
dsvDesc.Texture2D.MipSlice = 0;
g_pDevice->CreateDepthStencilView(g_pDepthStencilBuffer, &dsvDesc, g_pDsvHeap->GetCPUDescriptorHandleForHeapStart());
// Transition the resource from its initial state to be used as a depth buffer.
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pDepthStencilBuffer,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_DEPTH_WRITE));
}
void CreateConstantBuffer()
{
// The heap on which constant buffer will create
g_nConstantBufferSize = ((sizeof(ObjectConstants) + 255) & ~255);
if (FAILED(g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(g_nConstantBufferSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&g_pConstantBuffer)
)))
{
return;
}
// create const buffer view
D3D12_CONSTANT_BUFFER_VIEW_DESC cbvDesc = {};
cbvDesc.BufferLocation = g_pConstantBuffer->GetGPUVirtualAddress();
cbvDesc.SizeInBytes = g_nConstantBufferSize;
g_pDevice->CreateConstantBufferView(&cbvDesc, g_pCbvHeap->GetCPUDescriptorHandleForHeapStart());
return;
}
void CreateVertexBuffer()
{
g_pCommandList->Reset(g_pCommandAllocator, nullptr);
// create default vertex buffer
uint32_t verticesByteSize = vertices.size() * sizeof(Vertex);
if (FAILED(g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(verticesByteSize),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&g_pDefaultVertexBuffer)
)))
{
return;
}
if (FAILED(g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(verticesByteSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&g_pUploadVertexBuffer)
)))
{
return;
}
// copy the data
D3D12_SUBRESOURCE_DATA vertexData = {};
vertexData.pData = vertices.data();
vertexData.RowPitch = verticesByteSize;
vertexData.SlicePitch = verticesByteSize;
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultVertexBuffer,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
UpdateSubresources<1>(g_pCommandList, g_pDefaultVertexBuffer, g_pUploadVertexBuffer, 0, 0, 1, &vertexData);
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultVertexBuffer,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_GENERIC_READ));
// Initialize the vertex buffer view
g_VertexBufferView.BufferLocation = g_pDefaultVertexBuffer->GetGPUVirtualAddress();
g_VertexBufferView.StrideInBytes = sizeof(Vertex);
g_VertexBufferView.SizeInBytes = vertices.size() * sizeof(Vertex);
g_pCommandList->Close();
// execute the command list
ID3D12CommandList* ppCommandLists[] = { g_pCommandList };
g_pCommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
FlushCommandQueue();
}
void CreateIndexBuffer()
{
g_pCommandList->Reset(g_pCommandAllocator, nullptr);
/// create default index buffer
uint32_t indicesByteSize = indices.size() * sizeof(uint16_t);
if (FAILED(g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(indicesByteSize),
D3D12_RESOURCE_STATE_COMMON,
nullptr,
IID_PPV_ARGS(&g_pDefaultIndexBuffer)
)))
{
return;
}
if (FAILED(g_pDevice->CreateCommittedResource(
&CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
D3D12_HEAP_FLAG_NONE,
&CD3DX12_RESOURCE_DESC::Buffer(indicesByteSize),
D3D12_RESOURCE_STATE_GENERIC_READ,
nullptr,
IID_PPV_ARGS(&g_pUploadIndexBuffer)
)))
{
return;
}
// create upload index buffer
D3D12_SUBRESOURCE_DATA indexData = {};
indexData.pData = indices.data();
indexData.RowPitch = indicesByteSize;
indexData.SlicePitch = indicesByteSize;
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultIndexBuffer,
D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_COPY_DEST));
UpdateSubresources<1>(g_pCommandList, g_pDefaultIndexBuffer, g_pUploadIndexBuffer, 0, 0, 1, &indexData);
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultIndexBuffer,
D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_GENERIC_READ));
// initialize the index buffer view
g_IndexBufferView.BufferLocation = g_pDefaultIndexBuffer->GetGPUVirtualAddress();
g_IndexBufferView.Format = DXGI_FORMAT_R16_UINT;
g_IndexBufferView.SizeInBytes = indicesByteSize;
g_pCommandList->Close();
// execute the command list
ID3D12CommandList* ppCommandLists[] = { g_pCommandList };
g_pCommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
FlushCommandQueue();
return;
}
void CreateRootSignature()
{
// Shader programs typically require resources as input (constant buffers,
// textures, samplers). The root signature defines the resources the shader
// programs expect. If we think of the shader programs as a function, and
// the input resources as function parameters, then the root signature can be
// thought of as defining the function signature.
CD3DX12_ROOT_PARAMETER slotRootParameter[1];
// Create a single descriptor table of CBVs.
CD3DX12_DESCRIPTOR_RANGE cbvTable;
cbvTable.Init(D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 0);
slotRootParameter[0].InitAsDescriptorTable(1, &cbvTable);
// A root signature is an array of root parameters.
CD3DX12_ROOT_SIGNATURE_DESC rootSigDesc(1, slotRootParameter, 0, nullptr,
D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
ID3DBlob* signature = nullptr;
ID3DBlob* error = nullptr;
if (FAILED(D3D12SerializeRootSignature(&rootSigDesc, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error)))
{
return;
}
if (FAILED(g_pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature))))
{
return;
}
//SafeRelease(&signature);
//SafeRelease(&error);
return;
}
void InitializeShaders()
{
ID3DBlob* pVS = CompileShader(L"color.hlsl", nullptr, "VS", "vs_5_0");
ID3DBlob* pPS = CompileShader(L"color.hlsl", nullptr, "PS", "ps_5_0");
g_VertexShaderByteCode.pShaderBytecode = reinterpret_cast<BYTE*>(pVS->GetBufferPointer());
g_VertexShaderByteCode.BytecodeLength = pVS->GetBufferSize();
g_PixelShaderByteCode.pShaderBytecode = reinterpret_cast<BYTE*>(pPS->GetBufferPointer());
g_PixelShaderByteCode.BytecodeLength = pPS->GetBufferSize();
}
void CreatePSOs()
{
D3D12_GRAPHICS_PIPELINE_STATE_DESC psoDesc;
ZeroMemory(&psoDesc, sizeof(D3D12_GRAPHICS_PIPELINE_STATE_DESC));
psoDesc.InputLayout = { g_ieds, _countof(g_ieds) };
psoDesc.pRootSignature = g_pRootSignature;
psoDesc.VS = g_VertexShaderByteCode;
psoDesc.PS = g_PixelShaderByteCode;
psoDesc.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
psoDesc.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
psoDesc.DepthStencilState = CD3DX12_DEPTH_STENCIL_DESC(D3D12_DEFAULT);
psoDesc.SampleMask = UINT_MAX;
psoDesc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
psoDesc.NumRenderTargets = 1;
psoDesc.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
psoDesc.SampleDesc.Count = 1;
psoDesc.SampleDesc.Quality = 0;
psoDesc.DSVFormat = DXGI_FORMAT_D24_UNORM_S8_UINT;
if (FAILED(g_pDevice->CreateGraphicsPipelineState(&psoDesc, IID_PPV_ARGS(&g_pPso))))
{
return;
}
return;
}
void PopulateCommandList()
{
// command list allocators can only be reset when the associated
// command lists have finished execution on GPU; apps should use
// fences to determine GPU execution progress.
if (g_pCommandAllocator->Reset())
{
return;
}
// however, when ExecuteCommandList() is called on a particular command
// list, that command list can then be reset at any time and must be before
// re-recording
if (g_pCommandList->Reset(g_pCommandAllocator, g_pPso))
{
return;
}
g_pCommandList->RSSetViewports(1, &g_ViewPort);
g_pCommandList->RSSetScissorRects(1, &g_ScissorPort);
// Indicate a state transition on the resource usage.
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pRenderTargets[g_nFrameIndex],
D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_RENDER_TARGET));
// clear the back buffer and depth buffer
const FLOAT clearColor[] = {0.0f, 0.1f, 0.2f, 1.0f};
g_pCommandList->ClearRenderTargetView(CD3DX12_CPU_DESCRIPTOR_HANDLE(
g_pRtvHeap->GetCPUDescriptorHandleForHeapStart(),
g_nFrameIndex,
g_nRtvDescriptorSize), clearColor, 0, nullptr);
g_pCommandList->ClearDepthStencilView(g_pDsvHeap->GetCPUDescriptorHandleForHeapStart(), D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 1.0f, 0, 0, nullptr);
g_pCommandList->OMSetRenderTargets(1, &CD3DX12_CPU_DESCRIPTOR_HANDLE(
g_pRtvHeap->GetCPUDescriptorHandleForHeapStart(),
g_nFrameIndex,
g_nRtvDescriptorSize), true, &g_pDsvHeap->GetCPUDescriptorHandleForHeapStart());
ID3D12DescriptorHeap* ppHeaps[] = {g_pCbvHeap};
g_pCommandList->SetDescriptorHeaps(_countof(ppHeaps), ppHeaps);
// Set necessary state.
g_pCommandList->SetGraphicsRootSignature(g_pRootSignature);
g_pCommandList->IASetVertexBuffers(0, 1, &g_VertexBufferView);
g_pCommandList->IASetIndexBuffer(&g_IndexBufferView);
g_pCommandList->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
g_pCommandList->SetGraphicsRootDescriptorTable(0, g_pCbvHeap->GetGPUDescriptorHandleForHeapStart());
g_pCommandList->DrawIndexedInstanced(
indices.size(), 1, 0, 0, 0);
g_pCommandList->ResourceBarrier(1, &CD3DX12_RESOURCE_BARRIER::Transition(g_pRenderTargets[g_nFrameIndex],
D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_PRESENT));
return;
}
void Update()
{
Vector3Df cameraPos({ 5.0f, 5.0f, 5.0f });
Vector3Df target({ 0.0f, 0.0f, 0.0f });
Vector3Df up({ 0.0f, 1.0f, 0.0f });
Matrix4f world;
world.SetIdentity();
Matrix4f view;
BuildViewMatrixLH(view, cameraPos, target, up);
Matrix4f proj;
BuildPerspectiveFovLHMatrix(proj, PI / 4, (float)nScreenWidth / (float)nScreenHeight, 1.0f, 1000.0f);
Matrix4f combine;
combine = proj * view * world;
Matrix4f aCombine;
aCombine = world * view * proj;
TransposeMatrix(aCombine, aCombine);
BYTE* mappedData = nullptr;
g_pConstantBuffer->Map(0, nullptr, reinterpret_cast<void**>(&mappedData));
memcpy(&mappedData[0], aCombine, sizeof(ObjectConstants));
g_pConstantBuffer->Unmap(0, nullptr);
//////////////////////////////////////////////////////////////////////////////////
// Convert Spherical to Cartesian coordinates.
//float x = mRadius * sinf(mPhi)*cosf(mTheta);
//float z = mRadius * sinf(mPhi)*sinf(mTheta);
//float y = mRadius * cosf(mPhi);
//XMFLOAT4X4 mWorld(
// 1.0f, 0.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);
//XMFLOAT4X4 mView(
// 1.0f, 0.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
//);
//XMFLOAT4X4 mProj(
// 1.0f, 0.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
//);
//// Build the view matrix.
//XMVECTOR pos = XMVectorSet(0.0f, 0.0f, 5.0f, 1.0f);
//XMVECTOR target = XMVectorZero();
//XMVECTOR up = XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
////mProj = XMMatrixPerspectiveFovLH(0.25f*PI, static_cast<float>(nScreenWidth) / nScreenHeight, 1.0f, 1000.0f);
//XMMATRIX world = XMLoadFloat4x4(&mWorld);
//XMMATRIX proj = XMMatrixPerspectiveFovLH(0.25f*PI, static_cast<float>(nScreenWidth) / nScreenHeight, 1.0f, 1000.0f);
//XMMATRIX view = XMMatrixLookAtLH(pos, target, up);
//XMStoreFloat4x4(&mView, view);
//XMMATRIX worldViewProj = world * view*proj;
//// Update the constant buffer with the latest worldViewProj matrix.
//ObjectConstants objConstants;
//XMStoreFloat4x4(objConstants.WorldViewProj.GetAddressOf(), XMMatrixTranspose(worldViewProj));
//uint8_t* data;
//g_pConstantBuffer->Map(0, nullptr, reinterpret_cast<void**>(&data));
//memcpy(data, &objConstants, sizeof(ObjectConstants));
//g_pConstantBuffer->Unmap(0, nullptr);
}
void Draw()
{
g_pCommandList->Close();
// execute the command list
ID3D12CommandList* ppCommandLists[] = {g_pCommandList};
g_pCommandQueue->ExecuteCommandLists(_countof(ppCommandLists), ppCommandLists);
// swap the back buffer and the front buffer
g_pSwapChain->Present(0, 0);
g_nFrameIndex = (g_nFrameIndex + 1) % nFrameCount;
}
void FlushCommandQueue()
{
// Advance the fence value to mark commands up to this fence point.
g_nFenceValue++;
// Add an instruction to the command queue to set a new fence point. Because we
// are on the GPU timeline, the new fence point won't be set until the GPU finishes
// processing all the commands prior to this Signal().
g_pCommandQueue->Signal(g_pFence, g_nFenceValue);
// Wait until the GPU has completed commands up to this fence point.
if(g_pFence->GetCompletedValue() < g_nFenceValue)
{
HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
// Fire event when GPU hits current fence.
g_pFence->SetEventOnCompletion(g_nFenceValue, eventHandle);
// Wait until the GPU hits current fence event is fired.
WaitForSingleObject(eventHandle, INFINITE);
CloseHandle(eventHandle);
}
}
void InitDirect3D()
{
CreateDevice();
CreateCommandObjects();
CreateSwapChain();
CreateDescriptorHeaps();
CreateRenderTarget();
CreateDepthStencilBuffer();
CreateConstantBuffer();
CreateRootSignature();
InitializeShaders();
CreateVertexBuffer();
CreateIndexBuffer();
CreatePSOs();
}
ID3DBlob* CompileShader(const std::wstring& filename,
const D3D_SHADER_MACRO* defines,
const std::string& entrypoint,
const std::string& target)
{
UINT compileFlags = 0;
HRESULT hr = S_OK;
ID3DBlob* byteCode = nullptr;
ID3DBlob* errors;
hr = D3DCompileFromFile(filename.c_str(), defines, D3D_COMPILE_STANDARD_FILE_INCLUDE,
entrypoint.c_str(), target.c_str(), compileFlags, 0, &byteCode, &errors);
if (errors != nullptr)
OutputDebugStringA((char*)errors->GetBufferPointer());
return byteCode;
}
///////////////////////////////////////////////////////////////////////////////////////
//// include the basic windows header file
//#include <windows.h>
//#include <windowsx.h>
//#include <stdio.h>
//#include <tchar.h>
//#include <stdint.h>
//
//#include <d3d12.h>
//#include "d3dx12.h"
//#include <DXGI1_4.h> // DXGI (DirectX Graphics Infrastructure) is an API used along with Direct3D. The basic idea of
// // DXGI is that some graphics related tasks are common to multipile graphics APIs. Here are some
// // common functionality, swap chain, display adapters, monitors and supported display modes(
// // resolution, refresh rate), surface formats
//#include <D3DCompiler.h>
//#include <DirectXMath.h>
//#include <DirectXPackedVector.h>
//#include <DirectXColors.h>
//
//#include <wrl/client.h>
//
//#include <string>
//#include <exception>
//
//namespace Panda {
// // Helper class for COM exceptions
// class com_exception : public std::exception {
// public:
// com_exception(HRESULT hr) : result(hr) {
// }
//
// virtual const char* what() const override {
// static char s_str[64] = { 0 };
// sprintf_s(s_str, "Failure with HRESULT of %08X",
// static_cast<unsigned int>(result));
// return s_str;
// }
//
// private:
// HRESULT result;
// };
//
// // Helper utility converts D3D API failures into exceptions.
// inline void ThrowIfFailed(HRESULT hr) {
// if (FAILED(hr)) {
// throw com_exception(hr);
// }
// }
//};
//
//using namespace Panda;
//using namespace DirectX;
//using namespace DirectX::PackedVector;
//using namespace Microsoft::WRL;
//using namespace std;
//
//ComPtr<IDXGIFactory4> g_pDXGIFactory = nullptr; // dxgi factory
//ComPtr<ID3D12Device> g_pDevice = nullptr; // the pointer to out Direct3D device interface
//D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS g_msQualityLevels; // multi-sample support information
//
//ComPtr<ID3D12CommandQueue> g_pCommandQueue; // the pointer to command queue
//ComPtr<ID3D12CommandAllocator> g_pCommandAllocator; // the pointer to command buffer allocator
//ComPtr<ID3D12GraphicsCommandList> g_pCommandList; // a list to store CPU commands, which will be submmited to GPU to execute
//
//const uint32_t g_FrameCount = 2; // buffer count
//HWND g_hWnd; // window handle
//
//ComPtr<IDXGISwapChain3> g_pSwapChain = nullptr; // the pointer to the swap chain interface
//uint32_t g_ScreenWidth = 960;
//uint32_t g_ScreenHeight = 480;
//
//ComPtr<ID3D12Fence> g_pFence; // the pointer to the fence
//uint32_t g_CurrentFence = 0; // current fence value
//uint32_t g_rtvDescriptorSize = 0;
//uint32_t g_dsvDescriptorSize = 0;
//ComPtr<ID3D12DescriptorHeap> g_pRtvHeap;
//ComPtr<ID3D12DescriptorHeap> g_pDsvHeap;
//
//uint32_t g_currentBackBuffer = 0;
//ComPtr<ID3D12Resource> g_SwapChainBuffer[g_FrameCount];
//ComPtr<ID3D12Resource> g_DepthStencilBuffer;
//
//ComPtr<ID3D12Resource> g_pDefaultVertexBuffer;
//D3D12_VERTEX_BUFFER_VIEW g_DefaultVertexBufferView;
//ComPtr<ID3D12Resource> g_pUploadVertexBuffer;
//D3D12_VERTEX_BUFFER_VIEW g_UploadVertexBufferView;
//
//D3D12_VIEWPORT g_ScreenViewport;
//D3D12_RECT g_ScissorRect;
//
//ComPtr<ID3D12RootSignature> g_pRootSignature;
//ComPtr<ID3D12PipelineState> g_pPipelineState;
//
//struct VERTEX
//{
// XMFLOAT3 Position;
// XMFLOAT4 Color;
//};
//
//
//LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam);
//void OnResize();
//void FlushCommandQueue();
//
//bool InitMainWindow(HINSTANCE hInstance, int nCmdShow) {
// WNDCLASSEX wc;
//
// // clear out the window class for use
// ZeroMemory(&wc, sizeof(WNDCLASSEX));
//
// // fill in the struct with the needed information
// wc.cbSize = sizeof(WNDCLASSEX);
// wc.style = CS_HREDRAW | CS_VREDRAW;
// wc.lpfnWndProc = WindowProc;
// wc.hInstance = hInstance;
// wc.hCursor = LoadCursor(nullptr, IDC_ARROW);
// wc.hbrBackground = (HBRUSH)COLOR_WINDOW;
// wc.lpszClassName = _T("HelloD3D12");
//
// // register the window class
// RegisterClassEx(&wc);
//
// // create the window and use the result as the handle
// g_hWnd = CreateWindowEx(0,
// _T("HelloD3D12"), // name of the window class
// _T("Hello Direct 12"), // title of the window
// WS_OVERLAPPEDWINDOW, // window style
// 100, // x-position of the window
// 100, // y-position of the window
// g_ScreenWidth, // width of the window
// g_ScreenHeight, // height of the window
// NULL, // we have no parent window, NULL
// NULL, // we aren't using menus, NULL
// hInstance, // application handle
// NULL); // used with multiple windows, NULL
//
// if (!g_hWnd) {
// MessageBoxW(0, L"Create window failed.", 0, 0);
// return false;
// }
//
// // display the window on the screen
// ShowWindow(g_hWnd, nCmdShow);
// UpdateWindow(g_hWnd);
//
// return true;
//}
//
///***************************************************************************************/
///*
// * DirectX 12
// */
//
//void CreateDevice() {
// // Try to create hardware device.
// HRESULT hardwareResult = D3D12CreateDevice(
// nullptr, // default adapter
// D3D_FEATURE_LEVEL_11_0,
// IID_PPV_ARGS(&g_pDevice));
//
// // Fallback to WARP(Windows Advanced Rasterization Platform) device
// ThrowIfFailed(CreateDXGIFactory1(IID_PPV_ARGS(&g_pDXGIFactory)));
// if (FAILED(hardwareResult)) {
// ComPtr<IDXGIAdapter> pWarpAdapter;
// ThrowIfFailed(g_pDXGIFactory->EnumWarpAdapter(IID_PPV_ARGS(&pWarpAdapter)));
//
// ThrowIfFailed(D3D12CreateDevice(
// pWarpAdapter.Get(),
// D3D_FEATURE_LEVEL_11_0,
// IID_PPV_ARGS(&g_pDevice)));
// }
//
// // Check 4X MSAA quality support for our back buffer format.
// // All Direct3D 11 capable devices support 4X MSAA for all render
// // target formats, so we only need to check quality support.
// g_msQualityLevels.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// g_msQualityLevels.SampleCount = 4;
// g_msQualityLevels.Flags = D3D12_MULTISAMPLE_QUALITY_LEVELS_FLAG_NONE;
// g_msQualityLevels.NumQualityLevels = 0;
// ThrowIfFailed(g_pDevice->CheckFeatureSupport(
// D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS,
// &g_msQualityLevels,
// sizeof(g_msQualityLevels)));
//}
//
//void CreateCommandObjects() {
// // Command Queue
// D3D12_COMMAND_QUEUE_DESC queueDesc = {};
// queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
// queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
// ThrowIfFailed(g_pDevice->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&g_pCommandQueue)));
//
// // command allocator and command list
// ThrowIfFailed(g_pDevice->CreateCommandAllocator(
// D3D12_COMMAND_LIST_TYPE_DIRECT,
// IID_PPV_ARGS(g_pCommandAllocator.GetAddressOf())));
//
// ThrowIfFailed(g_pDevice->CreateCommandList(
// 0,
// D3D12_COMMAND_LIST_TYPE_DIRECT,
// g_pCommandAllocator.Get(), // assocated command allocator
// nullptr, // initial pipelinestateobject
// IID_PPV_ARGS(g_pCommandList.GetAddressOf())));
//
// // close command list.
// g_pCommandList->Close();
//}
//
//void CreateSwapChain() {
// // Release the previous swapchain we will be recreating.
// //if (g_pSwapChain.Get() != nullptr)
// g_pSwapChain.Reset();
//
// DXGI_SWAP_CHAIN_DESC sd;
// sd.BufferDesc.Width = g_ScreenWidth;
// sd.BufferDesc.Height = g_ScreenHeight;
// sd.BufferDesc.RefreshRate.Numerator = 60;
// sd.BufferDesc.RefreshRate.Denominator = 1;
// sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
// sd.BufferDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;
// sd.BufferDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
// sd.SampleDesc.Count = 1;
// sd.SampleDesc.Quality = 0;
// sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
// sd.BufferCount = g_FrameCount;
// sd.OutputWindow = g_hWnd;
// sd.Windowed = true;
// sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD; // This flag cannot be used with multisampling and partial presentation
// sd.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH;
//
// // Note: Swap chain uses queue to perform flush
// ComPtr<IDXGISwapChain> swapChain;
// ThrowIfFailed(g_pDXGIFactory->CreateSwapChain(
// g_pCommandQueue.Get(),
// &sd,
// swapChain.GetAddressOf()));
// swapChain.As(&g_pSwapChain);
//
// g_currentBackBuffer = g_pSwapChain->GetCurrentBackBufferIndex();
//}
//
//void CreateDescriptorHeaps() {
// // fence
// ThrowIfFailed(g_pDevice->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&g_pFence)));
//
// // RTVs
// g_rtvDescriptorSize = g_pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV);
// D3D12_DESCRIPTOR_HEAP_DESC rtvHeapDesc;
// rtvHeapDesc.NumDescriptors = g_FrameCount;
// rtvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV;
// rtvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
// rtvHeapDesc.NodeMask = 0;
// ThrowIfFailed(g_pDevice->CreateDescriptorHeap(
// &rtvHeapDesc,
// IID_PPV_ARGS(g_pRtvHeap.GetAddressOf())));
//
// // DSVs
// g_dsvDescriptorSize = g_pDevice->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV);
// D3D12_DESCRIPTOR_HEAP_DESC dsvHeapDesc;
// dsvHeapDesc.NumDescriptors = 1;
// dsvHeapDesc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_DSV;
// dsvHeapDesc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_NONE;
// dsvHeapDesc.NodeMask = 0;
// ThrowIfFailed(g_pDevice->CreateDescriptorHeap(
// &dsvHeapDesc,
// IID_PPV_ARGS(g_pDsvHeap.GetAddressOf())));
//}
//
//void CreateRtvsAndDsv() {
// // Release the previous resources we will be recreating.
// for (int i = 0; i < g_FrameCount; ++i)
// g_SwapChainBuffer[i].Reset();
// g_DepthStencilBuffer.Reset();
//
// // Resize the swap chain
// ThrowIfFailed(g_pSwapChain->ResizeBuffers(
// g_FrameCount,
// g_ScreenWidth, g_ScreenHeight,
// DXGI_FORMAT_R8G8B8A8_UNORM,
// DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH));
//
// g_currentBackBuffer = 0;
//
// // Create render target views.
// CD3DX12_CPU_DESCRIPTOR_HANDLE rtvHeapHandle(g_pRtvHeap->GetCPUDescriptorHandleForHeapStart());
// for (int i = 0; i < g_FrameCount; ++i) {
// ThrowIfFailed(g_pSwapChain->GetBuffer(i, IID_PPV_ARGS(&g_SwapChainBuffer[i])));
// g_pDevice->CreateRenderTargetView(g_SwapChainBuffer[i].Get(), nullptr, rtvHeapHandle);
// rtvHeapHandle.Offset(1, g_rtvDescriptorSize);
// }
//
// // Create the depth/stencil buffer and view.
// D3D12_RESOURCE_DESC depthStencilDesc;
// depthStencilDesc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D;
// depthStencilDesc.Alignment = 0;
// depthStencilDesc.Width = g_ScreenWidth;
// depthStencilDesc.Height = g_ScreenHeight;
// depthStencilDesc.DepthOrArraySize = 1;
// depthStencilDesc.MipLevels = 1;
// depthStencilDesc.Format = DXGI_FORMAT_R24G8_TYPELESS;
// depthStencilDesc.SampleDesc.Count = 1;
// depthStencilDesc.SampleDesc.Quality = 0;
// depthStencilDesc.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN;
// depthStencilDesc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL;
//
// // Create clear value.
// D3D12_CLEAR_VALUE optClear;
// optClear.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
// optClear.DepthStencil.Depth = 1.0f;
// optClear.DepthStencil.Stencil = 0;
// ThrowIfFailed(g_pDevice->CreateCommittedResource(
// &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
// D3D12_HEAP_FLAG_NONE,
// &depthStencilDesc,
// D3D12_RESOURCE_STATE_COMMON,
// &optClear,
// IID_PPV_ARGS(g_DepthStencilBuffer.GetAddressOf())));
//
// // Create descriptor to mip level 0 of entire resource using the format of the resource.
// D3D12_DEPTH_STENCIL_VIEW_DESC dsvDesc;
// dsvDesc.Flags = D3D12_DSV_FLAG_NONE;
// dsvDesc.ViewDimension = D3D12_DSV_DIMENSION_TEXTURE2D;
// dsvDesc.Format = DXGI_FORMAT_D24_UNORM_S8_UINT;
// dsvDesc.Texture2D.MipSlice = 0;
// g_pDevice->CreateDepthStencilView(g_DepthStencilBuffer.Get(), &dsvDesc, g_pDsvHeap->GetCPUDescriptorHandleForHeapStart());
//
// // Transtion the resource from its initial
// g_pCommandList->ResourceBarrier(
// 1,
// &CD3DX12_RESOURCE_BARRIER::Transition(
// g_DepthStencilBuffer.Get(),
// D3D12_RESOURCE_STATE_COMMON,
// D3D12_RESOURCE_STATE_DEPTH_WRITE));
//
//}
//
//void CreateVertexBuffer()
//{
// ThrowIfFailed(g_pCommandList->Reset(g_pCommandAllocator.Get(), nullptr));
//
// VERTEX OutVertices[] =
// {
// {XMFLOAT3(0.0f, 0.5f, 0.0f), XMFLOAT4(1.0f, 0.0f, 0.0f, 1.0f)},
// {XMFLOAT3(0.45f, -0.5, 0.0f), XMFLOAT4(0.0f, 1.0f, 0.0f, 1.0f)},
// {XMFLOAT3(-0.45f, -0.5f, 0.0f), XMFLOAT4(0.0f, 0.0f, 1.0f, 1.0f)}
// };
// const UINT vertexBufferSize = sizeof(OutVertices);
//
// // Create default buffer resource
// ThrowIfFailed(g_pDevice->CreateCommittedResource(
// &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_DEFAULT),
// D3D12_HEAP_FLAG_NONE,
// &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
// D3D12_RESOURCE_STATE_COMMON,
// nullptr,
// IID_PPV_ARGS(&g_pDefaultVertexBuffer)));
//
// ThrowIfFailed(g_pDevice->CreateCommittedResource(
// &CD3DX12_HEAP_PROPERTIES(D3D12_HEAP_TYPE_UPLOAD),
// D3D12_HEAP_FLAG_NONE,
// &CD3DX12_RESOURCE_DESC::Buffer(vertexBufferSize),
// D3D12_RESOURCE_STATE_GENERIC_READ,
// nullptr,
// IID_PPV_ARGS(&g_pUploadVertexBuffer)));
//
// // Describe the data
// D3D12_SUBRESOURCE_DATA subResourceData = {};
// subResourceData.pData = OutVertices;
// subResourceData.RowPitch = vertexBufferSize;
// subResourceData.SlicePitch = vertexBufferSize;
//
// // upload the vertex
// g_pCommandList->ResourceBarrier(1,
// &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultVertexBuffer.Get(),
// D3D12_RESOURCE_STATE_COMMON,
// D3D12_RESOURCE_STATE_COPY_DEST));
//
// UpdateSubresources<1>(g_pCommandList.Get(), g_pDefaultVertexBuffer.Get(), g_pUploadVertexBuffer.Get(),
// 0, 0, 1, &subResourceData);
//
// g_pCommandList->ResourceBarrier(1,
// &CD3DX12_RESOURCE_BARRIER::Transition(g_pDefaultVertexBuffer.Get(),
// D3D12_RESOURCE_STATE_COPY_DEST,
// D3D12_RESOURCE_STATE_GENERIC_READ));
//
// // create the vertex buffer descriptor, or just call it "view"
// g_DefaultVertexBufferView.BufferLocation = g_pDefaultVertexBuffer->GetGPUVirtualAddress();
// g_DefaultVertexBufferView.StrideInBytes = sizeof(VERTEX);
// g_DefaultVertexBufferView.SizeInBytes = vertexBufferSize;
//
// g_UploadVertexBufferView.BufferLocation = g_pUploadVertexBuffer->GetGPUVirtualAddress();
// g_UploadVertexBufferView.StrideInBytes = sizeof(VERTEX);
// g_UploadVertexBufferView.SizeInBytes = vertexBufferSize;
//
// // Execute the initialization commands.
// ThrowIfFailed(g_pCommandList->Close());
// ID3D12CommandList* cmdsLists[] = { g_pCommandList.Get() };
// g_pCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
//
// // Wait until initialization is complete.
// FlushCommandQueue();
//}
//
//void CreateRootSignature()
//{
// // create an empty root signature
// CD3DX12_ROOT_SIGNATURE_DESC rsd;
// rsd.Init(0, nullptr, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_ALLOW_INPUT_ASSEMBLER_INPUT_LAYOUT);
//
// ComPtr<ID3DBlob> signature;
// ComPtr<ID3DBlob> error;
// ThrowIfFailed(D3D12SerializeRootSignature(&rsd, D3D_ROOT_SIGNATURE_VERSION_1, &signature, &error));
// ThrowIfFailed(g_pDevice->CreateRootSignature(0, signature->GetBufferPointer(), signature->GetBufferSize(), IID_PPV_ARGS(&g_pRootSignature)));
//}
//
//void InitPipeline()
//{
// ComPtr<ID3DBlob> error;
//
// ComPtr<ID3DBlob> vertexShader;
// ComPtr<ID3DBlob> pixelShader;
//
// D3DCompileFromFile(
// L"copy.vs",
// nullptr,
// D3D_COMPILE_STANDARD_FILE_INCLUDE,
// "main",
// "vs_5_0",
// 0,
// 0,
// &vertexShader,
// &error);
// if (error) { OutputDebugString((LPCTSTR)error->GetBufferPointer()); error->Release(); throw std::exception(); }
//
// D3DCompileFromFile(
// L"copy.ps",
// nullptr,
// D3D_COMPILE_STANDARD_FILE_INCLUDE,
// "main",
// "ps_5_0",
// 0,
// 0,
// &pixelShader,
// &error);
// if (error) { OutputDebugString((LPCTSTR)error->GetBufferPointer()); error->Release(); throw std::exception(); }
//
// // create the input layout object
// D3D12_INPUT_ELEMENT_DESC ied[] =
// {
// {"POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
// {"COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 12, D3D12_INPUT_CLASSIFICATION_PER_VERTEX_DATA, 0},
// };
//
// // describe and create the graphics pipeline state object (PSO)
// D3D12_GRAPHICS_PIPELINE_STATE_DESC psod = {};
// psod.InputLayout = { ied, _countof(ied) };
// psod.pRootSignature = g_pRootSignature.Get();
// psod.VS = { reinterpret_cast<UINT8*>(vertexShader->GetBufferPointer()), vertexShader->GetBufferSize() };
// psod.PS = { reinterpret_cast<UINT8*>(pixelShader->GetBufferPointer()), pixelShader->GetBufferSize() };
// psod.RasterizerState = CD3DX12_RASTERIZER_DESC(D3D12_DEFAULT);
// psod.BlendState = CD3DX12_BLEND_DESC(D3D12_DEFAULT);
// psod.DepthStencilState.DepthEnable = FALSE;
// psod.DepthStencilState.StencilEnable = FALSE;
// psod.SampleMask = UINT_MAX;
// psod.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
// psod.NumRenderTargets = 1;
// psod.RTVFormats[0] = DXGI_FORMAT_R8G8B8A8_UNORM;
// psod.SampleDesc.Count = 1;
// ThrowIfFailed(g_pDevice->CreateGraphicsPipelineState(&psod, IID_PPV_ARGS(&g_pPipelineState)));
//}
//
//void FlushCommandQueue() {
// const uint64_t fence = g_CurrentFence;
// ThrowIfFailed(g_pCommandQueue->Signal(g_pFence.Get(), fence));
//
// // Advance the fence value to mark commands up to this fence point.
// g_CurrentFence++;
//
// // Wait until the GPU has completed commands up to this fence point.
// if (g_pFence->GetCompletedValue() < fence) {
// HANDLE eventHandle = CreateEventEx(nullptr, false, false, EVENT_ALL_ACCESS);
//
// // Set fire event when GPU hits current fence.
// ThrowIfFailed(g_pFence->SetEventOnCompletion(fence, eventHandle));
//
// // Wait until the GPU hits current fence event is fired.
// WaitForSingleObject(eventHandle, INFINITE);
// CloseHandle(eventHandle);
// }
//
// g_currentBackBuffer = g_pSwapChain->GetCurrentBackBufferIndex();
//}
//
//void OnResize() {
// // We won't resize it until the device,swap chain, command allocator are created.
// if (g_pDevice == nullptr || g_pSwapChain == nullptr || g_pCommandAllocator == nullptr) {
// return;
// }
//
// // Fluse before changing any resources.
// FlushCommandQueue();
//
// ThrowIfFailed(g_pCommandList->Reset(g_pCommandAllocator.Get(), nullptr));
//
// CreateRtvsAndDsv();
//
// // Execute the resize commands.
// ThrowIfFailed(g_pCommandList->Close());
// ID3D12CommandList* cmdLists[] = { g_pCommandList.Get() };
// g_pCommandQueue->ExecuteCommandLists(_countof(cmdLists), cmdLists);
//
// // Wait until resize is complete.
// FlushCommandQueue();
//
// // Update the viewport transform to cover the client area.
// g_ScreenViewport.TopLeftX = 0;
// g_ScreenViewport.TopLeftY = 0;
// g_ScreenViewport.Width = static_cast<float>(g_ScreenWidth);
// g_ScreenViewport.Height = static_cast<float>(g_ScreenHeight);
// g_ScreenViewport.MinDepth = 0.0f;
// g_ScreenViewport.MaxDepth = 1.0f;
//
// g_ScissorRect = { 0, 0, static_cast<LONG>(g_ScreenWidth), static_cast<LONG>(g_ScreenHeight) };
//}
//
//void InitDirect3D12() {
// CreateDevice();
//
// CreateCommandObjects();
//
// CreateSwapChain();
//
// CreateDescriptorHeaps();
//
// OnResize();
//
// CreateRootSignature();
//
// CreateVertexBuffer();
//
// InitPipeline();
//
//
//}
//
//void Draw() {
// // Reuse the memory associated with command recording.
// // We can only reset when the associated command lists have finished execution on the GPU.
// ThrowIfFailed(g_pCommandAllocator->Reset());
//
// // A command list can be reset after it has been added to the command queue via ExecuteCommandList.
// // Reusing the command list reuses memory.
// ThrowIfFailed(g_pCommandList->Reset(g_pCommandAllocator.Get(), g_pPipelineState.Get()));
//
// g_pCommandList->SetGraphicsRootSignature(g_pRootSignature.Get());
// // Set the viewport and scissor rect. This needs to be reset whenever the command list is reset.
// g_pCommandList->RSSetViewports(1, &g_ScreenViewport);
// g_pCommandList->RSSetScissorRects(1, &g_ScissorRect);
//
// // Indicate a state transition on the resource usage.
// g_pCommandList->ResourceBarrier(1,
// &CD3DX12_RESOURCE_BARRIER::Transition(g_SwapChainBuffer[g_currentBackBuffer].Get(),
// D3D12_RESOURCE_STATE_PRESENT,
// D3D12_RESOURCE_STATE_RENDER_TARGET));
//
// // Specify the buffers we are going to render to.
// g_pCommandList->OMSetRenderTargets(1,
// &CD3DX12_CPU_DESCRIPTOR_HANDLE(
// g_pRtvHeap->GetCPUDescriptorHandleForHeapStart(),
// g_currentBackBuffer,
// g_rtvDescriptorSize),
// true,
// &g_pDsvHeap->GetCPUDescriptorHandleForHeapStart());
//
// // Clear the back buffer and depth buffer.
// g_pCommandList->ClearRenderTargetView(
// CD3DX12_CPU_DESCRIPTOR_HANDLE(
// g_pRtvHeap->GetCPUDescriptorHandleForHeapStart(),
// g_currentBackBuffer,
// g_rtvDescriptorSize),
// Colors::LightSteelBlue,
// 0,
// nullptr);
// g_pCommandList->ClearDepthStencilView(
// g_pDsvHeap->GetCPUDescriptorHandleForHeapStart(),
// D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL,
// 1.0f,
// 0,
// 0,
// nullptr);
//
// {
// //g_pCommandList->IASetVertexBuffers(0, 1, &g_UploadVertexBufferView);
// g_pCommandList->IASetVertexBuffers(0, 1, &g_DefaultVertexBufferView);
//
// g_pCommandList->IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_TRIANGLELIST);
//
// g_pCommandList->DrawInstanced(3, 1, 0, 0);
// }
//
//
// // Indicate a state transition on the resource usage.
// g_pCommandList->ResourceBarrier(
// 1,
// &CD3DX12_RESOURCE_BARRIER::Transition(
// g_SwapChainBuffer[g_currentBackBuffer].Get(),
// D3D12_RESOURCE_STATE_RENDER_TARGET,
// D3D12_RESOURCE_STATE_PRESENT));
//
// // Done recording commands.
// ThrowIfFailed(g_pCommandList->Close());
//
// // Add the command list to the queue for execution.
// ID3D12CommandList* cmdsLists[] = { g_pCommandList.Get() };
// g_pCommandQueue->ExecuteCommandLists(_countof(cmdsLists), cmdsLists);
//
// // swap the back and fornt buffers.
// ThrowIfFailed(g_pSwapChain->Present(0, 0));
//
//
// // Wait until frame commands are complete. This waiting is inefficient and is
// // done for simplicity. But it's enough for a show case.
// FlushCommandQueue();
//}
//
///***************************************************************************************/
//
//int Run() {
// // this struct holds Windows event messages
// MSG msg = {};
//
// // wait for the next message in the queue, store the result in 'msg'
// while (msg.message != WM_QUIT) {
// // If there are window message then process them
// if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) {
// // translate keystroke messages into the right format
// TranslateMessage(&msg);
//
// // send the message to the WindowProc function
// DispatchMessage(&msg);
// }
// else {
// Sleep(100);
// Draw();
// }
// }
//
// // return this part of the WM_QUIT message to Windows
// return msg.wParam;
//}
//
//// this is the main message handler for the program
//LRESULT CALLBACK WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
// LRESULT result = 0;
// bool wasHandled = false;
//
// // sort through and find what code to run for the message given
// switch (message)
// {
// case WM_CREATE:
// wasHandled = true;
// break;
//
// // case WM_PAINT:
// // wasHandled = true;
// // break;
//
// case WM_SIZE:
// // Save the new client area dimensions.
// g_ScreenWidth = LOWORD(lParam);
// g_ScreenHeight = HIWORD(lParam);
// if (g_pDevice) {
// if (wParam == SIZE_MAXIMIZED || wParam == SIZE_RESTORED) {
// OnResize();
// }
// }
// wasHandled = true;
// break;
//
// case WM_DESTROY:
// FlushCommandQueue();
// PostQuitMessage(0);
// wasHandled = true;
// break;
// }
//
// // Handle any messages the switch statement didn't
// if (!wasHandled) { result = DefWindowProc(hWnd, message, wParam, lParam); }
// return result;
//}
//
//// the entry point for any Windows program
//int WINAPI WinMain(HINSTANCE hInstance,
// HINSTANCE hPrevInstance,
// LPTSTR lpCmdLine,
// int nCmdShow)
//{
// // Create window
// InitMainWindow(hInstance, nCmdShow);
//
// // Initialize DirectX 12
// InitDirect3D12();
//
// OnResize();
//
// return Run();
//} | [
"[email protected]"
] | |
6b7cd5f146dadd217ba6e22ef2830865b6186b2e | 2953d6c761d485d23f7ce7df12cea3183d923c6d | /nnet2bin/nnet-am-switch-preconditioning.cc | 3054ab5b7faf0ba687439685bf056cc7c7997b7a | [] | no_license | yccheng31/kaldi_trunk | 1504ea6a719733fff436378d05504c04178bf7fe | 0ea8c9cefcd9d5b18fa8373e438f77e5de0b31a4 | refs/heads/master | 2021-01-22T01:28:11.621726 | 2014-09-29T18:57:06 | 2014-09-29T18:57:06 | 23,676,161 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,630 | cc | // nnet2bin/nnet-am-switch-preconditioning.cc
// Copyright 2012 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "base/kaldi-common.h"
#include "util/common-utils.h"
#include "hmm/transition-model.h"
#include "nnet2/am-nnet.h"
#include "hmm/transition-model.h"
#include "tree/context-dep.h"
int main(int argc, char *argv[]) {
try {
using namespace kaldi;
using namespace kaldi::nnet2;
typedef kaldi::int32 int32;
const char *usage =
"Copy a (cpu-based) neural net and its associated transition model,\n"
"and switch it to online preconditioning, i.e. change components from\n"
"AffineComponentPreconditioned to AffineComponentPreconditionedOnline.\n"
"\n"
"Usage: nnet-am-switch-preconditioning [options] <nnet-in> <nnet-out>\n"
"e.g.:\n"
" nnet-am-switch-preconditioning --binary=false 1.mdl text.mdl\n";
int32 rank_in = 20, rank_out = 80, update_period = 1;
BaseFloat num_samples_history = 2000.0;
BaseFloat alpha = 4.0;
bool binary_write = true;
ParseOptions po(usage);
po.Register("binary", &binary_write, "Write output in binary mode");
po.Register("rank-in", &rank_in,
"Rank used in online-preconditioning on input side of each layer");
po.Register("rank-out", &rank_out,
"Rank used in online-preconditioning on output side of each layer");
po.Register("update-period", &update_period,
"Affects how frequently we update the Fisher-matrix estimate (every "
"this-many minibatches).");
po.Register("num-samples-history", &num_samples_history,
"Number of samples of history to use in online preconditioning "
"(affects speed vs accuracy of update of Fisher matrix)");
po.Register("alpha", &alpha,
"Parameter that affects amount of smoothing with unit matrix "
"in online preconditioning (larger -> more smoothing)");
po.Read(argc, argv);
if (po.NumArgs() != 2) {
po.PrintUsage();
exit(1);
}
std::string nnet_rxfilename = po.GetArg(1),
nnet_wxfilename = po.GetArg(2);
TransitionModel trans_model;
AmNnet am_nnet;
{
bool binary;
Input ki(nnet_rxfilename, &binary);
trans_model.Read(ki.Stream(), binary);
am_nnet.Read(ki.Stream(), binary);
}
am_nnet.GetNnet().SwitchToOnlinePreconditioning(rank_in, rank_out, update_period,
num_samples_history, alpha);
{
Output ko(nnet_wxfilename, binary_write);
trans_model.Write(ko.Stream(), binary_write);
am_nnet.Write(ko.Stream(), binary_write);
}
KALDI_LOG << "Copied neural net from " << nnet_rxfilename
<< " to " << nnet_wxfilename;
return 0;
} catch(const std::exception &e) {
std::cerr << e.what() << '\n';
return -1;
}
}
| [
"[email protected]"
] | |
7da9e11d899eb511f4add0506d101cb975cef685 | 2f19e39d581eaa8298ca08192460fe3ac9f8d02b | /fhe3/fhe/math/Quat.h | 0eebb5d7cf099ec32d395186876988243c31a03f | [] | no_license | davecarr1024/libfhe | 77497b67c2ead85fc0bd6a7837a765daf6ccfe30 | 31682b423fc2255a10235f28c17cbdc7c6d7668b | refs/heads/master | 2021-05-08T05:22:02.635076 | 2016-08-22T20:11:06 | 2016-08-22T20:11:06 | 31,622,347 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | h | #ifndef QUAT_H
#define QUAT_H
#include <iostream>
#include "fheMath.h"
#include <boost/python.hpp>
namespace fhe
{
class Vec3;
class Quat
{
public:
float w, x, y, z;
Quat();
Quat(float _w, float _x, float _y, float _z);
Quat(const Vec3& axis, float angle);
Quat(const Vec3& v);
Quat(const Quat& q);
Quat& operator=(const Quat& q);
void toAxisAngle(Vec3& axis, float& angle) const;
Quat operator*(const Quat& q) const;
Vec3 operator*(const Vec3& v) const;
Quat operator*(float f) const;
Quat operator/(float f) const;
Quat conjugate() const;
float magnitude() const;
Quat norm() const;
Quat inverse() const;
bool equals(const Quat& q, float eps = Math::EPSILON) const;
friend std::ostream& operator<<(std::ostream& os, const Quat& q);
const static Quat IDENTITY;
std::string toString();
bool pyEquals( const Quat& q );
boost::python::object pyToAxisAngle();
static boost::python::object defineClass();
};
}
#endif
| [
"dave.carr.re2@a83f7b76-a30c-11de-8ba5-91705c1537ed"
] | dave.carr.re2@a83f7b76-a30c-11de-8ba5-91705c1537ed |
ff8dcd44cda7e8089c2a65c0d67f550f9931d43b | de08068df4a7338d49c46b632e5d1182b097c582 | /VOPractice/src/config.cpp | 6e8994a4d0753835baebc8766b3e739651c06ccd | [] | no_license | liuchang-t/SlamPracticeD435 | 6219e972cf35af0b9b12343115a77d5c1975f5ea | add761b76c4d1b09de0c48933f2d82cbc3ac37ff | refs/heads/master | 2021-05-22T13:28:27.762963 | 2020-07-08T10:29:01 | 2020-07-08T10:29:01 | 252,946,723 | 0 | 0 | null | 2020-04-04T09:34:03 | 2020-04-04T08:26:26 | C++ | UTF-8 | C++ | false | false | 936 | cpp | #include "myslam/config.h"
namespace myslam
{
void Config::setParameterFile(const std::string& filename)
{
if (config_ == nullptr)
config_ = shared_ptr<Config>(new Config);
/*config_->file_ = cv::FileStorage( filename.c_str(), cv::FileStorage::READ );
if ( config_->file_.isOpened() == false )
{
std::cerr<<"parameter file "<<filename<<" does not exist."<<std::endl;
config_->file_.release();
return;
}*/
config_->yamlConfig_ = YAML::LoadFile(filename);
if (config_->yamlConfig_.IsNull())
{
std::cerr << "parameter file " << filename << " does not exist." << std::endl;
config_->yamlConfig_.reset();
return;
}
}
Config::~Config()
{
/*if ( file_.isOpened() )
file_.release();*/
}
shared_ptr<Config> Config::config_ = nullptr;
} | [
"[email protected]"
] | |
7b5c5fc03aef5bfd3842de789ae6d978e84c5141 | 97d14a9bc00ba6ed3e1e5d650dbe2f5b307871d7 | /src/index/segment_enum_test.cpp | ddf0f6b474f64479072c88cdaa1613b4c0ed0e2c | [
"MIT"
] | permissive | nemesit/acoustid-index | 3725def0cc333216b8785bcf4affb4833c030e9a | f6b4dcf50af9f2558d40410cfe642e83f212ed04 | refs/heads/master | 2021-01-21T01:43:25.394042 | 2011-04-14T21:06:25 | 2011-04-14T21:06:25 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,729 | cpp | // Copyright (C) 2011 Lukas Lalinsky
// Distributed under the MIT license, see the LICENSE file for details.
#include <gtest/gtest.h>
#include <QFile>
#include "util/test_utils.h"
#include "store/ram_directory.h"
#include "store/input_stream.h"
#include "store/output_stream.h"
#include "segment_data_reader.h"
#include "segment_data_writer.h"
#include "segment_index.h"
#include "segment_index_reader.h"
#include "segment_index_writer.h"
#include "segment_enum.h"
using namespace Acoustid;
TEST(SegmentEnumTest, Iterate)
{
RAMDirectory dir;
{
ScopedPtr<OutputStream> indexOutput(dir.createFile("segment_0.fii"));
SegmentIndexWriter indexWriter(indexOutput.get());
indexWriter.setBlockSize(8);
ScopedPtr<OutputStream> dataOutput(dir.createFile("segment_0.fid"));
SegmentDataWriter writer(dataOutput.get(), &indexWriter, indexWriter.blockSize());
writer.addItem(200, 300);
writer.addItem(201, 301);
writer.addItem(201, 302);
writer.addItem(202, 303);
writer.close();
}
ScopedPtr<InputStream> indexInput(dir.openFile("segment_0.fii"));
ScopedPtr<InputStream> dataInput(dir.openFile("segment_0.fid"));
ScopedPtr<SegmentIndex> index(SegmentIndexReader(indexInput.get()).read());
SegmentDataReader dataReader(dataInput.get(), index->blockSize());
SegmentEnum reader(index.get(), &dataReader);
ASSERT_TRUE(reader.next());
ASSERT_EQ(200, reader.key());
ASSERT_EQ(300, reader.value());
ASSERT_TRUE(reader.next());
ASSERT_EQ(201, reader.key());
ASSERT_EQ(301, reader.value());
ASSERT_TRUE(reader.next());
ASSERT_EQ(201, reader.key());
ASSERT_EQ(302, reader.value());
ASSERT_TRUE(reader.next());
ASSERT_EQ(202, reader.key());
ASSERT_EQ(303, reader.value());
ASSERT_FALSE(reader.next());
}
| [
"[email protected]"
] | |
c27deb943c285d2f7df497af0d5ce7b96afc6158 | 3aa317f44322d3b4a9b46fa7a79f889ea373e2aa | /Project/04. Scripts/InstinctScript.cpp | 062c6e460ce0d7db44bd8b1b31209177e893738c | [] | no_license | oung/MapleStory-1 | 11580c7ee28337e0ba8f2cb70dcb54ab1c106f26 | 3ddbbbcd7c20a0bf835e724046be1072908b9bae | refs/heads/master | 2023-08-11T11:03:52.630096 | 2021-10-07T14:00:39 | 2021-10-07T14:00:39 | null | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 9,462 | cpp | #include "stdafx.h"
#include "InstinctScript.h"
#include "KeyMgr.h"
#include "TimeMgr.h"
#include "Transform.h"
#include "AnrealEngine/Collider.h"
#include "ResMgr.h"
#include "AnrealEngine/Material.h"
#include "AnrealEngine/MeshRender.h"
#include "AnrealEngine/Animator2D.h"
#include "AnrealEngine/Animation2D.h"
#include "AnrealEngine/CollisionMgr.h"
#include "AnrealEngine/SceneMgr.h"
#include "AnrealEngine/Scene.h"
#include "AnrealEngine/define.h"
#include "AnrealEngine/Script.h"
#include "PlayerScript.h"
#include "RagingBlowScript.h"
#include "ScriptMgr.h"
#include "QuestMgr.h"
#include "EffectScript.h"
bool CInstinctScript::PlayerAction = false;
bool CInstinctScript::m_bInstinctActive = false;
bool CInstinctScript::PrevConfirm = false;
CInstinctScript::CInstinctScript()
: m_iInstinctNumber(0)
, InstinctDamage{}
, Critical_Value(0)
{
SetScriptType((UINT)SCRIPT_TYPE::INSTINCTSCRIPT);
}
CInstinctScript::~CInstinctScript()
{
}
void CInstinctScript::OnCollisionEnter(CCollider * _pOther)
{
if (INSTINCT_SkillState == INSTINCT_FSM::ATTACK)
{
if (_pOther->GetGameObject()->GetLayerIdx() == CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetIdx())
{
for (UINT i = 0; i < CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetObjectVec().size(); ++i)
{
if (_pOther->GetGameObject() == CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetObjectVec()[i])
{
if (_pOther->GetGameObject()->Confirm_Life())
{
for (size_t i = 0; i < _pOther->GetGameObject()->GetScript().size(); ++i)
{
if (_pOther->GetGameObject()->GetScript()[i]->GetScriptType() != (UINT)SCRIPT_TYPE::MOBGRAVITYSCRIPT)
{
// if (((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->GetSkillType() != ((UINT)SKILL_TYPE::RAGINGBLOW_PHASE1) || ((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->GetSkillType() != ((UINT)SKILL_TYPE::RAGINGBLOW_PHASE2))
if (_pOther->GetGameObject()->GetScript()[i]->InstinctCollision == false)
{
_pOther->GetGameObject()->GetScript()[i]->InstinctCollision = true;
}
// if (Animator2D()->GetCurAnim()->GetCurFrm() <= 5)
{
((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->SetPushed(true);
((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->SetSkillType((UINT)SKILL_TYPE::COMBO_INSTINCT);
((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->m_bAggro = true;
}
}
}
}
}
}
}
}
}
void CInstinctScript::OnCollision(CCollider * _pOther)
{
if (INSTINCT_SkillState == INSTINCT_FSM::ATTACK)
{
if (_pOther->GetGameObject()->GetLayerIdx() == CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetIdx())
{
for (UINT i = 0; i < CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetObjectVec().size(); ++i)
{
if (_pOther->GetGameObject() == CSceneMgr::GetInst()->GetLayer(L"MONSTER")->GetObjectVec()[i])
{
if (_pOther->GetGameObject()->Confirm_Life())
{
for (UINT i = 0; i < _pOther->GetGameObject()->GetScript().size(); ++i)
{
if (_pOther->GetGameObject()->GetScript()[i]->GetScriptType() != (UINT)SCRIPT_TYPE::MOBGRAVITYSCRIPT)
{
_pOther->GetGameObject()->GetScript()[i]->InstinctCount += DT;
if ((CScript*)(_pOther->GetGameObject()->GetScript()[i])->InstinctCollision)
{
((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->SetSkillType((UINT)SKILL_TYPE::COMBO_INSTINCT);
((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->m_bAggro = true;
if (_pOther->GetGameObject()->GetScript()[i]->InstinctCount <= 0.07f)
{
return;
}
if (CSceneMgr::GetInst()->GetLayer(L"EFFECT_DUMMY")->GetObjectVec()[0]->GetName() == L"EFFECT")
{
if (CSceneMgr::GetInst()->GetLayer(L"EFFECT_DUMMY")->GetObjectVec()[0]->GetChild().size() != 0)
{
CGameObject* EffectPtr = CSceneMgr::GetInst()->GetLayer(L"EFFECT_DUMMY")->GetObjectVec()[0]->GetChild()[0];
CSceneMgr::GetInst()->GetLayer(L"EFFECT_DUMMY")->GetObjectVec()[0]->GetChild()[0]->DisconnectParent();
((CEffectScript*)(EffectPtr->GetScript()[0]))->EffectSequence = _pOther->GetGameObject()->GetScript()[i]->InstinctEffectCount;
_pOther->GetGameObject()->AddChild(EffectPtr);
((CEffectScript*)EffectPtr->GetScript()[0])->EFFECT_SkillState = SKILL_TYPE::COMBO_INSTINCT;
}
}
// ((CScript*)(_pOther->GetGameObject()->GetScript()[i]))->SubHP(AlphaDamage[_pOther->GetGameObject()->GetScript()[i]->AlphaEffectCount]);
_pOther->GetGameObject()->GetScript()[i]->InstinctCount = 0.f;
_pOther->GetGameObject()->GetScript()[i]->InstinctEffectCount += 1; // 최초 1회 재생 후 안되는 이유 검수해서 다시 보기 여기까지 했음.
if (INSTINCT_OF_TIME <= _pOther->GetGameObject()->GetScript()[i]->InstinctEffectCount)
{
_pOther->GetGameObject()->GetScript()[i]->InstinctEffectCount = 0;
_pOther->GetGameObject()->GetScript()[i]->InstinctCollision = false;
}
}
}
}
}
}
}
}
}
}
void CInstinctScript::OnCollisionExit(CCollider * _pOther)
{
}
bool CInstinctScript::Critical_Calculate()
{
Critical_Value = Well512Random::Instance().GetValue(0, 100);
if ((CPlayerScript::CRITICAL + CPlayerScript::MAPLESOLDIER) >= Critical_Value)
{
return true;
}
else
return false;
}
void CInstinctScript::awake()
{
m_pSharedMtrl = MeshRender()->GetSharedMaterial();
m_pCloneMtrl = MeshRender()->GetCloneMaterial();
}
void CInstinctScript::Skillstate()
{
switch (INSTINCT_SkillState)
{
case INSTINCT_FSM::DISABLE:
Animator2D()->PlayAnim(L"blink");
break;
case INSTINCT_FSM::ATTACK:
CurDirSet();
SkillPos();
switch (m_iInstinctNumber % 3)
{
case 0: Animator2D()->PlayAnim(L"400011074.effect.frames");
++m_iInstinctNumber;
if (m_iInstinctNumber >= 100)
{
m_iInstinctNumber = 0;
m_bInstinctActive = false;
}
break;
case 1: Animator2D()->PlayAnim(L"400011075.effect.frames");
++m_iInstinctNumber;
break;
case 2: Animator2D()->PlayAnim(L"400011076.effect.frames");
++m_iInstinctNumber;
break;
default:
break;
}
break;
//case INSTINCT_FSM::ENABLE:
// Animator2D()->PlayAnim(L"400011073.effect.frames");
// break;
case INSTINCT_FSM::END:
break;
default:
break;
}
}
void CInstinctScript::SkillPos()
{
PlayerDir = CRagingBlowScript::RagingDir;
if (PlayerDir == DIR::RIGHT)
{
if (INSTINCT_SkillState == INSTINCT_FSM::DISABLE && PrevConfirm)
{
INSTINCT_SkillState = INSTINCT_FSM::ATTACK;
vPos = CPlayerScript::GetPlayerPos();
vPos.x += 200.f;
vPos.z -= 300.f;
Transform()->SetLocalPos(vPos);
return;
}
}
else if (PlayerDir == DIR::LEFT)
{
if (INSTINCT_SkillState == INSTINCT_FSM::DISABLE && PrevConfirm)
{
INSTINCT_SkillState = INSTINCT_FSM::ATTACK;
vPos = CPlayerScript::GetPlayerPos();
vPos.x -= 200.f;
vPos.z -= 300.f;
Transform()->SetLocalPos(vPos);
return;
}
}
if (INSTINCT_SkillState == INSTINCT_FSM::NONE)
{
Transform()->SetLocalPos(DISABLE_POS);
GetGameObject()->SetActive(false);
}
}
void CInstinctScript::SkillChangeState()
{
PlayerState = CPlayerScript::GetPlayerState();
if (PlayerAction)
{
if (PlayerState == FSM::PRONE || PlayerState == FSM::ROPE || PlayerState == FSM::LADDER || PlayerState == FSM::SHOUT || PlayerState == FSM::SHADOWFLASH_ALPHA || PlayerState == FSM::SHADOWFLASH_BETA || PlayerState == FSM::DEATHFAULT || PlayerState == FSM::BUFF)
{
return;
}
if (m_bInstinctActive)
{
//
CPlayerScript::PlayerSkillPos = CPlayerScript::GetPlayerPos();
for (size_t i = 0; i < INSTINCT_OF_TIME; ++i)
{
if (Critical_Calculate())
{
InstinctDamage[i] = (int)(Well512Random::Instance().GetFloatValue(CPlayerScript::MIN_ATT * 1.2f, CPlayerScript::MAX_ATT * 1.2f) * 4.4f);
}
else
InstinctDamage[i] = (int)(Well512Random::Instance().GetFloatValue((float)CPlayerScript::MIN_ATT, (float)CPlayerScript::MAX_ATT) * 4.4f);
}
//
INSTINCT_SkillState = INSTINCT_FSM::DISABLE;
PlayerAction = false;
}
return;
}
if (Animator2D()->GetCurAnim() != nullptr)
{
if (Animator2D()->GetCurAnim()->IsFinish()) //현재 스킬 오브젝트의 현재 프레임이 끝이거나 0 일 경우 NONE으로
{
INSTINCT_SkillState = INSTINCT_FSM::NONE;
}
}
return;
}
void CInstinctScript::CurDirSet()
{
switch (PlayerDir)
{
case DIR::RIGHT:
vRot = Transform()->GetLocalRot();
vRot = { 0.f, PI, 0.f };
Transform()->SetLocalRot(vRot);
break;
case DIR::LEFT:
vRot = Transform()->GetLocalRot();
vRot = { 0.f, 0.f, 0.f };
Transform()->SetLocalRot(vRot);
break;
default:
break;
}
}
//
//void CInstinctScript::InstinctActivePos()
//{
//// InstinctActive = true;
//
// vPos = CSceneMgr::GetInst()->GetCurScene()->GetLayer(L"PLAYER")->GetObjectVec()[0]->Transform()->GetLocalPos();
// vPos.y += 50.f;
// vPos.z -= 300.f;
// Transform()->SetLocalPos(vPos);
//
//}
int CInstinctScript::update()
{
// CCollisionMgr::GetInst()->CollisionCheck(L"Default", L"MONSTER");
SkillPos();
SkillChangeState();
if (INSTINCT_PrevSKILLState != INSTINCT_SkillState)
{
if (INSTINCT_SkillState != INSTINCT_FSM::NONE)
{
GetGameObject()->SetActive(true);
}
Skillstate();
}
INSTINCT_PrevSKILLState = INSTINCT_SkillState;
return 0;
}
| [
"[email protected]"
] | |
0d39eae61c4ca902e5168b5d3744a3329166303d | 651cbae33f34feeb9b45931910c1ba83cb48ba69 | /SP3_Framework/App/Source/Scene2D/Physics2D.h | 17ef77a10a88035f444fb8a44ad796adb361f91a | [] | no_license | beatsmoon/SP3 | 0fa605a1fa16794a0f6eeb8a8d20185021cb3507 | 2abc6c9d3609544dda9888569f8714ee67d3ffa4 | refs/heads/master | 2022-12-03T08:10:01.618874 | 2020-08-20T04:52:26 | 2020-08-20T04:52:26 | 288,071,534 | 0 | 0 | null | 2020-08-19T09:05:29 | 2020-08-17T03:07:51 | C++ | UTF-8 | C++ | false | false | 1,807 | h | /**
CPhysics2D
By: Toh Da Jun
Date: Mar 2020
*/
#pragma once
#include <includes/glm.hpp>
#include <includes/gtc/matrix_transform.hpp>
#include <includes/gtc/type_ptr.hpp>
class CPhysics2D
{
public:
enum STATUS
{
IDLE = 0,
JUMP,
FALL,
NUM_STATUS
};
// Constructor
CPhysics2D(void);
// Destructor
virtual ~CPhysics2D(void);
// Init
bool Init(void);
// Set methods
void SetInitialVelocity(const glm::vec2 v2InitialVelocity); // Set Initial velocity
void SetFinalVelocity(const glm::vec2 v2FinalVelocity); // Set Final velocity
void SetAcceleration(const glm::vec2 v2Acceleration); // Set Acceleration
void SetDisplacement(const glm::vec2 v2Displacement); // Set Displacement
void SetTime(const float fTime); // Set Time
void SetStatus(const STATUS sStatus); // Set Status
// Get methods
glm::vec2 GetInitialVelocity(void) const; // Get Initial velocity
glm::vec2 GetFinalVelocity(void) const; // Get Final velocity
glm::vec2 GetAcceleration(void) const; // Get Acceleration
glm::vec2 GetDisplacement(void) const; // Get Displacement
float GetTime(void) const; // Get Time
STATUS GetStatus(void) const; // Get Status
// Update
void Update(void);
// Add elapsed time
void AddElapsedTime(const float fElapseTime);
// Calculate the distance between two vec2 varables
float CalculateDistance(glm::vec2 source, glm::vec2 destination);
// PrintSelf
void PrintSelf(void);
protected:
// Variables for SUVAT calculations
glm::vec2 v2InitialVelocity; // Initial velocity
glm::vec2 v2FinalVelocity; // Final velocity
glm::vec2 v2Acceleration; // Acceleration
glm::vec2 v2Displacement; // Displacement
float fTime; // Time
const glm::vec2 v2Gravity = glm::vec2( 0.0f, -10.f); // Gravity constant
STATUS sCurrentStatus;
};
| [
"[email protected]"
] | |
79454c874ec4c8d37394b6e9f0ae931f8543991c | 3d4560f23d2167c654f63ef9a4365d3c761c05f4 | /src/vehicle_attitude.cpp | f5deb4c295b81a525062928612c4aea01c5c827f | [
"BSD-3-Clause"
] | permissive | mayahaah/micrortps_agent | 9b127ccb27c87559cc4ca5f87e7725b3ff97ee80 | 3dcca9cb5b5a08e84728aaaf3a265d520be4158b | refs/heads/master | 2023-05-28T03:04:20.769987 | 2021-06-03T05:35:30 | 2021-06-03T05:35:30 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,791 | cpp | // Copyright 2016 Proyectos y Sistemas de Mantenimiento SL (eProsima).
//
// 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.
/*!
* @file vehicle_attitude.cpp
* This source file contains the definition of the described types in the IDL file.
*
* This file was generated by the tool gen.
*/
#ifdef _WIN32
// Remove linker warning LNK4221 on Visual Studio
namespace { char dummy; }
#endif
#include "vehicle_attitude.h"
#include <fastcdr/Cdr.h>
#include <fastcdr/exceptions/BadParamException.h>
using namespace eprosima::fastcdr::exception;
#include <utility>
vehicle_attitude::vehicle_attitude()
{
// m_timestamp_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@51e2adc7
m_timestamp_ = 0;
// m_timestamp_sample_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@1a8a8f7c
m_timestamp_sample_ = 0;
// m_q com.eprosima.idl.parser.typecode.AliasTypeCode@2353b3e6
memset(&m_q, 0, (4) * 4);
// m_delta_q_reset com.eprosima.idl.parser.typecode.AliasTypeCode@2353b3e6
memset(&m_delta_q_reset, 0, (4) * 4);
// m_quat_reset_counter_ com.eprosima.idl.parser.typecode.PrimitiveTypeCode@631330c
m_quat_reset_counter_ = 0;
}
vehicle_attitude::~vehicle_attitude()
{
}
vehicle_attitude::vehicle_attitude(const vehicle_attitude &x)
{
m_timestamp_ = x.m_timestamp_;
m_timestamp_sample_ = x.m_timestamp_sample_;
m_q = x.m_q;
m_delta_q_reset = x.m_delta_q_reset;
m_quat_reset_counter_ = x.m_quat_reset_counter_;
}
vehicle_attitude::vehicle_attitude(vehicle_attitude &&x)
{
m_timestamp_ = x.m_timestamp_;
m_timestamp_sample_ = x.m_timestamp_sample_;
m_q = std::move(x.m_q);
m_delta_q_reset = std::move(x.m_delta_q_reset);
m_quat_reset_counter_ = x.m_quat_reset_counter_;
}
vehicle_attitude& vehicle_attitude::operator=(const vehicle_attitude &x)
{
m_timestamp_ = x.m_timestamp_;
m_timestamp_sample_ = x.m_timestamp_sample_;
m_q = x.m_q;
m_delta_q_reset = x.m_delta_q_reset;
m_quat_reset_counter_ = x.m_quat_reset_counter_;
return *this;
}
vehicle_attitude& vehicle_attitude::operator=(vehicle_attitude &&x)
{
m_timestamp_ = x.m_timestamp_;
m_timestamp_sample_ = x.m_timestamp_sample_;
m_q = std::move(x.m_q);
m_delta_q_reset = std::move(x.m_delta_q_reset);
m_quat_reset_counter_ = x.m_quat_reset_counter_;
return *this;
}
size_t vehicle_attitude::getMaxCdrSerializedSize(size_t current_alignment)
{
size_t initial_alignment = current_alignment;
current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8);
current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8);
current_alignment += ((4) * 4) + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
current_alignment += ((4) * 4) + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1);
return current_alignment - initial_alignment;
}
size_t vehicle_attitude::getCdrSerializedSize(const vehicle_attitude& data, size_t current_alignment)
{
(void)data;
size_t initial_alignment = current_alignment;
current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8);
current_alignment += 8 + eprosima::fastcdr::Cdr::alignment(current_alignment, 8);
if ((4) > 0)
{
current_alignment += ((4) * 4) + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
}
if ((4) > 0)
{
current_alignment += ((4) * 4) + eprosima::fastcdr::Cdr::alignment(current_alignment, 4);
}
current_alignment += 1 + eprosima::fastcdr::Cdr::alignment(current_alignment, 1);
return current_alignment - initial_alignment;
}
void vehicle_attitude::serialize(eprosima::fastcdr::Cdr &scdr) const
{
scdr << m_timestamp_;
scdr << m_timestamp_sample_;
scdr << m_q;
scdr << m_delta_q_reset;
scdr << m_quat_reset_counter_;
}
void vehicle_attitude::deserialize(eprosima::fastcdr::Cdr &dcdr)
{
dcdr >> m_timestamp_;
dcdr >> m_timestamp_sample_;
dcdr >> m_q;
dcdr >> m_delta_q_reset;
dcdr >> m_quat_reset_counter_;
}
/*!
* @brief This function sets a value in member timestamp_
* @param _timestamp_ New value for member timestamp_
*/
void vehicle_attitude::timestamp_(uint64_t _timestamp_)
{
m_timestamp_ = _timestamp_;
}
/*!
* @brief This function returns the value of member timestamp_
* @return Value of member timestamp_
*/
uint64_t vehicle_attitude::timestamp_() const
{
return m_timestamp_;
}
/*!
* @brief This function returns a reference to member timestamp_
* @return Reference to member timestamp_
*/
uint64_t& vehicle_attitude::timestamp_()
{
return m_timestamp_;
}
/*!
* @brief This function sets a value in member timestamp_sample_
* @param _timestamp_sample_ New value for member timestamp_sample_
*/
void vehicle_attitude::timestamp_sample_(uint64_t _timestamp_sample_)
{
m_timestamp_sample_ = _timestamp_sample_;
}
/*!
* @brief This function returns the value of member timestamp_sample_
* @return Value of member timestamp_sample_
*/
uint64_t vehicle_attitude::timestamp_sample_() const
{
return m_timestamp_sample_;
}
/*!
* @brief This function returns a reference to member timestamp_sample_
* @return Reference to member timestamp_sample_
*/
uint64_t& vehicle_attitude::timestamp_sample_()
{
return m_timestamp_sample_;
}
/*!
* @brief This function copies the value in member q
* @param _q New value to be copied in member q
*/
void vehicle_attitude::q(const vehicle_attitude__float_array_4 &_q)
{
m_q = _q;
}
/*!
* @brief This function moves the value in member q
* @param _q New value to be moved in member q
*/
void vehicle_attitude::q(vehicle_attitude__float_array_4 &&_q)
{
m_q = std::move(_q);
}
/*!
* @brief This function returns a constant reference to member q
* @return Constant reference to member q
*/
const vehicle_attitude__float_array_4& vehicle_attitude::q() const
{
return m_q;
}
/*!
* @brief This function returns a reference to member q
* @return Reference to member q
*/
vehicle_attitude__float_array_4& vehicle_attitude::q()
{
return m_q;
}
/*!
* @brief This function copies the value in member delta_q_reset
* @param _delta_q_reset New value to be copied in member delta_q_reset
*/
void vehicle_attitude::delta_q_reset(const vehicle_attitude__float_array_4 &_delta_q_reset)
{
m_delta_q_reset = _delta_q_reset;
}
/*!
* @brief This function moves the value in member delta_q_reset
* @param _delta_q_reset New value to be moved in member delta_q_reset
*/
void vehicle_attitude::delta_q_reset(vehicle_attitude__float_array_4 &&_delta_q_reset)
{
m_delta_q_reset = std::move(_delta_q_reset);
}
/*!
* @brief This function returns a constant reference to member delta_q_reset
* @return Constant reference to member delta_q_reset
*/
const vehicle_attitude__float_array_4& vehicle_attitude::delta_q_reset() const
{
return m_delta_q_reset;
}
/*!
* @brief This function returns a reference to member delta_q_reset
* @return Reference to member delta_q_reset
*/
vehicle_attitude__float_array_4& vehicle_attitude::delta_q_reset()
{
return m_delta_q_reset;
}
/*!
* @brief This function sets a value in member quat_reset_counter_
* @param _quat_reset_counter_ New value for member quat_reset_counter_
*/
void vehicle_attitude::quat_reset_counter_(uint8_t _quat_reset_counter_)
{
m_quat_reset_counter_ = _quat_reset_counter_;
}
/*!
* @brief This function returns the value of member quat_reset_counter_
* @return Value of member quat_reset_counter_
*/
uint8_t vehicle_attitude::quat_reset_counter_() const
{
return m_quat_reset_counter_;
}
/*!
* @brief This function returns a reference to member quat_reset_counter_
* @return Reference to member quat_reset_counter_
*/
uint8_t& vehicle_attitude::quat_reset_counter_()
{
return m_quat_reset_counter_;
}
size_t vehicle_attitude::getKeyMaxCdrSerializedSize(size_t current_alignment)
{
size_t current_align = current_alignment;
return current_align;
}
bool vehicle_attitude::isKeyDefined()
{
return false;
}
void vehicle_attitude::serializeKey(eprosima::fastcdr::Cdr &scdr) const
{
(void) scdr;
}
| [
"[email protected]"
] | |
2e9a8b194d7477872041217a9ec3320576db5ff0 | c836e1b688a904ce2f8f106a874cc2a8c6c92617 | /09-passivityTests/simviz.cpp | d7421afb6828f25e3fda4f647aa5709144565358 | [] | no_license | airsus/Sigma7Applications | fb4bcc4c0cd15c9fa5b505e5e2a1270c5d61c035 | 29a4b708c90b793d14c02c56a3d779669c2f8d2b | refs/heads/master | 2022-07-02T18:40:24.029346 | 2020-05-13T16:34:49 | 2020-05-13T16:34:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,183 | cpp | // This example tests the haptic device driver and the open-loop bilateral teleoperation controller.
#include "Sai2Model.h"
#include "Sai2Graphics.h"
#include "Sai2Simulation.h"
#include <dynamics3d.h>
#include "redis/RedisClient.h"
#include "timer/LoopTimer.h"
#include <GLFW/glfw3.h> //must be loaded after loading opengl/glew
#include "force_sensor/ForceSensorSim.h" // Add force sensor simulation and display classes
#include "force_sensor/ForceSensorDisplay.h"
#include <iostream>
#include <string>
#include <signal.h>
bool fSimulationRunning = false;
void sighandler(int){fSimulationRunning = false;}
using namespace std;
using namespace Eigen;
using namespace chai3d;
const string world_file = "../resources/09-passivityTests/world.urdf";
const string robot_file = "../resources/09-passivityTests/panda_arm.urdf";
const string robot_name = "panda";
const string camera_name = "camera";
const string link_name = "link7"; //robot end-effector
// Set sensor frame transform in end-effector frame
Affine3d sensor_transform_in_link = Affine3d::Identity();
const Vector3d sensor_pos_in_link = Eigen::Vector3d(0.0,0.0,0.117);
VectorXd f_task = VectorXd::Zero(6);
// redis keys:
// - write (from simulation or robot sensors):
string JOINT_ANGLES_KEY = "sai2::Sigma7Applications::sensors::q";
string JOINT_VELOCITIES_KEY = "sai2::Sigma7Applications::sensors::dq";
string FORCE_SENSED_KEY = "sai2::Sigma7Applications::sensors::force_task_sensed";
// - read (from haptic device command input):
string JOINT_TORQUES_COMMANDED_KEY = "sai2::Sigma7Applications::actuators::torque_joint_robot";
RedisClient redis_client;
// create graphics object
auto graphics = new Sai2Graphics::Sai2Graphics(world_file, true);
// simulation function prototype
void simulation(Sai2Model::Sai2Model* robot, Simulation::Sai2Simulation* sim);
void simulation_dummy(Sai2Model::Sai2Model* robot, Simulation::Sai2Simulation* sim);
// callback to print glfw errors
void glfwError(int error, const char* description);
// callback when a key is pressed
void keySelect(GLFWwindow* window, int key, int scancode, int action, int mods);
// callback when a mouse button is pressed
void mouseClick(GLFWwindow* window, int button, int action, int mods);
// flags for scene camera movement
bool fTransXp = false;
bool fTransXn = false;
bool fTransYp = false;
bool fTransYn = false;
bool fTransZp = false;
bool fTransZn = false;
bool fshowCameraPose = false;
bool fRotPanTilt = false;
// flag for enabling/disabling remote task
bool fOnOffRemote = false;
int k=0;
const bool flag_simulation = true;
int main() {
cout << "Loading URDF world model file: " << world_file << endl;
cout << "Keyboard Options:" << endl << endl;
cout << "[1] - Enable-Disable remote task" << endl;
// if(!flag_simulation)
// {
// JOINT_TORQUES_COMMANDED_KEY = "sai2::FrankaPanda::Bonnie::actuators::fgc";
// JOINT_ANGLES_KEY = "sai2::FrankaPanda::Bonnie::sensors::q";
// JOINT_VELOCITIES_KEY = "sai2::FrankaPanda::Bonnie::sensors::dq";
// FORCE_SENSED_KEY= "sai2::ATIGamma_Sensor::force_torque";
// }
// start redis client
redis_client = RedisClient();
redis_client.connect();
// load graphics scene
Vector3d camera_pos, camera_lookat, camera_vertical;
graphics->getCameraPose(camera_name, camera_pos, camera_vertical, camera_lookat);
// // create a camera
// auto camera = new cCamera(graphics->_world);
// // add the camera to the world
// graphics->_world->addChild(camera);
// camera->setUseMultipassTransparency(true);
// load robots
auto robot = new Sai2Model::Sai2Model(robot_file, false);
// load simulation world
auto sim = new Simulation::Sai2Simulation(world_file, false);
sim->setCollisionRestitution(0);
sim->setCoeffFrictionStatic(0.2);
// read joint positions, velocities, update model
sim->getJointPositions(robot_name, robot->_q);
sim->getJointVelocities(robot_name, robot->_dq);
robot->updateKinematics();
/*------- Set up visualization -------*/
// set up error callback
glfwSetErrorCallback(glfwError);
// initialize GLFW
glfwInit();
// retrieve resolution of computer display and position window accordingly
GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary);
// information about computer screen and GLUT display window
int screenW = mode->width;
int screenH = mode->height;
int windowW = 0.8 * screenH;
int windowH = 0.5 * screenH;
int windowPosY = (screenH - windowH) / 2;
int windowPosX = windowPosY;
// create window and make it current
glfwWindowHint(GLFW_VISIBLE, 0);
GLFWwindow* window = glfwCreateWindow(windowW, windowH, "SAI2.0 - Sigma7Applications", NULL, NULL);
glfwSetWindowPos(window, windowPosX, windowPosY);
glfwShowWindow(window);
glfwMakeContextCurrent(window);
glfwSwapInterval(1);
// set callbacks
glfwSetKeyCallback(window, keySelect);
glfwSetMouseButtonCallback(window, mouseClick);
// cache variables
double last_cursorx, last_cursory;
fSimulationRunning = true;
thread sim_thread(simulation_dummy, robot, sim);
if(flag_simulation)
{
// start the simulation thread first
thread sim_thread_bis(simulation, robot, sim);
sim_thread.swap(sim_thread_bis);
sim_thread_bis.join();
}
auto handler = new cHapticDeviceHandler();
// while window is open:
while (!glfwWindowShouldClose(window))
{
if(!flag_simulation)
{
// robot->_q = redis_client.getEigenMatrixJSON(JOINT_ANGLES_KEY);
// robot->_dq = redis_client.getEigenMatrixJSON(JOINT_VELOCITIES_KEY);
// robot->updateKinematics();
}
// update graphics. this automatically waits for the correct amount of time
int width, height;
glfwGetFramebufferSize(window, &width, &height);
graphics->updateGraphics(robot_name, robot);
graphics->render(camera_name, width, height);
// swap buffers
glfwSwapBuffers(window);
// wait until all GL commands are completed
glFinish();
// check for any OpenGL errors
GLenum err;
err = glGetError();
assert(err == GL_NO_ERROR);
// poll for events
glfwPollEvents();
// move scene camera as required
// graphics->getCameraPose(camera_name, camera_pos, camera_vertical, camera_lookat);
Eigen::Vector3d cam_depth_axis;
cam_depth_axis = camera_lookat - camera_pos;
cam_depth_axis.normalize();
Eigen::Vector3d cam_up_axis;
// cam_up_axis = camera_vertical;
// cam_up_axis.normalize();
cam_up_axis << 0.0, 0.0, 1.0; //TODO: there might be a better way to do this
Eigen::Vector3d cam_roll_axis = (camera_lookat - camera_pos).cross(cam_up_axis);
cam_roll_axis.normalize();
Eigen::Vector3d cam_lookat_axis = camera_lookat;
cam_lookat_axis.normalize();
if (fTransXp) {
camera_pos = camera_pos + 0.05*cam_roll_axis;
camera_lookat = camera_lookat + 0.05*cam_roll_axis;
}
if (fTransXn) {
camera_pos = camera_pos - 0.05*cam_roll_axis;
camera_lookat = camera_lookat - 0.05*cam_roll_axis;
}
if (fTransYp) {
// camera_pos = camera_pos + 0.05*cam_lookat_axis;
camera_pos = camera_pos + 0.05*cam_up_axis;
camera_lookat = camera_lookat + 0.05*cam_up_axis;
}
if (fTransYn) {
// camera_pos = camera_pos - 0.05*cam_lookat_axis;
camera_pos = camera_pos - 0.05*cam_up_axis;
camera_lookat = camera_lookat - 0.05*cam_up_axis;
}
if (fTransZp) {
camera_pos = camera_pos + 0.1*cam_depth_axis;
camera_lookat = camera_lookat + 0.1*cam_depth_axis;
}
if (fTransZn) {
camera_pos = camera_pos - 0.1*cam_depth_axis;
camera_lookat = camera_lookat - 0.1*cam_depth_axis;
}
if (fshowCameraPose) {
cout << endl;
cout << "camera position : " << camera_pos.transpose() << endl;
cout << "camera lookat : " << camera_lookat.transpose() << endl;
cout << endl;
}
if (fRotPanTilt) {
// get current cursor position
double cursorx, cursory;
glfwGetCursorPos(window, &cursorx, &cursory);
//TODO: might need to re-scale from screen units to physical units
double compass = 0.006*(cursorx - last_cursorx);
double azimuth = 0.006*(cursory - last_cursory);
double radius = (camera_pos - camera_lookat).norm();
Eigen::Matrix3d m_tilt; m_tilt = Eigen::AngleAxisd(azimuth, -cam_roll_axis);
camera_pos = camera_lookat + m_tilt*(camera_pos - camera_lookat);
Eigen::Matrix3d m_pan; m_pan = Eigen::AngleAxisd(compass, -cam_up_axis);
camera_pos = camera_lookat + m_pan*(camera_pos - camera_lookat);
}
graphics->setCameraPose(camera_name, camera_pos, cam_up_axis, camera_lookat);
glfwGetCursorPos(window, &last_cursorx, &last_cursory);
}
// stop simulation
fSimulationRunning = false;
sim_thread.join();
// destroy context
glfwDestroyWindow(window);
// terminate
glfwTerminate();
return 0;
}
//------------------------------------------------------------------------------
void simulation_dummy(Sai2Model::Sai2Model* robot, Simulation::Sai2Simulation* sim) {}
//------------------------------------------------------------------------------
void simulation(Sai2Model::Sai2Model* robot, Simulation::Sai2Simulation* sim) {
VectorXd command_torques = VectorXd::Zero(robot->dof());
redis_client.setEigenMatrixJSON(JOINT_TORQUES_COMMANDED_KEY, command_torques);
sensor_transform_in_link.translation() = sensor_pos_in_link;
//sensor_transform_in_link.linear() = Matrix3d::Identity();
// Add force sensor to the end-effector
auto force_sensor = new ForceSensorSim(robot_name, link_name, sensor_transform_in_link, robot);
auto fsensor_display = new ForceSensorDisplay(force_sensor, graphics);
Vector3d sensed_force = Vector3d::Zero();
Vector3d sensed_moment = Vector3d::Zero();
// force_sensor->enableFilter(0.016);
// create a timer
LoopTimer timer;
timer.initializeTimer();
timer.setLoopFrequency(2000);
double last_time = timer.elapsedTime(); //secs
bool fTimerDidSleep = true;
unsigned long long simulation_counter = 0;
while (fSimulationRunning) {
fTimerDidSleep = timer.waitForNextLoop();
// read arm torques from redis
command_torques = redis_client.getEigenMatrixJSON(JOINT_TORQUES_COMMANDED_KEY);
sim->setJointTorques(robot_name, command_torques);
// integrate forward
double curr_time = timer.elapsedTime();
double loop_dt = curr_time - last_time;
sim->integrate(loop_dt);
// read joint positions, velocities, update model
sim->getJointPositions(robot_name, robot->_q);
sim->getJointVelocities(robot_name, robot->_dq);
robot->updateKinematics();
// write new robot state to redis
redis_client.setEigenMatrixJSON(JOINT_ANGLES_KEY, robot->_q);
redis_client.setEigenMatrixJSON(JOINT_VELOCITIES_KEY, robot->_dq);
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// read end-effector task forces from the force sensor simulation
force_sensor->update(sim);
force_sensor->getForce(sensed_force);
force_sensor->getMoment(sensed_moment);
f_task << sensed_force, sensed_moment;
// write task force in redis
redis_client.setEigenMatrixJSON(FORCE_SENSED_KEY,f_task);
//update last time
last_time = curr_time;
simulation_counter++;
}
double end_time = timer.elapsedTime();
std::cout << "\n";
std::cout << "Simulation Loop run time : " << end_time << " seconds\n";
std::cout << "Simulation Loop updates : " << timer.elapsedCycles() << "\n";
std::cout << "Simulation Loop frequency : " << timer.elapsedCycles()/end_time << "Hz\n";
}
//------------------------------------------------------------------------------
void glfwError(int error, const char* description) {
cerr << "GLFW Error: " << description << endl;
exit(1);
}
//------------------------------------------------------------------------------
void keySelect(GLFWwindow* window, int key, int scancode, int action, int mods)
{
bool set = (action != GLFW_RELEASE);
switch(key) {
case GLFW_KEY_ESCAPE:
// exit application
glfwSetWindowShouldClose(window,GL_TRUE);
break;
case GLFW_KEY_RIGHT:
fTransXp = set;
break;
case GLFW_KEY_LEFT:
fTransXn = set;
break;
case GLFW_KEY_UP:
fTransYp = set;
break;
case GLFW_KEY_DOWN:
fTransYn = set;
break;
case GLFW_KEY_A:
fTransZp = set;
break;
case GLFW_KEY_Z:
fTransZn = set;
break;
case GLFW_KEY_R:
fOnOffRemote = set;
break;
case GLFW_KEY_S:
fshowCameraPose = set;
break;
default:
break;
}
}
//------------------------------------------------------------------------------
void mouseClick(GLFWwindow* window, int button, int action, int mods) {
bool set = (action != GLFW_RELEASE);
//TODO: mouse interaction with robot
switch (button) {
// left click pans and tilts
case GLFW_MOUSE_BUTTON_LEFT:
fRotPanTilt = set;
// NOTE: the code below is recommended but doesn't work well
// if (fRotPanTilt) {
// // lock cursor
// glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
// } else {
// glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
// }
break;
// if right click: don't handle. this is for menu selection
case GLFW_MOUSE_BUTTON_RIGHT:
//TODO: menu
break;
// if middle click: don't handle. doesn't work well on laptops
case GLFW_MOUSE_BUTTON_MIDDLE:
break;
default:
break;
}
}
| [
"[email protected]"
] | |
9e59f5366604c522cd2f51e3a85d37b6077d618f | e26d77b5b54aaae9aa0ad5f50a181ce29896f0a6 | /src/train.cpp | bda609df9faecf6a7953ca16ecca69b75e5b09ed | [] | no_license | Lrwin16g/inpaint | 216de3ff8355dc3db28898f7d886638490178698 | f6c8cfdeeef7b34745d04adf139eb26d04d10b85 | refs/heads/master | 2020-04-06T07:05:44.802113 | 2014-11-24T10:45:16 | 2014-11-24T10:45:16 | 14,288,873 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,403 | cpp | #include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include "gFoE.h"
// GaussFoEの学習プログラム
int main(int argc, char *argv[])
{
if (argc != 5)
{
std::cerr << "Usage: " << argv[0] << " <input> <output> <eta> <epsilon>" << std::endl;
return -1;
}
// 学習用画像パスのリストを読込み
std::ifstream ifs(argv[1]);
if (ifs.is_open() == false)
{
std::cerr << "File open error: " << argv[1] << std::endl;
return -1;
}
std::string str;
std::vector<std::string> filelist;
while (getline(ifs, str))
{
filelist.push_back(str);
}
ifs.close();
// 学習用画像をvectorに格納
int width = 16;
int height = 16;
std::vector<std::vector<double> > supervisor;
for (size_t i = 0; i < filelist.size(); ++i)
{
cv::Mat_<double> image = cv::imread(filelist[i].c_str(), 0);
image = image.reshape(0, 1) / 255.0;
std::vector<double> value;
image.copyTo(value);
supervisor.push_back(value);
}
// 学習
GaussFoE model(8, 3, 3);
model.train(supervisor, atof(argv[3]), atof(argv[4]), 1000000, width, height);
model.saveParameter(argv[2]);
return 0;
}
| [
"[email protected]"
] | |
e13ec723642ce5037c9e4d7ea18ebaf29c51f090 | 8ba63ac00df1619d1f710d863ffc531abe2fa0ed | /algorithms/dynamic programming/howSum(tabulation).cpp | f44f61a5c72b4d657083276611913d38d3ee76d0 | [] | no_license | abhigyani/code-practice | fe25ed019e48138cf29db5c982c770f02a3f7507 | 9227e12a22367de5e9a34e856d0e25332e6f98c9 | refs/heads/master | 2023-07-18T21:48:20.524741 | 2021-09-25T07:43:47 | 2021-09-25T07:43:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,278 | cpp | #include<iostream>
#include<vector>
using namespace std;
vector<int>howsum(int target, vector<int>given_vector){
vector<vector<int>>ans_vector;
for(int i=0;i<=target;i++){
vector<int>inside;
inside.push_back(0);
ans_vector.push_back(inside);
}
ans_vector[0].pop_back();
ans_vector[0].push_back(1);
for( int i=0;i<target;i++){
if(ans_vector[i][0]>0){
for( int j=0;j<given_vector.size();j++){
int x=i+given_vector[j];
if(x<=target){
ans_vector[x].pop_back();
if(i>0)ans_vector[x]=ans_vector[i];
ans_vector[x].push_back(given_vector[j]);
}
}
}
}
return ans_vector[target];
}
int main(){
int target;
cout<<"Tragetsum:"<<endl;
cin>>target;
int size;
cout<<"size of vector"<<endl;
cin>>size;
vector<int>given_vector;
for( int i=0;i<size;i++){
int x;
cout<<"vector value"<<endl;
cin>>x;
given_vector.push_back(x);
}
vector<int>ans=howsum(target,given_vector);
cout<<"how to calculate the target value"<<endl;
for(int i=0;i<ans.size();i++){
cout<<ans[i]<<" ";
}
} | [
"[email protected]"
] | |
08977ecdeb4de5a1065362c9f45e45fbab7240c6 | 06bf4d60f4414321dce33dd887fe74e262b7f38d | /module08/ex02/mutantstack.cpp | 7dc820f9ccc333b7981239a634ad9014834c9225 | [] | no_license | subin195-09/42_CPP | 6d32bf6d6fb9f41ece469c1dfccdf1c416d5e942 | b8791c81c0eafdd7dafdd1efd81efc24cae3556e | refs/heads/main | 2023-07-14T07:57:17.794462 | 2021-08-28T18:44:02 | 2021-08-28T18:44:02 | 383,376,046 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,810 | cpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* mutantstack.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: skim <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/08 20:42:00 by skim #+# #+# */
/* Updated: 2021/08/22 15:36:38 by skim ### ########.fr */
/* */
/* ************************************************************************** */
#ifdef MUTANTSTACK_HPP
#define MUTANTSTACK_HPP
#include "mutantstack.hpp"
template<typename T>
MutantStack<T>::MutantStack() { }
template<typename T>
MutantStack<T>::MutantStack( const MutantStack & src )
{
this->operator=(src);
}
template<typename T>
MutantStack<T>::~MutantStack()
{
}
template<typename T>
MutantStack<T> &MutantStack<T>::operator=( MutantStack<T> const & rhs )
{
if ( this != &rhs )
this->c = rhs->c;
return *this;
}
template<typename T>
typename MutantStack<T>::iterator MutantStack<T>::begin(void)
{
return this->c.begin();
}
template<typename T>
typename MutantStack<T>::iterator MutantStack<T>::end(void)
{
return this->c.end();
}
template<typename T>
typename MutantStack<T>::reverse_iterator MutantStack<T>::rbegin(void)
{
return this->c.rbegin();
}
template<typename T>
typename MutantStack<T>::reverse_iterator MutantStack<T>::rend(void)
{
return this->c.rend();
}
#endif
| [
"[email protected]"
] | |
81156b3a53bfba4664a391704c7e1131d7384117 | 5d4f80445645f0771d5bed3aebeac2c7c1d4210b | /motor/StepperDriver.h | c0839b1b801ea1b83f6393c9af2de4dcb200d595 | [] | no_license | Kaldie/GeRoBot | ac9f3699dbfd91111d2e60b939d82046f4636fdc | b7ad01d62df52995f5c82298b06113b0a26f79ce | refs/heads/master | 2020-12-24T16:15:57.102544 | 2017-03-21T13:23:56 | 2017-03-21T13:23:56 | 25,439,362 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,659 | h | #ifndef StepperDriver_h
#define StepperDriver_h
#include <BaseMotor.h>
// Forward declared classes
class StateSequence;
class SequenceVector;
class StepperDriver: public BaseMotor {
public:
typedef std::shared_ptr<StepperDriver> DriverPointer;
/// Maximum frequency (in deca hertz) which the motor starts from
GETSET(int, m_pullIn, PullIn);
/// Maximum frequency (in deca hertz) which the motor can stop from
GETSET(int, m_pullOut, PullOut);
/// Maximum frequency (in deca hertz)
GETSET(int, m_maxSpeed, MaxSpeed);
/// Possible increment of the speed after pull in
GETSET(int, m_incremental, Incremental);
private:
// Private methods to have easy acces to certain pins, such as enable pin
const int getPin(const int i_number) const
{return getCurrentPinState().getPinVector()[i_number];}
int enablePin() const {return getPin(0);}
int directionPin() const {return getPin(1);}
int stepPin() const {return getPin(2);}
bool setDirection(const std::string&);
int getPinValueForDirection(const std::string&);
public:
// Constructors
StepperDriver();
// Construct Driver from given pin numbers:
// enable pin, direction pin, en step pin
explicit StepperDriver(const PinVector&);
// Constructor given pin number and default direction
StepperDriver(const PinVector& i_pinVector,
const std::string& i_defaultDirection,
const int& i_pullIn,
const int& i_pullOut,
const int& i_max);
// Enable functions of the driver!
virtual bool setEnable(const bool&);
/// Add to the Statesequence states which will ensure the motor sets a step
virtual void moveStep(const std::string&,
StateSequence*);
virtual void moveSteps(const std::string& i_motorDirection,
const int& i_numberOfSteps,
SequenceVector* i_vector);
/// return the maximum speed the motor could achive right now
/// including acceleration etc.
virtual int getMaximumSpeed() const;
/// return the minimum speed the motor could achive right now
/// including breaking etc.
virtual int getMinimumSpeed() const;
/// Return the number of states needed per step
virtual int numberOfStatesPerStep() const {return 2;}
/// from a pin state, determine the status of the motor at that point
virtual void getMotorStatus(const PinState& i_pinState,
bool* i_isEnabled,
std::string* i_rotationDirection) const;
// Display pin state vector
virtual void displayPinState(const PinState&) const;
virtual void displayPinState()const;
};
#endif // MOTOR_STEPPERDRIVER_H_
| [
"[email protected]"
] | |
57910708ff28404aa91d8b4e44a7e73d2912477d | 3270af3dc2f0021a34aca7540417172e4c2603f2 | /Exercises/SBCC-H.cpp | 4bb1aff22f37bc566854861b17196d58d6133c17 | [] | no_license | lucasandre22/programming-club | 24433339d80a7e744795d49b8a068888ff91fba9 | 5aa7926c51eed330559719caa3cea842b92859af | refs/heads/master | 2023-09-01T23:10:03.937877 | 2021-10-30T22:31:28 | 2021-10-30T22:31:28 | 415,341,352 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 530 | cpp | #include <bits/stdc++.h>
#include <iostream>
using namespace std;
int main(void) {
int n, k, i;
int a, b;
vector<pair<int, int>> vetor;
pair<int, int> aux;
scanf("%d %d", &n, &k);
for(i = 0; i < n; i++) {
scanf("%d %d", &a, &b);
aux.first = a; aux.second = b;
vetor.push_back(aux);
}
for(i = 0; i < n; i++) {
if(vetor[vetor[i].first-1].second != vetor[i].second) {
printf("N\n");
return 0;
}
}
printf("Y\n");
return 0;
} | [
"[email protected]"
] | |
ae95a74f731474bb3dd789e5fe7c39804619ae22 | 185b00fc2b448497991418a5214b49445afe18e7 | /SDK/PUBG_HudAlwaysOn_parameters.hpp | fd2975d47c470593b390e81325b319c04de1c249 | [] | no_license | cpkt9762/PPLAY_SDK | f562e3391df2a46abca33d202884705fdd03a1f8 | 30bf1a7fadab2ed07635e55c9c9749720cd79528 | refs/heads/master | 2021-04-28T10:19:19.392994 | 2018-02-19T07:20:44 | 2018-02-19T07:20:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,762 | hpp | #pragma once
// PlayerUnknown's Battlegrounds (2.6.23) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function HudAlwaysOn.HudAlwaysOn_C.OnPrepass_4
struct UHudAlwaysOn_C_OnPrepass_4_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.SetCharacterInfoDown
struct UHudAlwaysOn_C_SetCharacterInfoDown_Params
{
};
// Function HudAlwaysOn.HudAlwaysOn_C.SetCharacterInfoUp
struct UHudAlwaysOn_C_SetCharacterInfoUp_Params
{
};
// Function HudAlwaysOn.HudAlwaysOn_C.OnPrepass_3
struct UHudAlwaysOn_C_OnPrepass_3_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.UpdatePlayerHealth
struct UHudAlwaysOn_C_UpdatePlayerHealth_Params
{
};
// Function HudAlwaysOn.HudAlwaysOn_C.TeamInfoPrepass
struct UHudAlwaysOn_C_TeamInfoPrepass_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.On_ReportBotton_Prepass_1
struct UHudAlwaysOn_C_On_ReportBotton_Prepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.OnPrepass_2
struct UHudAlwaysOn_C_OnPrepass_2_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.On_CharacterCanvas_Prepass_1
struct UHudAlwaysOn_C_On_CharacterCanvas_Prepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.GetVisibilityOnMatchState
struct UHudAlwaysOn_C_GetVisibilityOnMatchState_Params
{
ESlateVisibility ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.On_BlueZoneGpsWidget_RoundType_Prepass_1
struct UHudAlwaysOn_C_On_BlueZoneGpsWidget_RoundType_Prepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.OnPrepass_1
struct UHudAlwaysOn_C_OnPrepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function HudAlwaysOn.HudAlwaysOn_C.Construct
struct UHudAlwaysOn_C_Construct_Params
{
};
// Function HudAlwaysOn.HudAlwaysOn_C.BndEvt__ReportBotton_K2Node_ComponentBoundEvent_5_OnButtonClickedEvent__DelegateSignature
struct UHudAlwaysOn_C_BndEvt__ReportBotton_K2Node_ComponentBoundEvent_5_OnButtonClickedEvent__DelegateSignature_Params
{
};
// Function HudAlwaysOn.HudAlwaysOn_C.ExecuteUbergraph_HudAlwaysOn
struct UHudAlwaysOn_C_ExecuteUbergraph_HudAlwaysOn_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
339aff1588537db63f748fef6c970a7c2185c80d | 628145d99093790651a7ecbe88b2f8e5867823df | /Strings/main.cpp | 23afa30f585f2dfa46d39b29b54e779aec6d7d3e | [] | no_license | da230896/Practically-Dumb | 235dde3a81dcdfae5b3c8b7f7209214fda6edf18 | 814562fbab9bf388ec99cdc24afda96d7661e352 | refs/heads/master | 2021-01-23T05:24:51.806229 | 2017-08-20T20:01:28 | 2017-08-20T20:01:28 | 92,963,263 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,005 | cpp | #include <iostream>
#include <string>
#include "Z-algorithm.h"
using namespace std;
int main()
{
// compressedTrie root;
// root.initialise();
// root.insertWord("");
// root.insertWord("facebook");
// root.insertWord("doing");
// root.insertWord("face");
// root.insertWord("facebooker");
// root.insertWord("facepalm");
// root.insertWord("thereafter");
// root.insertWord("thereis");
// root.insertWord("this");
// cout << root.countWord("this") << '\n';
// root.deleteWord("doing");
// cout << root.countWord("doing") << '\n';
// root.deleteWord("this");
// root.deleteWord("thereis");
// cout << root.countWord("thereafter") << '\n';
// root.deleteWord((string ("deer").c_str()));
// //root.deleteWord((string("dog")).c_str());
// cout << root.countPrefix("de") << '\n';
if(find("aaabbbxxcccfff","bxxcc"))
{
cout << "Pattern Found\n";
}else{
cout << "Pattern Not Found\n";
}
} | [
"[email protected]"
] | |
29ed0ab1c0148fb8bae1b013c2cd6c74882eb1c2 | 8a1969c70bfe9c43e5611fe9e306855fc9a0e36a | /Fem_Liphy_Kamran/include/memory.h | 740b1487e5e4c5e22e18f5cd5279d26d8bc0cde9 | [] | no_license | LucaMarradi/FEM_Kamran | 0fdb4f13d69fa8c612de33e76fb76a6c58df9f7a | fb871c6d3a51832f40fb12db5009e52f785ae159 | refs/heads/master | 2021-01-10T16:54:18.344481 | 2016-02-25T21:14:29 | 2016-02-25T21:14:29 | 52,544,556 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 409 | h | #ifndef MEMORY_H
#define MEMORY_H
class Memory
{
public:
Memory();
~Memory();
void doubleMat( double **&, const unsigned int, const unsigned int );
void doubleVec( double *&, const unsigned int );
void Delete2ndMat( double **, const unsigned int );
void Delete2ndMat( unsigned int **, const unsigned int );
void Delete3rdMat( double ***, const unsigned int, const unsigned int );
};
#endif
| [
"[email protected]"
] | |
aef28bfde81fdd89c55a0b1b8dc5e584d6f96984 | 49f88ff91aa582e1a9d5ae5a7014f5c07eab7503 | /gen/third_party/blink/renderer/bindings/core/v8/string_or_array_buffer.cc | 4a8f49c52f566cec9038ce7536a3cc473afb466f | [] | no_license | AoEiuV020/kiwibrowser-arm64 | b6c719b5f35d65906ae08503ec32f6775c9bb048 | ae7383776e0978b945e85e54242b4e3f7b930284 | refs/heads/main | 2023-06-01T21:09:33.928929 | 2021-06-22T15:56:53 | 2021-06-22T15:56:53 | 379,186,747 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,540 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/union_container.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "third_party/blink/renderer/bindings/core/v8/string_or_array_buffer.h"
#include "third_party/blink/renderer/bindings/core/v8/idl_types.h"
#include "third_party/blink/renderer/bindings/core/v8/native_value_traits_impl.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/bindings/core/v8/v8_array_buffer.h"
namespace blink {
StringOrArrayBuffer::StringOrArrayBuffer() : type_(SpecificType::kNone) {}
DOMArrayBuffer* StringOrArrayBuffer::GetAsArrayBuffer() const {
DCHECK(IsArrayBuffer());
return array_buffer_;
}
void StringOrArrayBuffer::SetArrayBuffer(DOMArrayBuffer* value) {
DCHECK(IsNull());
array_buffer_ = value;
type_ = SpecificType::kArrayBuffer;
}
StringOrArrayBuffer StringOrArrayBuffer::FromArrayBuffer(DOMArrayBuffer* value) {
StringOrArrayBuffer container;
container.SetArrayBuffer(value);
return container;
}
const String& StringOrArrayBuffer::GetAsString() const {
DCHECK(IsString());
return string_;
}
void StringOrArrayBuffer::SetString(const String& value) {
DCHECK(IsNull());
string_ = value;
type_ = SpecificType::kString;
}
StringOrArrayBuffer StringOrArrayBuffer::FromString(const String& value) {
StringOrArrayBuffer container;
container.SetString(value);
return container;
}
StringOrArrayBuffer::StringOrArrayBuffer(const StringOrArrayBuffer&) = default;
StringOrArrayBuffer::~StringOrArrayBuffer() = default;
StringOrArrayBuffer& StringOrArrayBuffer::operator=(const StringOrArrayBuffer&) = default;
void StringOrArrayBuffer::Trace(blink::Visitor* visitor) {
visitor->Trace(array_buffer_);
}
void V8StringOrArrayBuffer::ToImpl(v8::Isolate* isolate, v8::Local<v8::Value> v8Value, StringOrArrayBuffer& impl, UnionTypeConversionMode conversionMode, ExceptionState& exceptionState) {
if (v8Value.IsEmpty())
return;
if (conversionMode == UnionTypeConversionMode::kNullable && IsUndefinedOrNull(v8Value))
return;
if (v8Value->IsArrayBuffer()) {
DOMArrayBuffer* cppValue = V8ArrayBuffer::ToImpl(v8::Local<v8::Object>::Cast(v8Value));
impl.SetArrayBuffer(cppValue);
return;
}
{
V8StringResource<> cppValue = v8Value;
if (!cppValue.Prepare(exceptionState))
return;
impl.SetString(cppValue);
return;
}
}
v8::Local<v8::Value> ToV8(const StringOrArrayBuffer& impl, v8::Local<v8::Object> creationContext, v8::Isolate* isolate) {
switch (impl.type_) {
case StringOrArrayBuffer::SpecificType::kNone:
return v8::Null(isolate);
case StringOrArrayBuffer::SpecificType::kArrayBuffer:
return ToV8(impl.GetAsArrayBuffer(), creationContext, isolate);
case StringOrArrayBuffer::SpecificType::kString:
return V8String(isolate, impl.GetAsString());
default:
NOTREACHED();
}
return v8::Local<v8::Value>();
}
StringOrArrayBuffer NativeValueTraits<StringOrArrayBuffer>::NativeValue(v8::Isolate* isolate, v8::Local<v8::Value> value, ExceptionState& exceptionState) {
StringOrArrayBuffer impl;
V8StringOrArrayBuffer::ToImpl(isolate, value, impl, UnionTypeConversionMode::kNotNullable, exceptionState);
return impl;
}
} // namespace blink
| [
"[email protected]"
] | |
23514b1e2f564ce46afe261f0e0014e79ec7e5ca | 8ef2077a6472a7fed2c3961d64e32eaa9acca237 | /WidgetAnimator.h | 510f7dbdaad0e01d5541f4dda7444e62c9fad8c5 | [] | no_license | diskzero/workspace | 087b850cbaf6f9c094d9d9c57abe4c6c4f598c8a | 6391b3db70e72476e00624f75f2231b980df8312 | refs/heads/master | 2016-09-06T16:19:54.820459 | 2015-03-03T22:44:54 | 2015-03-03T22:44:54 | 31,625,494 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | h | /*
The MIT License (MIT)
Copyright (c) 2011 Gene Z. Ragan
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
#ifndef WIDGETANIMATOR_HAS_BEEN_INCLUDED
#define WIDGETANIMATOR_HAS_BEEN_INCLUDED
// Qt
#include <QMap>
#include <QObject>
// Forward declarations
class DynamicGridLayout;
class QPropertyAnimation;
class QRect;
class QWidget;
//=============================================================================
// class WidgetAnimator
//=============================================================================
class WidgetAnimator : public QObject
{
Q_OBJECT
public:
WidgetAnimator(DynamicGridLayout* inLayout);
void animate(QWidget* inWidget, const QRect& inDestination, bool animate);
bool animating() const;
bool animating(QWidget* inWidget) const;
void abort(QWidget* inWidget);
private Q_SLOTS:
void animationFinished();
void animationObjectDestroyed();
private:
typedef QMap<QWidget*, QPropertyAnimation*> AnimationMap;
AnimationMap mAnimationMap;
DynamicGridLayout* mLayout;
};
#endif // !WIDGETANIMATOR_HAS_BEEN_INCLUDED
| [
"[email protected]"
] | |
4083edbe6bc8dcea7bdb3932e92705c4cf395b05 | bd833dcac4bd73157d3b9d87f731f3800e1d692e | /v3/micro/src/MillisTimer.h | b3437d2f968678f0d2ec36a4d976b42d7d233abd | [] | no_license | piotr07da/LedController | c431183b00b10de3188a8ea0dbd3035c4c79bdf4 | aae281f43a9a9c2758fcfc8d119edc1921f0b353 | refs/heads/master | 2022-02-07T10:12:08.721333 | 2022-01-20T14:08:31 | 2022-01-20T14:08:31 | 132,886,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 264 | h | #ifndef __MILLIS_TIMER__
#define __MILLIS_TIMER__
#include "Particle.h"
class MillisTimer
{
private:
uint32_t _interval;
uint32_t _lastTime;
public:
void Setup(uint32_t interval);
bool Check();
bool Check(uint32_t& lastValidCheckInterval);
};
#endif
| [
"[email protected]"
] | |
6a720cc15c45be06113bace38c6441099ac6cfee | a9762e452d2f53d5e1a30698d55cfeac85973706 | /Fish.cpp | 31b142c2e4613cf5605c63ba054a9d77da3680ca | [] | no_license | CircuitFreakCoder/Cpp_Inheritance | 50b055939fcf2be04ab9b453700036e6059e4105 | 5684888b57f2a7e0d2f57bbb3dc3d6a95c98ac41 | refs/heads/master | 2020-03-30T01:15:05.736003 | 2013-06-01T14:23:08 | 2013-06-01T14:23:08 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 725 | cpp | #include <iostream>
using namespace std;
class Fish
{
public:
bool FreshWaterFish;
void Swim()
{
cout<<((FreshWaterFish)?"Swims in lake":"Swims in sea")<<endl;
}
};
class Tuna: public Fish
{
public:
Tuna()
{
FreshWaterFish = false;
}
};
class Carp: public Fish
{
public:
Carp()
{
FreshWaterFish = true;
}
};
int main()
{
Carp myLunch;
Tuna myDinner;
cout << "Getting my food to swim" << endl;
cout << "Lunch: ";
myLunch.Swim();
cout << "Dinner: ";
myDinner.Swim();
return 0;
}
/*
Getting my food to swim
Lunch: Swims in lake
Dinner: Swims in sea
*/
| [
"[email protected]"
] | |
59ac5ead63d3c5437bf5681e90978dda74f8de5a | 97163be23ec46d35737c9e41aa34107479d1e323 | /Bit Magic/aloneInCouple.cpp | 0da76d00f26052294c3ff0022582cf28599e2dee | [] | no_license | Kamrul-Hasan-1971/Code | 54612faea047f523306158bd936850a2c599ef3e | 7ca4da7b1e23a3c3fef06f598f11ba83054373ae | refs/heads/master | 2023-09-02T09:06:05.462951 | 2021-11-05T06:53:18 | 2021-11-05T06:53:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 363 | cpp | #include <iostream>
#include <set>
using namespace std;
int main(){
int t;
cin >> t;
while(t--){
int n, i;
cin >> n;
int arr[n];
for(i = 0; i < n; i++) cin >> arr[i];
set <int> s;
for(i = 0; i < n; i++){
if(s.find(arr[i]) == s.end()) s.insert(arr[i]);
else s.erase(arr[i]);
}
cout << (*s.begin()) << "\n";
}
}
| [
"[email protected]"
] | |
ee4291743e00b150da193bac78cf24764d2d899a | ac719e4e5d8bf134a6ad3ce1175e68a10ad52da2 | /Classes/Native/mscorlib_System_Collections_Generic_KeyValuePair_22300064352.h | f4fc512aed0c34c5a49c64965e34186573f63706 | [
"MIT"
] | permissive | JasonMcCoy/BOOM-Bound | b5fa6305ec23fd6742d804da0e206a923ff22118 | 574223c5643f8d89fdad3b8fc3c5d49a6a669e6e | refs/heads/master | 2021-01-11T06:23:28.917883 | 2020-05-20T17:28:58 | 2020-05-20T17:28:58 | 72,157,115 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,822 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Type
struct Type_t;
// System.Collections.Generic.IDictionary`2<System.String,System.Collections.Generic.KeyValuePair`2<System.Type,SimpleJson.Reflection.ReflectionUtils/SetDelegate>>
struct IDictionary_2_t2295861161;
#include "mscorlib_System_ValueType1744280289.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.KeyValuePair`2<System.Type,System.Collections.Generic.IDictionary`2<System.String,System.Collections.Generic.KeyValuePair`2<System.Type,SimpleJson.Reflection.ReflectionUtils/SetDelegate>>>
struct KeyValuePair_2_t2300064352
{
public:
// TKey System.Collections.Generic.KeyValuePair`2::key
Type_t * ___key_0;
// TValue System.Collections.Generic.KeyValuePair`2::value
Il2CppObject* ___value_1;
public:
inline static int32_t get_offset_of_key_0() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2300064352, ___key_0)); }
inline Type_t * get_key_0() const { return ___key_0; }
inline Type_t ** get_address_of_key_0() { return &___key_0; }
inline void set_key_0(Type_t * value)
{
___key_0 = value;
Il2CppCodeGenWriteBarrier(&___key_0, value);
}
inline static int32_t get_offset_of_value_1() { return static_cast<int32_t>(offsetof(KeyValuePair_2_t2300064352, ___value_1)); }
inline Il2CppObject* get_value_1() const { return ___value_1; }
inline Il2CppObject** get_address_of_value_1() { return &___value_1; }
inline void set_value_1(Il2CppObject* value)
{
___value_1 = value;
Il2CppCodeGenWriteBarrier(&___value_1, value);
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"[email protected]"
] | |
dd57c2f7693da967b33d0f6543d673c3cc4f34d7 | 365bac64e7d5f70669d8dff3f5b2f2b7bd3f4fa7 | /Step4/City\City\MemberReport.cpp | 2b8ef093226b08432cbe452bb77ad15daa7f1e9a | [] | no_license | winnie1027/CSE-335-MSU | cce1b97d77906d6232481c2f75c15d58f19b480d | 4a6d20bbffa452019fecbeaf7d6b267733033f4c | refs/heads/main | 2023-04-21T21:32:27.590813 | 2021-05-05T04:51:39 | 2021-05-05T04:51:39 | 343,647,844 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 529 | cpp | #include "pch.h"
#include <sstream>
#include <iostream>
#include "MemberReport.h"
#include "Tile.h"
using namespace std;
/**
* Constructor
* @param tile File this report is for.
*/
CMemberReport::CMemberReport(std::shared_ptr<CTile> tile) : mTile(tile)
{
}
/**
* Generate the report line that is displayed.
* @return String report line
*/
std::wstring CMemberReport::Report()
{
wstringstream str;
str << mTile->GetX() << L", " << mTile->GetY() << L": " << mReport;
return str.str();
} | [
"[email protected]"
] | |
bb6e19ee193673e62af9e3f6cb6fa5a835e9a737 | acf1f88bd88dff4d05f319006a0fcae51e511abf | /Level2/servoMotionModule.ino | 1094ce7719f49d0817758668e0bd427029681179 | [] | no_license | andrewwu0629/Firex | f1bccc583ead2c1c8303936411e2641e47acec39 | 34edf5456432ff430fcff3d12fec08357a81d7d5 | refs/heads/master | 2020-07-24T10:39:19.149895 | 2019-06-04T10:26:01 | 2019-06-04T10:26:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,426 | ino | /* servoMotionModule.ino
A wheeled robot servo module
by C.D.Odom on 2.17.2015. Updated 7.18.17.
Configured for TRINITY COLLEGE INTERNATIONAL FIRE FIGHTING ROBOT CONTEST 2019 by Robin D. on 3.30.19
*/
/*
const int leftServoPin = 11;
const int rightServoPin = 12;
*/
// Left Servo Pulse Width Constants
const int left_forward_fast = 1785; // CCW Fast
const int left_forward_slow = 1600; // CCW Slow
const int left_stop = 1500; // Center position
const int left_reverse_slow = 1400; // CW Slow
const int left_reverse_fast = 1000; // CW Fast
// Right Servo Pulse Width Constants
const int right_forward_fast = 1000; // CW Fast
const int right_forward_slow = 1400; // CW Slow
const int right_stop = 1500; // Center position
const int right_reverse_slow = 1600; // CCW Slow
const int right_reverse_fast = 2000; // CCW Fast
/* For Fast motors
// Left Servo Pulse Width Constants
const int left_forward_fast = 1350; // CCW Fast
const int left_forward_slow = 1400; // CCW Slow
const int left_stop = 1500; // Center position
const int left_reverse_slow = 1600; // CW Slow
const int left_reverse_fast = 2000; // CW Fast
// Right Servo Pulse Width Constants
const int right_forward_fast = 2000; // CW Fast
const int right_forward_slow = 1600; // CW Slow
const int right_stop = 1500; // Center position
const int right_reverse_slow = 1400; // CCW Slow
const int right_reverse_fast = 1000; // CCW Fast
*/
// Current issue with the new motor is that it explicitly turns left at the start of the first "long" forward
void blinkOK(int numBlinks) {
// blink the onboard LED to let the user know the code was properly uploaded
for (int i = 0; i < numBlinks; i++) {
digitalWrite(LEDPin, HIGH);
delay(250);
digitalWrite(LEDPin, LOW);
delay(250);
}
}
void motionFastTest() {
// a diagnostic test of basic robot motion at high speed
forwardFast(88); // take 88 quick "steps" forward (about 31 cm with my OneBot)
robotStop(10); // stop motors to prevent high current drain
leftFast(50); // pivot left 50 quick "steps" (about 180 degrees with my OneBot)
robotStop(10);
forwardFast(88); // return to starting point
robotStop(10);
rightFast(94); // pivot right 94 quick "steps" (about 360 degrees with my OneBot)
robotStop(10);
reverseFast(88); // take 88 quick "steps" in reverse (about 33 cm with my OneBot)
}
void motionSlowTest() {
// a diagnostic test of basic robot motion at slow speed
forwardSlow(88); // take 88 slow "steps" forward (about 9 cm with my OneBot)
robotStop(10); // stop motors to prevent high current drain
leftSlow(220); // pivot left 220 slow "steps" (about 180 degrees with my OneBot)
robotStop(10);
forwardSlow(88); // return to starting point
robotStop(10);
rightSlow(453); // pivot right 453 slow "steps" (about 360 degrees with my OneBot)
robotStop(10);
reverseSlow(88); // take 88 slow "steps" in reverse (about 8 cm with my OneBot)
}
// These movement functions are the HIGHEST LEVEL commands. They cause the robot to
// take a certain number of steps in the designated direction and speed, or to stop
// for a certain number of "steps". These functions call the "step" functions below.
void robotStop(int x) {
for (int i = 0; i <= x ; i++) {
stopStep(); // a hard stop (not a coasting stop)
}
}
void forwardFast(int x) {
for (int i = 0; i <= x ; i++) {
forwardStepFast();
}
}
void forwardSlow(int x) {
for (int i = 0; i <= x ; i++) {
forwardStepSlow();
}
}
void reverseFast(int x) {
for (int i = 0; i <= x ; i++) {
reverseStepFast();
}
}
void reverseSlow(int x) {
for (int i = 0; i <= x ; i++) {
reverseStepSlow();
}
}
void rightFast(int x) {
for (int i = 0; i <= x ; i++) {
rightStepFast();
}
}
void rightSlow(int x) {
for (int i = 0; i <= x ; i++) {
rightStepSlow();
}
}
void leftFast(int x) {
for (int i = 0; i <= x ; i++) {
leftStepFast();
}
}
void leftSlow(int x) {
for (int i = 0; i <= x ; i++) {
leftStepSlow();
}
}
// These "step" functions are the SECOND LOWEST LEVEL of the movement commands. They are
// used to turn both servo wheels in concert to make the robot take exactly one step in
// some direction, or to send a hard stop to both wheels. This is done by calling the
// createPulse() function, once for each wheel. It is CRITICAL that you keep the 20ms
// delay, because it is necessary to give the motors time to respond!
void stopStep() {
createPulse(leftServoPin, left_stop);
createPulse(rightServoPin, right_stop);
delay(20); // do NOT alter this delay time!
}
void forwardStepFast() {
createPulse(leftServoPin, left_forward_fast);
createPulse(rightServoPin, right_forward_fast);
delay(20); // do NOT alter this delay time!
}
void forwardStepSlow() {
createPulse(leftServoPin, left_forward_slow);
createPulse(rightServoPin, right_forward_slow);
delay(20); // do NOT alter this delay time!
}
void reverseStepFast() {
createPulse(leftServoPin, left_reverse_fast);
createPulse(rightServoPin, right_reverse_fast);
delay(20); // do NOT alter this delay time!
}
void reverseStepSlow() {
createPulse(leftServoPin, left_reverse_slow);
createPulse(rightServoPin, right_reverse_slow);
delay(20); // do NOT alter this delay time!
}
void rightStepSlow() {
createPulse(leftServoPin, left_forward_slow);
createPulse(rightServoPin, right_reverse_slow);
delay(20); // do NOT alter this delay time!
}
void leftStepSlow() {
createPulse(leftServoPin, left_reverse_slow);
createPulse(rightServoPin, right_forward_slow);
delay(20); // do NOT alter this delay time!
}
void rightStepFast() {
createPulse(leftServoPin, left_forward_fast);
createPulse(rightServoPin, right_reverse_fast);
delay(20); // do NOT alter this delay time!
}
void leftStepFast() {
createPulse(leftServoPin, left_reverse_fast);
createPulse(rightServoPin, right_forward_fast);
delay(20); // do NOT alter this delay time!
}
// createPulse() is the LOWEST LEVEL (most basic) of the movement commands.
// It simply creates a single pulse of a given pulse width on a given pin.
// This command makes ONE servo (set by the servoPin variable) take ONE
// step whose speed and direction is set by the pulseWidth variable.
void createPulse(byte servoPin, int pulseWidth) {
// take one step with one servo
digitalWrite(servoPin, HIGH); // create the rising edge of the pulse
delayMicroseconds(pulseWidth); // precisely set pulse width in microseconds!
digitalWrite(servoPin, LOW); // create the falling edge of the pulse
}
////////////// Robin's
const int turnSteps = 1; // steps taken per turn action
const int forwardSteps = 1; // steps taken per walk action
const int right90Steps = 24;
const int left90Steps = 25;
const float firstSensorTailDistance = 15.0; // distance between front sensor to robot's tail
const float firstSensorDoorwayDistance = 3.0;
const int stepsForwardAfterTurn = 25 * stepsPerCm; // measure from distance between the bot at door's end to another, min steps to confirm the "stick" (180 turn) ACTUALLY SHOULD USE stepsPerCm2 but nvm since the longer the better, and stick doesn't exist in practical
const int stepsForwardAfterTurn2 = 13; // steps forward the robot will take after side90Ex() has been suspended to prevent false isFar() or stick
const int stepsAwayBefore90 = 5; // initialize turn(this) in opposite direction before do the sharp turn to prevent crashing
void readyServo() {
pinMode(leftServoPin, OUTPUT);
pinMode(rightServoPin, OUTPUT);
}
void rightSlightly(int multiplier) {
rightSlow(turnSteps * multiplier);
}
void leftSlightly(int multiplier) {
leftSlow(turnSteps * multiplier);
}
void forwardSlightly(int multiplier) {
forwardFast(forwardSteps * multiplier);
}
void right90(int multiplier) {
rightFast(right90Steps * multiplier);
}
void left90(int multiplier) {
leftFast(left90Steps * multiplier);
}
void right90Ex(float lastSense, bool justComeOut) {
if(!justComeOut){
leftSlightly(stepsAwayBefore90);
}
const float tailAdder = 1.0;
int moveSteps = (int)((tailAdder + firstSensorTailDistance - firstSensorDoorwayDistance*justComeOut) * stepsPerCm + lastSense * stepsPerCm);
// if(fireExtinguished){
for (int i = 0; i < moveSteps; i++) {
if (detectLine()) {
return;
}
forwardFast(1);
}
// }
// else{
// forwardFast(moveSteps);
// }
right90(1);
for (int i = 0; i < stepsForwardAfterTurn; i++) {
if (detectLine() || (!isFarIR(getRangeFrontLow()) && getRangeFrontLow() < minWalkable)) {
return;
}
forwardFast(1);
float s1 = getRangeRightFront();
float s2 = getRangeRightFront();
float s3 = getRangeRightFront();
float rangeRightFront = selectRange(s1, s2, s3);
if(!isFar(rangeRightFront)){
for(int j = 0; j < stepsForwardAfterTurn2; j++){
if (detectLine() || (!isFarIR(getRangeFrontLow()) && getRangeFrontLow() < minWalkable)){
return;
}
forwardFast(1);
}
return;
}
}
}
void left90Ex(float lastSense, bool justComeOut) {
if(!justComeOut){
rightSlightly(stepsAwayBefore90);
}
const float tailAdder = 1.0;
int moveSteps = (int)((tailAdder + firstSensorTailDistance - firstSensorDoorwayDistance*justComeOut) * stepsPerCm + lastSense * stepsPerCm);
// if(fireExtinguished){
for (int i = 0; i < moveSteps; i++) {
if (detectLine()) {
return;
}
forwardFast(1);
}
// }
// else{
// forwardFast(moveSteps);
// }
left90(1);
for (int i = 0; i < stepsForwardAfterTurn; i++) {
if (detectLine() || (!isFarIR(getRangeFrontLow()) && getRangeFrontLow() < minWalkable)) {
return;
}
forwardFast(1);
float s1 = getRangeLeftFront();
float s2 = getRangeLeftFront();
float s3 = getRangeLeftFront();
float rangeLeftFront = selectRange(s1, s2, s3);
if(!isFar(rangeLeftFront)){
for(int j = 0; j < stepsForwardAfterTurn2; j++){
if (detectLine() || (!isFarIR(getRangeFrontLow()) && getRangeFrontLow() < minWalkable)){
return;
}
forwardFast(1);
}
return;
}
}
}
| [
"[email protected]"
] | |
f3c79d1be53cef1b68d6c685b8fd5a3b0d604ab8 | 38e9b9c2d550ee208cfc4b526babb9f63f98e866 | /rpmessagequeue.h | 762df807af49f69f95966334cb34f098ab1837a2 | [] | no_license | hankhank/rplib | 1c824742324117f165e082365983e8602737bdbd | 8378ee75cbff2afd9b901c3231fb6776c7b66dfb | refs/heads/master | 2020-04-06T11:29:57.480117 | 2012-02-08T20:04:05 | 2012-02-08T20:04:05 | 2,976,118 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 333 | h | #ifndef RPMESSAGEQUEUE_H_
#define RPMESSAGEQUEUE_H_
#include "rpqueue.h"
#include "rpmessage.h"
namespace rp
{
template <typename T, int QUEUE_SIZE>
class RpMessageQueue : public RpQueue<RpMessage<T>, QUEUE_SIZE>
{
public:
RpMessageQueue(){};
RpMessageQueue(const RpMessageQueue&);
};
};
#endif
| [
"[email protected]"
] | |
45cab54405e077fb0038e02d27aee9c03c7341cc | b28305dab0be0e03765c62b97bcd7f49a4f8073d | /ui/base/ime/chromeos/ime_keymap.cc | 4b5dbde88ca5ee58c1d9b47dedf147d00741301d | [
"BSD-3-Clause"
] | permissive | svarvel/browser-android-tabs | 9e5e27e0a6e302a12fe784ca06123e5ce090ced5 | bd198b4c7a1aca2f3e91f33005d881f42a8d0c3f | refs/heads/base-72.0.3626.105 | 2020-04-24T12:16:31.442851 | 2019-08-02T19:15:36 | 2019-08-02T19:15:36 | 171,950,555 | 1 | 2 | NOASSERTION | 2019-08-02T19:15:37 | 2019-02-21T21:47:44 | null | UTF-8 | C++ | false | false | 7,941 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ui/base/ime/chromeos/ime_keymap.h"
#include <stddef.h>
#include <map>
#include "base/lazy_instance.h"
#include "base/macros.h"
namespace ui {
namespace {
const struct KeyCodeTable {
KeyboardCode keyboard_code;
const char* dom_code;
} kKeyCodeTable[] = {{VKEY_BACK, "Backspace"},
{VKEY_TAB, "Tab"},
{VKEY_RETURN, "Enter"},
{VKEY_MENU, "ContextMenu"},
{VKEY_PAUSE, "Pause"},
{VKEY_CAPITAL, "CapsLock"},
{VKEY_KANA, "KanaMode"},
{VKEY_HANGUL, "HangulMode"},
{VKEY_HANJA, "Hanja"},
{VKEY_KANJI, "Kanji"},
{VKEY_ESCAPE, "Escape"},
{VKEY_CONVERT, "Convert"},
{VKEY_NONCONVERT, "NoConvert"},
{VKEY_SPACE, "Space"},
{VKEY_END, "End"},
{VKEY_HOME, "Home"},
{VKEY_LEFT, "ArrowLeft"},
{VKEY_UP, "ArrowUp"},
{VKEY_RIGHT, "ArrowRight"},
{VKEY_DOWN, "ArrowDown"},
{VKEY_SNAPSHOT, "PrintScreen"},
{VKEY_INSERT, "Insert"},
{VKEY_DELETE, "Delete"},
{VKEY_HELP, "Help"},
{VKEY_0, "Digit0"},
{VKEY_1, "Digit1"},
{VKEY_2, "Digit2"},
{VKEY_3, "Digit3"},
{VKEY_4, "Digit4"},
{VKEY_5, "Digit5"},
{VKEY_6, "Digit6"},
{VKEY_7, "Digit7"},
{VKEY_8, "Digit8"},
{VKEY_9, "Digit9"},
{VKEY_A, "KeyA"},
{VKEY_B, "KeyB"},
{VKEY_C, "KeyC"},
{VKEY_D, "KeyD"},
{VKEY_E, "KeyE"},
{VKEY_F, "KeyF"},
{VKEY_G, "KeyG"},
{VKEY_H, "KeyH"},
{VKEY_I, "KeyI"},
{VKEY_J, "KeyJ"},
{VKEY_K, "KeyK"},
{VKEY_L, "KeyL"},
{VKEY_M, "KeyM"},
{VKEY_N, "KeyN"},
{VKEY_O, "KeyO"},
{VKEY_P, "KeyP"},
{VKEY_Q, "KeyQ"},
{VKEY_R, "KeyR"},
{VKEY_S, "KeyS"},
{VKEY_T, "KeyT"},
{VKEY_U, "KeyU"},
{VKEY_V, "KeyV"},
{VKEY_W, "KeyW"},
{VKEY_X, "KeyX"},
{VKEY_Y, "KeyY"},
{VKEY_Z, "KeyZ"},
{VKEY_LWIN, "OSLeft"},
{VKEY_RWIN, "OSRight"},
{VKEY_NUMPAD0, "Numpad0"},
{VKEY_NUMPAD1, "Numpad1"},
{VKEY_NUMPAD2, "Numpad2"},
{VKEY_NUMPAD3, "Numpad3"},
{VKEY_NUMPAD4, "Numpad4"},
{VKEY_NUMPAD5, "Numpad5"},
{VKEY_NUMPAD6, "Numpad6"},
{VKEY_NUMPAD7, "Numpad7"},
{VKEY_NUMPAD8, "Numpad8"},
{VKEY_NUMPAD9, "Numpad9"},
{VKEY_MULTIPLY, "NumpadMultiply"},
{VKEY_ADD, "NumpadAdd"},
{VKEY_SUBTRACT, "NumpadSubtract"},
{VKEY_DECIMAL, "NumpadDecimal"},
{VKEY_DIVIDE, "NumpadDivide"},
{VKEY_F1, "F1"},
{VKEY_F2, "F2"},
{VKEY_F3, "F3"},
{VKEY_F4, "F4"},
{VKEY_F5, "F5"},
{VKEY_F6, "F6"},
{VKEY_F7, "F7"},
{VKEY_F8, "F8"},
{VKEY_F9, "F9"},
{VKEY_F10, "F10"},
{VKEY_F11, "F11"},
{VKEY_F12, "F12"},
{VKEY_F13, "F13"},
{VKEY_F14, "F14"},
{VKEY_F15, "F15"},
{VKEY_F16, "F16"},
{VKEY_F17, "F17"},
{VKEY_F18, "F18"},
{VKEY_F19, "F19"},
{VKEY_F20, "F20"},
{VKEY_F21, "F21"},
{VKEY_F22, "F22"},
{VKEY_F23, "F23"},
{VKEY_F24, "F24"},
{VKEY_NUMLOCK, "NumLock"},
{VKEY_SCROLL, "ScrollLock"},
{VKEY_LSHIFT, "ShiftLeft"},
{VKEY_RSHIFT, "ShiftRight"},
{VKEY_LCONTROL, "ControlLeft"},
{VKEY_RCONTROL, "ControlRight"},
{VKEY_LMENU, "AltLeft"},
{VKEY_RMENU, "AltRight"},
{VKEY_BROWSER_BACK, "BrowserBack"},
{VKEY_BROWSER_FORWARD, "BrowserForward"},
{VKEY_BROWSER_REFRESH, "BrowserRefresh"},
{VKEY_BROWSER_STOP, "BrowserStop"},
{VKEY_BROWSER_SEARCH, "BrowserSearch"},
{VKEY_BROWSER_HOME, "BrowserHome"},
{VKEY_VOLUME_MUTE, "VolumeMute"},
{VKEY_VOLUME_DOWN, "VolumeDown"},
{VKEY_VOLUME_UP, "VolumeUp"},
{VKEY_BRIGHTNESS_DOWN, "BrightnessDown"},
{VKEY_BRIGHTNESS_UP, "BrightnessUp"},
{VKEY_MEDIA_LAUNCH_APP1, "ChromeOSSwitchWindow"},
{VKEY_MEDIA_LAUNCH_APP2, "ChromeOSFullscreen"},
{VKEY_MEDIA_NEXT_TRACK, "MediaTrackNext"},
{VKEY_MEDIA_PREV_TRACK, "MediaTrackPrevious"},
{VKEY_MEDIA_STOP, "MediaStop"},
{VKEY_MEDIA_PLAY_PAUSE, "MediaPlayPause"},
{VKEY_MEDIA_LAUNCH_MAIL, "LaunchMail"},
{VKEY_OEM_1, "Semicolon"},
{VKEY_OEM_PLUS, "Equal"},
{VKEY_OEM_COMMA, "Comma"},
{VKEY_OEM_MINUS, "Minus"},
{VKEY_OEM_PERIOD, "Period"},
{VKEY_OEM_2, "Slash"},
{VKEY_OEM_3, "Backquote"},
{VKEY_OEM_4, "BracketLeft"},
{VKEY_OEM_5, "Backslash"},
{VKEY_OEM_6, "BracketRight"},
{VKEY_OEM_7, "Quote"}};
class KeyCodeMap {
public:
KeyCodeMap() {
for (size_t i = 0; i < arraysize(kKeyCodeTable); ++i) {
map_dom_key_[kKeyCodeTable[i].dom_code] = kKeyCodeTable[i].keyboard_code;
map_key_dom_[kKeyCodeTable[i].keyboard_code] = kKeyCodeTable[i].dom_code;
}
}
KeyboardCode GetKeyboardCode(const std::string& dom_code) const {
std::map<std::string, KeyboardCode>::const_iterator it =
map_dom_key_.find(dom_code);
return (it == map_dom_key_.end()) ? VKEY_UNKNOWN : it->second;
}
std::string GetDomKeycode(KeyboardCode key_code) const {
std::map<KeyboardCode, std::string>::const_iterator it =
map_key_dom_.find(key_code);
return (it == map_key_dom_.end()) ? "" : it->second;
}
private:
std::map<std::string, KeyboardCode> map_dom_key_;
std::map<KeyboardCode, std::string> map_key_dom_;
};
base::LazyInstance<KeyCodeMap>::Leaky g_keycode_map =
LAZY_INSTANCE_INITIALIZER;
} // namespace
KeyboardCode DomKeycodeToKeyboardCode(const std::string& code) {
return g_keycode_map.Get().GetKeyboardCode(code);
}
std::string KeyboardCodeToDomKeycode(KeyboardCode code) {
return g_keycode_map.Get().GetDomKeycode(code);
}
} // namespace ui
| [
"[email protected]"
] | |
3218c5921f0c02c05572695a35806bdaa223abc4 | 93b24e6296dade8306b88395648377e1b2a7bc8c | /client/wxWidgets/wx/build.h | 308073db9131e9d6405173aeb1221aa0dc7a02c5 | [] | no_license | dahahua/pap_wclinet | 79c5ac068cd93cbacca5b3d0b92e6c9cba11a893 | d0cde48be4d63df4c4072d4fde2e3ded28c5040f | refs/heads/master | 2022-01-19T21:41:22.000190 | 2013-10-12T04:27:59 | 2013-10-12T04:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,552 | h | ///////////////////////////////////////////////////////////////////////////////
// Name: wx/build.h
// Purpose: Runtime build options checking
// Author: Vadim Zeitlin, Vaclav Slavik
// Modified by:
// Created: 07.05.02
// RCS-ID: $Id: build.h,v 1.18 2004/09/09 17:42:29 ABX Exp $
// Copyright: (c) 2002 Vadim Zeitlin <[email protected]>
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
#ifndef _WX_BUILD_H_
#define _WX_BUILD_H_
#include "wx/version.h"
// NB: This file contains macros for checking binary compatibility of libraries
// in multilib buildm, plugins and user components.
// The WX_BUILD_OPTIONS_SIGNATURE macro expands into string that should
// uniquely identify binary compatible builds: i.e. if two builds of the
// library are binary compatible, their signature string should be the
// same; if two builds are binary incompatible, their signatures should
// be different.
//
// Therefore, wxUSE_XXX flags that affect binary compatibility (vtables,
// function signatures) should be accounted for here. So should compilers
// and compiler versions (but note that binary compatible compiler versions
// such as gcc-2.95.2 and gcc-2.95.3 should have same signature!).
// ----------------------------------------------------------------------------
// WX_BUILD_OPTIONS_SIGNATURE
// ----------------------------------------------------------------------------
#define __WX_BO_STRINGIZE(x) __WX_BO_STRINGIZE0(x)
#define __WX_BO_STRINGIZE0(x) #x
#if (wxMINOR_VERSION % 2) == 0
#define __WX_BO_VERSION(x,y,z) \
__WX_BO_STRINGIZE(x) "." __WX_BO_STRINGIZE(y)
#else
#define __WX_BO_VERSION(x,y,z) \
__WX_BO_STRINGIZE(x) "." __WX_BO_STRINGIZE(y) "." __WX_BO_STRINGIZE(z)
#endif
#ifdef __WXDEBUG__
#define __WX_BO_DEBUG "debug"
#else
#define __WX_BO_DEBUG "no debug"
#endif
#if wxUSE_UNICODE
#define __WX_BO_UNICODE "Unicode"
#else
#define __WX_BO_UNICODE "ANSI"
#endif
// GCC and Intel C++ share same C++ ABI (and possibly others in the future),
// check if compiler versions are compatible:
#if defined(__GXX_ABI_VERSION)
#define __WX_BO_COMPILER \
",compiler with C++ ABI " __WX_BO_STRINGIZE(__GXX_ABI_VERSION)
#elif defined(__INTEL_COMPILER)
#define __WX_BO_COMPILER ",Intel C++"
#elif defined(__GNUG__)
#define __WX_BO_COMPILER ",GCC " \
__WX_BO_STRINGIZE(__GNUC__) "." __WX_BO_STRINGIZE(__GNUC_MINOR__)
#elif defined(__VISUALC__)
#define __WX_BO_COMPILER ",Visual C++"
#elif defined(__BORLANDC__)
#define __WX_BO_COMPILER ",Borland C++"
#elif defined(__DIGITALMARS__)
#define __WX_BO_COMPILER ",DigitalMars"
#elif defined(__WATCOMC__)
#define __WX_BO_COMPILER ",Watcom C++"
#else
#define __WX_BO_COMPILER
#endif
// WXWIN_COMPATIBILITY macros affect presence of virtual functions
#if WXWIN_COMPATIBILITY_2_2
#define __WX_BO_WXWIN_COMPAT_2_2 ",compatible with 2.2"
#else
#define __WX_BO_WXWIN_COMPAT_2_2
#endif
#if WXWIN_COMPATIBILITY_2_4
#define __WX_BO_WXWIN_COMPAT_2_4 ",compatible with 2.4"
#else
#define __WX_BO_WXWIN_COMPAT_2_4
#endif
// deriving wxWin containers from STL ones changes them completely:
#if wxUSE_STL
#define __WX_BO_STL ",STL containers"
#else
#define __WX_BO_STL ",wx containers"
#endif
// This macro is passed as argument to wxConsoleApp::CheckBuildOptions()
#define WX_BUILD_OPTIONS_SIGNATURE \
__WX_BO_VERSION(wxMAJOR_VERSION, wxMINOR_VERSION, wxRELEASE_NUMBER) \
" (" __WX_BO_DEBUG "," __WX_BO_UNICODE \
__WX_BO_COMPILER \
__WX_BO_STL \
__WX_BO_WXWIN_COMPAT_2_2 __WX_BO_WXWIN_COMPAT_2_4 \
")"
// ----------------------------------------------------------------------------
// WX_CHECK_BUILD_OPTIONS
// ----------------------------------------------------------------------------
// Use this macro to check build options. Adding it to a file in DLL will
// ensure that the DLL checks build options in same way IMPLEMENT_APP() does.
#define WX_CHECK_BUILD_OPTIONS(libName) \
static bool wxCheckBuildOptions() \
{ \
wxAppConsole::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, \
libName); \
return true; \
}; \
static bool gs_buildOptionsCheck = wxCheckBuildOptions();
#if WXWIN_COMPATIBILITY_2_4
// ----------------------------------------------------------------------------
// wxBuildOptions
// ----------------------------------------------------------------------------
// NB: Don't use this class in new code, it relies on the ctor being always
// inlined. WX_BUILD_OPTIONS_SIGNATURE always works.
class wxBuildOptions
{
public:
// the ctor must be inline to get the compilation settings of the code
// which included this header
wxBuildOptions() : m_signature(WX_BUILD_OPTIONS_SIGNATURE) {}
private:
const char *m_signature;
// actually only CheckBuildOptions() should be our friend but well...
friend class wxAppConsole;
};
#endif // WXWIN_COMPATIBILITY_2_4
#endif // _WX_BUILD_H_
| [
"[email protected]"
] | |
7c3d9531fc061907ff69dd4ac23cd3b7da75a98c | 53733f73b922407a958bebde5e674ec7f045d1ba | /temp/0901am/abc158/F/main.cpp | 20040adcdb5582fd59435ca3fb46fa7b77ee009a | [] | no_license | makio93/atcoder | 040c3982e5e867b00a0d0c34b2a918dd15e95796 | 694a3fd87b065049f01f7a3beb856f8260645d94 | refs/heads/master | 2021-07-23T06:22:59.674242 | 2021-03-31T02:25:55 | 2021-03-31T02:25:55 | 245,409,583 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,473 | cpp | #include <bits/stdc++.h>
using namespace std;
const long long mod = 1e9 + 7;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
#define ull unsigned long long
#define ld long double
#define vi vector<int>
#define vll vector<ll>
#define vc vector<char>
#define vs vector<string>
#define vpii vector<pii>
#define vpll vector<pll>
#define rep(i, n) for (int i = 0, i##_len = (n); i < i##_len; i++)
#define rep1(i, n) for (int i = 1, i##_len = (n); i <= i##_len; i++)
#define repr(i, n) for (int i = ((int)(n)-1); i >= 0; i--)
#define rep1r(i, n) for (int i = ((int)(n)); i >= 1; i--)
#define sz(x) ((int)(x).size())
#define all(x) (x).begin(), (x).end()
#define rall(x) (x).rbegin(), (x).rend()
#define SORT(v, n) sort(v, v + n);
#define VSORT(v) sort(v.begin(), v.end());
#define RSORT(x) sort(rall(x));
#define pb push_back
#define mp make_pair
#define INF (1e9)
#define PI (acos(-1))
#define EPS (1e-7)
ull gcd(ull a, ull b) { return b ? gcd(b, a % b) : a; }
ull lcm(ull a, ull b) { return a / gcd(a, b) * b; }
const long long MOD = 998244353;
void func(long long N, std::vector<long long> X, std::vector<long long> D){
}
int main(){
// cout << fixed << setprecision(5);
long long N;
scanf("%lld",&N);
std::vector<long long> X(N);
std::vector<long long> D(N);
for(int i = 0 ; i < N ; i++){
scanf("%lld",&X[i]);
scanf("%lld",&D[i]);
}
func(N, std::move(X), std::move(D));
return 0;
}
| [
"[email protected]"
] | |
927e204801d4e78d0b5f8348a13240d26d77cd41 | bad16eb9b35971135f8fc055b40d87006621d2de | /offline/2021/spring/ICPC2020KunmingRC/L.cc | be264c4ab1684a2eeef1a184c189741c157af589 | [] | no_license | ymd45921/HUST-ACM-training | 1e1c47e40d419987731e047f493d614f0220346b | 1976e8351c0ba445ad8bfe0124dd88215d768cc8 | refs/heads/master | 2023-06-12T13:52:31.974586 | 2021-07-14T14:30:49 | 2021-07-14T14:30:49 | 317,748,883 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,033 | cc | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll read()
{
ll x = 0; char ch = getchar();
for(; ch > '9' || ch < '0'; ch = getchar());
for(; ch >= '0' && ch <= '9'; ch = getchar())x = x * 10 + ch - 48;
return x;
}
const int N = 1e6 + 2;
int a[N];
int stk[N];
bool vis[N];
int hd[N], nxt[N << 1], to[N << 1], tot;
inline void addedge(int u, int v)
{
nxt[++tot] = hd[u]; hd[u] = tot; to[tot] = v;
nxt[++tot] = hd[v]; hd[v] = tot; to[tot] = u;
}
void dfs(int u)
{
if(vis[u]) return ;
vis[u] = 1;
for(int i = 1; )
}
int main()
{
for(int T = read(); T--;) {
int n = read();
for(int i = 1; i <= n; ++i) a[i] = read();
int ans = 0;
int tp = -1;
for(int i = 1; i <= n; ++i) {
while(tp >= 0 && stk[tp] < a[i]) --tp;
stk[++tp] = a[i];
ans = max(ans, tp + 1);
}
for(int i = 1; i <= n; ++i) vis[i] = 0;
for(int i = 1; i <= n; ++i)
if(!vis[i]) dfs(i);
}
return 0;
} | [
"[email protected]"
] | |
531123f759f66b9010c23c759617f98f92999c72 | d58ee89c2f4004398195608fc3e6c2ea28a65e77 | /cpp/util/TestString.h | 4700ab67c2ab258d1b88ea72aec6e3adbd30fc62 | [
"MIT"
] | permissive | tvdmerwe/matasano-challenges | 6c79cbad599cd2b91860f5427a2e286052d80bfd | 9f1681f6dc88427e542dc97a126d2cd616906c3f | refs/heads/master | 2020-04-08T14:11:25.518045 | 2016-03-09T11:52:13 | 2016-03-09T11:52:13 | 50,509,328 | 0 | 0 | null | 2016-01-27T13:32:32 | 2016-01-27T13:32:32 | null | UTF-8 | C++ | false | false | 525 | h | #include <string>
#include <vector>
#include <stdint.h>
#ifndef TESTSTRING_H
#define TESTSTRING_H
class TestString {
private:
std::string plain_text;
std::string cipher_text;
uint8_t key;
int32_t score;
public:
TestString(std::string plain_input, std::string cipher_input, uint8_t key_input);
TestString(std::string cipher_input, uint8_t key_input);
std::string GetPlainText();
std::string GetCipherText();
uint8_t GetKey();
int32_t GetScore();
void SetScore(int32_t score_input);
};
#endif /* TESTSTRING_H */
| [
"[email protected]"
] | |
db0d25831a89af732c313838e0f4950598865b5a | 1d234a90501f6533082af555dbb428f7d902e7be | /easy/BOJ_5597.cpp | c5ba9d48260a89ffd83cc0c1fa0fd74166670eba | [] | no_license | gimozzi/algorithm | 475aab79dd6579d80499da09c3a86a071161134d | 9e0d6e4d6b671f9e5626e404ee62b38b6d128183 | refs/heads/master | 2020-04-06T07:09:53.497364 | 2016-09-03T04:12:42 | 2016-09-03T04:12:42 | 64,645,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <iostream>
using namespace std;
int main (void) {
int student[31] ={0, };
for(int i=0 ; i<28 ; i++){
int in;
cin >> in;
student[in]++;
}
for(int i=1 ; i<=30 ; i++){
if(student[i] == 0)
cout << i << endl;
}
return 0;
}
| [
"[email protected]"
] | |
1e4fdc98f875e34f25f2f8164d6600cd6c46b847 | 26a3dbc5c9367e8cc9ea770f34c8864503fef09b | /src/include/Pose.h | 92555a5f43995aa9f2c12459cdcd16993eca23f2 | [
"MIT"
] | permissive | edwardchaos/cgalabc | 6a95669414fb9408bed3640edcd7668e6e036b9d | 0403e1694f8371467981a7e9bde6a3571a6890a0 | refs/heads/main | 2023-02-09T22:41:56.247927 | 2021-01-06T21:44:15 | 2021-01-06T21:44:15 | 320,071,896 | 0 | 0 | MIT | 2021-01-06T21:44:16 | 2020-12-09T20:30:05 | C++ | UTF-8 | C++ | false | false | 387 | h | #pragma once
#ifdef Success
#undef Success
#endif
#include <Eigen/Dense>
namespace cg{
struct Pose{
// Homogenous coordinates for convenience
Eigen::Matrix4d orientation;
Eigen::Vector4d position;
[[nodiscard]] Eigen::Matrix4d matrix() const;
Pose();
Pose(Eigen::Vector4d position, Eigen::Matrix4d orientation);
bool operator==(const Pose&other);
};
} // namespace cg | [
"[email protected]"
] | |
255e679c0bbaaf9571ffbdfaaf6cac34b9a338ad | d34f94a4740256901edfb2ee2325505ca834ba30 | /C++/skola/div1.cpp | 0c0e5fbe829f854e4fe80735e4a998357ddb3aaa | [] | no_license | dimitarkole/CPlusPlusTasks | 706a15e533e657a91fe5c7d0ccee2cc129a2ac5f | 8b3adf02ab359babdc36b73085a83fb9055b0716 | refs/heads/master | 2020-12-04T23:07:48.601834 | 2020-01-05T14:25:05 | 2020-01-05T14:25:05 | 231,928,854 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 540 | cpp | #include<iostream>
using namespace std;
int main()
{
int ch1,ch2,min,flag=0,flag2=2;
cin>>ch1>>ch2;
min=ch1;
if(ch2<min)min=ch2;
for(int i=2;i<=min/2;i++)//vsi4ki prost chisla
{
if((ch1%i==0)&&(ch2%i==0))
{
for(int j=2;j<i/2;j++)//j da li e prosto
{
if(i%j==0)flag==1;
}
if(flag==0)
{
cout<<i<<" ";
flag2=3;
flag=0;
}
}
}
if(flag2==2)cout<<"-1";
}
| [
"[email protected]"
] | |
716deabe5e18c6344ea42d3f7abd409c18cc0753 | b4052809a4a08eb9ddc4551b6fc34ef61b90a24c | /frameworks/vtk.framework/Headers/vtkHierarchicalDataLevelFilter.h | 5f96a600eb4ad73f90ae269c2018798a28710b99 | [] | no_license | 9gel/hellopcl | 548687167b0b17bd393b55f37e99d05207971a9e | 19c39b39ad169c0a79b42cd72232d51b419f4f3d | refs/heads/master | 2020-02-26T17:05:09.470167 | 2014-02-27T07:59:52 | 2014-02-27T07:59:52 | 17,192,517 | 21 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,620 | h | /*=========================================================================
Program: Visualization Toolkit
Module: vtkHierarchicalDataLevelFilter.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
// .NAME vtkHierarchicalDataLevelFilter - generate scalars from levels
// .SECTION Description
// Legacy class. Use vtkLevelIdScalars instead.
//
// .SECTION See Also
// vtkLevelIdScalars
#ifndef __vtkHierarchicalDataLevelFilter_h
#define __vtkHierarchicalDataLevelFilter_h
#include "vtkFiltersGeneralModule.h" // For export macro
#include "vtkLevelIdScalars.h"
class VTKFILTERSGENERAL_EXPORT vtkHierarchicalDataLevelFilter : public vtkLevelIdScalars
{
public:
vtkTypeMacro(vtkHierarchicalDataLevelFilter,vtkLevelIdScalars);
void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Construct object with PointIds and CellIds on; and ids being generated
// as scalars.
static vtkHierarchicalDataLevelFilter *New();
protected:
vtkHierarchicalDataLevelFilter();
~vtkHierarchicalDataLevelFilter();
private:
vtkHierarchicalDataLevelFilter(const vtkHierarchicalDataLevelFilter&); // Not implemented.
void operator=(const vtkHierarchicalDataLevelFilter&); // Not implemented.
};
#endif
| [
"[email protected]"
] | |
e8537f2e4ce87bbc70a0b94a3ac7105fe2522b6c | a1f8c89e7bae66563ffd4300d7d46fc6e4bc2625 | /Lab2/HTMLEncode/htmlencode/HTMLEncode.h | 4ecae70396a5c84b921488089ea8e18a0aab6a63 | [] | no_license | Reywam/OOP | b3078d2a2ebefbf935615d9126ead554dfb4b7c5 | 1c5e7446a8acc6e80eb0b832f04d194f555b876a | refs/heads/master | 2021-01-13T07:49:24.642059 | 2017-01-19T07:22:45 | 2017-01-19T07:22:45 | 71,701,964 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 92 | h | #pragma once
#include <string>
using namespace std;
string HtmlEncode(string const &text); | [
"[email protected]"
] | |
e75aa5bec33ce4465e1899d55099a3d4e59a3c22 | 4588d4dc7e375d7bd05bf7223b44a2383b1e7d8f | /main.cpp | a33e992f0138ed184cd99715de6c4f3720dd5b6d | [] | no_license | Djole01/airCooler | b236f87c0c7f5a691cf89bed127afa028d406e39 | 79d10fb42635992844b71c8b8702f1563be6f8cc | refs/heads/master | 2020-09-07T02:35:20.195100 | 2020-04-11T15:35:49 | 2020-04-11T15:35:49 | 220,631,627 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 403 | cpp | #include <Arduino.h>
#include "DhtAirConditioner.h"
#include "Remote.h"
void setup() {
Serial.begin(115200);
//DHTsetup();
remoteSetup();
}
void loop() {
//DHTloop();
remoteLoop();
}
// my remote's decoded values
// 1 FF30CF
// 2 FF18E7
// 3 FF7A85
// + FF906F
// - FFE01F
// TO DO:
// implement remote functionality, make the remote display temperature
// add dc fan to act as a cooler.
| [
"[email protected]"
] | |
f1a57ee4b644c4dbf500c6c02f9a7677bd97931e | fd71442b0c6bdff4c65e95a23dc7dbc929727e5e | /aws-cpp-sdk-kendra/include/aws/kendra/model/CapacityUnitsConfiguration.h | e9623fab7d6da6d4d69a0622164237a986bdec1a | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | captain-chengzi/aws-sdk-cpp | 85abafb3f144aea578a0cc4ae40ed344152e8a2e | 6eed89da1a99d5acaf14f14fd933a784e49e724b | refs/heads/main | 2023-06-28T10:52:55.280940 | 2021-07-21T09:00:25 | 2021-07-21T09:00:25 | 388,056,640 | 0 | 0 | Apache-2.0 | 2021-07-21T08:58:47 | 2021-07-21T08:58:46 | null | UTF-8 | C++ | false | false | 5,981 | h | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/kendra/Kendra_EXPORTS.h>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace kendra
{
namespace Model
{
/**
* <p>Specifies capacity units configured for your enterprise edition index. You
* can add and remove capacity units to tune an index to your
* requirements.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/kendra-2019-02-03/CapacityUnitsConfiguration">AWS
* API Reference</a></p>
*/
class AWS_KENDRA_API CapacityUnitsConfiguration
{
public:
CapacityUnitsConfiguration();
CapacityUnitsConfiguration(Aws::Utils::Json::JsonView jsonValue);
CapacityUnitsConfiguration& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The amount of extra storage capacity for an index. A single capacity unit for
* an index provides 150 GB of storage space or 500,000 documents, whichever is
* reached first.</p>
*/
inline int GetStorageCapacityUnits() const{ return m_storageCapacityUnits; }
/**
* <p>The amount of extra storage capacity for an index. A single capacity unit for
* an index provides 150 GB of storage space or 500,000 documents, whichever is
* reached first.</p>
*/
inline bool StorageCapacityUnitsHasBeenSet() const { return m_storageCapacityUnitsHasBeenSet; }
/**
* <p>The amount of extra storage capacity for an index. A single capacity unit for
* an index provides 150 GB of storage space or 500,000 documents, whichever is
* reached first.</p>
*/
inline void SetStorageCapacityUnits(int value) { m_storageCapacityUnitsHasBeenSet = true; m_storageCapacityUnits = value; }
/**
* <p>The amount of extra storage capacity for an index. A single capacity unit for
* an index provides 150 GB of storage space or 500,000 documents, whichever is
* reached first.</p>
*/
inline CapacityUnitsConfiguration& WithStorageCapacityUnits(int value) { SetStorageCapacityUnits(value); return *this;}
/**
* <p>The amount of extra query capacity for an index and <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/API_GetQuerySuggestions.html">GetQuerySuggestions</a>
* capacity.</p> <p>A single extra capacity unit for an index provides 0.5 queries
* per second or approximately 40,000 queries per day.</p> <p>
* <code>GetQuerySuggestions</code> capacity is 5 times the provisioned query
* capacity for an index. For example, the base capacity for an index is 0.5
* queries per second, so GetQuerySuggestions capacity is 2.5 calls per second. If
* adding another 0.5 queries per second to total 1 queries per second for an
* index, the <code>GetQuerySuggestions</code> capacity is 5 calls per second.</p>
*/
inline int GetQueryCapacityUnits() const{ return m_queryCapacityUnits; }
/**
* <p>The amount of extra query capacity for an index and <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/API_GetQuerySuggestions.html">GetQuerySuggestions</a>
* capacity.</p> <p>A single extra capacity unit for an index provides 0.5 queries
* per second or approximately 40,000 queries per day.</p> <p>
* <code>GetQuerySuggestions</code> capacity is 5 times the provisioned query
* capacity for an index. For example, the base capacity for an index is 0.5
* queries per second, so GetQuerySuggestions capacity is 2.5 calls per second. If
* adding another 0.5 queries per second to total 1 queries per second for an
* index, the <code>GetQuerySuggestions</code> capacity is 5 calls per second.</p>
*/
inline bool QueryCapacityUnitsHasBeenSet() const { return m_queryCapacityUnitsHasBeenSet; }
/**
* <p>The amount of extra query capacity for an index and <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/API_GetQuerySuggestions.html">GetQuerySuggestions</a>
* capacity.</p> <p>A single extra capacity unit for an index provides 0.5 queries
* per second or approximately 40,000 queries per day.</p> <p>
* <code>GetQuerySuggestions</code> capacity is 5 times the provisioned query
* capacity for an index. For example, the base capacity for an index is 0.5
* queries per second, so GetQuerySuggestions capacity is 2.5 calls per second. If
* adding another 0.5 queries per second to total 1 queries per second for an
* index, the <code>GetQuerySuggestions</code> capacity is 5 calls per second.</p>
*/
inline void SetQueryCapacityUnits(int value) { m_queryCapacityUnitsHasBeenSet = true; m_queryCapacityUnits = value; }
/**
* <p>The amount of extra query capacity for an index and <a
* href="https://docs.aws.amazon.com/kendra/latest/dg/API_GetQuerySuggestions.html">GetQuerySuggestions</a>
* capacity.</p> <p>A single extra capacity unit for an index provides 0.5 queries
* per second or approximately 40,000 queries per day.</p> <p>
* <code>GetQuerySuggestions</code> capacity is 5 times the provisioned query
* capacity for an index. For example, the base capacity for an index is 0.5
* queries per second, so GetQuerySuggestions capacity is 2.5 calls per second. If
* adding another 0.5 queries per second to total 1 queries per second for an
* index, the <code>GetQuerySuggestions</code> capacity is 5 calls per second.</p>
*/
inline CapacityUnitsConfiguration& WithQueryCapacityUnits(int value) { SetQueryCapacityUnits(value); return *this;}
private:
int m_storageCapacityUnits;
bool m_storageCapacityUnitsHasBeenSet;
int m_queryCapacityUnits;
bool m_queryCapacityUnitsHasBeenSet;
};
} // namespace Model
} // namespace kendra
} // namespace Aws
| [
"[email protected]"
] | |
3fd31397dd50440b497c181a6cff9eab78df29d1 | 315b1995949c82d2cf097c54e01de214f6249b72 | /AutoTrader/AutoTrader/Trader.cpp | 1485ca3a464498f76715e1dea3148b8127ed5c08 | [] | no_license | MinjunHuang/AutoTrader | 87c64ef614d38811ab606cfd6cd2952f6a0ec5e7 | e078305a50448495435a8a85a25d0d9572fbb561 | refs/heads/master | 2021-01-22T20:12:52.580628 | 2014-06-25T05:46:01 | 2014-06-25T05:46:01 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 15,520 | cpp | #include "StdAfx.h"
#include "Trader.h"
#include "AutoTrader.h"
// #define MainWinName _T("东航期货网上交易系统(V3.0.12.5)--『7698037』")
//
// // 定义单个数据单元 句柄,标题,类型名称
// typedef tuple<HWND,CString,CString> WINTUPLE;
// typedef vector<WINTUPLE> WINVEC;
// typedef vector<int> LayerIndex;
// typedef tuple<HWND,LayerIndex> WinIndex;
// typedef vector<WinIndex> MAININDEX;
//
// static MAININDEX m_MainIndex;
// vector<WINVEC> m_MainVec;
//using namespace std;
BOOL CALLBACK EnumChild_Entrust(HWND hwnd,LPARAM lParam)
{
CTrader *this2 = (CTrader*)lParam;
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
CHAR szClassName[MAX_PATH];
GetClassNameA(hwnd, szClassName, MAX_PATH);
WINTUPLE tempTuple;
get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=szClassName;
this2->m_Entrust_Tuple_Vec.push_back(tempTuple);
return TRUE;
}
BOOL CALLBACK EnumChild_Status(HWND hwnd,LPARAM lParam)
{
CTrader *this2 = (CTrader*)lParam;
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
CHAR szClassName[MAX_PATH];
GetClassNameA(hwnd, szClassName, MAX_PATH);
WINTUPLE tempTuple;
get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=szClassName;
this2->m_Status_Tuple_Vec.push_back(tempTuple);
return TRUE;
}
BOOL CALLBACK EnumChild_1L(HWND hwnd,LPARAM lParam)
{
CTrader *this2 = (CTrader*)lParam;
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
CHAR szClassName[MAX_PATH];
GetClassNameA(hwnd, szClassName, MAX_PATH);
WINTUPLE tempTuple;
get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=szClassName;
this2->m_TupleVec.push_back(tempTuple);
return TRUE;
}
//*************************************
// 函数名:
// 目的: 查找程序主进程句柄
// 时间: 2014/03/25
//*************************************
BOOL CALLBACK EnumMainWinTrade(HWND hwnd,LPARAM lParam)
{
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
LPWSTR* ss = new LPWSTR();
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
GetClassName(hwnd,*ss,10);
//
CTrader *this2 = (CTrader*)lParam;
if (_tcsicmp(szTitle, MainWinName) == 0)
{
//::ShowWindow(hwnd,SW_SHOW);
//LPRECT rect;
//GetWindowRect(hwnd,rect);
//::SetWindowPos(hwnd,HWND_BOTTOM,0,0,rect->left-rect->right, rect->top-rect->bottom,SWP_SHOWWINDOW);
// 枚举所有子窗口
EnumChildWindows(hwnd, EnumChild_1L, (LPARAM)this2);
}
return TRUE;
}
CTrader::CTrader(void)
{
//(strrchr(szAppPath, '\\'))[0] = 0;
//////////////////////////////////////////////////////////////////////////
EnumWindows(EnumMainWinTrade, (LPARAM)this);
if (m_TupleVec.size() == 0)
{
theApp.MessageShow(_T("HS isn't run!"));
return;
}
//
int tempPos = FindWIN(m_TupleVec,_T("委托[1]"),_T("TTabSheet"));
if (tempPos != -1)
{
m_OrderList_Tuple = m_TupleVec.at(tempPos+1);
}
//
//::ShowWindow(get<0>(m_OrderList_Tuple));
m_bmp1 = theApp.m_AppPath + _T("bmp1.bmp");
m_bmp2 = theApp.m_AppPath + _T("bmp2.bmp");
//////////////////////////////////////////////////////////////////////////
// 截图测试
CDC dc;
CDC *pDC = &dc;//屏幕DC
HDC activeDC = ::GetWindowDC(get<0>(m_OrderList_Tuple)); //获得要截屏的窗口的hDC
pDC->Attach(activeDC);//获取当前活动窗口的DC
RECT rect;
::GetWindowRect(get<0>(m_OrderList_Tuple),&rect);//得到窗口的大小
int Width = rect.right - rect.left;
int Height = rect.bottom - rect.top;
CDC memDC;//内存DC
memDC.CreateCompatibleDC(pDC);
CBitmap memBitmap, *oldmemBitmap;//建立和屏幕兼容的bitmap
memBitmap.CreateCompatibleBitmap(pDC, Width, Height);
oldmemBitmap = memDC.SelectObject(&memBitmap);//将memBitmap选入内存DC
memDC.BitBlt(0, 0, Width, Height, pDC, 0, 0, SRCCOPY);//复制屏幕图像到内存DC
BITMAP bmp;
memBitmap.GetBitmap(&bmp);//获得位图信息
FILE *fp = fopen(CString2CharPt(m_bmp1), "w+b");
BITMAPINFOHEADER bih = {0};//位图信息头
bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
bih.biCompression = BI_RGB;
bih.biHeight = bmp.bmHeight;//高度
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
bih.biWidth = bmp.bmWidth;//宽度
BITMAPFILEHEADER bfh = {0};//位图文件头
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
bfh.bfType = (WORD)0x4d42;
fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头
fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头
byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据
GetDIBits(memDC.m_hDC, (HBITMAP) memBitmap.m_hObject, 0, Height, p,
(LPBITMAPINFO) &bih, DIB_RGB_COLORS);//获取位图数据
fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);//写入位图数据
delete [] p;
fclose(fp);
//////////////////////////////////////////////////////////////////////////
int StatusPos = FindWIN(m_TupleVec,_T("PnlStatus"),_T("TPanel"));
if (StatusPos != -1)
{
m_Status_Tuple = m_TupleVec.at(StatusPos);
EnumChildWindows(get<0>(m_Status_Tuple),EnumChild_Status,(LPARAM)this);
m_Query_Tuple = m_Status_Tuple_Vec.at(1);
}
int EntrustPos = FindWIN(m_TupleVec,_T("普通委托"),_T("TTabSheet"));
{
m_Entrust_Tuple = m_TupleVec.at(EntrustPos);
EnumChildWindows(get<0>(m_Entrust_Tuple),EnumChild_Entrust,(LPARAM)this);
m_Code_Tuple = m_Entrust_Tuple_Vec.at(7);
m_OK_Tuple = m_Entrust_Tuple_Vec.at(14);// 确认按钮 14
m_Value_Tuple = m_Entrust_Tuple_Vec.at(16);// 价格16
m_Volume_Tuple = m_Entrust_Tuple_Vec.at(17);// 手数 17
m_OpenClose_Tuple = m_Entrust_Tuple_Vec.at(18);//买卖 18
m_BuySell_Tuple = m_Entrust_Tuple_Vec.at(19);// 开平 19
}
}
CTrader::~CTrader(void)
{
}
int CTrader::FindWIN( TUPLEVEC tupleVec,CString Title,CString ClassName )
{
WINTUPLE temp;CString tempTitle;CString tempClassName;
for (int i = 0; i < tupleVec.size(); i++)
{
temp = tupleVec.at(i);
tempTitle = get<1>(temp);
tempClassName = get<2>(temp);
if (tempTitle == Title && tempClassName == ClassName)
{
return i;
}
}
return -1;
}
bool CTrader::SetCode( CString Scode )
{
//m_Code_Tuple
char * clearStr = "";
char tempChar;
CString tempCStr;
SendMessage(get<0>(m_Code_Tuple),WM_SETTEXT,2,LPARAM(clearStr));//可用于清空
for(int i=0; i<Scode.GetLength();i++)
{
tempCStr = Scode.GetAt(i);
tempChar = *CString2CharPt(tempCStr);
//char tempTest = 'a';
SendMessage(get<0>(m_Code_Tuple), WM_CHAR, (WPARAM)tempChar, 0);//填写文本框。
}
return true;
}
char* CTrader::CString2CharPt( CString InputString )
{
CString str = InputString;
//注意:以下n和len的值大小不同,n是按字符计算的,len是按字节计算的
int n = str.GetLength(); // n = 14, len = 18
//获取宽字节字符的大小,大小是按字节计算的
int len = WideCharToMultiByte(CP_ACP,0,str,str.GetLength(),NULL,0,NULL,NULL);
char * pFileName = new char[len+1]; //以字节为单位
//宽字节编码转换成多字节编码
WideCharToMultiByte(CP_ACP,0,str,str.GetLength() + 1 ,pFileName,len + 1 ,NULL,NULL);
return pFileName;
}
bool CTrader::SetValue( CString Svalue )
{
char * clearStr = "";
char tempChar;
CString tempCStr;
SendMessage(get<0>(m_Value_Tuple),WM_SETTEXT,2,LPARAM(clearStr));//可用于清空
for(int i=0; i<Svalue.GetLength();i++)
{
tempCStr = Svalue.GetAt(i);
tempChar = *CString2CharPt(tempCStr);
SendMessage(get<0>(m_Value_Tuple), WM_CHAR, (WPARAM)tempChar, 0);//填写文本框。
}
return true;
}
bool CTrader::SetVolume( CString Svolume )
{
char * clearStr = "";
char tempChar;
CString tempCStr;
SendMessage(get<0>(m_Volume_Tuple),WM_SETTEXT,2,LPARAM(clearStr));//可用于清空
for(int i=0; i<Svolume.GetLength();i++)
{
tempCStr = Svolume.GetAt(i);
tempChar = *CString2CharPt(tempCStr);
SendMessage(get<0>(m_Volume_Tuple), WM_CHAR, (WPARAM)tempChar, 0);//填写文本框。
}
return true;
}
//*************************************
// 函数名: SetOpenClose
// 目的: 设置开平仓 0:开仓 1:平仓 2:平今仓
// 时间: 2014/03/25
//*************************************
bool CTrader::SetOpenClose( int Sbuy_sell )
{
SendMessage(get<0>(m_OpenClose_Tuple),CB_SETCURSEL,Sbuy_sell,0);// Hwd, CB_SETCURSEL, Index, 0
return true;
}
//*************************************
// 函数名: SetBuy_Sell
// 目的: 设置开平仓 0:买入 1:卖出
// 时间: 2014/03/25
//*************************************
bool CTrader::SetBuy_Sell( int Sbuild )
{
SendMessage(get<0>(m_BuySell_Tuple),CB_SETCURSEL,Sbuild,0);// Hwd, CB_SETCURSEL, Index, 0
return true;
}
BOOL CALLBACK EnumChild_Error(HWND hwnd,LPARAM lParam)
{
CTrader *this2 = (CTrader*)lParam;
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
CHAR szClassName[MAX_PATH];
GetClassNameA(hwnd, szClassName, MAX_PATH);
//
// if (szClassName == "TMessageForm")
// {
WINTUPLE tempTuple;
get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=szClassName;
this2->m_Error_Tuple_Vec.push_back(tempTuple);
/* }*/
}
//*************************************
// 函数名:
// 目的: 查找程序错误句柄
// 时间: 2014/03/25
//*************************************
BOOL CALLBACK EnumMainWinError(HWND hwnd,LPARAM lParam)
{
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
//LPWSTR* ss = new LPWSTR();
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
//CHAR szClassName[MAX_PATH];
TCHAR szClassName[MAX_PATH];
GetClassName(hwnd, szClassName, MAX_PATH);
//0x003de1d4 "TMessageForm"
CTrader *this2 = (CTrader*)lParam;
//if (_tcsicmp(szTitle, _T("警告")) == 0 && ClassName == _T("TMessageForm"))
if (_tcsicmp(szTitle, _T("警告")) == 0)
{
//WINTUPLE tempTuple;
//if (szClassName == _T("TMessageForm") )
if( _tcsicmp(szClassName, _T("TMessageForm")) == 0 )
{
// 枚举所有子窗口
EnumChildWindows(hwnd, EnumChild_Error, (LPARAM)this2);
//get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=ClassName;
//this2->m_Error_Tuple = tempTuple;
}
}
return TRUE;
}
bool CTrader::SendOrder( void )
{
CString OriStr = GetStatusText();
//SendMessage(get<0>(m_OK_Tuple),CB_SETCURSEL,Sbuild,0);// Hwd, CB_SETCURSEL, Index, 0
SendMessage(get<0>(m_OK_Tuple),WM_LBUTTONDOWN,0,0);
SendMessage(get<0>(m_OK_Tuple),WM_LBUTTONUP,0,0);
//
//
//EnumChildWindows(get<0>(m_Error_Tuple),EnumChild_Error,(LPARAM)this);
//
return true;
}
CString CTrader::GetStatusText()
{
//m_Status_Tuple
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(get<0>(m_Query_Tuple), szTitle, ARRAYSIZE(szTitle));
CString res;
res = szTitle;
return res;
}
BOOL CALLBACK EnumChild_ErrorIO(HWND hwnd,LPARAM lParam)
{
CTrader *this2 = (CTrader*)lParam;
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
CHAR szClassName[MAX_PATH];
GetClassNameA(hwnd, szClassName, MAX_PATH);
// if (szClassName == "TMessageForm")
// {
WINTUPLE tempTuple;
get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=szClassName;
//}
this2->m_ErrorIO_Tuple_Vec.push_back(tempTuple);
}
BOOL CALLBACK EnumMainWinErrorIO(HWND hwnd,LPARAM lParam)
{
if (hwnd == NULL)
{
return FALSE;
}
TCHAR szTitle[MAX_PATH] = {0};
//LPWSTR* ss = new LPWSTR();
GetWindowText(hwnd, szTitle, ARRAYSIZE(szTitle));
//CHAR szClassName[MAX_PATH];
TCHAR szClassName[MAX_PATH];
GetClassName(hwnd, szClassName, MAX_PATH);
//0x003de1d4 "TMessageForm"
CTrader *this2 = (CTrader*)lParam;
//if (_tcsicmp(szTitle, _T("警告")) == 0 && ClassName == _T("TMessageForm"))
if (_tcsicmp(szTitle, _T("『7698037』--牛牧广")) == 0)
{
//WINTUPLE tempTuple;
//if (szClassName == _T("TMessageForm") )
if( _tcsicmp(szClassName, _T("#32770")) == 0 )
{
// 枚举所有子窗口
EnumChildWindows(hwnd, EnumChild_ErrorIO, (LPARAM)this2);
//get<0>(tempTuple) =hwnd;get<1>(tempTuple)=szTitle;get<2>(tempTuple)=ClassName;
//this2->m_Error_Tuple = tempTuple;
}
}
return TRUE;
}
void CTrader::CloseError()
{
EnumWindows(EnumMainWinError, (LPARAM)this);
EnumWindows(EnumMainWinErrorIO, (LPARAM)this);
if (m_Error_Tuple_Vec.size() != 0)
{
m_Error_Tuple = m_Entrust_Tuple_Vec.at(0);
SendMessage(get<0>(m_Error_Tuple),WM_LBUTTONDOWN,0,0);
SendMessage(get<0>(m_Error_Tuple),WM_LBUTTONUP,0,0);
m_Error_Tuple_Vec.pop_back();
}
if (m_ErrorIO_Tuple_Vec.size() != 0)
{
m_ErrorIO_Tuple = m_ErrorIO_Tuple_Vec.at(0);
SendMessage(get<0>(m_ErrorIO_Tuple),WM_LBUTTONDOWN,0,0);
SendMessage(get<0>(m_ErrorIO_Tuple),WM_LBUTTONUP,0,0);
//Sleep(2000);
m_ErrorIO_Tuple_Vec.clear();
}
}
CString CTrader::TestList()
{
LPLVCOLUMN listCol;
char str_buff[255];
int count = SendMessage(get<0>(m_OrderList_Tuple),WM_GETTEXT, 255,(LPARAM)str_buff);
//SendMessage()
//ReadProcessMemory()
//LVM_INSERTCOLUMN,1,(LPARAM)&listCol
//SendMessage(get<0>(m_OrderList_Tuple),LVM_INSERTCOLUMN,1,(LPARAM)&listCol);
return _T("");
}
void CTrader::ListSnapshot(CString bmpPath)
{
//////////////////////////////////////////////////////////////////////////
// 截图测试
CDC dc;
CDC *pDC = &dc;//屏幕DC
HDC activeDC = ::GetWindowDC(get<0>(m_OrderList_Tuple)); //获得要截屏的窗口的hDC
pDC->Attach(activeDC);//获取当前活动窗口的DC
RECT rect;
::GetWindowRect(get<0>(m_OrderList_Tuple),&rect);//得到窗口的大小
int Width = rect.right - rect.left;
int Height = rect.bottom - rect.top;
CDC memDC;//内存DC
memDC.CreateCompatibleDC(pDC);
CBitmap memBitmap, *oldmemBitmap;//建立和屏幕兼容的bitmap
memBitmap.CreateCompatibleBitmap(pDC, Width, Height);
oldmemBitmap = memDC.SelectObject(&memBitmap);//将memBitmap选入内存DC
memDC.BitBlt(0, 0, Width, Height, pDC, 0, 0, SRCCOPY);//复制屏幕图像到内存DC
BITMAP bmp;
memBitmap.GetBitmap(&bmp);//获得位图信息
FILE *fp = fopen(CString2CharPt(bmpPath), "w+b");
BITMAPINFOHEADER bih = {0};//位图信息头
bih.biBitCount = bmp.bmBitsPixel;//每个像素字节大小
bih.biCompression = BI_RGB;
bih.biHeight = bmp.bmHeight;//高度
bih.biPlanes = 1;
bih.biSize = sizeof(BITMAPINFOHEADER);
bih.biSizeImage = bmp.bmWidthBytes * bmp.bmHeight;//图像数据大小
bih.biWidth = bmp.bmWidth;//宽度
BITMAPFILEHEADER bfh = {0};//位图文件头
bfh.bfOffBits = sizeof(BITMAPFILEHEADER) + sizeof(BITMAPINFOHEADER);//到位图数据的偏移量
bfh.bfSize = bfh.bfOffBits + bmp.bmWidthBytes * bmp.bmHeight;//文件总的大小
bfh.bfType = (WORD)0x4d42;
fwrite(&bfh, 1, sizeof(BITMAPFILEHEADER), fp);//写入位图文件头
fwrite(&bih, 1, sizeof(BITMAPINFOHEADER), fp);//写入位图信息头
byte * p = new byte[bmp.bmWidthBytes * bmp.bmHeight];//申请内存保存位图数据
GetDIBits(memDC.m_hDC, (HBITMAP) memBitmap.m_hObject, 0, Height, p,
(LPBITMAPINFO) &bih, DIB_RGB_COLORS);//获取位图数据
fwrite(p, 1, bmp.bmWidthBytes * bmp.bmHeight, fp);//写入位图数据
delete [] p;
fclose(fp);
}
| [
"[email protected]"
] | |
fc42f6ef6f2a103a39f59f5a56eece8121a60d19 | 1c38b1403f0024b7eaf583db01836d1bd2a1d62c | /GameEngine/Include/Device.h | cdace63ec42367f1551ff57fc68a278cf43cd3f4 | [] | no_license | chimec153/DirectX11-2D-Game | 46f349418fae2e4420d0eb6e768b57b0a3f4d990 | fbedaad9bc0fd33666393480be041f9fc8f89e19 | refs/heads/master | 2023-06-13T23:28:51.831499 | 2021-06-11T16:19:25 | 2021-06-11T16:19:25 | 295,000,343 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | h | #pragma once
#include "GameEngine.h"
class CDevice
{
private:
ID3D11Device* m_pDevice;
ID3D11DeviceContext* m_pContext;
IDXGISwapChain* m_pSwapChain;
ID3D11RenderTargetView* m_pTargetView;
ID3D11DepthStencilView* m_pDepthView;
Resolution m_tRS;
float m_pColor[4];
HWND m_hWnd;
ID2D1Factory* m_p2DFactory;
ID2D1RenderTarget* m_p2DTarget;
public:
ID3D11Device* GetDevice() const;
ID3D11DeviceContext* GetContext() const;
IDXGISwapChain* GetSwapChain() const;
Resolution GetResolution() const;
Vector2 GetRatio() const;
ID2D1Factory* GetFactory2D() const;
ID2D1RenderTarget* GetRenderTarget2D() const;
public:
bool Init(HWND hWnd, int iWidth, int iHeight, bool bWindowed);
void ClearState();
void Render();
void SetTarget();
DECLARE_SINGLE(CDevice)
};
| [
"[email protected]"
] | |
ae231a51d466cc8e39201ff04f2cf6ecfb281523 | fcfb8ef8f325eca5df9c750cd5d14417c7505486 | /100/195.cpp | e9bcd4ce876aa65ca524617ffc1062e00e62b3bf | [] | no_license | ijliao/uva | c83547d042521a488380f03144cf2ce5bdd46bb8 | c7b6b34dee4c5399dd68932920adb8fc2f1d84c9 | refs/heads/master | 2016-09-06T05:53:03.002135 | 2013-06-05T03:22:47 | 2013-06-05T03:22:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 289 | cpp | #include <iostream>
#include <string>
#include <algorithm>
int main(void)
{
int N;
cin >> N;
for (int i = 0; i < N; i++) {
string s;
cin >> s;
sort(s.begin(), s.end());
cout << s << endl;
while (next_permutation(s.begin(), s.end()))
cout << s << endl;
}
return 0;
}
| [
"[email protected]"
] | |
d38a1610e8f54b53b134d0ca1e7e96583e16dfd2 | af097999eb5d5d0f7838d783049b8a5715f84e06 | /printBinaryTreeFromBottom.cpp | b0e4bb60a128e98eb933b026b613f9f22dcccf90 | [] | no_license | tuancaraballo/Summer2016CodingFun | 8dfd4aa4f8fa3e2817799c6055712ac40d57f20e | 1812f077d23305da3cafc5624cf384bdd6efaf41 | refs/heads/master | 2021-01-22T17:33:47.943143 | 2017-07-11T05:53:22 | 2017-07-11T05:53:22 | 63,389,868 | 0 | 0 | null | 2017-07-11T05:53:22 | 2016-07-15T03:49:00 | C++ | UTF-8 | C++ | false | false | 142 | cpp | //
// printBinaryTreeFromBottom.cpp
//
//
// Created by Tuan Anh Tran Caraballo on 1/28/17.
//
//
#include "printBinaryTreeFromBottom.h"
| [
"[email protected]"
] | |
19de6434bb216e14cf8dc280ee1f07b0f36121fc | 2215a07d209846ba020e43e30a7a6d6ec5607479 | /potyczki-algorytmiczne/2006/4-pole-uprawne/pole-uprawne.cpp | 5853b83ea73017750106c9a8edbdae2204ed0d83 | [] | no_license | sfindeisen/prgctst | 01ab9d3306622b2113fff57536fe6a34121acfec | 3123004907adba18a12f8de96f36956efed752c3 | refs/heads/master | 2022-05-18T20:10:06.965895 | 2022-05-14T17:13:17 | 2022-05-14T17:13:17 | 31,426,791 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,046 | cpp | #include <algorithm>
//#include <iostream>
#include <cstdio>
#include <queue>
#include <functional>
#include <vector>
using namespace std;
struct TOdcinek {
long l;
long r;
TOdcinek() : l(0), r(0) {
}
TOdcinek(long a, long b) : l(a), r(b) {
}
inline long width() const {
return (r+1-l);
}
};
const long MaxN = 5000000;
long a, b, c, d;
long long res = 0;
TOdcinek plansza[MaxN];
struct cmpl {
bool operator()(const long &a, const long &b) const {
return (plansza[a].l < plansza[b].l);
}
};
struct cmpr {
bool operator()(const long &a, const long &b) const {
return (plansza[b].r < plansza[a].r);
}
};
priority_queue<long, vector<long>, cmpl> ql;
priority_queue<long, vector<long>, cmpr> qr;
void init() {
priority_queue<long, vector<long>, cmpl> qle;
priority_queue<long, vector<long>, cmpr> qre;
swap(qr, qre);
swap(ql, qle);
//while (! ql.empty())
// ql.pop();
//while (! qr.empty())
// qr.pop();
}
void oblicz() {
//priority_queue<long, vector<long>, greater<long> > qle;
//swap(ql, qle);
//priority_queue<long, vector<long>, less<long> > qre;
//swap(qr, qre);
if ((a < c) || (b < d))
return;
init();
long first=0;
for (long i = 0; i < b; ++i) {
const TOdcinek& odc = plansza[i];
// cerr << "i=" << i << " odc: " << odc.l << ".." << odc.r << endl;
if ((odc.width()) < c) {
init();
first = 1+i;
continue;
}
ql.push(i);
qr.push(i);
while ((first + d - 1 <= i) && (! ql.empty()) && (! qr.empty())) {
const long li = ql.top();
const long ri = qr.top();
// cerr << " li: " << li << " ri: " << ri << endl;
if (li < first) {
ql.pop();
continue;
}
if (ri < first) {
qr.pop();
continue;
}
if (plansza[ri].r < (plansza[li].l + c - 1)) {
// too narrow!
first = 1 + min(li,ri);
// cerr << " too narrow! first=" << first << endl;
} else {
// match!
const long w = (plansza[ri].r - plansza[li].l - c + 2);
res += w;
++first;
// cerr << " ## match! w=" << w << endl;
}
}
}
}
void wczytaj() {
scanf("%lu %lu %lu %lu", &a, &b, &c, &d);
// cerr << "a=" << a << " b=" << b << " c=" << c << " d=" << d << endl;
long x,y;
for (long i = 0; i < b; ++i) {
scanf("%lu %lu", &x, &y);
// cerr << "x=" << x << " y=" << y << endl;
plansza[i].l = x-1;
plansza[i].r = x+y-2;
// cerr << "i: " << i << " odc: " << plansza[i].l << ".." << plansza[i].r << endl;
}
}
int main() {
wczytaj();
oblicz();
if (c != d) {
swap(c,d);
oblicz();
}
printf("%lld\n", res);
return 0;
}
| [
"[email protected]"
] | |
8fd9ff5f96d3bc501084143054b6c59a3d4b94c7 | 36c6da628508a7adfd3f2a044874ffd416e2d621 | /16_true_type_fonts/16_true_type_fonts.cpp | e44489744e46a181c8d5fdcbb50dcbda51bed9c0 | [] | no_license | rmarchiori/SDL2_Tutorial_Examples | d7502a0da2ac6b1b3e291110214cf9bedcf510df | 8e5ec5bd7ead414fe47fec75584b166ef764e9db | refs/heads/master | 2021-08-08T03:26:10.722021 | 2017-11-09T13:17:55 | 2017-11-09T13:17:55 | 110,055,370 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,989 | cpp | /*This source code copyrighted by Lazy Foo' Productions (2004-2015)
and may not be redistributed without written permission.*/
//Using SDL, SDL_image, SDL_ttf, standard IO, math, and strings
#include <SDL.h>
#include <SDL_image.h>
#include <SDL_ttf.h>
#include <stdio.h>
#include <string>
#include <cmath>
//Screen dimension constants
const int SCREEN_WIDTH = 640;
const int SCREEN_HEIGHT = 480;
//Texture wrapper class
class LTexture
{
public:
//Initializes variables
LTexture();
//Deallocates memory
~LTexture();
//Loads image at specified path
bool loadFromFile( std::string path );
//Creates image from font string
bool loadFromRenderedText( std::string textureText, SDL_Color textColor );
//Deallocates texture
void free();
//Set color modulation
void setColor( Uint8 red, Uint8 green, Uint8 blue );
//Set blending
void setBlendMode( SDL_BlendMode blending );
//Set alpha modulation
void setAlpha( Uint8 alpha );
//Renders texture at given point
void render( int x, int y, SDL_Rect* clip = NULL, double angle = 0.0, SDL_Point* center = NULL, SDL_RendererFlip flip = SDL_FLIP_NONE );
//Gets image dimensions
int getWidth();
int getHeight();
private:
//The actual hardware texture
SDL_Texture* mTexture;
//Image dimensions
int mWidth;
int mHeight;
};
//Starts up SDL and creates window
bool init();
//Loads media
bool loadMedia();
//Frees media and shuts down SDL
void close();
//The window we'll be rendering to
SDL_Window* gWindow = NULL;
//The window renderer
SDL_Renderer* gRenderer = NULL;
//Globally used font
TTF_Font *gFont = NULL;
//Rendered texture
LTexture gTextTexture;
LTexture::LTexture()
{
//Initialize
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
LTexture::~LTexture()
{
//Deallocate
free();
}
bool LTexture::loadFromFile( std::string path )
{
//Get rid of preexisting texture
free();
//The final texture
SDL_Texture* newTexture = NULL;
//Load image at specified path
SDL_Surface* loadedSurface = IMG_Load( path.c_str() );
if( loadedSurface == NULL )
{
printf( "Unable to load image %s! SDL_image Error: %s\n", path.c_str(), IMG_GetError() );
}
else
{
//Color key image
SDL_SetColorKey( loadedSurface, SDL_TRUE, SDL_MapRGB( loadedSurface->format, 0, 0xFF, 0xFF ) );
//Create texture from surface pixels
newTexture = SDL_CreateTextureFromSurface( gRenderer, loadedSurface );
if( newTexture == NULL )
{
printf( "Unable to create texture from %s! SDL Error: %s\n", path.c_str(), SDL_GetError() );
}
else
{
//Get image dimensions
mWidth = loadedSurface->w;
mHeight = loadedSurface->h;
}
//Get rid of old loaded surface
SDL_FreeSurface( loadedSurface );
}
//Return success
mTexture = newTexture;
return mTexture != NULL;
}
bool LTexture::loadFromRenderedText( std::string textureText, SDL_Color textColor )
{
//Get rid of preexisting texture
free();
//Render text surface
SDL_Surface* textSurface = TTF_RenderText_Solid( gFont, textureText.c_str(), textColor );
if( textSurface == NULL )
{
printf( "Unable to render text surface! SDL_ttf Error: %s\n", TTF_GetError() );
}
else
{
//Create texture from surface pixels
mTexture = SDL_CreateTextureFromSurface( gRenderer, textSurface );
if( mTexture == NULL )
{
printf( "Unable to create texture from rendered text! SDL Error: %s\n", SDL_GetError() );
}
else
{
//Get image dimensions
mWidth = textSurface->w;
mHeight = textSurface->h;
}
//Get rid of old surface
SDL_FreeSurface( textSurface );
}
//Return success
return mTexture != NULL;
}
void LTexture::free()
{
//Free texture if it exists
if( mTexture != NULL )
{
SDL_DestroyTexture( mTexture );
mTexture = NULL;
mWidth = 0;
mHeight = 0;
}
}
void LTexture::setColor( Uint8 red, Uint8 green, Uint8 blue )
{
//Modulate texture rgb
SDL_SetTextureColorMod( mTexture, red, green, blue );
}
void LTexture::setBlendMode( SDL_BlendMode blending )
{
//Set blending function
SDL_SetTextureBlendMode( mTexture, blending );
}
void LTexture::setAlpha( Uint8 alpha )
{
//Modulate texture alpha
SDL_SetTextureAlphaMod( mTexture, alpha );
}
void LTexture::render( int x, int y, SDL_Rect* clip, double angle, SDL_Point* center, SDL_RendererFlip flip )
{
//Set rendering space and render to screen
SDL_Rect renderQuad = { x, y, mWidth, mHeight };
//Set clip rendering dimensions
if( clip != NULL )
{
renderQuad.w = clip->w;
renderQuad.h = clip->h;
}
//Render to screen
SDL_RenderCopyEx( gRenderer, mTexture, clip, &renderQuad, angle, center, flip );
}
int LTexture::getWidth()
{
return mWidth;
}
int LTexture::getHeight()
{
return mHeight;
}
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Set texture filtering to linear
if( !SDL_SetHint( SDL_HINT_RENDER_SCALE_QUALITY, "1" ) )
{
printf( "Warning: Linear texture filtering not enabled!" );
}
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH, SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Create vsynced renderer for window
gRenderer = SDL_CreateRenderer( gWindow, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC );
if( gRenderer == NULL )
{
printf( "Renderer could not be created! SDL Error: %s\n", SDL_GetError() );
success = false;
}
else
{
//Initialize renderer color
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
//Initialize PNG loading
int imgFlags = IMG_INIT_PNG;
if( !( IMG_Init( imgFlags ) & imgFlags ) )
{
printf( "SDL_image could not initialize! SDL_image Error: %s\n", IMG_GetError() );
success = false;
}
//Initialize SDL_ttf
if( TTF_Init() == -1 )
{
printf( "SDL_ttf could not initialize! SDL_ttf Error: %s\n", TTF_GetError() );
success = false;
}
}
}
}
return success;
}
bool loadMedia()
{
//Loading success flag
bool success = true;
//Open the font
gFont = TTF_OpenFont( "16_true_type_fonts/lazy.ttf", 28 );
if( gFont == NULL )
{
printf( "Failed to load lazy font! SDL_ttf Error: %s\n", TTF_GetError() );
success = false;
}
else
{
//Render text
SDL_Color textColor = { 0, 0, 0 };
if( !gTextTexture.loadFromRenderedText( "The quick brown fox jumps over the lazy dog", textColor ) )
{
printf( "Failed to render text texture!\n" );
success = false;
}
}
return success;
}
void close()
{
//Free loaded images
gTextTexture.free();
//Free global font
TTF_CloseFont( gFont );
gFont = NULL;
//Destroy window
SDL_DestroyRenderer( gRenderer );
SDL_DestroyWindow( gWindow );
gWindow = NULL;
gRenderer = NULL;
//Quit SDL subsystems
TTF_Quit();
IMG_Quit();
SDL_Quit();
}
int main( int argc, char* args[] )
{
//Start up SDL and create window
if( !init() )
{
printf( "Failed to initialize!\n" );
}
else
{
//Load media
if( !loadMedia() )
{
printf( "Failed to load media!\n" );
}
else
{
//Main loop flag
bool quit = false;
//Event handler
SDL_Event e;
//While application is running
while( !quit )
{
//Handle events on queue
while( SDL_PollEvent( &e ) != 0 )
{
//User requests quit
if( e.type == SDL_QUIT )
{
quit = true;
}
}
//Clear screen
SDL_SetRenderDrawColor( gRenderer, 0xFF, 0xFF, 0xFF, 0xFF );
SDL_RenderClear( gRenderer );
//Render current frame
gTextTexture.render( ( SCREEN_WIDTH - gTextTexture.getWidth() ) / 2, ( SCREEN_HEIGHT - gTextTexture.getHeight() ) / 2 );
//Update screen
SDL_RenderPresent( gRenderer );
}
}
}
//Free resources and close SDL
close();
return 0;
} | [
"[email protected]"
] | |
90b5b31137797eca9c2d4a0618e6339494a996bd | c09f57c292ceab8e88cfa81e15961c643d0c270f | /HW4/cylindricalProj.cpp | 033a441a785780ad420e3315814392df4b547775 | [] | no_license | OniricRain/CVHW4 | 5780f14c19e7aa9ba0aefba9fad5764e51121166 | 7b92d71d688a569b501e2134a5077762e4a5ad7c | refs/heads/master | 2022-11-07T21:43:30.955711 | 2020-06-09T08:30:54 | 2020-06-09T08:30:54 | 268,253,532 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 290 | cpp |
#include <memory>
#include <iostream>
//#include <opencv2/opencv.hpp>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
//#include <opencv2/xfeatures2d.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/calib3d.hpp>
//#include <opencv2/stitching.hpp>
#include "myinclude.h"
| [
"[email protected]"
] | |
2212ecc620064423e78c8c75cbff49f41b33a7fe | 8923ca987ad4e6c00842906397930a5e8c735c31 | /Capacitance_Testor/Capacitance_Testor.ino | 0c2f0a8641fc44f19436f297392137f6765add74 | [] | no_license | willybh11/Arduino | b251e3aba71b0095c913e450bfcd701c0b67acf6 | b1b8a23d98b10cf0646f51d7a31c49ec2e8d189d | refs/heads/master | 2021-07-20T14:39:45.686257 | 2021-05-27T21:25:22 | 2021-05-27T21:25:22 | 121,543,766 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | ino | const byte pulsePin = 2; //white plugged into 7, green into 6
const unsigned long resistance = 10000; //red-white -> 5v-gnd
volatile boolean triggered;
volatile boolean active;
volatile unsigned long startTime;
volatile unsigned long duration;
ISR (ANALOG_COMP_vect)
{
unsigned long now = micros ();
if (active)
{
duration = now - startTime;
triggered = true;
digitalWrite (pulsePin, LOW);
}
}
void setup ()
{
pinMode(pulsePin, OUTPUT);
digitalWrite(pulsePin, LOW);
Serial.begin(9600);
ADCSRB = 0;
ACSR = _BV (ACI)
| _BV (ACIE)
| _BV (ACIS0) | _BV (ACIS1);
}
void loop ()
{
if (!active)
{
active = true;
triggered = false;
digitalWrite (pulsePin, HIGH);
startTime = micros ();
}
if (active && triggered)
{
active = false;
Serial.print (duration / resistance);
Serial.println (" uF");
triggered = false;
delay (1000);
}
}
| [
"[email protected]"
] | |
d2e9814fd571c5264c22b66f28276f1316bd7b87 | 7a3e08c3363a3a1428cdf89198932ff3bcef784e | /SynchPointDelim/SynchPoint.hpp | 0962e9c61a040c81e46525df34995c4632f39ca9 | [] | no_license | sawansib/xDRFPublicCode | ed84145ae2e1a31dddac2def63fcb69e64edd052 | 5cb7e2cb4e05513d6e5f956d7bd19b08ce56e8f3 | refs/heads/master | 2021-04-05T12:37:34.801843 | 2016-12-16T13:21:56 | 2016-12-16T13:21:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,408 | hpp | //===---- Defines Synchronization Points and Related Data Structures ------===//
//
//
//===----------------------------------------------------------------------===//
// Created at 1/2 -16
// Jonatan Waern
//===----------------------------------------------------------------------===//
#ifndef _SYNCHPOINTHEADER_
#define _SYNCHPOINTHEADER_
#include <set>
#include <map>
#include "llvm/IR/Instruction.h"
#include "llvm/ADT/SmallPtrSet.h"
using namespace llvm;
using namespace std;
class SynchronizationPoint;
class CriticalRegion;
//A collection of synchronization points
class SynchronizationVariable {
public:
SynchronizationVariable() {
static int IDCount = 0;
ID = IDCount++;
}
//Usefull for debugging
int ID;
bool operator < (SynchronizationVariable other) const {
return ID < other.ID;
}
//The constituent synchronization points
SmallPtrSet<SynchronizationPoint*,8> synchronizationPoints;
//The pairs of data conflicts (before, after) detected for this synchronization
//variable
//set<pair<Instruction*,Instruction*> > conflicts;
void merge(SynchronizationVariable *other);
};
//A point of synchronization in the program
class SynchronizationPoint {
public:
SynchronizationPoint() {
static int IDcount=0;
ID = IDcount++;
}
//ID useful for debugging
int ID;
bool operator < (SynchronizationPoint other) const {
return ID < other.ID;
}
//The corresponding instruction
Instruction *val;
//Flags for checking specific attributes of synch points
//The synch point begins an isolated region (e.g. an aquire of a lock)
bool isCritBegin=false;
bool isCritEnd=false;
//The synch point is part of a one-way synchronization
//(e.g. a signal would be FROM, a wait would be TO)
bool isOnewayFrom=false;
bool isOnewayTo=false;
//What argument of the instruction is the memorylocation of synchronization
int op=-1; //-1 Means that all arguments should be searched
//The synchronization points that reach this without passing
//over other synch points
SmallPtrSet<SynchronizationPoint*,2> preceding;
//For each preceding synchpoint, these are the instructions
//that can be executed on the path leading here
map<SynchronizationPoint*,SmallPtrSet<Instruction*,16> > precedingInsts;
//The synchronization points reachable from this without
//passing over other synch points
SmallPtrSet<SynchronizationPoint*,2> following;
//For each following synchpoint, these are the instructions
//that can be executed on the path leading there
map<SynchronizationPoint*,SmallPtrSet<Instruction*,16> > followingInsts;
//The synchronization variable this is part of (if any)
SynchronizationVariable *synchVar=NULL;
//The critical region this is part of (if any)
CriticalRegion *critRegion=NULL;
//Returns a SmallPtrSet containing all points associated with this
//point, including itself
SmallPtrSet<SynchronizationPoint*,8> getAssociatedPoints() {
if (synchVar)
return synchVar->synchronizationPoints;
else {
SmallPtrSet<SynchronizationPoint*,8> toReturn;
toReturn.insert(this);
return toReturn;
}
}
//Returns a SmallPtrSet containing all point associated with this
//point, not including itself
SmallPtrSet<SynchronizationPoint*,8> getOtherPoints() {
SmallPtrSet<SynchronizationPoint*,8> toReturn;
if (synchVar) {
toReturn = synchVar->synchronizationPoints;
toReturn.erase(this);
}
return toReturn;
}
//Sets the associated synchVar correctly
void setSynchronizationVariable(SynchronizationVariable* other) {
if (synchVar)
synchVar->synchronizationPoints.erase(this);
synchVar = other;
synchVar->synchronizationPoints.insert(this);
}
//Iterator-safe variant
void setSynchronizationVariableIterSafe(SynchronizationVariable* other) {
// if (synchVar)
// synchVar->synchronizationPoints.erase(this);
synchVar = other;
// synchVar->synchronizationPoints.insert(this);
}
SmallPtrSet<Instruction*,128> getPrecedingInsts() {
SmallPtrSet<Instruction*,128> toReturn;
for (SynchronizationPoint* synchPoint : preceding)
toReturn.insert(precedingInsts[synchPoint].begin(),
precedingInsts[synchPoint].end());
return toReturn;
}
SmallPtrSet<Instruction*,128> getFollowingInsts() {
SmallPtrSet<Instruction*,128> toReturn;
for (SynchronizationPoint* synchPoint : following)
toReturn.insert(followingInsts[synchPoint].begin(),
followingInsts[synchPoint].end());
return toReturn;
}
};
//Obtains and sets the syncpoints of "other"
void SynchronizationVariable::merge(SynchronizationVariable *other) {
for (SynchronizationPoint *synchPoint : other->synchronizationPoints) {
synchPoint->setSynchronizationVariableIterSafe(this);
synchronizationPoints.insert(synchPoint);
}
other->synchronizationPoints.clear();
//conflicts.insert(other->conflicts.begin(),other->conflicts.end());
}
//Describes a region of code which cannot be executed by more than 1 thread
//at a time. Basically a subset of the SynchronizationPoint graph
class CriticalRegion {
public:
CriticalRegion() {
static int IDcount=0;
ID = IDcount++;
}
//ID useful for debugging
int ID;
//The list of synch variables this Critical Region uses
SmallPtrSet<SynchronizationVariable*,1> synchsOn;
SmallPtrSet<SynchronizationPoint*,3> containedSynchPoints;
SmallPtrSet<SynchronizationPoint*,1> entrySynchPoints;
SmallPtrSet<SynchronizationPoint*,1> exitSynchPoints;
bool firstRegionInEntry=false;
void mergeWith(CriticalRegion* other) {
other->containedSynchPoints.insert(containedSynchPoints.begin(),
containedSynchPoints.end());
other->entrySynchPoints.insert(entrySynchPoints.begin(),
entrySynchPoints.end());
other->exitSynchPoints.insert(exitSynchPoints.begin(),
exitSynchPoints.end());
other->synchsOn.insert(synchsOn.begin(),
synchsOn.end());
for (SynchronizationPoint* synchPoint : containedSynchPoints) {
synchPoint->critRegion=other;
}
}
SmallPtrSet<SynchronizationPoint*,2> getPrecedingRegions() {
SmallPtrSet<SynchronizationPoint*,2> toReturn;
for (SynchronizationPoint* synchPoint : entrySynchPoints) {
toReturn.insert(synchPoint->preceding.begin(),
synchPoint->preceding.end());
}
return toReturn;
}
SmallPtrSet<SynchronizationPoint*,2> getFollowingRegions() {
SmallPtrSet<SynchronizationPoint*,2> toReturn;
for (SynchronizationPoint* synchPoint : exitSynchPoints) {
toReturn.insert(synchPoint->following.begin(),
synchPoint->following.end());
}
return toReturn;
}
SmallPtrSet<Instruction*,128> getPrecedingInsts() {
SmallPtrSet<Instruction*,128> toReturn;
for (SynchronizationPoint* synchPoint : entrySynchPoints) {
SmallPtrSet<Instruction*,128> preceding_ = synchPoint->getPrecedingInsts();
toReturn.insert(preceding_.begin(),
preceding_.end());
}
return toReturn;
}
SmallPtrSet<Instruction*,128> getFollowingInsts() {
SmallPtrSet<Instruction*,128> toReturn;
for (SynchronizationPoint* synchPoint : exitSynchPoints) {
SmallPtrSet<Instruction*,128> following_ = synchPoint->getFollowingInsts();
toReturn.insert(following_.begin(),
following_.end());
}
return toReturn;
}
};
#endif
| [
"[email protected]"
] | |
4a2c4c79502bd8174654f3a3cb6d7b06ceae0aeb | 47f9c8c46cb7a43bc2d390c7f1039ad8ffbc339f | /src_mod/public/vgui/IInput.h | 7fb2d99d51bba027942fbb2bc4be2aa4125dda35 | [] | no_license | SourceEnginePlayground/source-sdk-2004 | 4135e00b06d8491baf174d19897950c40ef6112c | 962ba835716d3e6d778054ab3fb4534bf3b35e1a | refs/heads/master | 2023-03-27T15:04:00.381752 | 2021-03-24T06:42:27 | 2021-03-24T06:42:27 | null | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 5,251 | h | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//=============================================================================//
#ifndef VGUI_IINPUT_H
#define VGUI_IINPUT_H
#ifdef _WIN32
#pragma once
#endif
#include <vgui/VGUI.h>
#include "interface.h"
namespace vgui
{
enum MouseCode;
enum KeyCode;
class Cursor;
typedef unsigned long HCursor;
#define VGUI_GCS_COMPREADSTR 0x0001
#define VGUI_GCS_COMPREADATTR 0x0002
#define VGUI_GCS_COMPREADCLAUSE 0x0004
#define VGUI_GCS_COMPSTR 0x0008
#define VGUI_GCS_COMPATTR 0x0010
#define VGUI_GCS_COMPCLAUSE 0x0020
#define VGUI_GCS_CURSORPOS 0x0080
#define VGUI_GCS_DELTASTART 0x0100
#define VGUI_GCS_RESULTREADSTR 0x0200
#define VGUI_GCS_RESULTREADCLAUSE 0x0400
#define VGUI_GCS_RESULTSTR 0x0800
#define VGUI_GCS_RESULTCLAUSE 0x1000
// style bit flags for WM_IME_COMPOSITION
#define VGUI_CS_INSERTCHAR 0x2000
#define VGUI_CS_NOMOVECARET 0x4000
class IInput : public IBaseInterface
{
public:
virtual void SetMouseFocus(VPANEL newMouseFocus) = 0;
virtual void SetMouseCapture(VPANEL panel) = 0;
// returns the string name of a scan code
virtual void GetKeyCodeText(KeyCode code, char *buf, int buflen) = 0;
// focus
virtual VPANEL GetFocus() = 0;
virtual VPANEL GetMouseOver() = 0; // returns the panel the mouse is currently over, ignoring mouse capture
// mouse state
virtual void SetCursorPos(int x, int y) = 0;
virtual void GetCursorPos(int &x, int &y) = 0;
virtual bool WasMousePressed(MouseCode code) = 0;
virtual bool WasMouseDoublePressed(MouseCode code) = 0;
virtual bool IsMouseDown(MouseCode code) = 0;
// cursor override
virtual void SetCursorOveride(HCursor cursor) = 0;
virtual HCursor GetCursorOveride() = 0;
// key state
virtual bool WasMouseReleased(MouseCode code) = 0;
virtual bool WasKeyPressed(KeyCode code) = 0;
virtual bool IsKeyDown(KeyCode code) = 0;
virtual bool WasKeyTyped(KeyCode code) = 0;
virtual bool WasKeyReleased(KeyCode code) = 0;
virtual VPANEL GetAppModalSurface() = 0;
// set the modal dialog panel.
// all events will go only to this panel and its children.
virtual void SetAppModalSurface(VPANEL panel) = 0;
// release the modal dialog panel
// do this when your modal dialog finishes.
virtual void ReleaseAppModalSurface() = 0;
virtual void GetCursorPosition( int &x, int &y ) = 0;
virtual void SetIMEWindow( void *hwnd ) = 0;
virtual void *GetIMEWindow() = 0;
virtual void OnChangeIME( bool forward ) = 0;
virtual int GetCurrentIMEHandle() = 0;
virtual int GetEnglishIMEHandle() = 0;
// Returns the Language Bar label (Chinese, Korean, Japanese, Russion, Thai, etc.)
virtual void GetIMELanguageName( wchar_t *buf, int unicodeBufferSizeInBytes ) = 0;
// Returns the short code for the language (EN, CH, KO, JP, RU, TH, etc. ).
virtual void GetIMELanguageShortCode( wchar_t *buf, int unicodeBufferSizeInBytes ) = 0;
struct LanguageItem
{
wchar_t shortname[ 4 ];
wchar_t menuname[ 128 ];
int handleValue;
bool active; // true if this is the active language
};
struct ConversionModeItem
{
wchar_t menuname[ 128 ];
int handleValue;
bool active; // true if this is the active conversion mode
};
struct SentenceModeItem
{
wchar_t menuname[ 128 ];
int handleValue;
bool active; // true if this is the active sentence mode
};
// Call with NULL dest to get item count
virtual int GetIMELanguageList( LanguageItem *dest, int destcount ) = 0;
virtual int GetIMEConversionModes( ConversionModeItem *dest, int destcount ) = 0;
virtual int GetIMESentenceModes( SentenceModeItem *dest, int destcount ) = 0;
virtual void OnChangeIMEByHandle( int handleValue ) = 0;
virtual void OnChangeIMEConversionModeByHandle( int handleValue ) = 0;
virtual void OnChangeIMESentenceModeByHandle( int handleValue ) = 0;
virtual void OnInputLanguageChanged() = 0;
virtual void OnIMEStartComposition() = 0;
virtual void OnIMEComposition( int flags ) = 0;
virtual void OnIMEEndComposition() = 0;
virtual void OnIMEShowCandidates() = 0;
virtual void OnIMEChangeCandidates() = 0;
virtual void OnIMECloseCandidates() = 0;
virtual void OnIMERecomputeModes() = 0;
virtual int GetCandidateListCount() = 0;
virtual void GetCandidate( int num, wchar_t *dest, int destSizeBytes ) = 0;
virtual int GetCandidateListSelectedItem() = 0;
virtual int GetCandidateListPageSize() = 0;
virtual int GetCandidateListPageStart() = 0;
//NOTE: We render our own candidate lists most of the time...
virtual void SetCandidateWindowPos( int x, int y ) = 0;
virtual bool GetShouldInvertCompositionString() = 0;
virtual bool CandidateListStartsAtOne() = 0;
virtual void SetCandidateListPageStart( int start ) = 0;
};
#define VGUI_INPUT_INTERFACE_VERSION "VGUI_Input005"
} // namespace vgui
#endif // VGUI_IINPUT_H
| [
"[email protected]"
] | |
5615d2d2c9a24d15d7b128a5adf31492df20ea43 | 6712bd69a7a162d89f8fb2548e98d5900ad47287 | /HorsebackArcheryGame/Queue.cpp | 70d94a4690a3017c4f3a5ae6fe874da0b84be308 | [] | no_license | Belize22/HorsebackArcheryGame | ac9bb64289ae1a3dd4e5c21142d45f3e6af517d0 | 3422d5f554205607cbb0716e0fc13dabe99fad2e | refs/heads/master | 2020-03-15T18:04:58.166971 | 2018-05-05T19:31:48 | 2018-05-05T19:31:48 | 132,275,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 860 | cpp | #include "Queue.h"
//Let item in queue.
void Queue::enqueue(int id) {
queueList.push_back(id);
}
//Let item in front of queue leave.
int Queue::dequeue() {
if (getSize() > 0) {
int front = queueList.at(0);
queueList.erase(queueList.begin());
return front;
}
return -1;
}
//Remove element from queue (not conventional but important so that we can keep track of proper collisions that leave).
void Queue::removeElement(int id) {
for (int i = 0; i < getSize(); i++)
if (queueList.at(i) == id) {
queueList.erase(queueList.begin() + i);
break;
}
}
//Get item at front of queue.
int Queue::getFront() {
return queueList.at(0);
}
//Get size of queue.
int Queue::getSize() {
return queueList.size();
}
//Get element of queue (not conventional but needed for collision lookups).
int Queue::getElement(int pos) {
return queueList.at(pos);
} | [
"[email protected]"
] | |
ef8975ae4cce95ab42f88abad4d05c44bd8a9675 | c3bb9ffcd9ce924f21eb80df90bb16c54cf63dca | /Code/Book/C++ Primer Plus/12_类和动态内存分配/1_String类的简单实现/String.cpp | e3b40449f04b8acf4fce05748372732d6b2b1a13 | [] | no_license | Summer-fox9/Cpp-Primer | a9be9cb982273aec785c0f35e6161fd6b99c4f5d | ba773fd4d14fd70176e35effb002535cb9e8dfd6 | refs/heads/master | 2022-12-16T08:59:46.442758 | 2020-09-22T13:32:49 | 2020-09-22T13:32:49 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 2,658 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include"String.h"
int String::num_strings = 0;
String::String()
{
len = 1;
str = new char[len];
/*
* str = new char[1] 为和不写成 str = new char
* 这个目的是为了让 new[] 与 delete[] 匹配
* 在析构函数中,我们使用的是 delete[] ,如果是其他形式会不匹配
*/
str[0] = '\0';
// 上面的代码也可以改为 str = 0; // sets str to null pointer
num_strings++;
//std::cout << "String() invoked: " << num_strings << " "
// << str << std::endl;
}
String::String(const char* s)
{
len = std::strlen(s);
str = new char[len + 1];
std::strcpy(str, s);
num_strings++;
//std::cout << "String(const char* s) invoked: " << num_strings << " "
// << str << std::endl;
}
String::String(const String& s)
{
len = s.len;
num_strings++;
str = new char[len + 1];
std::strcpy(str, s.str);
//std::cout << "String(const String& s) invoked: " << num_strings << " "
// << str << std::endl;
}
String::~String()
{
if (str)
{
len = 0;
num_strings--;
delete[] str;
//std::cout << "~String() invoked: " << num_strings << " "
// << std::endl;
}
}
String& String::operator=(const String& s)
{
if (&s != this)
{
delete[] str;
len = s.len;
str = new char[len + 1];
std::strcpy(str, s.str);
/* std::cout << "operator=(const String& s) invoked: " << num_strings << " "
<< std::endl;*/
}
return *this;
}
String& String::operator=(const char* s)
{
delete[] str;
len = std::strlen(s);
str = new char[len + 1];
str = std::strcpy(str, s);
return *this;
}
bool operator<(const String& s1, const String& s2)
{
// 如果第一个字符串的字符在第二个字符串的字符之前,返回负值
// 相等,返回 0
return (std::strcmp(s1.str, s2.str) < 0);
}
bool operator>(const String& s1, const String& s2)
{
return (std::strcmp(s1.str, s2.str) > 0);
}
bool operator==(const String& s1, const String& s2)
{
return (std::strcmp(s1.str, s2.str) == 0);
}
char& String::operator[](int n)
{
return str[n];
}
/*
* const String s("Shepard");
* cout << s[1]; // 要确保 s[1] 不被改变
*/
const char& String::operator[](int n) const
{
return str[n];
}
std::ostream& operator<<(std::ostream& os, const String& s)
{
os << s.str;
return os;
}
/*
* if判断:如果因为某种原因(到达文件尾,或者读取到了空行)导致输入失败,is 的值为置为 false
* while 循环:读取多余的输入
*/
std::istream& operator>>(std::istream& is, String& s)
{
char buffer[String::CINLIM];
is.get(buffer, String::CINLIM);
if (is)
s = buffer;
while (is && is.get() != '\n')
;
return is;
}
| [
"[email protected]"
] | |
29d8df4e68b2642eba870c085c1f9ddf1dc395d2 | 1942a0d16bd48962e72aa21fad8d034fa9521a6c | /aws-cpp-sdk-swf/source/model/StartChildWorkflowExecutionInitiatedEventAttributes.cpp | 2f38624fcebf8cfbcb9cbc99466f4ed095fa4a05 | [
"Apache-2.0",
"JSON",
"MIT"
] | permissive | yecol/aws-sdk-cpp | 1aff09a21cfe618e272c2c06d358cfa0fb07cecf | 0b1ea31e593d23b5db49ee39d0a11e5b98ab991e | refs/heads/master | 2021-01-20T02:53:53.557861 | 2018-02-11T11:14:58 | 2018-02-11T11:14:58 | 83,822,910 | 0 | 1 | null | 2017-03-03T17:17:00 | 2017-03-03T17:17:00 | null | UTF-8 | C++ | false | false | 6,144 | cpp | /*
* Copyright 2010-2016 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/swf/model/StartChildWorkflowExecutionInitiatedEventAttributes.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace SWF
{
namespace Model
{
StartChildWorkflowExecutionInitiatedEventAttributes::StartChildWorkflowExecutionInitiatedEventAttributes() :
m_workflowIdHasBeenSet(false),
m_workflowTypeHasBeenSet(false),
m_controlHasBeenSet(false),
m_inputHasBeenSet(false),
m_executionStartToCloseTimeoutHasBeenSet(false),
m_taskListHasBeenSet(false),
m_taskPriorityHasBeenSet(false),
m_decisionTaskCompletedEventId(0),
m_decisionTaskCompletedEventIdHasBeenSet(false),
m_childPolicy(ChildPolicy::NOT_SET),
m_childPolicyHasBeenSet(false),
m_taskStartToCloseTimeoutHasBeenSet(false),
m_tagListHasBeenSet(false),
m_lambdaRoleHasBeenSet(false)
{
}
StartChildWorkflowExecutionInitiatedEventAttributes::StartChildWorkflowExecutionInitiatedEventAttributes(const JsonValue& jsonValue) :
m_workflowIdHasBeenSet(false),
m_workflowTypeHasBeenSet(false),
m_controlHasBeenSet(false),
m_inputHasBeenSet(false),
m_executionStartToCloseTimeoutHasBeenSet(false),
m_taskListHasBeenSet(false),
m_taskPriorityHasBeenSet(false),
m_decisionTaskCompletedEventId(0),
m_decisionTaskCompletedEventIdHasBeenSet(false),
m_childPolicy(ChildPolicy::NOT_SET),
m_childPolicyHasBeenSet(false),
m_taskStartToCloseTimeoutHasBeenSet(false),
m_tagListHasBeenSet(false),
m_lambdaRoleHasBeenSet(false)
{
*this = jsonValue;
}
StartChildWorkflowExecutionInitiatedEventAttributes& StartChildWorkflowExecutionInitiatedEventAttributes::operator =(const JsonValue& jsonValue)
{
if(jsonValue.ValueExists("workflowId"))
{
m_workflowId = jsonValue.GetString("workflowId");
m_workflowIdHasBeenSet = true;
}
if(jsonValue.ValueExists("workflowType"))
{
m_workflowType = jsonValue.GetObject("workflowType");
m_workflowTypeHasBeenSet = true;
}
if(jsonValue.ValueExists("control"))
{
m_control = jsonValue.GetString("control");
m_controlHasBeenSet = true;
}
if(jsonValue.ValueExists("input"))
{
m_input = jsonValue.GetString("input");
m_inputHasBeenSet = true;
}
if(jsonValue.ValueExists("executionStartToCloseTimeout"))
{
m_executionStartToCloseTimeout = jsonValue.GetString("executionStartToCloseTimeout");
m_executionStartToCloseTimeoutHasBeenSet = true;
}
if(jsonValue.ValueExists("taskList"))
{
m_taskList = jsonValue.GetObject("taskList");
m_taskListHasBeenSet = true;
}
if(jsonValue.ValueExists("taskPriority"))
{
m_taskPriority = jsonValue.GetString("taskPriority");
m_taskPriorityHasBeenSet = true;
}
if(jsonValue.ValueExists("decisionTaskCompletedEventId"))
{
m_decisionTaskCompletedEventId = jsonValue.GetInt64("decisionTaskCompletedEventId");
m_decisionTaskCompletedEventIdHasBeenSet = true;
}
if(jsonValue.ValueExists("childPolicy"))
{
m_childPolicy = ChildPolicyMapper::GetChildPolicyForName(jsonValue.GetString("childPolicy"));
m_childPolicyHasBeenSet = true;
}
if(jsonValue.ValueExists("taskStartToCloseTimeout"))
{
m_taskStartToCloseTimeout = jsonValue.GetString("taskStartToCloseTimeout");
m_taskStartToCloseTimeoutHasBeenSet = true;
}
if(jsonValue.ValueExists("tagList"))
{
Array<JsonValue> tagListJsonList = jsonValue.GetArray("tagList");
for(unsigned tagListIndex = 0; tagListIndex < tagListJsonList.GetLength(); ++tagListIndex)
{
m_tagList.push_back(tagListJsonList[tagListIndex].AsString());
}
m_tagListHasBeenSet = true;
}
if(jsonValue.ValueExists("lambdaRole"))
{
m_lambdaRole = jsonValue.GetString("lambdaRole");
m_lambdaRoleHasBeenSet = true;
}
return *this;
}
JsonValue StartChildWorkflowExecutionInitiatedEventAttributes::Jsonize() const
{
JsonValue payload;
if(m_workflowIdHasBeenSet)
{
payload.WithString("workflowId", m_workflowId);
}
if(m_workflowTypeHasBeenSet)
{
payload.WithObject("workflowType", m_workflowType.Jsonize());
}
if(m_controlHasBeenSet)
{
payload.WithString("control", m_control);
}
if(m_inputHasBeenSet)
{
payload.WithString("input", m_input);
}
if(m_executionStartToCloseTimeoutHasBeenSet)
{
payload.WithString("executionStartToCloseTimeout", m_executionStartToCloseTimeout);
}
if(m_taskListHasBeenSet)
{
payload.WithObject("taskList", m_taskList.Jsonize());
}
if(m_taskPriorityHasBeenSet)
{
payload.WithString("taskPriority", m_taskPriority);
}
if(m_decisionTaskCompletedEventIdHasBeenSet)
{
payload.WithInt64("decisionTaskCompletedEventId", m_decisionTaskCompletedEventId);
}
if(m_childPolicyHasBeenSet)
{
payload.WithString("childPolicy", ChildPolicyMapper::GetNameForChildPolicy(m_childPolicy));
}
if(m_taskStartToCloseTimeoutHasBeenSet)
{
payload.WithString("taskStartToCloseTimeout", m_taskStartToCloseTimeout);
}
if(m_tagListHasBeenSet)
{
Array<JsonValue> tagListJsonList(m_tagList.size());
for(unsigned tagListIndex = 0; tagListIndex < tagListJsonList.GetLength(); ++tagListIndex)
{
tagListJsonList[tagListIndex].AsString(m_tagList[tagListIndex]);
}
payload.WithArray("tagList", std::move(tagListJsonList));
}
if(m_lambdaRoleHasBeenSet)
{
payload.WithString("lambdaRole", m_lambdaRole);
}
return payload;
}
} // namespace Model
} // namespace SWF
} // namespace Aws | [
"[email protected]"
] | |
f92d4a3fdecac122dc30b6fc07060f9059d378c7 | e51d009c6c6a1633c2c11ea4e89f289ea294ec7e | /xr2-dsgn/sources/WildMagic/SDK/Include/Wm4HullTriangle3.h | 544cae2b15f137c8b3184292ade502cac101ea4e | [] | no_license | avmal0-Cor/xr2-dsgn | a0c726a4d54a2ac8147a36549bc79620fead0090 | 14e9203ee26be7a3cb5ca5da7056ecb53c558c72 | refs/heads/master | 2023-07-03T02:05:00.566892 | 2021-08-06T03:10:53 | 2021-08-06T03:10:53 | 389,939,196 | 3 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,133 | h | // Wild Magic Source Code
// David Eberly
// http://www.geometrictools.com
// Copyright (c) 1998-2009
//
// This library is free software; you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation; either version 2.1 of the License, or (at
// your option) any later version. The license is available for reading at
// either of the locations:
// http://www.gnu.org/copyleft/lgpl.html
// http://www.geometrictools.com/License/WildMagicLicense.pdf
//
// Version: 4.0.0 (2006/06/28)
#ifndef WM4HULLTRIANGLE3_H
#define WM4HULLTRIANGLE3_H
#include "Wm4FoundationLIB.h"
#include "Wm4Query3.h"
namespace Wm4
{
template <class Real>
class WM4_FOUNDATION_ITEM HullTriangle3
{
public:
HullTriangle3 (int iV0, int iV1, int iV2);
int GetSign (int i, const Query3<Real>* pkQuery);
void AttachTo (HullTriangle3* pkAdj0, HullTriangle3* pkAdj1,
HullTriangle3* pkAdj2);
int DetachFrom (int iAdj, HullTriangle3* pkAdj);
int V[3];
HullTriangle3* A[3];
int Sign;
int Time;
bool OnStack;
};
}
#endif
| [
"[email protected]"
] | |
335245b1101cc0e8ce7729c283f8d221d121c767 | 97ecc5fde4c31ced724f99560960fdd6d2fa9de5 | /src/LCR.cpp | 3beb429738f70ed5e51cc31892da312ac8b6052d | [
"BSD-3-Clause"
] | permissive | marbl/parsnp | 53373c36d10afb08617c2f7aa263550077a88adc | 6e9586968406fbb8dc4a1eda2a78ef5aa88321ea | refs/heads/master | 2023-09-05T01:25:13.798862 | 2023-07-27T16:07:35 | 2023-07-27T16:07:35 | 21,587,852 | 100 | 19 | NOASSERTION | 2023-08-17T18:58:21 | 2014-07-07T21:42:06 | C++ | UTF-8 | C++ | false | false | 2,291 | cpp | /////////////////////////////////////////
// LCR.cpp
// IntraMUM region class
// If collinear across all genomes, will be aligned
/////////////////////////////////////////
// See the LICENSE file included with this software for license information.
#include "LCR.hh"
long TRegion::counter = 1;
TRegion::TRegion()
{
this->id = counter++;
}
TRegion::TRegion( vector<long>& start, vector<long>& end)
{
long slength = 500000000;
long llength = 0;
this->id = counter++;
for( vector<long>::iterator it = start.begin(); it != start.end(); it++)
this->start.push_back(*it);
for( vector<long>::iterator it = end.begin(); it != end.end(); it++)
this->end.push_back(*it);
for ( int i = 0; i < int(start.size()); i ++)
{
this->length.push_back( end.at(i) - start.at(i) );
if ( this->length.at(i) < slength )
slength = this->length.at(i);
if ( this->length.at(i) > llength )
llength = this->length.at(i);
}
this->slength = slength;
this->llength = llength;
}
TRegion::~TRegion()
{}
int operator<( const TRegion &r1, const TRegion &r2)
{
return r1.start.at(0) < r2.start.at(0);
}
int operator==( const TRegion &r1, const TRegion &r2)
{
for ( int i = 0; i < int(r1.start.size()); i++)
{
if ( r1.start.at(i) != r2.start.at(i) || r1.end.at(i) != r2.end.at(i) )
return 0;
}
return 1;
}
int TRegion::getId( void )
{
return this->id;
}// end TRegion::getId
void TRegion::getLength( void )
{
//return this->length;
}// end TRegion::getLength
void TRegion::setLength( long l )
{
//this->length = l;
}// end TRegion::setLength
void TRegion::getStart( vector<long>& start )
{
start = this->start;
}// end TRegion::getStart
void TRegion::setStart( vector<long> start )
{
for( vector<long>::iterator it = start.begin(); it != start.end(); it++)
this->start.push_back(*it);
//this->start = start;
}// end TRegion::setStart
void TRegion::getEnd( vector<long>& end )
{
end = this->end;
}// end TRegion::getEnd
void TRegion::setEnd( vector<long> end )
{
//this->end = end;
for( vector<long>::iterator it = end.begin(); it != end.end(); it++)
this->end.push_back(*it);
}// end TRegion::setEnd
| [
"[email protected]"
] | |
a27fd35250e93a7671a4200fed3781dea96a1c13 | d797ac5321ef1ed94d9d4084cb602a7874dcab60 | /alex_codes/mat_red/phat_lib/boundary_matrix.h | 6b2fbd6d58a9c551392659abb03342e8703c56ea | [] | no_license | JingzeChen/matrix_reduction | 901109e5fcbc29e6acb53d5be8038a2ce1519be2 | ac6a32a3429fe84cc46215dc98163dc7f43f23d0 | refs/heads/master | 2020-04-01T13:19:00.119869 | 2018-12-04T08:06:31 | 2018-12-04T08:06:31 | 153,247,118 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,907 | h | /*
This file is part of PHAT.
PHAT is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
PHAT is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with PHAT. If not, see <http://www.gnu.org/licenses/>. */
#pragma once
//#include <phat_lib/helpers/misc.h>
//#include <phat_lib/representations/bit_tree_pivot_column.h>
#include "./helpers/misc.h"
#include "./representations/bit_tree_pivot_column.h"
// interface class for the main data structure -- implementations of the interface can be found in ./representations
namespace phat {
template< class Representation = bit_tree_pivot_column >
class boundary_matrix
{
protected:
Representation rep;
// interface functions -- actual implementation and complexity depends on chosen @Representation template
public:
// get overall number of columns in boundary_matrix
index get_num_cols() const { return rep._get_num_cols(); }
// set overall number of columns in boundary_matrix
void set_num_cols( index nr_of_columns ) { rep._set_num_cols( nr_of_columns ); }
// get dimension of given index
dimension get_dim( index idx ) const { return rep._get_dim( idx ); }
// set dimension of given index
void set_dim( index idx, dimension dim ) { rep._set_dim( idx, dim ); }
// replaces content of @col with boundary of given index
void get_col( index idx, column& col ) const { col.clear(); rep._get_col( idx, col ); }
// set column @idx to the values contained in @col
void set_col( index idx, const column& col ) { rep._set_col( idx, col ); }
// true iff boundary of given column is empty
bool is_empty( index idx ) const { return rep._is_empty( idx ); }
// largest index of given column (new name for lowestOne()) -- NOT thread-safe
index get_max_index( index idx ) const { return rep._get_max_index( idx ); }
// removes maximal index from given column
void remove_max( index idx ) { rep._remove_max( idx ); }
// adds column @source to column @target'
void add_to( index source, index target ) { rep._add_to( source, target ); }
// clears given column
void clear( index idx ) { rep._clear( idx ); }
// finalizes given column
void finalize( index idx ) { rep._finalize( idx ); }
// syncronizes all internal data structures -- has to be called before and after any multithreaded access!
void sync() { rep._sync(); }
// info functions -- independent of chosen 'Representation'
public:
// maximal dimension
dimension get_max_dim() const {
dimension cur_max_dim = 0;
for( index idx = 0; idx < get_num_cols(); idx++ )
cur_max_dim = get_dim( idx ) > cur_max_dim ? get_dim( idx ) : cur_max_dim;
return cur_max_dim;
}
// number of nonzero rows for given column @idx
index get_num_rows( index idx ) const {
column cur_col;
get_col( idx, cur_col );
return cur_col.size();
}
// maximal number of nonzero rows of all columns
index get_max_col_entries() const {
index max_col_entries = -1;
const index nr_of_columns = get_num_cols();
for( index idx = 0; idx < nr_of_columns; idx++ )
max_col_entries = get_num_rows( idx ) > max_col_entries ? get_num_rows( idx ) : max_col_entries;
return max_col_entries;
}
// maximal number of nonzero cols of all rows
index get_max_row_entries() const {
size_t max_row_entries = 0;
const index nr_of_columns = get_num_cols();
std::vector< std::vector< index > > transposed_matrix( nr_of_columns );
column temp_col;
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) {
get_col( cur_col, temp_col );
for( index idx = 0; idx < (index)temp_col.size(); idx++)
transposed_matrix[ temp_col[ idx ] ].push_back( cur_col );
}
for( index idx = 0; idx < nr_of_columns; idx++ )
max_row_entries = transposed_matrix[ idx ].size() > max_row_entries ? transposed_matrix[ idx ].size() : max_row_entries;
return max_row_entries;
}
// overall number of entries in the matrix
index get_num_entries() const {
index number_of_nonzero_entries = 0;
const index nr_of_columns = get_num_cols();
for( index idx = 0; idx < nr_of_columns; idx++ )
number_of_nonzero_entries += get_num_rows( idx );
return number_of_nonzero_entries;
}
// operators / constructors
public:
boundary_matrix() {};
template< class OtherRepresentation >
boundary_matrix( const boundary_matrix< OtherRepresentation >& other ) {
*this = other;
}
template< typename OtherRepresentation >
bool operator==( const boundary_matrix< OtherRepresentation >& other_boundary_matrix ) const {
const index number_of_columns = this->get_num_cols();
if( number_of_columns != other_boundary_matrix.get_num_cols() )
return false;
column temp_col;
column other_temp_col;
for( index idx = 0; idx < number_of_columns; idx++ ) {
this->get_col( idx, temp_col );
other_boundary_matrix.get_col( idx, other_temp_col );
if( temp_col != other_temp_col || this->get_dim( idx ) != other_boundary_matrix.get_dim( idx ) )
return false;
}
return true;
}
template< typename OtherRepresentation >
bool operator!=( const boundary_matrix< OtherRepresentation >& other_boundary_matrix ) const {
return !( *this == other_boundary_matrix );
}
template< typename OtherRepresentation >
boundary_matrix< Representation >& operator=( const boundary_matrix< OtherRepresentation >& other )
{
const index nr_of_columns = other.get_num_cols();
this->set_num_cols( nr_of_columns );
column temp_col;
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) {
this->set_dim( cur_col, other.get_dim( cur_col ) );
other.get_col( cur_col, temp_col );
this->set_col( cur_col, temp_col );
}
// by convention, always return *this
return *this;
}
// I/O -- independent of chosen 'Representation'
public:
// initializes boundary_matrix from (vector<vector>, vector) pair -- untested
template< typename index_type, typename dimemsion_type >
void load_vector_vector( const std::vector< std::vector< index_type > >& input_matrix, const std::vector< dimemsion_type >& input_dims ) {
const index nr_of_columns = (index)input_matrix.size();
this->set_num_cols( nr_of_columns );
column temp_col;
#pragma omp parallel for private( temp_col )
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) {
this->set_dim( cur_col, (dimension)input_dims[ cur_col ] );
index num_rows = input_matrix[ cur_col ].size();
temp_col.resize( num_rows );
for( index cur_row = 0; cur_row < num_rows; cur_row++ )
temp_col[ cur_row ] = (index)input_matrix[ cur_col ][ cur_row ];
this->set_col( cur_col, temp_col );
}
}
template< typename index_type, typename dimension_type >
void save_scs(
uint **iRow, //= (uint *) malloc (N * AVG_NUM_PER_COL * sizeof(uint));
uint **iPrefix, //= (uint *) malloc ( (N+1) * sizeof(uint) );
uint *iNumSimplex,
uint *iNumItem,
uint *iMaxIdx
){
index nr_of_columns = get_num_cols();
dimension_type max_dim = get_max_dim();
std::vector< index > new_index( nr_of_columns );
std::vector< std::vector<index> > old_index(max_dim+1); //this is what we need to get old indices from new indices, TODO: return it
memset( iNumSimplex, 0, sizeof(uint) * max_dim + 1);
memset( iNumItem, 0, sizeof(uint) * max_dim + 1);
index_type l = 0;
for( dimension_type dim = 0; dim < max_dim + 1; dim++ )
{
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ )
if( get_dim( cur_col ) == dim )
{
old_index[dim].push_back( cur_col );
new_index[cur_col] = l ++;
iNumItem[dim] += get_num_rows(cur_col);
iNumSimplex[dim] += 1;
}
}
*iMaxIdx = get_num_cols();
for( dimension_type dim = 0; dim < max_dim + 1; dim++ )
{
index nr_of_columns_in_dim = iNumSimplex[dim];
index nr_of_entries_in_dim = iNumItem[dim];
iRow[dim] = (uint *) malloc ( (nr_of_entries_in_dim) * sizeof(uint));
iPrefix[dim] = (uint *) malloc ( (nr_of_columns_in_dim+1) * sizeof(uint));
iPrefix[dim][nr_of_columns_in_dim]=nr_of_entries_in_dim;
index_type i = 0; //col number in new indexing
index prefix = 0;
index global_index = 0;
column temp_col;
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ )
if( get_dim( cur_col ) == dim )
{
get_col( cur_col, temp_col );
index num_rows = temp_col.size();
iPrefix[dim][i++]= prefix;
prefix += num_rows;
for( index cur_row = 0; cur_row < num_rows; cur_row++ )
iRow[dim][global_index++] = new_index[temp_col[cur_row]];
}
}
}
template< typename index_type, typename dimemsion_type >
void save_scs(
uint **iRow, //= (uint *) malloc (N * AVG_NUM_PER_COL * sizeof(uint));
uint **iPrefix //= (uint *) malloc ( (N+1) * sizeof(uint) );
//,output_matrix, std::vector< dimemsion_type >& output_dims
) {
const index nr_of_columns = get_num_cols();
//output_matrix.resize( nr_of_columns );
const index nr_of_entries = get_num_entries();
*iRow =(uint*) malloc (nr_of_entries * sizeof(uint));
*iPrefix = (uint *) malloc ( (nr_of_columns+1) * sizeof(uint) );
(*iPrefix)[nr_of_columns]=nr_of_entries;
column temp_col;
index prefix = 0;
index global_index = 0;
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) {
//output_dims[ cur_col ] = (dimemsion_type)get_dim( cur_col );
get_col( cur_col, temp_col );
index num_rows = temp_col.size();
(*iPrefix)[cur_col]= prefix;
prefix += num_rows;
//output_matrix[ cur_col ].clear();
//output_matrix[ cur_col ].resize( num_rows );
for( index cur_row = 0; cur_row < num_rows; cur_row++ )
//output_matrix[ cur_col ][ cur_row ] = (index_type)temp_col[ cur_row ];
(*iRow)[global_index++] = temp_col[cur_row];
}
}
template< typename index_type, typename dimemsion_type >
void save_scs_decreasing(
uint **iRow, //= (uint *) malloc (N * AVG_NUM_PER_COL * sizeof(uint));
uint **iPrefix //= (uint *) malloc ( (N+1) * sizeof(uint) );
//,output_matrix, std::vector< dimemsion_type >& output_dims
) {
const index nr_of_columns = get_num_cols();
//output_matrix.resize( nr_of_columns );
const index nr_of_entries = get_num_entries();
*iRow =(uint*) malloc (nr_of_entries * sizeof(uint));
*iPrefix = (uint *) malloc ( (nr_of_columns+1) * sizeof(uint) );
(*iPrefix)[nr_of_columns]=nr_of_entries;
column temp_col;
index prefix = 0;
index global_index = 0;
for( index cur_col = 0; cur_col < nr_of_columns; cur_col++ ) {
//output_dims[ cur_col ] = (dimemsion_type)get_dim( cur_col );
get_col( cur_col, temp_col );
index num_rows = temp_col.size();
(*iPrefix)[cur_col]= prefix;
prefix += num_rows;
//output_matrix[ cur_col ].clear();
//output_matrix[ cur_col ].resize( num_rows );
for( index cur_row = num_rows-1; cur_row >= 0; cur_row-- )
//output_matrix[ cur_col ][ cur_row ] = (index_type)temp_col[ cur_row ];
(*iRow)[global_index++] = temp_col[cur_row];
}
}
// Loads the boundary_matrix from given file in ascii format
// Format: each line represents a column, first number is dimension, other numbers are the content of the column.
// Ignores empty lines and lines starting with a '#'.
bool load_ascii( std::string filename ) {
// first count number of columns:
std::string cur_line;
std::ifstream dummy( filename .c_str() );
if( dummy.fail() )
return false;
index number_of_columns = 0;
while( getline( dummy, cur_line ) ) {
cur_line.erase(cur_line.find_last_not_of(" \t\n\r\f\v") + 1);
if( cur_line != "" && cur_line[ 0 ] != '#' )
number_of_columns++;
}
this->set_num_cols( number_of_columns );
dummy.close();
std::ifstream input_stream( filename.c_str() );
if( input_stream.fail() )
return false;
column temp_col;
index cur_col = -1;
while( getline( input_stream, cur_line ) ) {
cur_line.erase(cur_line.find_last_not_of(" \t\n\r\f\v") + 1);
if( cur_line != "" && cur_line[ 0 ] != '#' ) {
cur_col++;
std::stringstream ss( cur_line );
int64_t temp_dim;
ss >> temp_dim;
this->set_dim( cur_col, (dimension) temp_dim );
int64_t temp_index;
temp_col.clear();
while( ss.good() ) {
ss >> temp_index;
temp_col.push_back( (index)temp_index );
}
std::sort( temp_col.begin(), temp_col.end() );
this->set_col( cur_col, temp_col );
}
}
input_stream.close();
return true;
}
// Saves the boundary_matrix to given file in ascii format
// Format: each line represents a column, first number is dimension, other numbers are the content of the column
bool save_ascii( std::string filename ) {
std::ofstream output_stream( filename.c_str() );
if( output_stream.fail() )
return false;
const index nr_columns = this->get_num_cols();
column tempCol;
for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) {
output_stream << (int64_t)this->get_dim( cur_col );
this->get_col( cur_col, tempCol );
for( index cur_row_idx = 0; cur_row_idx < (index)tempCol.size(); cur_row_idx++ )
output_stream << " " << tempCol[ cur_row_idx ];
output_stream << std::endl;
}
output_stream.close();
return true;
}
// Loads boundary_matrix from given file
// Format: nr_columns % dim1 % N1 % row1 row2 % ...% rowN1 % dim2 % N2 % ...
bool load_binary( std::string filename )
{
std::ifstream input_stream( filename.c_str( ), std::ios_base::binary | std::ios_base::in );
if( input_stream.fail( ) )
return false;
int64_t nr_columns;
input_stream.read( (char*)&nr_columns, sizeof( int64_t ) );
this->set_num_cols( (index)nr_columns );
column temp_col;
for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) {
int64_t cur_dim;
input_stream.read( (char*)&cur_dim, sizeof( int64_t ) );
this->set_dim( cur_col, (dimension)cur_dim );
int64_t nr_rows;
input_stream.read( (char*)&nr_rows, sizeof( int64_t ) );
temp_col.resize( ( std::size_t )nr_rows );
for( index idx = 0; idx < nr_rows; idx++ ) {
int64_t cur_row;
input_stream.read( (char*)&cur_row, sizeof( int64_t ) );
temp_col[ idx ] = (index)cur_row;
}
this->set_col( cur_col, temp_col );
}
input_stream.close( );
return true;
}
// Saves the boundary_matrix to given file in binary format
// Format: nr_columns % dim1 % N1 % row1 row2 % ...% rowN1 % dim2 % N2 % ...
bool save_binary( std::string filename )
{
std::ofstream output_stream( filename.c_str( ), std::ios_base::binary | std::ios_base::out );
if( output_stream.fail( ) )
return false;
const int64_t nr_columns = this->get_num_cols( );
output_stream.write( (char*)&nr_columns, sizeof( int64_t ) );
column tempCol;
for( index cur_col = 0; cur_col < nr_columns; cur_col++ ) {
int64_t cur_dim = this->get_dim( cur_col );
output_stream.write( (char*)&cur_dim, sizeof( int64_t ) );
this->get_col( cur_col, tempCol );
int64_t cur_nr_rows = tempCol.size( );
output_stream.write( (char*)&cur_nr_rows, sizeof( int64_t ) );
for( index cur_row_idx = 0; cur_row_idx < (index)tempCol.size( ); cur_row_idx++ ) {
int64_t cur_row = tempCol[ cur_row_idx ];
output_stream.write( (char*)&cur_row, sizeof( int64_t ) );
}
}
output_stream.close( );
return true;
}
};
}
| [
"[email protected]"
] | |
34216e11a46f180acbe85a547423cad0f23cfa74 | c44b0897e535918901818c1e25acbff8983c6c66 | /2_12/A.cpp | 39a87054433ada4b50c46e2507e8f0809718407a | [] | no_license | teleport1995/shad_algorithms_2015 | 90a4c0f7e714fdf378c8888e1045f123b8ff8997 | cbcff5c872bd6195963bb7e7a8aab86572aeae00 | refs/heads/master | 2021-01-10T02:58:42.092773 | 2016-02-20T11:09:14 | 2016-02-20T11:09:14 | 52,149,446 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,346 | cpp | #include <iostream>
#include <cstdio>
#include <vector>
#include <map>
#include <algorithm>
using std::cin;
using std::istream;
using std::ostream;
using std::cout;
using std::vector;
using std::max;
using std::map;
class Node
{
public:
int left, right;
vector < int > sorted;
Node()
{
}
Node(int left, int right): left(left), right(right)
{
}
};
class IntervalsTree
{
private:
int size;
vector < Node > data;
void init(int node_index, int left, int right, vector < int > &sequence)
{
data[node_index] = Node(left, right);
data[node_index].sorted.resize(right - left);
if (right - left == 1)
{
data[node_index].sorted[0] = sequence[left];
return;
}
int middle = (left + right) / 2;
init(node_index * 2 + 0, left, middle, sequence);
init(node_index * 2 + 1, middle, right, sequence);
merge(begin(data[node_index * 2 + 0].sorted), end(data[node_index * 2 + 0].sorted),
begin(data[node_index * 2 + 1].sorted), end(data[node_index * 2 + 1].sorted),
begin(data[node_index].sorted));
}
int get_answer(int node_index, int left, int right)
{
if (data[node_index].left >= left && data[node_index].right <= right)
{
return lower_bound(data[node_index].sorted.begin(), data[node_index].sorted.end(), left)
- data[node_index].sorted.begin();
}
int answer = 0;
int middle = data[node_index * 2 + 0].right;
if (left < middle)
{
answer += get_answer(node_index * 2 + 0, left, right);
}
if (middle < right)
{
answer += get_answer(node_index * 2 + 1, left, right);
}
return answer;
}
public:
void init(vector < int > &sequence)
{
data.resize(sequence.size() * 4);
init(1, 0, sequence.size(), sequence);
}
int get_answer(int left, int right)
{
return get_answer(1, left, right);
}
};
class Query
{
public:
int left, right;
Query()
{
}
Query(int left, int right): left(left), right(right)
{
}
};
class UniqueCountSolver
{
private:
vector < int > data;
vector < Query > queries;
vector < int > answers;
vector < int > get_prev_positions()
{
const int NO_PREV = -1;
map < int , int > last_position;
vector < int > prev_positions(data.size());
for (size_t i = 0; i < data.size(); ++i)
{
if (last_position.find(data[i]) == last_position.end())
prev_positions[i] = NO_PREV;
else
prev_positions[i] = last_position[data[i]];
last_position[data[i]] = i;
}
return prev_positions;
}
public:
void read(istream &in)
{
int data_size, queries_size;
in >> data_size >> queries_size;
data.resize(data_size);
for (int i = 0; i < data_size; ++i)
{
in >> data[i];
}
queries.resize(queries_size);
for (int i = 0; i < queries_size; ++i)
{
int left, right;
in >> left >> right;
queries[i] = Query(left - 1, right);
}
}
void solve()
{
vector < int > prev_positions = get_prev_positions();
IntervalsTree tree;
tree.init(prev_positions);
answers.resize(queries.size());
for (size_t i = 0; i < queries.size(); ++i)
{
answers[i] = tree.get_answer(queries[i].left, queries[i].right);
}
}
void write(ostream &out)
{
for (size_t i = 0; i < answers.size(); ++i)
{
out << answers[i] << "\n";
}
}
};
int main()
{
UniqueCountSolver solver;
solver.read(cin);
solver.solve();
solver.write(cout);
return 0;
}
| [
"teleport1995"
] | teleport1995 |
42a0030cc2916155d08ca7d2d9a23141958942c7 | 259e49b9e9c5f721243a7b36a06f6b2b2283e067 | /src/main.h | 6074819aed07a068869477fae71b483f9b0da8ff | [
"MIT"
] | permissive | startlifecoin/startlife | 99f919072fa1f0abde69af4a67b5c7f9b66c949b | 2f61067f76c4d7f5ca18d2ea51b06d6808eb884c | refs/heads/master | 2020-04-10T15:35:26.968352 | 2018-12-18T22:01:24 | 2018-12-18T22:01:24 | 161,114,655 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 24,981 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2017-2018 The StartLife developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_MAIN_H
#define BITCOIN_MAIN_H
#if defined(HAVE_CONFIG_H)
#include "config/startlife-config.h"
#endif
#include "amount.h"
#include "chain.h"
#include "chainparams.h"
#include "coins.h"
#include "net.h"
#include "pow.h"
#include "primitives/block.h"
#include "primitives/transaction.h"
#include "script/script.h"
#include "script/sigcache.h"
#include "script/standard.h"
#include "sync.h"
#include "tinyformat.h"
#include "txmempool.h"
#include "uint256.h"
#include "undo.h"
#include <algorithm>
#include <exception>
#include <map>
#include <set>
#include <stdint.h>
#include <string>
#include <utility>
#include <vector>
#include <boost/unordered_map.hpp>
class CBlockIndex;
class CBlockTreeDB;
class CBloomFilter;
class CInv;
class CScriptCheck;
class CValidationInterface;
class CValidationState;
struct CBlockTemplate;
struct CNodeStateStats;
/** Default for -blockmaxsize and -blockminsize, which control the range of sizes the mining code will create **/
static const unsigned int DEFAULT_BLOCK_MAX_SIZE = 750000;
static const unsigned int DEFAULT_BLOCK_MIN_SIZE = 0;
/** Default for -blockprioritysize, maximum space for zero/low-fee transactions **/
static const unsigned int DEFAULT_BLOCK_PRIORITY_SIZE = 50000;
/** Default for accepting alerts from the P2P network. */
static const bool DEFAULT_ALERTS = true;
/** The maximum size for transactions we're willing to relay/mine */
static const unsigned int MAX_STANDARD_TX_SIZE = 100000;
/** The maximum allowed number of signature check operations in a block (network rule) */
static const unsigned int MAX_BLOCK_SIGOPS = MAX_BLOCK_SIZE / 50;
/** Maximum number of signature check operations in an IsStandard() P2SH script */
static const unsigned int MAX_P2SH_SIGOPS = 15;
/** The maximum number of sigops we're willing to relay/mine in a single tx */
static const unsigned int MAX_TX_SIGOPS = MAX_BLOCK_SIGOPS / 5;
/** Default for -maxorphantx, maximum number of orphan transactions kept in memory */
static const unsigned int DEFAULT_MAX_ORPHAN_TRANSACTIONS = 100;
/** The maximum size of a blk?????.dat file (since 0.8) */
static const unsigned int MAX_BLOCKFILE_SIZE = 0x8000000; // 128 MiB
/** The pre-allocation chunk size for blk?????.dat files (since 0.8) */
static const unsigned int BLOCKFILE_CHUNK_SIZE = 0x1000000; // 16 MiB
/** The pre-allocation chunk size for rev?????.dat files (since 0.8) */
static const unsigned int UNDOFILE_CHUNK_SIZE = 0x100000; // 1 MiB
/** Coinbase transaction outputs can only be spent after this number of new blocks (network rule) */
static const int COINBASE_MATURITY = 100;
/** Threshold for nLockTime: below this value it is interpreted as block number, otherwise as UNIX timestamp. */
static const unsigned int LOCKTIME_THRESHOLD = 500000000; // Tue Nov 5 00:53:20 1985 UTC
/** Maximum number of script-checking threads allowed */
static const int MAX_SCRIPTCHECK_THREADS = 16;
/** -par default (number of script-checking threads, 0 = auto) */
static const int DEFAULT_SCRIPTCHECK_THREADS = 0;
/** Number of blocks that can be requested at any given time from a single peer. */
static const int MAX_BLOCKS_IN_TRANSIT_PER_PEER = 16;
/** Timeout in seconds during which a peer must stall block download progress before being disconnected. */
static const unsigned int BLOCK_STALLING_TIMEOUT = 2;
/** Number of headers sent in one getheaders result. We rely on the assumption that if a peer sends
* less than this number, we reached their tip. Changing this value is a protocol upgrade. */
static const unsigned int MAX_HEADERS_RESULTS = 2000;
/** Size of the "block download window": how far ahead of our current height do we fetch?
* Larger windows tolerate larger download speed differences between peer, but increase the potential
* degree of disordering of blocks on disk (which make reindexing and in the future perhaps pruning
* harder). We'll probably want to make this a per-peer adaptive value at some point. */
static const unsigned int BLOCK_DOWNLOAD_WINDOW = 1024;
/** Time to wait (in seconds) between writing blockchain state to disk. */
static const unsigned int DATABASE_WRITE_INTERVAL = 3600;
/** Maximum length of reject messages. */
static const unsigned int MAX_REJECT_MESSAGE_LENGTH = 111;
static const bool DEFAULT_PEERBLOOMFILTERS = true;
/** "reject" message codes */
static const unsigned char REJECT_MALFORMED = 0x01;
static const unsigned char REJECT_INVALID = 0x10;
static const unsigned char REJECT_OBSOLETE = 0x11;
static const unsigned char REJECT_DUPLICATE = 0x12;
static const unsigned char REJECT_NONSTANDARD = 0x40;
static const unsigned char REJECT_DUST = 0x41;
static const unsigned char REJECT_INSUFFICIENTFEE = 0x42;
static const unsigned char REJECT_CHECKPOINT = 0x43;
struct BlockHasher {
size_t operator()(const uint256& hash) const { return hash.GetLow64(); }
};
extern CScript COINBASE_FLAGS;
extern CCriticalSection cs_main;
extern CTxMemPool mempool;
typedef boost::unordered_map<uint256, CBlockIndex*, BlockHasher> BlockMap;
extern BlockMap mapBlockIndex;
extern uint64_t nLastBlockTx;
extern uint64_t nLastBlockSize;
extern const std::string strMessageMagic;
extern int64_t nTimeBestReceived;
extern CWaitableCriticalSection csBestBlock;
extern CConditionVariable cvBlockChange;
extern bool fImporting;
extern bool fReindex;
extern int nScriptCheckThreads;
extern bool fTxIndex;
extern bool fIsBareMultisigStd;
extern bool fCheckBlockIndex;
extern unsigned int nCoinCacheSize;
extern CFeeRate minRelayTxFee;
extern bool fAlerts;
extern bool fLargeWorkForkFound;
extern bool fLargeWorkInvalidChainFound;
extern unsigned int nStakeMinAge;
extern int64_t nLastCoinStakeSearchInterval;
extern int64_t nLastCoinStakeSearchTime;
extern int64_t nReserveBalance;
extern std::map<uint256, int64_t> mapRejectedBlocks;
extern std::map<unsigned int, unsigned int> mapHashedBlocks;
extern std::set<std::pair<COutPoint, unsigned int> > setStakeSeen;
/** Best header we've seen so far (used for getheaders queries' starting points). */
extern CBlockIndex* pindexBestHeader;
/** Minimum disk space required - used in CheckDiskSpace() */
static const uint64_t nMinDiskSpace = 52428800;
/** Register a wallet to receive updates from core */
void RegisterValidationInterface(CValidationInterface* pwalletIn);
/** Unregister a wallet from core */
void UnregisterValidationInterface(CValidationInterface* pwalletIn);
/** Unregister all wallets from core */
void UnregisterAllValidationInterfaces();
/** Push an updated transaction to all registered wallets */
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock = NULL);
/** Register with a network node to receive its signals */
void RegisterNodeSignals(CNodeSignals& nodeSignals);
/** Unregister a network node */
void UnregisterNodeSignals(CNodeSignals& nodeSignals);
/**
* Process an incoming block. This only returns after the best known valid
* block is made active. Note that it does not, however, guarantee that the
* specific block passed to it has been checked for validity!
*
* @param[out] state This may be set to an Error state if any error occurred processing it, including during validation/connection/etc of otherwise unrelated blocks during reorganisation; or it may be set to an Invalid state if pblock is itself invalid (but this is not guaranteed even when the block is checked). If you want to *possibly* get feedback on whether pblock is valid, you must also install a CValidationInterface - this will have its BlockChecked method called whenever *any* block completes validation.
* @param[in] pfrom The node which we are receiving the block from; it is added to mapBlockSource and may be penalised if the block is invalid.
* @param[in] pblock The block we want to process.
* @param[out] dbp If pblock is stored to disk (or already there), this will be set to its location.
* @return True if state.IsValid()
*/
bool ProcessNewBlock(CValidationState& state, CNode* pfrom, CBlock* pblock, CDiskBlockPos* dbp = NULL);
/** Check whether enough disk space is available for an incoming block */
bool CheckDiskSpace(uint64_t nAdditionalBytes = 0);
/** Open a block file (blk?????.dat) */
FILE* OpenBlockFile(const CDiskBlockPos& pos, bool fReadOnly = false);
/** Open an undo file (rev?????.dat) */
FILE* OpenUndoFile(const CDiskBlockPos& pos, bool fReadOnly = false);
/** Translation to a filesystem path */
boost::filesystem::path GetBlockPosFilename(const CDiskBlockPos& pos, const char* prefix);
/** Import blocks from an external file */
bool LoadExternalBlockFile(FILE* fileIn, CDiskBlockPos* dbp = NULL);
/** Initialize a new block tree database + block data on disk */
bool InitBlockIndex();
/** Load the block tree and coins database from disk */
bool LoadBlockIndex();
/** Unload database information */
void UnloadBlockIndex();
/** See whether the protocol update is enforced for connected nodes */
int ActiveProtocol();
/** Process protocol messages received from a given node */
bool ProcessMessages(CNode* pfrom);
/**
* Send queued protocol messages to be sent to a give node.
*
* @param[in] pto The node which we are sending messages to.
* @param[in] fSendTrickle When true send the trickled data, otherwise trickle the data until true.
*/
bool SendMessages(CNode* pto, bool fSendTrickle);
/** Run an instance of the script checking thread */
void ThreadScriptCheck();
// ***TODO*** probably not the right place for these 2
/** Check whether a block hash satisfies the proof-of-work requirement specified by nBits */
bool CheckProofOfWork(uint256 hash, unsigned int nBits);
/** Check whether we are doing an initial block download (synchronizing from disk or network) */
bool IsInitialBlockDownload();
/** Format a string that describes several potential problems detected by the core */
std::string GetWarnings(std::string strFor);
/** Retrieve a transaction (from memory pool, or from disk, if possible) */
bool GetTransaction(const uint256& hash, CTransaction& tx, uint256& hashBlock, bool fAllowSlow = false);
/** Find the best known block, and make it the tip of the block chain */
bool DisconnectBlocksAndReprocess(int blocks);
// ***TODO***
double ConvertBitsToDouble(unsigned int nBits);
int64_t GetMasternodePayment(int nHeight, int64_t blockValue, int nMasternodeCount = 0);
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader* pblock, bool fProofOfStake);
bool ActivateBestChain(CValidationState& state, CBlock* pblock = NULL);
CAmount GetBlockValue(int nHeight);
/** Create a new block index entry for a given block hash */
CBlockIndex* InsertBlockIndex(uint256 hash);
/** Abort with a message */
bool AbortNode(const std::string& msg, const std::string& userMessage = "");
/** Get statistics from node state */
bool GetNodeStateStats(NodeId nodeid, CNodeStateStats& stats);
/** Increase a node's misbehavior score. */
void Misbehaving(NodeId nodeid, int howmuch);
/** Flush all state, indexes and buffers to disk. */
void FlushStateToDisk();
/** (try to) add transaction to memory pool **/
bool AcceptToMemoryPool(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false, bool ignoreFees = false);
bool AcceptableInputs(CTxMemPool& pool, CValidationState& state, const CTransaction& tx, bool fLimitFree, bool* pfMissingInputs, bool fRejectInsaneFee = false, bool isDSTX = false);
int GetInputAge(CTxIn& vin);
int GetInputAgeIX(uint256 nTXHash, CTxIn& vin);
bool GetCoinAge(const CTransaction& tx, unsigned int nTxTime, uint64_t& nCoinAge);
int GetIXConfirmations(uint256 nTXHash);
struct CNodeStateStats {
int nMisbehavior;
int nSyncHeight;
int nCommonHeight;
std::vector<int> vHeightInFlight;
};
struct CDiskTxPos : public CDiskBlockPos {
unsigned int nTxOffset; // after header
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(*(CDiskBlockPos*)this);
READWRITE(VARINT(nTxOffset));
}
CDiskTxPos(const CDiskBlockPos& blockIn, unsigned int nTxOffsetIn) : CDiskBlockPos(blockIn.nFile, blockIn.nPos), nTxOffset(nTxOffsetIn)
{
}
CDiskTxPos()
{
SetNull();
}
void SetNull()
{
CDiskBlockPos::SetNull();
nTxOffset = 0;
}
};
CAmount GetMinRelayFee(const CTransaction& tx, unsigned int nBytes, bool fAllowFree);
/**
* Check transaction inputs, and make sure any
* pay-to-script-hash transactions are evaluating IsStandard scripts
*
* Why bother? To avoid denial-of-service attacks; an attacker
* can submit a standard HASH... OP_EQUAL transaction,
* which will get accepted into blocks. The redemption
* script can be anything; an attacker could use a very
* expensive-to-check-upon-redemption script like:
* DUP CHECKSIG DROP ... repeated 100 times... OP_1
*/
/**
* Check for standard transaction types
* @param[in] mapInputs Map of previous transactions that have outputs we're spending
* @return True if all inputs (scriptSigs) use only standard transaction forms
*/
bool AreInputsStandard(const CTransaction& tx, const CCoinsViewCache& mapInputs);
/**
* Count ECDSA signature operations the old-fashioned (pre-0.6) way
* @return number of sigops this transaction's outputs will produce when spent
* @see CTransaction::FetchInputs
*/
unsigned int GetLegacySigOpCount(const CTransaction& tx);
/**
* Count ECDSA signature operations in pay-to-script-hash inputs.
*
* @param[in] mapInputs Map of previous transactions that have outputs we're spending
* @return maximum number of sigops required to validate this transaction's inputs
* @see CTransaction::FetchInputs
*/
unsigned int GetP2SHSigOpCount(const CTransaction& tx, const CCoinsViewCache& mapInputs);
/**
* Check whether all inputs of this transaction are valid (no double spends, scripts & sigs, amounts)
* This does not modify the UTXO set. If pvChecks is not NULL, script checks are pushed onto it
* instead of being performed inline.
*/
bool CheckInputs(const CTransaction& tx, CValidationState& state, const CCoinsViewCache& view, bool fScriptChecks, unsigned int flags, bool cacheStore, std::vector<CScriptCheck>* pvChecks = NULL);
/** Apply the effects of this transaction on the UTXO set represented by view */
void UpdateCoins(const CTransaction& tx, CValidationState& state, CCoinsViewCache& inputs, CTxUndo& txundo, int nHeight);
/** Context-independent validity checks */
bool CheckTransaction(const CTransaction& tx, CValidationState& state);
/**
* Check if transaction will be final in the next block to be created.
*
* Calls IsFinalTx() with current block height and appropriate block time.
*
* See consensus/consensus.h for flag definitions.
*/
bool CheckFinalTx(const CTransaction& tx, int flags = -1);
/** Check for standard transaction types
* @return True if all outputs (scriptPubKeys) use only standard transaction forms
*/
bool IsStandardTx(const CTransaction& tx, std::string& reason);
bool IsFinalTx(const CTransaction& tx, int nBlockHeight = 0, int64_t nBlockTime = 0);
/** Undo information for a CBlock */
class CBlockUndo
{
public:
std::vector<CTxUndo> vtxundo; // for all but the coinbase
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(vtxundo);
}
bool WriteToDisk(CDiskBlockPos& pos, const uint256& hashBlock);
bool ReadFromDisk(const CDiskBlockPos& pos, const uint256& hashBlock);
};
/**
* Closure representing one script verification
* Note that this stores references to the spending transaction
*/
class CScriptCheck
{
private:
CScript scriptPubKey;
const CTransaction* ptxTo;
unsigned int nIn;
unsigned int nFlags;
bool cacheStore;
ScriptError error;
public:
CScriptCheck() : ptxTo(0), nIn(0), nFlags(0), cacheStore(false), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
CScriptCheck(const CCoins& txFromIn, const CTransaction& txToIn, unsigned int nInIn, unsigned int nFlagsIn, bool cacheIn) : scriptPubKey(txFromIn.vout[txToIn.vin[nInIn].prevout.n].scriptPubKey),
ptxTo(&txToIn), nIn(nInIn), nFlags(nFlagsIn), cacheStore(cacheIn), error(SCRIPT_ERR_UNKNOWN_ERROR) {}
bool operator()();
void swap(CScriptCheck& check)
{
scriptPubKey.swap(check.scriptPubKey);
std::swap(ptxTo, check.ptxTo);
std::swap(nIn, check.nIn);
std::swap(nFlags, check.nFlags);
std::swap(cacheStore, check.cacheStore);
std::swap(error, check.error);
}
ScriptError GetScriptError() const { return error; }
};
/** Functions for disk access for blocks */
bool WriteBlockToDisk(CBlock& block, CDiskBlockPos& pos);
bool ReadBlockFromDisk(CBlock& block, const CDiskBlockPos& pos);
bool ReadBlockFromDisk(CBlock& block, const CBlockIndex* pindex);
/** Functions for validating blocks and updating the block tree */
/** Undo the effects of this block (with given index) on the UTXO set represented by coins.
* In case pfClean is provided, operation will try to be tolerant about errors, and *pfClean
* will be true if no problems were found. Otherwise, the return value will be false in case
* of problems. Note that in any case, coins may be modified. */
bool DisconnectBlock(CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool* pfClean = NULL);
/** Reprocess a number of blocks to try and get on the correct chain again **/
bool DisconnectBlocksAndReprocess(int blocks);
/** Apply the effects of this block (with given index) on the UTXO set represented by coins */
bool ConnectBlock(const CBlock& block, CValidationState& state, CBlockIndex* pindex, CCoinsViewCache& coins, bool fJustCheck = false);
/** Context-independent validity checks */
bool CheckBlockHeader(const CBlockHeader& block, CValidationState& state, bool fCheckPOW = true);
bool CheckBlock(const CBlock& block, CValidationState& state, bool fCheckPOW = true, bool fCheckMerkleRoot = true, bool fCheckSig = true);
bool CheckWork(const CBlock block, CBlockIndex* const pindexPrev);
/** Context-dependent validity checks */
bool ContextualCheckBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex* pindexPrev);
/** Check a block is completely valid from start to finish (only works on top of our current best block, with cs_main held) */
bool TestBlockValidity(CValidationState& state, const CBlock& block, CBlockIndex* pindexPrev, bool fCheckPOW = true, bool fCheckMerkleRoot = true);
/** Store block on disk. If dbp is provided, the file is known to already reside on disk */
bool AcceptBlock(CBlock& block, CValidationState& state, CBlockIndex** pindex, CDiskBlockPos* dbp = NULL);
bool AcceptBlockHeader(const CBlockHeader& block, CValidationState& state, CBlockIndex** ppindex = NULL);
class CBlockFileInfo
{
public:
unsigned int nBlocks; //! number of blocks stored in file
unsigned int nSize; //! number of used bytes of block file
unsigned int nUndoSize; //! number of used bytes in the undo file
unsigned int nHeightFirst; //! lowest height of block in file
unsigned int nHeightLast; //! highest height of block in file
uint64_t nTimeFirst; //! earliest time of block in file
uint64_t nTimeLast; //! latest time of block in file
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(VARINT(nBlocks));
READWRITE(VARINT(nSize));
READWRITE(VARINT(nUndoSize));
READWRITE(VARINT(nHeightFirst));
READWRITE(VARINT(nHeightLast));
READWRITE(VARINT(nTimeFirst));
READWRITE(VARINT(nTimeLast));
}
void SetNull()
{
nBlocks = 0;
nSize = 0;
nUndoSize = 0;
nHeightFirst = 0;
nHeightLast = 0;
nTimeFirst = 0;
nTimeLast = 0;
}
CBlockFileInfo()
{
SetNull();
}
std::string ToString() const;
/** update statistics (does not update nSize) */
void AddBlock(unsigned int nHeightIn, uint64_t nTimeIn)
{
if (nBlocks == 0 || nHeightFirst > nHeightIn)
nHeightFirst = nHeightIn;
if (nBlocks == 0 || nTimeFirst > nTimeIn)
nTimeFirst = nTimeIn;
nBlocks++;
if (nHeightIn > nHeightLast)
nHeightLast = nHeightIn;
if (nTimeIn > nTimeLast)
nTimeLast = nTimeIn;
}
};
/** Capture information about block/transaction validation */
class CValidationState
{
private:
enum mode_state {
MODE_VALID, //! everything ok
MODE_INVALID, //! network rule violation (DoS value may be set)
MODE_ERROR, //! run-time error
} mode;
int nDoS;
std::string strRejectReason;
unsigned char chRejectCode;
bool corruptionPossible;
public:
CValidationState() : mode(MODE_VALID), nDoS(0), chRejectCode(0), corruptionPossible(false) {}
bool DoS(int level, bool ret = false, unsigned char chRejectCodeIn = 0, std::string strRejectReasonIn = "", bool corruptionIn = false)
{
chRejectCode = chRejectCodeIn;
strRejectReason = strRejectReasonIn;
corruptionPossible = corruptionIn;
if (mode == MODE_ERROR)
return ret;
nDoS += level;
mode = MODE_INVALID;
return ret;
}
bool Invalid(bool ret = false,
unsigned char _chRejectCode = 0,
std::string _strRejectReason = "")
{
return DoS(0, ret, _chRejectCode, _strRejectReason);
}
bool Error(std::string strRejectReasonIn = "")
{
if (mode == MODE_VALID)
strRejectReason = strRejectReasonIn;
mode = MODE_ERROR;
return false;
}
bool Abort(const std::string& msg)
{
AbortNode(msg);
return Error(msg);
}
bool IsValid() const
{
return mode == MODE_VALID;
}
bool IsInvalid() const
{
return mode == MODE_INVALID;
}
bool IsError() const
{
return mode == MODE_ERROR;
}
bool IsInvalid(int& nDoSOut) const
{
if (IsInvalid()) {
nDoSOut = nDoS;
return true;
}
return false;
}
bool CorruptionPossible() const
{
return corruptionPossible;
}
unsigned char GetRejectCode() const { return chRejectCode; }
std::string GetRejectReason() const { return strRejectReason; }
};
/** RAII wrapper for VerifyDB: Verify consistency of the block and coin databases */
class CVerifyDB
{
public:
CVerifyDB();
~CVerifyDB();
bool VerifyDB(CCoinsView* coinsview, int nCheckLevel, int nCheckDepth);
};
/** Find the last common block between the parameter chain and a locator. */
CBlockIndex* FindForkInGlobalIndex(const CChain& chain, const CBlockLocator& locator);
/** Mark a block as invalid. */
bool InvalidateBlock(CValidationState& state, CBlockIndex* pindex);
/** Remove invalidity status from a block and its descendants. */
bool ReconsiderBlock(CValidationState& state, CBlockIndex* pindex);
/** The currently-connected chain of blocks. */
extern CChain chainActive;
/** Global variable that points to the active CCoinsView (protected by cs_main) */
extern CCoinsViewCache* pcoinsTip;
/** Global variable that points to the active block tree (protected by cs_main) */
extern CBlockTreeDB* pblocktree;
struct CBlockTemplate {
CBlock block;
std::vector<CAmount> vTxFees;
std::vector<int64_t> vTxSigOps;
};
/*
class CValidationInterface
{
protected:
virtual void SyncTransaction(const CTransaction& tx, const CBlock* pblock){};
virtual void EraseFromWallet(const uint256& hash){};
virtual void SetBestChain(const CBlockLocator& locator){};
virtual bool UpdatedTransaction(const uint256& hash) { return false; };
virtual void Inventory(const uint256& hash){};
virtual void ResendWalletTransactions(){};
virtual void BlockChecked(const CBlock&, const CValidationState&){};
friend void ::RegisterValidationInterface(CValidationInterface*);
friend void ::UnregisterValidationInterface(CValidationInterface*);
friend void ::UnregisterAllValidationInterfaces();
};
*/
#endif // BITCOIN_MAIN_H
| [
"[email protected]"
] | |
bc30d2858eba04eeb70327760c29e35b39200f02 | fa71823e92b13c8a012f7a61e20e14e50351d6bb | /eqmacemu/Zone/BindWound.cpp | 8e4c5c95e3a0e1a3dcbb15058efc2c3b3ea13600 | [] | no_license | cavedude00/eqmacemu | 5159542269131002e136c45f8969cdd6976b1e97 | e7da5dd48d475decdcc3112fdb9210a508ccbd17 | refs/heads/master | 2021-01-10T13:27:47.280390 | 2013-08-28T05:42:59 | 2013-08-28T05:42:59 | 43,084,600 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,246 | cpp | #include "client.h"
#include "skills.h"
#include "mob.h"
#include "itemtypes.h"
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////// MORAJ - BIND WOUND 08/2009 /////////////////////////////////////////////
//////////////////////// todo - FORMULA CONFIRM //////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////////////////
void Client::ProcessOP_BindWound(APPLAYER* pApp)//MORAJ
{
//Yeahlight: Purge client's invisibility
CancelAllInvisibility();
if(pApp->size != sizeof(BindWound_Struct)){
cout << "Invalid BindWound Packet Size" << endl;
return;
}
BindWound_Struct* bw = (BindWound_Struct*)pApp->pBuffer;
Mob* tar = entity_list.GetMob(bw->to);
BindWound(tar,false);
return;
}
bool Client::BindWound(Mob* bindtar,bool fail){
APPLAYER* bwout_app = new APPLAYER(OP_BindWound,sizeof(BindWound_Struct));
BindWound_Struct* bwout = (BindWound_Struct*)bwout_app->pBuffer;
if(!fail){
if(GetFeigned()){ // Break Feign Death for Bind Wound
SetFeigned(false); //
}
int cap = 50; // Set % Cap/Heal Cap
int hp_cap = bindtar->GetMaxHP()/2; //
if(GetClass() == MONK && GetSkill(BIND_WOUND) > 200){ //
cap = 70; //
hp_cap += bindtar->GetMaxHP()/5; //
}
if(!bindwound_timer->Enabled()){ // Begin Bind Wound
if(bindtar->GetHP() >= hp_cap){ // INITIAL CAP CHECK
Message(DARK_BLUE, "You cannot bandage your target past %d percent of their hit points.", cap);
bwout->type = 3; //
QueuePacket(bwout_app); //
bwout->type = 2; //
QueuePacket(bwout_app); //
safe_delete(bwout_app); //
return true;
}
int16 bndg_slot = FindItemTypeInInventory(ItemTypeBandage); // Consume Bandage
RemoveOneCharge(bndg_slot,true); //
bindwound_timer->Start(10000); // Start Timer
bindwound_target = bindtar;
bwout->type = 3; // Unlock Interface
QueuePacket(bwout_app); //
bwout->type = 0; //
if(!bindtar){ // Target Dead
bwout->type = 4; //
QueuePacket(bwout_app); //
bwout->type = 0; //
bindwound_timer->Disable(); //
bindwound_target = 0; //
}
else if(bindtar!=this) // Send Bind Message to target if not binding self
bindtar->CastToClient()->Message(DARK_BLUE,"You are being bandaged. Stay relatively still.");
}
else{ // END Bind Wound
bindwound_timer->Disable(); // Stop Timer
bindwound_target = 0;
if(!bindtar){ // Target Not Found
bwout->type = 5; //
QueuePacket(bwout_app); //
bwout->type = 0; //
}
if((!GetFeigned() && bindtar->DistNoRoot(this->CastToMob()) <= 400)){ //// **** TAKEN FROM EQEMU, FD Check/Distance?
bwout->type = 1; // Finish Bind
QueuePacket(bwout_app); //
bwout->type = 0; //
if(this!=bindtar) // Message to target
bindtar->CastToClient()->Message(YELLOW,"The bandaging is complete.");
CheckAddSkill(BIND_WOUND); // Check Skill Up
if(bindtar->GetHP() < hp_cap){ // END CAP CHECK (Does not include heal amount)
int heal = 3; // Set Heal Amount
if(GetSkill(BIND_WOUND) > 200) // //
heal += GetSkill(BIND_WOUND)*4/10; // //
else if(GetSkill(BIND_WOUND) >= 10) // //
heal += GetSkill(BIND_WOUND)/4; // //
bindtar->SetHP(bindtar->GetHP()+heal); // Set Hp + Update
bindtar->SendHPUpdate(); //
}
else{ // Over Cap
Message(DARK_BLUE, "You cannot bandage your target past %d percent of their hit points.", cap);
if(this != bindtar) //
bindtar->CastToClient()->Message(DARK_BLUE, "You cannot be bandaged past %d percent of your max hit points.",cap);
}
}
else if(bindtar!=this){ // Failed Moved/Moved Away
bwout->type = 6; //
QueuePacket(bwout_app); //
bwout->type = 0; //
}
else{
//Feigned/Out of Range and binding self Not sure if anything needs to go here or not
}
}
}
else if(bindwound_timer->Enabled()){ // Failed: Ended Via Sit/Stand/Feign
if(!GetFeigned()){ // Sit/Stand
bindwound_timer->Disable(); //
bwout->type = 3; //
QueuePacket(bwout_app); //
bwout->type = 7; //
QueuePacket(bwout_app); //
}
else{
bindwound_timer->Disable(); // Feign Death
bindwound_target = 0; //
Message(YELLOW,"You have moved and your attempt to bandage has failed.");
}
}
safe_delete(bwout_app); // Delete packet
return true;
} | [
"[email protected]"
] | |
dd2a76166d7bd077ce52f7d7910992cd2a51e983 | 554d580d914fb3e2d37d26baa3e0239a6450989e | /CreaturePackDragon2D/Plugins/CreaturePackPlugin/Source/CreaturePackRuntimePlugin/Private/CreaturePackAnimationAsset.cpp | ed64c2e33cd4b6dbcb4261a5db431b11578a4344 | [
"LicenseRef-scancode-public-domain"
] | permissive | sengkel2/CreatureDemos | 8956502cb4e2dc6613c1a4ba0050431ba7470da3 | 0482b9c11bd36a5db6230f231b9ec51ba81b8c48 | refs/heads/master | 2021-10-20T18:26:12.320064 | 2019-03-01T06:00:28 | 2019-03-01T06:00:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,024 | cpp |
#include "CreaturePackRuntimePluginPCH.h"
#include "CreaturePackAnimationAsset.h"
FString UCreaturePackAnimationAsset::GetCreatureFilename() const
{
#if WITH_EDITORONLY_DATA
TArray<FString> filenames;
if (AssetImportData)
{
AssetImportData->ExtractFilenames(filenames);
}
if (filenames.Num() > 0)
{
return filenames[0];
}
else
{
return creature_filename;
}
#else
return creature_filename;
#endif
}
TArray<uint8>& UCreaturePackAnimationAsset::GetFileData()
{
// Decompress only when needed
if (CreatureFileData.Num() == 0)
{
FArchiveLoadCompressedProxy Decompressor =
FArchiveLoadCompressedProxy(CreatureZipBinary, ECompressionFlags::COMPRESS_ZLIB);
if (Decompressor.IsError() || (CreatureZipBinary.Num() == 0))
{
UE_LOG(LogTemp, Warning, TEXT("UCreatureAnimationAsset::Could not uncompress data"));
return CreatureFileData;
}
FBufferArchive DecompressedBinaryArray;
Decompressor << DecompressedBinaryArray;
CreatureFileData.SetNum(DecompressedBinaryArray.Num());
for(auto j = 0; j < CreatureFileData.Num(); j++)
{
CreatureFileData[j] = DecompressedBinaryArray[j];
}
}
return CreatureFileData;
}
void UCreaturePackAnimationAsset::Serialize(FArchive& Ar)
{
Super::Serialize(Ar);
}
#if WITH_EDITORONLY_DATA
void UCreaturePackAnimationAsset::SetCreatureFilename(const FString &newFilename)
{
AssetImportData->UpdateFilenameOnly(newFilename);
// extract again to ensure properly sanitised
TArray<FString> filenames;
AssetImportData->ExtractFilenames(filenames);
if (filenames.Num() > 0)
{
creature_filename = filenames[0];
}
}
void UCreaturePackAnimationAsset::GetAssetRegistryTags(TArray<FAssetRegistryTag>& OutTags) const
{
if (!creature_filename.IsEmpty())
{
OutTags.Add(FAssetRegistryTag(SourceFileTagName(), AssetImportData->GetSourceData().ToJson(), FAssetRegistryTag::TT_Hidden));
}
Super::GetAssetRegistryTags(OutTags);
}
void UCreaturePackAnimationAsset::PostLoad()
{
Super::PostLoad();
if (!creature_filename.IsEmpty() && AssetImportData && AssetImportData->GetSourceData().SourceFiles.Num() == 0)
{
// convert old source file path to proper UE4 Asset data system
FAssetImportInfo Info;
Info.Insert(FAssetImportInfo::FSourceFile(creature_filename));
AssetImportData->SourceData = MoveTemp(Info);
}
if ((CreatureZipBinary.Num() != 0) || (CreatureFileData.Num() != 0))
{
// load the animation data caches from the json data
GatherAnimationData();
}
}
void UCreaturePackAnimationAsset::GatherAnimationData()
{
// ensure the filenames are synced
creature_filename = GetCreatureFilename();
GetFileData();
}
void UCreaturePackAnimationAsset::PreSave()
{
Super::PreSave();
// before saving, always ensure animation data is up to date
GatherAnimationData();
}
void UCreaturePackAnimationAsset::PostInitProperties()
{
if (!HasAnyFlags(RF_ClassDefaultObject))
{
AssetImportData = NewObject<UAssetImportData>(this, TEXT("AssetImportData"));
}
Super::PostInitProperties();
}
#endif /*WITH_EDITORONLY_DATA*/ | [
"[email protected]"
] | |
d8fa7cd464105c5b5e8be1d3fab6f7daf719208f | 7ced70779f60b389054a9921f9ccfe31704086df | /RGBPointCloudBuilder/app/src/main/jni/rgb-depth-sync/util.h | cb4b5b6586a7229c086f2b19d63c61fd24397983 | [] | no_license | kirrmann/TangoProject | 0a8d1dc43ce389108aa78c03fd2e1803df2afb24 | 8e5991411a121cacc97884a910fbcb02283292d6 | refs/heads/master | 2021-01-21T03:34:02.529523 | 2016-04-25T13:49:40 | 2016-04-25T13:49:40 | 57,067,528 | 0 | 0 | null | 2016-04-25T18:53:19 | 2016-04-25T18:53:18 | null | UTF-8 | C++ | false | false | 2,063 | h | /*
* Copyright 2014 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef RGB_DEPTH_SYNC_UTIL_H_
#define RGB_DEPTH_SYNC_UTIL_H_
#include <Eigen/Geometry>
#include <tango_client_api.h> // NOLINT
#include <tango-gl/util.h>
#include <tango-gl/conversions.h>
namespace rgb_depth_sync {
// Utility functioins for Synchronization application.
namespace util {
Eigen::Isometry3f GetIsometryFromTangoPose(const TangoPoseData* pose_data);
Eigen::Vector3f GetTranslationFromIsometry(const Eigen::Isometry3f& pose);
Eigen::Quaternionf GetRotationFromIsometry(const Eigen::Isometry3f& pose);
// Returns a transformation matrix from a given TangoPoseData structure.
// - pose_data: The original pose is used for the conversion.
glm::mat4 GetMatrixFromPose(const TangoPoseData* pose_data);
glm::vec3 GetTranslationFromMatrix(const glm::mat4 transformation);
glm::quat GetRotationFromMatrix(const glm::mat4 transformation);
glm::mat4 GetPoseAppliedOpenGLWorldFrame( const glm::mat4 pose_matrix);
Eigen::Isometry3d CastIsometry3fTo3d(const Eigen::Isometry3f pose_f);
Eigen::Isometry3f CastIsometry3dTo3f(const Eigen::Isometry3d pose_d);
Eigen::Isometry3d CastGLMToEigenPosed(const glm::mat4& glm_pose);
Eigen::Isometry3f ConvertGLMToEigenPose(const glm::mat4 glm_pose);
glm::mat4 ConvertEigenToGLMPose(const Eigen::Isometry3f eigen_pose);
float Deg2Rad(float alpha);
} // namespace util
} // namespace rgb_depth_sync
#endif // RGB_DEPTH_SYNC_UTIL_H_
| [
"[email protected]"
] | |
28a8bef0e2c766b1f34806283488a0e9605d5cc1 | e4e5480d636bb1308396030dd70e88e471f74233 | /softwares/simddef/src/caixa_marcacao.h | fe657c02b28ceb763a3982745734f80d85e645f2 | [] | no_license | diogolr/diogolrmsc | 390cffe91b140719271b29a95fe6f7a0d3c04224 | c1ccdedf9d106026d70d0a94b42c6fd0bbb0ce06 | refs/heads/master | 2016-09-01T19:58:33.376373 | 2011-08-21T13:10:55 | 2011-08-21T13:10:55 | 32,116,465 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,216 | h | #ifndef CAIXA_MARCACAO_H_
#define CAIXA_MARCACAO_H_
#include <QBrush>
#include <QGraphicsScene>
#include <QRectF>
#include <QPair>
#include <QPen>
#include <QString>
#include <QWidget>
#include <qwt_plot_curve.h>
#include <qwt_text.h>
#include "funcoes.h"
#include "retangulo.h"
#include "ui_caixa_marcacao.h"
class CaixaMarcacao : public QWidget
{
Q_OBJECT
// Atributos publicos
public:
enum TipoItem{ Curva = 0, Deteccao };
// Metodos
public:
CaixaMarcacao( QwtPlotCurve * );
CaixaMarcacao( const QString &,
const QPair< QPen, QBrush > &,
QList< Retangulo * > * );
~CaixaMarcacao();
private:
void inicializa_curva( QwtPlotCurve * );
void inicializa_deteccao( const QString &,
const QPair< QPen, QBrush > &,
QList< Retangulo * > * );
private slots:
void on_cb_stateChanged( int );
signals:
void item_atualizado();
// Atributos
private:
QList< Retangulo * > *retangulos;
QwtPlotCurve *curva;
TipoItem tipo_item;
Ui_CaixaMarcacao *ui;
};
#endif
| [
"diogolr@114122ef-0f80-af60-45d5-5317cd78b39a"
] | diogolr@114122ef-0f80-af60-45d5-5317cd78b39a |
5902889ad3ec3404f90d739f142d9b7a64c4adaf | c894d603bd3f1451f867c9e699d3426c436ae289 | /practice/warehouse1.cpp | efdd2f5e2598356d6a9e9ed70eb508e4f03af6ea | [] | no_license | atul008/gfg | aa53126435c4a6755d4ce2dedec24665d2e3150d | 7d45e7a4a77f757d7b4d73d407aaadef3dfdc11d | refs/heads/master | 2021-01-19T07:07:37.498772 | 2016-09-16T17:09:45 | 2016-09-16T17:09:45 | 68,398,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,778 | cpp | #include <map>
#include <set>
#include <vector>
#include <list>
#include <cmath>
#include <cstring>
#include <string>
#include <sstream>
#include <iostream>
#include <algorithm>
#define sz(a) int((a).size())
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin()) i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define FOR(a,b,i) for(int i=a; i<=b; i++)
#define SET(c,x) memset(c,x,sizeof(c))
#define pb push_back
#define mp make_pair
#define int64 long long int
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> ii;
int main(){
int n,m,a,b;
cin >> n >> m;
vvi v(n+1,vi(n+1,0));
vi degree(n+1,0);
FOR(1,m,i){
cin >> a >> b;
degree[a]++;
degree[b]++;
v[a][b] = 1;
v[b][a] = 1;
}
set< ii > degreeSet;
FOR(1,n,i){
if(degree[i] > 0) degreeSet.insert(mp(degree[i],i));
}
//vector< ii > dset(all(degreeSet));
set<int> w,x;
set< ii >::iterator it;
for(it = degreeSet.begin(); it!=degreeSet.end();it++){
int ma=-1,node = -1 ;
if(!present(x,it->second)){
FOR(1,n,i){
if(v[it->second][i] == 1 && !present(w,i) && ma < degree[i]){
ma = degree[i];
node = i;
}
}
if(ma != -1 && node != -1){
w.insert(node);
//x.insert(it->second);
x.insert(node);
FOR(1,n,i){
if(v[node][i] == 1 && !present(x,i)){
x.insert(i);
}
}
}
}
}
cout << "w : ";
tr(w,it) cout << *it << " ";
cout << "x : ";
tr(x,it) cout << *it << " ";
int ans = w.size() + n-x.size();
cout << ans << endl;
return 0;
}
| [
"kumarat@yatra"
] | kumarat@yatra |
b355a8ad4417d8ac27631d50c1335acd689b7704 | 9e94ad5cdd1e137669e4d6da52387798aedb5614 | /src/learn/ALGMM.cpp | 9cdea9a8d6f7072826c7d57f7e4d4dbc1ce2e284 | [
"Apache-2.0"
] | permissive | jxt1234/Abstract_Learning | 332807b6e8b9c4420ad39663cb0f0e3f4759948a | 202c19c17dcb83cb8e93d8d23fb0d7ae83c56385 | refs/heads/master | 2020-08-05T16:11:23.947670 | 2016-11-19T12:15:03 | 2016-11-19T12:15:03 | 67,514,053 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 5,482 | cpp | #include "learn/ALGMM.h"
#include "learn/ALKMeans.h"
#include <vector>
#include <math.h>
#include <fstream>
//static const ALFLOAT PI = 3.141592654;
class ALGMMModel:public ALIMatrixPredictor
{
public:
ALGMMModel(ALSp<ALFloatMatrix> center, const std::vector<ALSp<ALFloatMatrix>>& covs, const std::vector<ALFLOAT>& coefs)
{
ALASSERT(center->height() == covs.size());
ALASSERT(covs.size() == coefs.size());
//ALFLOAT basic_parameter = 1.0/pow(2.0*PI, center->width()/2.0);
for (auto c : covs)
{
ALASSERT(c->width() == c->height() && c->width() == center->width());
}
mCenters = center;
for (int i=0; i<covs.size(); ++i)
{
auto c = covs[i];
auto size = c->width();
ALSp<ALFloatMatrix> inv_cov = ALFloatMatrix::create(size, size);
ALFLOAT cov_det = ALFloatMatrix::inverse_basic(c.get(), inv_cov.get());
mInverseCovs.push_back(inv_cov);
//mInverseCovs.push_back(c);//For Debug
//mCoefs.push_back(basic_parameter*coefs[i]/sqrt(cov_det));
mCoefs.push_back(coefs[i]/sqrt(cov_det+0.00000001));
}
}
virtual ~ALGMMModel()
{
}
virtual void vPredict(const ALFloatMatrix* X, ALFloatMatrix* Y/*Output*/) const
{
ALASSERT(NULL!=X);
ALASSERT(NULL!=Y);
ALASSERT(X->height() == Y->height());
ALASSERT(1 == Y->width());
ALASSERT(X->width() == mCenters->width());
auto h = X->height();
auto w = X->width();
ALAUTOSTORAGE(diff, ALFLOAT, w);
for (int i=0; i<h; ++i)
{
ALFLOAT sum = 0.0;
::memset(diff, 0, sizeof(ALFLOAT)*w);
auto data_ = X->vGetAddr(i);
for (int j=0; j<mInverseCovs.size(); ++j)
{
ALFLOAT multi = 0.0;
auto center_ = mCenters->vGetAddr(j);
auto invcov_ = mInverseCovs[j]->vGetAddr(0);
for (int k=0; k<w; ++k)
{
diff[k] = data_[k] - center_[k];
}
for (int x=0; x<w; ++x)
{
ALFLOAT csum = 0.0;
for (int y=0; y<w; ++y)
{
csum += invcov_[x*w+y]*diff[y];
}
multi += csum*diff[x];
}
sum += mCoefs[j]*exp(-0.5f*multi);
}
*(Y->vGetAddr(i)) = sum;
}
}
virtual void vPrint(std::ostream& output) const
{
output << "<ALGMM>\n";
output << "<Centers>\n";
ALFloatMatrix::print(mCenters.get(), output);
output << "</Centers>\n";
output << "<InverseCovs>\n";
for (auto cov : mInverseCovs)
{
ALFloatMatrix::print(cov.get(), output);
output << "\n";
}
output << "</InverseCovs>\n";
output << "<Coef>\n";
for (auto c : mCoefs)
{
output << c << " ";
}
output << "</Coef>\n";
output << "</ALGMM>\n";
}
private:
ALSp<ALFloatMatrix> mCenters;
std::vector<ALSp<ALFloatMatrix>> mInverseCovs;
std::vector<ALFLOAT> mCoefs;
};
ALGMM::ALGMM(int centernumber)
{
mCenters = centernumber;
}
ALGMM::~ALGMM()
{
}
ALIMatrixPredictor* ALGMM::vLearn(const ALFloatMatrix* data) const
{
ALASSERT(NULL!=data);
if(mCenters > data->height()/10)
{
FUNC_PRINT(mCenters);
FUNC_PRINT(data->height());
return new ALDummyMatrixPredictor;
}
ALSp<ALFloatMatrix> centerPoints = ALKMeans::learn(data, mCenters);
/*Compute the cov*/
auto w = data->width();
auto h = data->height();
int centers = mCenters;
std::vector<ALSp<ALFloatMatrix>> cov_matrixs;
for (int i=0; i<centers; ++i)
{
cov_matrixs.push_back(ALFloatMatrix::create(w, w));
}
for (int i=0; i<centers; ++i)
{
ALFloatMatrix::zero(cov_matrixs[i].get());
}
ALSp<ALFloatMatrix> mask = ALFloatMatrix::create(1, h);
ALKMeans::predict(data, centerPoints.get(), mask.get());
auto mask_ = mask->vGetAddr();
ALAUTOSTORAGE(counts, int, centers);
::memset(counts, 0, centers*sizeof(int));
for (int i=0; i<h; ++i)
{
auto data_ = data->vGetAddr(i);
int class_num = mask_[i];
auto targetCov = cov_matrixs[class_num];
counts[class_num]+=1;
auto center = centerPoints->vGetAddr(class_num);
for (int j=0; j<w; ++j)
{
auto targetCov_line = targetCov->vGetAddr(j);
for (int k=j; k<w; ++k)
{
targetCov_line[k] += (data_[j]-center[j])*(data_[k]-center[k]);
}
}
}
/*The coes is comput as c[i]/total*/
std::vector<ALFLOAT> coefs;
for (int i=0; i<centers; ++i)
{
if (0 == counts[i])
{
ALFloatMatrix::zero(cov_matrixs[i].get());
continue;
}
ALFLOAT count = counts[i];
auto _cov = cov_matrixs[i]->vGetAddr(0);
coefs.push_back(count / (float)h);
for (int j=0; j<w; ++j)
{
for (int k=j; k<w; ++k)
{
ALFLOAT temp = _cov[j*w+k]/count;
_cov[j*w+k] = temp;
_cov[k*w+j] = temp;
}
}
}
return new ALGMMModel(centerPoints, cov_matrixs, coefs);
}
| [
"[email protected]"
] | |
e4d25c82b7a5cb97ddcde40734b6bd27de9f5b97 | 35155c414b1596a290793a18bca054cb095ecd81 | /src/Scanner.cpp | 59ca3fdcc887a6e2a92369c93471b8c8448715a3 | [
"MIT"
] | permissive | somerandomdev49/enact | 6ecff63ba94eb04bcc57ce1be38b8fbf74d0aa8e | 58b83fabdca786de75cba7cc3b188d32a7997862 | refs/heads/master | 2021-05-27T02:33:08.955604 | 2020-03-22T05:58:00 | 2020-03-22T05:58:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,108 | cpp | #include <sstream>
#include "h/Scanner.h"
Scanner::Scanner(std::string source) : m_source{std::move(source)} {}
Token Scanner::scanToken() {
skipWhitespace();
m_start = m_current;
//if (m_last.type == TokenType::ENDFILE) return m_last;
if (isAtEnd()) return makeToken(TokenType::ENDFILE);
char c = advance();
if (isDigit(c)) return number();
if (isIdentifierStart(c)) return identifier();
switch (c) {
// Single character tokens.
case '(': ++m_openParen; return makeToken(TokenType::LEFT_PAREN);
case ')': --m_openParen; return makeToken(TokenType::RIGHT_PAREN);
case '[': ++m_openSquare; return makeToken(TokenType::LEFT_SQUARE);
case ']': --m_openSquare; return makeToken(TokenType::RIGHT_SQUARE);
case ':': return makeToken(TokenType::COLON);
case ',': return makeToken(TokenType::COMMA);
case '.': return makeToken(TokenType::DOT);
case '-': return makeToken(TokenType::MINUS);
case '+': return makeToken(TokenType::PLUS);
case '?': return makeToken(TokenType::QUESTION);
case ';': return makeToken(TokenType::SEMICOLON);
case '|': return makeToken(TokenType::SEPARATOR);
case '/': return makeToken(TokenType::SLASH);
case '*': return makeToken(TokenType::STAR);
case '\n': ++m_line; return makeToken(TokenType::NEWLINE);
// 1 or 2 character tokens.
case '!':
return makeToken(match('=') ? TokenType::BANG_EQUAL : TokenType::BANG);
case '=':
return makeToken(match('=') ? TokenType::EQUAL_EQUAL : TokenType::EQUAL);
case '>':
return makeToken(match('=') ? TokenType::GREATER_EQUAL : TokenType::GREATER);
case '<':
return makeToken(match('=') ? TokenType::LESS_EQUAL : TokenType::LESS);
case '"':
return string();
}
std::string errorMessage = "Unrecognized character '";
errorMessage.append(std::string{c});
errorMessage.append("'.");
return errorToken(errorMessage);
}
void Scanner::skipWhitespace() {
while (true) {
char c = peek();
switch (c) {
case ' ':
case '\t':
case '\r':
advance();
break;
case '/':
if (peekNext() == '/') {
while (peek() != '\n' && !isAtEnd()) advance();
} else {
return;
}
default:
return;
}
}
}
Token Scanner::number() {
while (isDigit(peek())) advance();
TokenType type = TokenType::INTEGER;
if (peek() == '.') {
type = TokenType::FLOAT;
advance();
while (isDigit(peek())) advance();
}
return makeToken(type);
}
Token Scanner::identifier() {
while (isIdentifier(peek())) advance();
return makeToken(identifierType(m_source.substr(m_start, m_current - m_start)));
}
Token Scanner::string() {
while (peek() != '"' && !isAtEnd()) advance();
if (isAtEnd()) {
return errorToken("Unterminated string.");
}
// Eat the close quote.
advance();
return makeToken(TokenType::STRING);
}
Token Scanner::makeToken(TokenType type) {
std::string lexeme{m_source.substr(m_start, m_current - m_start)};
m_last = Token{type, lexeme, m_line, m_col};
return m_last;
}
Token Scanner::errorToken(const std::string &what) {
return Token{TokenType::ERROR, what, m_line, m_col};
}
TokenType Scanner::identifierType(std::string candidate) {
if (candidate == "and") return TokenType::AND;
if (candidate == "assoc") return TokenType::ASSOC;
if (candidate == "block") return TokenType::BLOCK;
if (candidate == "break") return TokenType::BREAK;
if (candidate == "class") return TokenType::CLASS;
if (candidate == "const") return TokenType::CONST;
if (candidate == "continue") return TokenType::CONTINUE;
if (candidate == "copy") return TokenType::COPY;
if (candidate == "each") return TokenType::EACH;
if (candidate == "else") return TokenType::ELSE;
if (candidate == "end") return TokenType::END;
if (candidate == "false") return TokenType::FALSE;
if (candidate == "fun") return TokenType::FUN;
if (candidate == "for") return TokenType::FOR;
if (candidate == "given") return TokenType::GIVEN;
if (candidate == "if") return TokenType::IF;
if (candidate == "in") return TokenType::IN;
if (candidate == "is") return TokenType::IS;
if (candidate == "nil") return TokenType::NIL;
if (candidate == "or") return TokenType::OR;
if (candidate == "return") return TokenType::RETURN;
if (candidate == "struct") return TokenType::STRUCT;
if (candidate == "this") return TokenType::THIS;
if (candidate == "trait") return TokenType::TRAIT;
if (candidate == "true") return TokenType::TRUE;
if (candidate == "var") return TokenType::VAR;
if (candidate == "when") return TokenType::WHEN;
if (candidate == "while") return TokenType::WHILE;
return TokenType::IDENTIFIER;
}
bool Scanner::isAtEnd() {
return m_current >= m_source.length();
}
char Scanner::advance() {
++m_col;
return m_source[m_current++];
}
char Scanner::peek() {
return m_source[m_current];
}
char Scanner::peekNext() {
return m_source[m_current + 1];
}
char Scanner::previous() {
return m_source[m_current - 1];
}
bool Scanner::match(char expected) {
if (peek() == expected) {
advance();
return true;
}
return false;
}
bool Scanner::isDigit(char c) {
return c >= '0' && c <= '9';
}
bool Scanner::isIdentifierStart(char c) {
return (c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_';
}
bool Scanner::isIdentifier(char c) {
return isIdentifierStart(c) || isDigit(c);
}
Token Scanner::backtrack() {
m_current -= m_last.lexeme.size();
m_start = m_current;
return m_last;
} | [
"[email protected]"
] | |
bb6a024dc1420d63a71cba812798eb721e1b922d | ab1c643f224197ca8c44ebd562953f0984df321e | /wmi/wbem/winmgmt/wbemcomn/cimval.cpp | fbe1c4ae89e7360c245b403c62e84fc1e930d474 | [] | no_license | KernelPanic-OpenSource/Win2K3_NT_admin | e162e0452fb2067f0675745f2273d5c569798709 | d36e522f16bd866384bec440517f954a1a5c4a4d | refs/heads/master | 2023-04-12T13:25:45.807158 | 2021-04-13T16:33:59 | 2021-04-13T16:33:59 | 357,613,696 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,502 | cpp | /*++
Copyright (C) 1996-2001 Microsoft Corporation
Module Name:
Abstract:
History:
--*/
#include "precomp.h"
#include <stdlib.h>
#include <stdio.h>
#include <assert.h>
#include <wbemcli.h>
#include "cimval.h"
BOOL SecondsToInterval( long double ldbSeconds, LPWSTR wszText, size_t cchSize )
{
int nDay, nHour, nMinute, nSecond, nMicro;
nDay = int(ldbSeconds / 86400);
ldbSeconds -= nDay * 86400;
nHour = int(ldbSeconds / 3600);
ldbSeconds -= nHour * 3600;
nMinute = int(ldbSeconds / 60);
ldbSeconds -= nMinute * 60;
nSecond = int(ldbSeconds);
ldbSeconds -= nSecond;
nMicro = int(ldbSeconds * 1000000);
if(FAILED(StringCchPrintfW( wszText, cchSize, L"%08.8d%02.2d%02.2d%02.2d.%06.6d:000",
nDay, nHour, nMinute, nSecond, nMicro )))
return FALSE;
return TRUE;
}
// this should be a WBEM common thing ...
BOOL FileTimeToDateTime( FILETIME* pft, LPWSTR wszText, size_t cchSize )
{
SYSTEMTIME st;
__int64 llnss = *(__int64*)pft;
if ( !FileTimeToSystemTime( pft, &st ) )
{
return FALSE;
}
//
// have to account for microseconds as well (probably a much better way
// to do this.)
//
st.wMilliseconds = 0;
FILETIME ft;
if ( !SystemTimeToFileTime( &st, &ft ) )
{
return FALSE;
}
__int64 llnss2 = *(__int64*)&ft;
int nMicro = int((llnss - llnss2)/10);
if (FAILED(StringCchPrintfW( wszText, cchSize,
L"%04.4d%02.2d%02.2d%02.2d%02.2d%02.2d.%06.6d+000",
st.wYear, st.wMonth, st.wDay, st.wHour,
st.wMinute, st.wSecond, nMicro )))
return FALSE;
return TRUE;
}
BOOL SecondsToDateTime( long double ldbSeconds, LPWSTR wszText, size_t cchSize )
{
FILETIME* pft;
__int64 llnss = __int64(ldbSeconds * 10000000);
pft = (FILETIME*)&llnss;
return FileTimeToDateTime( pft, wszText, cchSize );
}
BOOL IntervalToSeconds( LPCWSTR wszText, long double& rldbSeconds )
{
int nDay, nHour, nMinute, nSecond, nMicro;
int nRes = swscanf( wszText, L"%8d%2d%2d%2d.%6d",
&nDay, &nHour, &nMinute, &nSecond, &nMicro );
if ( nRes != 5 )
{
return FALSE;
}
rldbSeconds = nSecond + 60*nMinute + 3600*nHour + 86400*nDay;
rldbSeconds += nMicro / 1000000.0;
return TRUE;
}
BOOL DateTimeToSeconds( LPCWSTR wszText, long double& rldbSeconds )
{
WORD nYear, nMonth, nDay, nHour, nMinute, nSecond, nMicro, nOffset;
WCHAR wchSep;
int nRes = swscanf( wszText, L"%4d%2d%2d%2d%2d%2d.%6d%c%3d",
&nYear, &nMonth, &nDay, &nHour, &nMinute,
&nSecond, &nMicro, &wchSep, &nOffset );
if(nRes != 9)
{
return FALSE;
}
int nSign;
if( wchSep == L'+' )
{
nSign = -1;
}
else if ( wchSep == L'-' )
{
nSign = 1;
}
else
{
return FALSE;
}
// Convert it to SYSTEMTIME
// ========================
SYSTEMTIME st;
st.wYear = nYear;
st.wMonth = nMonth;
st.wDay = nDay;
st.wHour = nHour;
st.wMinute = nMinute;
st.wSecond = nSecond;
st.wMilliseconds = 0;
//
// convert SYSTEMTIME to FILETIME
//
FILETIME ft;
if ( !SystemTimeToFileTime( &st, &ft ) )
{
return FALSE;
}
rldbSeconds = (long double)*(__int64*)&ft;
rldbSeconds += nMicro*10;
rldbSeconds /= 10000000;
// Now adjust for the offset
// =========================
rldbSeconds += nSign * nOffset * 60;
return TRUE;
}
BOOL DMTFToSeconds( LPCWSTR wszText, long double& rldbSeconds )
{
if( wcslen(wszText) != 25 )
{
return FALSE;
}
if ( wszText[21] != ':' )
{
return DateTimeToSeconds( wszText, rldbSeconds );
}
return IntervalToSeconds( wszText, rldbSeconds );
}
CCimValue::CCimValue( ) : m_eType( e_Int ), m_iVal( 0 ) { }
HRESULT CCimValue::GetValue( VARIANT& rvValue, ULONG lCimType )
{
VariantInit( &rvValue );
WCHAR achBuff[255];
BOOL bRes;
switch( lCimType )
{
case CIM_SINT8:
case CIM_SINT16:
case CIM_SINT32:
case CIM_BOOLEAN:
CoerceToInt();
V_VT(&rvValue) = VT_I4;
V_I4(&rvValue) = m_iVal;
break;
case CIM_UINT8:
case CIM_UINT16:
case CIM_UINT32:
CoerceToUnsignedInt();
V_VT(&rvValue) = VT_I4;
V_I4(&rvValue) = m_uiVal;
break;
case CIM_SINT64:
case CIM_STRING:
CoerceToLong();
_i64tow( m_lVal, achBuff, 10 );
V_VT(&rvValue) = VT_BSTR;
V_BSTR(&rvValue) = SysAllocString(achBuff);
break;
case CIM_REAL32:
CoerceToFloat();
V_VT(&rvValue) = VT_R4;
V_R4(&rvValue) = m_fVal;
break;
case CIM_REAL64:
CoerceToDouble();
V_VT(&rvValue) = VT_R8;
V_R8(&rvValue) = m_dbVal;
break;
case CIM_UINT64:
CoerceToUnsignedLong();
_ui64tow( m_ulVal, achBuff, 10 );
V_VT(&rvValue) = VT_BSTR;
V_BSTR(&rvValue) = SysAllocString(achBuff);
break;
case CIM_INTERVAL:
CoerceToLongDouble();
bRes = SecondsToInterval( m_ldbVal, achBuff, 255 );
if ( !bRes ) { return WBEM_E_TYPE_MISMATCH; }
V_VT(&rvValue) = VT_BSTR;
V_BSTR(&rvValue) = SysAllocString(achBuff);
break;
case CIM_DATETIME:
CoerceToLongDouble();
bRes = SecondsToDateTime( m_ldbVal, achBuff, 255 );
if ( !bRes ) { return WBEM_E_TYPE_MISMATCH; }
V_VT(&rvValue) = VT_BSTR;
V_BSTR(&rvValue) = SysAllocString(achBuff);
break;
default:
return WBEM_E_TYPE_MISMATCH;
};
return WBEM_S_NO_ERROR;
}
HRESULT CCimValue::SetValue( VARIANT& rvValue, ULONG lCimType )
{
HRESULT hr;
VARIANT vValue;
VariantInit( &vValue );
if ( lCimType == CIM_EMPTY )
{
//
// must be a numeric value.
//
switch( V_VT(&rvValue) )
{
case VT_R4:
m_eType = e_Float;
m_fVal = V_R4(&rvValue);
break;
case VT_R8:
m_eType = e_Double;
m_dbVal = V_R8(&rvValue);
break;
case VT_BSTR:
m_lVal = (__int64)_wtoi64( V_BSTR(&rvValue) );
break;
default:
hr = VariantChangeType( &vValue, &rvValue, 0, VT_I4 );
if ( FAILED(hr) ) return WBEM_E_TYPE_MISMATCH;
m_eType = e_Int;
m_iVal = V_I4(&vValue);
};
return WBEM_S_NO_ERROR;
}
switch( lCimType )
{
case CIM_SINT8:
case CIM_SINT16:
case CIM_SINT32:
case CIM_BOOLEAN:
hr = VariantChangeType( &vValue, &rvValue, 0, VT_I4 );
if ( FAILED(hr) ) return WBEM_E_TYPE_MISMATCH;
m_eType = e_Int;
m_iVal = V_I4(&vValue);
break;
case CIM_UINT8:
case CIM_UINT16:
case CIM_UINT32:
hr = VariantChangeType( &vValue, &rvValue, 0, VT_UI4 );
if ( FAILED(hr) ) return WBEM_E_TYPE_MISMATCH;
m_eType = e_UnsignedInt;
m_uiVal = V_UI4(&vValue);
break;
case CIM_SINT64:
case CIM_STRING:
if ( V_VT(&rvValue) == VT_BSTR )
{
m_lVal = _wtoi64( V_BSTR(&rvValue) );
}
else
{
return WBEM_E_TYPE_MISMATCH;
}
m_eType = e_Long;
break;
case CIM_UINT64:
if ( V_VT(&rvValue) == VT_BSTR )
{
m_ulVal = (unsigned __int64)_wtoi64( V_BSTR(&rvValue) );
}
else
{
return WBEM_E_TYPE_MISMATCH;
}
m_eType = e_UnsignedLong;
break;
case CIM_REAL32:
hr = VariantChangeType( &vValue, &rvValue, 0, VT_R4 );
if ( FAILED(hr) ) return WBEM_E_TYPE_MISMATCH;
m_eType = CCimValue::e_Float;
m_fVal = V_R4(&vValue);
break;
case CIM_REAL64:
hr = VariantChangeType( &vValue, &rvValue, 0, VT_R8 );
if ( FAILED(hr) ) return WBEM_E_TYPE_MISMATCH;
m_eType = CCimValue::e_Double;
m_dbVal = V_R8(&vValue);
break;
case CIM_DATETIME:
case CIM_INTERVAL:
if ( V_VT(&rvValue) == VT_BSTR )
{
BOOL bRes = DMTFToSeconds( V_BSTR(&rvValue), m_ldbVal );
if ( !bRes )
{
return WBEM_E_TYPE_MISMATCH;
}
}
else
{
return WBEM_E_TYPE_MISMATCH;
}
m_eType = e_LongDouble;
break;
default:
return WBEM_E_TYPE_MISMATCH;
};
return WBEM_S_NO_ERROR;
}
void CCimValue::CoerceToLongDouble()
{
switch( m_eType )
{
case e_Int:
m_ldbVal = (long double)m_iVal;
break;
case e_UnsignedInt:
m_ldbVal = (long double)m_uiVal;
break;
case e_Float:
m_ldbVal = (long double)m_fVal;
break;
case e_Double:
m_ldbVal = (long double)m_dbVal;
break;
case e_Long:
m_ldbVal = (long double)m_lVal;
break;
case e_UnsignedLong:
m_ldbVal = (long double)(__int64)m_ulVal;
break;
};
m_eType = e_LongDouble;
}
void CCimValue::CoerceToDouble()
{
switch( m_eType )
{
case e_Int:
m_dbVal = (double)m_iVal;
break;
case e_UnsignedInt:
m_dbVal = (double)m_uiVal;
break;
case e_Float:
m_dbVal = (double)m_fVal;
break;
case e_LongDouble:
m_dbVal = (double)m_ldbVal;
break;
case e_Long:
m_dbVal = (double)m_lVal;
break;
case e_UnsignedLong:
m_dbVal = (double)(__int64)m_ulVal;
break;
};
m_eType = e_Double;
}
void CCimValue::CoerceToFloat()
{
switch( m_eType )
{
case e_Int:
m_fVal = (float)m_iVal;
break;
case e_UnsignedInt:
m_fVal = (float)m_uiVal;
break;
case e_LongDouble:
m_fVal = (float)m_ldbVal;
break;
case e_Double:
m_fVal = (float)m_dbVal;
break;
case e_Long:
m_fVal = (float)m_lVal;
break;
case e_UnsignedLong:
m_fVal = (float)(__int64)m_ulVal;
break;
};
m_eType = e_Float;
}
void CCimValue::CoerceToUnsignedLong()
{
switch( m_eType )
{
case e_Int:
m_ulVal = (unsigned __int64)m_iVal;
break;
case e_UnsignedInt:
m_ulVal = (unsigned __int64)m_uiVal;
break;
case e_Float:
m_ulVal = (unsigned __int64)m_fVal;
break;
case e_Double:
m_ulVal = (unsigned __int64)m_dbVal;
break;
case e_Long:
m_ulVal = (unsigned __int64)m_lVal;
break;
case e_LongDouble:
m_ulVal = (unsigned __int64)m_ldbVal;
break;
};
m_eType = e_UnsignedLong;
}
void CCimValue::CoerceToLong()
{
switch( m_eType )
{
case e_Int:
m_lVal = (__int64)m_iVal;
break;
case e_UnsignedInt:
m_lVal = (__int64)m_uiVal;
break;
case e_Float:
m_lVal = (__int64)m_fVal;
break;
case e_Double:
m_lVal = (__int64)m_dbVal;
break;
case e_UnsignedLong:
m_lVal = (__int64)m_ulVal;
break;
case e_LongDouble:
m_lVal = (__int64)m_ldbVal;
break;
};
m_eType = e_Long;
}
void CCimValue::CoerceToUnsignedInt()
{
switch( m_eType )
{
case e_Int:
m_uiVal = (unsigned __int32)m_iVal;
break;
case e_Float:
m_uiVal = (unsigned __int32)m_fVal;
break;
case e_Double:
m_uiVal = (unsigned __int32)m_dbVal;
break;
case e_Long:
m_uiVal = (unsigned __int32)m_lVal;
break;
case e_UnsignedLong:
m_uiVal = (unsigned __int32)m_ulVal;
break;
case e_LongDouble:
m_uiVal = (unsigned __int32)m_ldbVal;
break;
};
m_eType = e_UnsignedInt;
}
void CCimValue::CoerceToInt()
{
switch( m_eType )
{
case e_Long:
m_iVal = (__int32)m_lVal;
break;
case e_UnsignedInt:
m_iVal = (__int32)m_uiVal;
break;
case e_Float:
m_iVal = (__int32)m_fVal;
break;
case e_Double:
m_iVal = (__int32)m_dbVal;
break;
case e_UnsignedLong:
m_iVal = (__int32)m_ulVal;
break;
case e_LongDouble:
m_iVal = (__int32)m_ldbVal;
break;
};
m_eType = e_Int;
}
void HandleConversion( CCimValue& rValA, CCimValue& rValB )
{
if ( rValA.m_eType == rValB.m_eType )
{
return;
}
if ( rValA.m_eType == CCimValue::e_LongDouble )
{
rValB.CoerceToLongDouble();
return;
}
if ( rValB.m_eType == CCimValue::e_LongDouble )
{
rValA.CoerceToLongDouble();
return;
}
if ( rValA.m_eType == CCimValue::e_Double )
{
rValB.CoerceToDouble();
return;
}
if ( rValB.m_eType == CCimValue::e_Double )
{
rValA.CoerceToDouble();
return;
}
if ( rValA.m_eType == CCimValue::e_Float )
{
rValB.CoerceToFloat();
return;
}
if ( rValB.m_eType == CCimValue::e_Float )
{
rValA.CoerceToFloat();
return;
}
if ( rValA.m_eType == CCimValue::e_UnsignedLong )
{
rValB.CoerceToUnsignedLong();
return;
}
if ( rValB.m_eType == CCimValue::e_UnsignedLong )
{
rValA.CoerceToUnsignedLong();
return;
}
if ( rValA.m_eType == CCimValue::e_Long &&
rValB.m_eType == CCimValue::e_UnsignedInt ||
rValB.m_eType == CCimValue::e_Long &&
rValA.m_eType == CCimValue::e_UnsignedInt )
{
rValA.CoerceToUnsignedLong();
rValB.CoerceToUnsignedLong();
return;
}
if ( rValA.m_eType == CCimValue::e_Long )
{
rValB.CoerceToLong();
return;
}
if ( rValB.m_eType == CCimValue::e_Long )
{
rValA.CoerceToLong();
return;
}
if ( rValA.m_eType == CCimValue::e_UnsignedInt )
{
rValB.CoerceToUnsignedInt();
return;
}
if ( rValB.m_eType == CCimValue::e_UnsignedInt )
{
rValA.CoerceToUnsignedInt();
return;
}
// this means both must be e_Int, but our check in the beginning
// should have handled this...
assert( 0 );
}
CCimValue operator+ ( CCimValue ValA, CCimValue ValB )
{
HandleConversion( ValA, ValB );
assert( ValA.m_eType == ValB.m_eType );
switch( ValA.m_eType )
{
case CCimValue::e_Int:
ValA.m_iVal += ValB.m_iVal;
break;
case CCimValue::e_UnsignedInt:
ValA.m_uiVal += ValB.m_uiVal;
break;
case CCimValue::e_Float:
ValA.m_fVal += ValB.m_fVal;
break;
case CCimValue::e_Double:
ValA.m_dbVal += ValB.m_dbVal;
break;
case CCimValue::e_LongDouble:
ValA.m_ldbVal += ValB.m_ldbVal;
break;
case CCimValue::e_Long:
ValA.m_lVal += ValB.m_lVal;
break;
case CCimValue::e_UnsignedLong:
ValA.m_ulVal += ValB.m_ulVal;
break;
default:
assert(0);
};
return ValA;
}
CCimValue operator- ( CCimValue ValA, CCimValue ValB )
{
HandleConversion( ValA, ValB );
assert( ValA.m_eType == ValB.m_eType );
switch( ValA.m_eType )
{
case CCimValue::e_Int:
ValA.m_iVal -= ValB.m_iVal;
break;
case CCimValue::e_UnsignedInt:
ValA.m_uiVal -= ValB.m_uiVal;
break;
case CCimValue::e_Float:
ValA.m_fVal -= ValB.m_fVal;
break;
case CCimValue::e_Double:
ValA.m_dbVal -= ValB.m_dbVal;
break;
case CCimValue::e_Long:
ValA.m_lVal -= ValB.m_lVal;
break;
case CCimValue::e_UnsignedLong:
ValA.m_ulVal -= ValB.m_ulVal;
break;
case CCimValue::e_LongDouble:
ValA.m_ldbVal -= ValB.m_ldbVal;
break;
default:
assert(0);
};
return ValA;
}
CCimValue operator* ( CCimValue ValA, CCimValue ValB )
{
HandleConversion( ValA, ValB );
assert( ValA.m_eType == ValB.m_eType );
switch( ValA.m_eType )
{
case CCimValue::e_Int:
ValA.m_iVal *= ValB.m_iVal;
break;
case CCimValue::e_UnsignedInt:
ValA.m_uiVal *= ValB.m_uiVal;
break;
case CCimValue::e_Float:
ValA.m_fVal *= ValB.m_fVal;
break;
case CCimValue::e_Double:
ValA.m_dbVal *= ValB.m_dbVal;
break;
case CCimValue::e_Long:
ValA.m_lVal *= ValB.m_lVal;
break;
case CCimValue::e_UnsignedLong:
ValA.m_ulVal *= ValB.m_ulVal;
break;
case CCimValue::e_LongDouble:
ValA.m_ldbVal *= ValB.m_ldbVal;
break;
default:
assert(0);
};
return ValA;
}
CCimValue operator/ ( CCimValue ValA, CCimValue ValB )
{
HandleConversion( ValA, ValB );
assert( ValA.m_eType == ValB.m_eType );
//
// will raise a structured exception if div by 0.
// caller is expected to handle this..
//
switch( ValA.m_eType )
{
case CCimValue::e_Int:
if ( ValB.m_iVal == 0 ) throw CX_DivideByZeroException();
ValA.m_iVal /= ValB.m_iVal;
break;
case CCimValue::e_UnsignedInt:
if ( ValB.m_uiVal == 0 ) throw CX_DivideByZeroException();
ValA.m_uiVal /= ValB.m_uiVal;
break;
case CCimValue::e_Float:
if ( ValB.m_fVal == 0 ) throw CX_DivideByZeroException();
ValA.m_fVal /= ValB.m_fVal;
break;
case CCimValue::e_Double:
if ( ValB.m_dbVal == 0 ) throw CX_DivideByZeroException();
ValA.m_dbVal /= ValB.m_dbVal;
break;
case CCimValue::e_Long:
if ( ValB.m_lVal == 0 ) throw CX_DivideByZeroException();
ValA.m_lVal /= ValB.m_lVal;
break;
case CCimValue::e_UnsignedLong:
if ( ValB.m_ulVal == 0 ) throw CX_DivideByZeroException();
ValA.m_ulVal /= ValB.m_ulVal;
break;
case CCimValue::e_LongDouble:
if ( ValB.m_ldbVal == 0 ) throw CX_DivideByZeroException();
ValA.m_ldbVal /= ValB.m_ldbVal;
break;
default:
assert(0);
};
return ValA;
}
CCimValue operator% ( CCimValue ValA, CCimValue ValB )
{
HandleConversion( ValA, ValB );
assert( ValA.m_eType == ValB.m_eType );
//
// will raise a structured exception if div by 0.
// caller is expected to handle this..
//
switch( ValA.m_eType )
{
case CCimValue::e_Int:
if ( ValB.m_iVal == 0 ) throw CX_DivideByZeroException();
ValA.m_iVal %= ValB.m_iVal;
break;
case CCimValue::e_UnsignedInt:
if ( ValB.m_uiVal == 0 ) throw CX_DivideByZeroException();
ValA.m_uiVal %= ValB.m_uiVal;
break;
case CCimValue::e_Float:
case CCimValue::e_Double:
case CCimValue::e_LongDouble:
throw CX_InvalidFloatingPointOperationException();
case CCimValue::e_Long:
if ( ValB.m_lVal == 0 ) throw CX_DivideByZeroException();
ValA.m_lVal %= ValB.m_lVal;
break;
case CCimValue::e_UnsignedLong:
if ( ValB.m_ulVal == 0 ) throw CX_DivideByZeroException();
ValA.m_ulVal %= ValB.m_ulVal;
break;
default:
assert(0);
};
return ValA;
}
| [
"[email protected]"
] | |
0446e411b9c0d1ad684440b96f9524e1f4db0c97 | 3e7ae0d825853090372e5505f103d8f3f39dce6d | /AutMarine v4.2.0/AutLib/Mesh/Volume/Optimization/Mesh3d_SmoothingConfig.cxx | 571c60fe92abcdf6e7b4ab39c10368ac85103c72 | [] | no_license | amir5200fx/AutMarine-v4.2.0 | bba1fe1aa1a14605c22a389c1bd3b48d943dc228 | 6beedbac1a3102cd1f212381a9800deec79cb31a | refs/heads/master | 2020-11-27T05:04:27.397790 | 2019-12-20T17:59:03 | 2019-12-20T17:59:03 | 227,961,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,231 | cxx | #include <Mesh3d_SmoothingConfig.hxx>
static const Standard_Real DEFAULT_ACTIVESETFACTOR = 1.03;
static const Standard_Integer DEFAULT_MAXLINEITER = 50;
static const Standard_Real DEFAULT_MINSTEPSIZE = 1.0E-5;
static const Standard_Real DEFAULT_MINSMOOTHITERIMPROVE = 1.0E-5;
static const Standard_Integer DEFAULT_MaxITERATIONS = 5;
AutLib::MeshLib::Mesh3d_SmoothingConfig::Mesh3d_SmoothingConfig()
: theActiveSetFactor_(DEFAULT_ACTIVESETFACTOR)
, theMaxLineIterations_(DEFAULT_MAXLINEITER)
, theMinStepSize_(DEFAULT_MINSTEPSIZE)
, theMinSmoothingImprovement_(DEFAULT_MINSMOOTHITERIMPROVE)
, theMaxIterations_(DEFAULT_MaxITERATIONS)
{
}
Standard_Integer AutLib::MeshLib::Mesh3d_SmoothingConfig::MaxLineIterations() const
{
return theMaxLineIterations_;
}
Standard_Integer AutLib::MeshLib::Mesh3d_SmoothingConfig::MaxSmoothingIterations() const
{
return theMaxIterations_;
}
Standard_Real AutLib::MeshLib::Mesh3d_SmoothingConfig::ActiveSetFactor() const
{
return theActiveSetFactor_;
}
Standard_Real AutLib::MeshLib::Mesh3d_SmoothingConfig::MinStepSize() const
{
return theMinStepSize_;
}
Standard_Real AutLib::MeshLib::Mesh3d_SmoothingConfig::MinSmoothingImprovement() const
{
return theMinSmoothingImprovement_;
} | [
"[email protected]"
] | |
64af520e6591918c702fb8d597dde6ebbadc3336 | f4499a8dc5cc89b5d15765530c230f51c679343a | /Tokens/NewLineToken.hpp | dd4d89035230579c1fe9139dadc3bb98cb554c5f | [] | no_license | chaydont/AbstractVM | 082e7957aeb2c370871c2bc97c7796c3c5e19502 | f65bbd89c9aafa021fea8a10d433f924a9741997 | refs/heads/master | 2020-06-17T18:40:38.506011 | 2019-07-17T17:19:44 | 2019-07-17T17:19:44 | 196,011,295 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,126 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* NewLineToken.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: chaydont <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2019/06/18 13:57:23 by chaydont #+# #+# */
/* Updated: 2019/07/10 13:48:09 by chaydont ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef NEWLINETOKEN_HPP
#define NEWLINETOKEN_HPP
#include "IToken.hpp"
struct NewLineToken : public IToken {
NewLineToken() {}
void display() const { std::cout << std::endl << std::endl; }
};
#endif /* NEWLINETOKEN_HPP */
| [
"[email protected]"
] | |
d0523bce5e74221488103aea18de2b5ed8cf4dbb | a7229f75af58bbe6e5dff85566324baf650aa089 | /meikaiCbasic/c7/list7-8.cpp | 8922a448f9d365d08911fbbfd9879e236b6d5061 | [
"MIT"
] | permissive | CC-WO/meikaiCbasic | beca7f7a837a0fff7128a7e3e3cc5f19121864d9 | a049de67b3bdbbf4185a6452936a4482df4b98f6 | refs/heads/main | 2023-01-30T11:53:18.397878 | 2020-12-12T11:53:33 | 2020-12-12T11:53:33 | 320,818,488 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 596 | cpp | //0~65535を10進・2進・8進・16進で表示
#include <stdio.h>
int count_bits(unsigned x)
{
int count = 0;
while (x){
if (x & 1U)
count++;
x >>= 1;
}
return(count);
}
int int_bits(void)
{
return(count_bits(~0U));
}
void print_bits(unsigned x, unsigned n)
{
int i = int_bits();
i = (n < i) ? n - 1 : i - 1;
for (; i >= 0; i--){
putchar(((x >> i) & 1U) ? '1' : '0');
}
}
int main(void)
{
unsigned i;
for (i = 0; i <= 65535U; i++){
printf("%5u ", i);
print_bits(i, 16);
printf(" %06o %04x\n", i, i);
}
return(0);
}
| [
"[email protected]"
] | |
ba4964961467f470859eb620edd9747df5e3751f | 9420d827756c583c5af48719f18e59c1115c69c9 | /Power of a number.cc | dc6537f0c180a2c670b738a708e117da3f86b1e8 | [] | no_license | sanjana2319/100-codes | 049188930e3e446380f12c49e9c524b9d900690e | 5dd5d842d8290eceb9720ea10ab0f6f95765a615 | refs/heads/master | 2023-03-10T18:24:54.048263 | 2021-03-02T10:45:00 | 2021-03-02T10:45:00 | 335,227,828 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 271 | cc | #include <iostream>
using namespace std;
int main()
{
int i, num, expo, power = 1;
cout<<"Enter the base number: ";
cin>>num;
cout<<"Enter the exponent: ";
cin>>expo;
for(i = 1; i<=expo; i++) {
power = power * num;
}
cout<<power;
return 0;
}
| [
"[email protected]"
] |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.