blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
a763f24e6acb6591e3e6fe43d3cc1b5d2e9cd0e6 | 1bda70125aa4da73a33fc20ab77326891977f331 | /.svn/pristine/a7/a763f24e6acb6591e3e6fe43d3cc1b5d2e9cd0e6.svn-base | 9315d6b6b93f66c70b12473423d143923d48a4db | [
"NCSA"
] | permissive | dekasthiti/llvm-projects | 62e8cfb6c65c142fc5ff90e1f5999f4c62f60f6a | 3f36fb9ba61c54f3ad0407d74bdbbfefbda1e614 | refs/heads/master | 2021-01-09T21:46:35.091458 | 2015-06-05T08:06:35 | 2015-06-05T08:06:35 | 36,936,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,720 | //===-- llvm/ADT/Triple.h - Target triple helper class ----------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_ADT_TRIPLE_H
#define LLVM_ADT_TRIPLE_H
#include "llvm/ADT/Twine.h"
// Some system headers or GCC predefined macros conflict with identifiers in
// this file. Undefine them here.
#undef NetBSD
#undef mips
#undef sparc
namespace llvm {
/// Triple - Helper class for working with autoconf configuration names. For
/// historical reasons, we also call these 'triples' (they used to contain
/// exactly three fields).
///
/// Configuration names are strings in the canonical form:
/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM
/// or
/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT
///
/// This class is used for clients which want to support arbitrary
/// configuration names, but also want to implement certain special
/// behavior for particular configurations. This class isolates the mapping
/// from the components of the configuration name to well known IDs.
///
/// At its core the Triple class is designed to be a wrapper for a triple
/// string; the constructor does not change or normalize the triple string.
/// Clients that need to handle the non-canonical triples that users often
/// specify should use the normalize method.
///
/// See autoconf/config.guess for a glimpse into what configuration names
/// look like in practice.
class Triple {
public:
enum ArchType {
UnknownArch,
arm, // ARM (little endian): arm, armv.*, xscale
armeb, // ARM (big endian): armeb
aarch64, // AArch64 (little endian): aarch64
aarch64_be, // AArch64 (big endian): aarch64_be
bpf, // eBPF or extended BPF or 64-bit BPF (little endian)
hexagon, // Hexagon: hexagon
mips, // MIPS: mips, mipsallegrex
mipsel, // MIPSEL: mipsel, mipsallegrexel
mips64, // MIPS64: mips64
mips64el, // MIPS64EL: mips64el
msp430, // MSP430: msp430
ppc, // PPC: powerpc
ppc64, // PPC64: powerpc64, ppu
ppc64le, // PPC64LE: powerpc64le
r600, // R600: AMD GPUs HD2XXX - HD6XXX
amdgcn, // AMDGCN: AMD GCN GPUs
sparc, // Sparc: sparc
sparcv9, // Sparcv9: Sparcv9
sparcel, // Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant
systemz, // SystemZ: s390x
tce, // TCE (http://tce.cs.tut.fi/): tce
thumb, // Thumb (little endian): thumb, thumbv.*
thumbeb, // Thumb (big endian): thumbeb
x86, // X86: i[3-9]86
x86_64, // X86-64: amd64, x86_64
xcore, // XCore: xcore
nvptx, // NVPTX: 32-bit
nvptx64, // NVPTX: 64-bit
le32, // le32: generic little-endian 32-bit CPU (PNaCl / Emscripten)
le64, // le64: generic little-endian 64-bit CPU (PNaCl / Emscripten)
amdil, // AMDIL
amdil64, // AMDIL with 64-bit pointers
hsail, // AMD HSAIL
hsail64, // AMD HSAIL with 64-bit pointers
spir, // SPIR: standard portable IR for OpenCL 32-bit version
spir64, // SPIR: standard portable IR for OpenCL 64-bit version
kalimba, // Kalimba: generic kalimba
LastArchType = kalimba
};
enum SubArchType {
NoSubArch,
ARMSubArch_v8_1a,
ARMSubArch_v8,
ARMSubArch_v7,
ARMSubArch_v7em,
ARMSubArch_v7m,
ARMSubArch_v7s,
ARMSubArch_v6,
ARMSubArch_v6m,
ARMSubArch_v6k,
ARMSubArch_v6t2,
ARMSubArch_v5,
ARMSubArch_v5te,
ARMSubArch_v4t,
KalimbaSubArch_v3,
KalimbaSubArch_v4,
KalimbaSubArch_v5
};
enum VendorType {
UnknownVendor,
Apple,
PC,
SCEI,
BGP,
BGQ,
Freescale,
IBM,
ImaginationTechnologies,
MipsTechnologies,
NVIDIA,
CSR,
LastVendorType = CSR
};
enum OSType {
UnknownOS,
CloudABI,
Darwin,
DragonFly,
FreeBSD,
IOS,
KFreeBSD,
Linux,
Lv2, // PS3
MacOSX,
NetBSD,
OpenBSD,
Solaris,
Win32,
Haiku,
Minix,
RTEMS,
NaCl, // Native Client
CNK, // BG/P Compute-Node Kernel
Bitrig,
AIX,
CUDA, // NVIDIA CUDA
NVCL, // NVIDIA OpenCL
AMDHSA, // AMD HSA Runtime
PS4,
LastOSType = PS4
};
enum EnvironmentType {
UnknownEnvironment,
GNU,
GNUEABI,
GNUEABIHF,
GNUX32,
CODE16,
EABI,
EABIHF,
Android,
MSVC,
Itanium,
Cygnus,
LastEnvironmentType = Cygnus
};
enum ObjectFormatType {
UnknownObjectFormat,
COFF,
ELF,
MachO,
};
private:
std::string Data;
/// The parsed arch type.
ArchType Arch;
/// The parsed subarchitecture type.
SubArchType SubArch;
/// The parsed vendor type.
VendorType Vendor;
/// The parsed OS type.
OSType OS;
/// The parsed Environment type.
EnvironmentType Environment;
/// The object format type.
ObjectFormatType ObjectFormat;
public:
/// @name Constructors
/// @{
/// \brief Default constructor is the same as an empty string and leaves all
/// triple fields unknown.
Triple() : Data(), Arch(), Vendor(), OS(), Environment(), ObjectFormat() {}
explicit Triple(const Twine &Str);
Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr);
Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr,
const Twine &EnvironmentStr);
bool operator==(const Triple &Other) const {
return Arch == Other.Arch && SubArch == Other.SubArch &&
Vendor == Other.Vendor && OS == Other.OS &&
Environment == Other.Environment &&
ObjectFormat == Other.ObjectFormat;
}
/// @}
/// @name Normalization
/// @{
/// normalize - Turn an arbitrary machine specification into the canonical
/// triple form (or something sensible that the Triple class understands if
/// nothing better can reasonably be done). In particular, it handles the
/// common case in which otherwise valid components are in the wrong order.
static std::string normalize(StringRef Str);
/// \brief Return the normalized form of this triple's string.
std::string normalize() const { return normalize(Data); }
/// @}
/// @name Typed Component Access
/// @{
/// getArch - Get the parsed architecture type of this triple.
ArchType getArch() const { return Arch; }
/// getSubArch - get the parsed subarchitecture type for this triple.
SubArchType getSubArch() const { return SubArch; }
/// getVendor - Get the parsed vendor type of this triple.
VendorType getVendor() const { return Vendor; }
/// getOS - Get the parsed operating system type of this triple.
OSType getOS() const { return OS; }
/// hasEnvironment - Does this triple have the optional environment
/// (fourth) component?
bool hasEnvironment() const {
return getEnvironmentName() != "";
}
/// getEnvironment - Get the parsed environment type of this triple.
EnvironmentType getEnvironment() const { return Environment; }
/// \brief Parse the version number from the OS name component of the
/// triple, if present.
///
/// For example, "fooos1.2.3" would return (1, 2, 3).
///
/// If an entry is not defined, it will be returned as 0.
void getEnvironmentVersion(unsigned &Major, unsigned &Minor,
unsigned &Micro) const;
/// getFormat - Get the object format for this triple.
ObjectFormatType getObjectFormat() const { return ObjectFormat; }
/// getOSVersion - Parse the version number from the OS name component of the
/// triple, if present.
///
/// For example, "fooos1.2.3" would return (1, 2, 3).
///
/// If an entry is not defined, it will be returned as 0.
void getOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const;
/// getOSMajorVersion - Return just the major version number, this is
/// specialized because it is a common query.
unsigned getOSMajorVersion() const {
unsigned Maj, Min, Micro;
getOSVersion(Maj, Min, Micro);
return Maj;
}
/// getMacOSXVersion - Parse the version number as with getOSVersion and then
/// translate generic "darwin" versions to the corresponding OS X versions.
/// This may also be called with IOS triples but the OS X version number is
/// just set to a constant 10.4.0 in that case. Returns true if successful.
bool getMacOSXVersion(unsigned &Major, unsigned &Minor,
unsigned &Micro) const;
/// getiOSVersion - Parse the version number as with getOSVersion. This should
/// only be called with IOS triples.
void getiOSVersion(unsigned &Major, unsigned &Minor,
unsigned &Micro) const;
/// @}
/// @name Direct Component Access
/// @{
const std::string &str() const { return Data; }
const std::string &getTriple() const { return Data; }
/// getArchName - Get the architecture (first) component of the
/// triple.
StringRef getArchName() const;
/// getVendorName - Get the vendor (second) component of the triple.
StringRef getVendorName() const;
/// getOSName - Get the operating system (third) component of the
/// triple.
StringRef getOSName() const;
/// getEnvironmentName - Get the optional environment (fourth)
/// component of the triple, or "" if empty.
StringRef getEnvironmentName() const;
/// getOSAndEnvironmentName - Get the operating system and optional
/// environment components as a single string (separated by a '-'
/// if the environment component is present).
StringRef getOSAndEnvironmentName() const;
/// @}
/// @name Convenience Predicates
/// @{
/// \brief Test whether the architecture is 64-bit
///
/// Note that this tests for 64-bit pointer width, and nothing else. Note
/// that we intentionally expose only three predicates, 64-bit, 32-bit, and
/// 16-bit. The inner details of pointer width for particular architectures
/// is not summed up in the triple, and so only a coarse grained predicate
/// system is provided.
bool isArch64Bit() const;
/// \brief Test whether the architecture is 32-bit
///
/// Note that this tests for 32-bit pointer width, and nothing else.
bool isArch32Bit() const;
/// \brief Test whether the architecture is 16-bit
///
/// Note that this tests for 16-bit pointer width, and nothing else.
bool isArch16Bit() const;
/// isOSVersionLT - Helper function for doing comparisons against version
/// numbers included in the target triple.
bool isOSVersionLT(unsigned Major, unsigned Minor = 0,
unsigned Micro = 0) const {
unsigned LHS[3];
getOSVersion(LHS[0], LHS[1], LHS[2]);
if (LHS[0] != Major)
return LHS[0] < Major;
if (LHS[1] != Minor)
return LHS[1] < Minor;
if (LHS[2] != Micro)
return LHS[1] < Micro;
return false;
}
bool isOSVersionLT(const Triple &Other) const {
unsigned RHS[3];
Other.getOSVersion(RHS[0], RHS[1], RHS[2]);
return isOSVersionLT(RHS[0], RHS[1], RHS[2]);
}
/// isMacOSXVersionLT - Comparison function for checking OS X version
/// compatibility, which handles supporting skewed version numbering schemes
/// used by the "darwin" triples.
unsigned isMacOSXVersionLT(unsigned Major, unsigned Minor = 0,
unsigned Micro = 0) const {
assert(isMacOSX() && "Not an OS X triple!");
// If this is OS X, expect a sane version number.
if (getOS() == Triple::MacOSX)
return isOSVersionLT(Major, Minor, Micro);
// Otherwise, compare to the "Darwin" number.
assert(Major == 10 && "Unexpected major version");
return isOSVersionLT(Minor + 4, Micro, 0);
}
/// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support both
/// "darwin" and "osx" as OS X triples.
bool isMacOSX() const {
return getOS() == Triple::Darwin || getOS() == Triple::MacOSX;
}
/// Is this an iOS triple.
bool isiOS() const {
return getOS() == Triple::IOS;
}
/// isOSDarwin - Is this a "Darwin" OS (OS X or iOS).
bool isOSDarwin() const {
return isMacOSX() || isiOS();
}
bool isOSNetBSD() const {
return getOS() == Triple::NetBSD;
}
bool isOSOpenBSD() const {
return getOS() == Triple::OpenBSD;
}
bool isOSFreeBSD() const {
return getOS() == Triple::FreeBSD;
}
bool isOSDragonFly() const { return getOS() == Triple::DragonFly; }
bool isOSSolaris() const {
return getOS() == Triple::Solaris;
}
bool isOSBitrig() const {
return getOS() == Triple::Bitrig;
}
bool isWindowsMSVCEnvironment() const {
return getOS() == Triple::Win32 &&
(getEnvironment() == Triple::UnknownEnvironment ||
getEnvironment() == Triple::MSVC);
}
bool isKnownWindowsMSVCEnvironment() const {
return getOS() == Triple::Win32 && getEnvironment() == Triple::MSVC;
}
bool isWindowsItaniumEnvironment() const {
return getOS() == Triple::Win32 && getEnvironment() == Triple::Itanium;
}
bool isWindowsCygwinEnvironment() const {
return getOS() == Triple::Win32 && getEnvironment() == Triple::Cygnus;
}
bool isWindowsGNUEnvironment() const {
return getOS() == Triple::Win32 && getEnvironment() == Triple::GNU;
}
/// \brief Tests for either Cygwin or MinGW OS
bool isOSCygMing() const {
return isWindowsCygwinEnvironment() || isWindowsGNUEnvironment();
}
/// \brief Is this a "Windows" OS targeting a "MSVCRT.dll" environment.
bool isOSMSVCRT() const {
return isWindowsMSVCEnvironment() || isWindowsGNUEnvironment() ||
isWindowsItaniumEnvironment();
}
/// \brief Tests whether the OS is Windows.
bool isOSWindows() const {
return getOS() == Triple::Win32;
}
/// \brief Tests whether the OS is NaCl (Native Client)
bool isOSNaCl() const {
return getOS() == Triple::NaCl;
}
/// \brief Tests whether the OS is Linux.
bool isOSLinux() const {
return getOS() == Triple::Linux;
}
/// \brief Tests whether the OS uses the ELF binary format.
bool isOSBinFormatELF() const {
return getObjectFormat() == Triple::ELF;
}
/// \brief Tests whether the OS uses the COFF binary format.
bool isOSBinFormatCOFF() const {
return getObjectFormat() == Triple::COFF;
}
/// \brief Tests whether the environment is MachO.
bool isOSBinFormatMachO() const {
return getObjectFormat() == Triple::MachO;
}
/// \brief Tests whether the target is the PS4 CPU
bool isPS4CPU() const {
return getArch() == Triple::x86_64 &&
getVendor() == Triple::SCEI &&
getOS() == Triple::PS4;
}
/// \brief Tests whether the target is the PS4 platform
bool isPS4() const {
return getVendor() == Triple::SCEI &&
getOS() == Triple::PS4;
}
/// @}
/// @name Mutators
/// @{
/// setArch - Set the architecture (first) component of the triple
/// to a known type.
void setArch(ArchType Kind);
/// setVendor - Set the vendor (second) component of the triple to a
/// known type.
void setVendor(VendorType Kind);
/// setOS - Set the operating system (third) component of the triple
/// to a known type.
void setOS(OSType Kind);
/// setEnvironment - Set the environment (fourth) component of the triple
/// to a known type.
void setEnvironment(EnvironmentType Kind);
/// setObjectFormat - Set the object file format
void setObjectFormat(ObjectFormatType Kind);
/// setTriple - Set all components to the new triple \p Str.
void setTriple(const Twine &Str);
/// setArchName - Set the architecture (first) component of the
/// triple by name.
void setArchName(StringRef Str);
/// setVendorName - Set the vendor (second) component of the triple
/// by name.
void setVendorName(StringRef Str);
/// setOSName - Set the operating system (third) component of the
/// triple by name.
void setOSName(StringRef Str);
/// setEnvironmentName - Set the optional environment (fourth)
/// component of the triple by name.
void setEnvironmentName(StringRef Str);
/// setOSAndEnvironmentName - Set the operating system and optional
/// environment components with a single string.
void setOSAndEnvironmentName(StringRef Str);
/// @}
/// @name Helpers to build variants of a particular triple.
/// @{
/// \brief Form a triple with a 32-bit variant of the current architecture.
///
/// This can be used to move across "families" of architectures where useful.
///
/// \returns A new triple with a 32-bit architecture or an unknown
/// architecture if no such variant can be found.
llvm::Triple get32BitArchVariant() const;
/// \brief Form a triple with a 64-bit variant of the current architecture.
///
/// This can be used to move across "families" of architectures where useful.
///
/// \returns A new triple with a 64-bit architecture or an unknown
/// architecture if no such variant can be found.
llvm::Triple get64BitArchVariant() const;
/// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
///
/// \param Arch the architecture name (e.g., "armv7s"). If it is an empty
/// string then the triple's arch name is used.
const char* getARMCPUForArch(StringRef Arch = StringRef()) const;
/// @}
/// @name Static helpers for IDs.
/// @{
/// getArchTypeName - Get the canonical name for the \p Kind architecture.
static const char *getArchTypeName(ArchType Kind);
/// getArchTypePrefix - Get the "prefix" canonical name for the \p Kind
/// architecture. This is the prefix used by the architecture specific
/// builtins, and is suitable for passing to \see
/// Intrinsic::getIntrinsicForGCCBuiltin().
///
/// \return - The architecture prefix, or 0 if none is defined.
static const char *getArchTypePrefix(ArchType Kind);
/// getVendorTypeName - Get the canonical name for the \p Kind vendor.
static const char *getVendorTypeName(VendorType Kind);
/// getOSTypeName - Get the canonical name for the \p Kind operating system.
static const char *getOSTypeName(OSType Kind);
/// getEnvironmentTypeName - Get the canonical name for the \p Kind
/// environment.
static const char *getEnvironmentTypeName(EnvironmentType Kind);
/// @}
/// @name Static helpers for converting alternate architecture names.
/// @{
/// getArchTypeForLLVMName - The canonical type for the given LLVM
/// architecture name (e.g., "x86").
static ArchType getArchTypeForLLVMName(StringRef Str);
/// @}
};
} // End llvm namespace
#endif
| [
"dekasthiti@gmail.com"
] | dekasthiti@gmail.com | |
ee661acfb0d06559de479f19c9b3945aafeade5a | ae936fb07d9478152cb998e94b9937d625f5c3dd | /Codeforces/CF1334A.cpp | a66349aceb6c00c18292ad5e044e962c86139b16 | [] | no_license | Jorgefiestas/CompetitiveProgramming | f035978fd2d3951dbd1ffd14d60236ef548a1974 | b35405d6be5adf87e9a257be2fa0b14f5eba3c83 | refs/heads/master | 2021-06-12T06:28:20.878137 | 2021-04-21T01:32:37 | 2021-04-21T01:32:37 | 164,651,348 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 502 | cpp | #include <bits/stdc++.h>
using namespace std;
const int N = 100;
int t, n;
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> t;
while (t--) {
cin >> n;
int lp = 0, lc = 0;
int pi, ci;
bool poss = true;
for (int i = 0; i < n; i++) {
cin >> pi >> ci;
if(ci - lc > pi - lp) {
poss = false;
}
if (lc > ci || lp > pi) {
poss = false;
}
lc = ci;
lp = pi;
}
if (poss) {
cout << "YES\n";
}
else {
cout << "NO\n";
}
}
return 0;
}
| [
"jorge.fiestas@utec.edu.pe"
] | jorge.fiestas@utec.edu.pe |
8f098765f36c1224e73ea357045040216dfd1397 | 15ae3c07d969f1e75bc2af9555cf3e952be9bfff | /analysis/pragma_before/pragma_909.hpp | b19f440848c66b35f4cf3d891f1cfde5e80708bf | [] | no_license | marroko/generators | d2d1855d9183cbc32f9cd67bdae8232aba2d1131 | 9e80511155444f42f11f25063c0176cb3b6f0a66 | refs/heads/master | 2023-02-01T16:55:03.955738 | 2020-12-12T14:11:17 | 2020-12-12T14:11:17 | 316,802,086 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 131 | hpp | #ifndef NJMFIPQIW_PZQZXPWXAVMN_XINREJD_HPP
#define NJMFIPQIW_PZQZXPWXAVMN_XINREJD_HPP
#endif // NJMFIPQIW_PZQZXPWXAVMN_XINREJD_HPP | [
"marcus1.2.3@wp.pl"
] | marcus1.2.3@wp.pl |
959a2adb663e20fae5ba30ce8841da5946d0f1e0 | 9b175b146a95bffecf2fc377641527cabed849cb | /GuangGIS-Core/RendererCore/SysLineElement.cpp | db466e4217f0369ed7ca4dbabdf2b502a228f8c1 | [] | no_license | xibeilang524/OGSE | 8e067f4c9c0785354a0cd6de33ae447e195f0b60 | a009ee0f91aca49be4068971f72b2ed9640d280a | refs/heads/master | 2021-10-11T02:02:22.891864 | 2019-01-21T09:16:37 | 2019-01-21T09:16:37 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 3,867 | cpp | #include "SysLineElement.h"
#include "SysCoordinate.h"
#include "SysEnvelope.h"
namespace SysDraw
{
SysLineElement::SysLineElement(void):SysGraphElement(type_PolyLine)
{
m_poPoints = NULL;
m_nPointCount = 0;
}
SysLineElement::~SysLineElement(void)
{
RemoveAllPoints();
}
void SysLineElement::AddPoint(double dx,double dy)
{
if (NULL == m_poPoints)
{
m_poPoints = (SysCoordinate *)malloc(sizeof(SysCoordinate)*1);
m_poPoints[0].x = dx;
m_poPoints[0].y = dy;
}
else
{
m_poPoints = (SysCoordinate *)realloc(m_poPoints,sizeof(SysCoordinate)*(m_nPointCount+1));
m_poPoints[m_nPointCount].x = dx;
m_poPoints[m_nPointCount].y = dy;
}
m_nPointCount += 1;
}
void SysLineElement::RemoveAllPoints()
{
if (m_poPoints != NULL)
{
free(m_poPoints);
m_poPoints = NULL;
}
m_nPointCount = 0;
}
bool SysLineElement::GetPoint(int nIndex,double &dx,double &dy) const
{
if (nIndex < 0 || nIndex > m_nPointCount-1)
{
return false;
}
dx = m_poPoints[nIndex].x;
dy = m_poPoints[nIndex].y;
return true;
}
SysCoordinate* SysLineElement::GetPoints() const
{
return m_poPoints;
}
int SysLineElement::GetPointCount() const
{
return m_nPointCount;
}
bool SysLineElement::Move(double dx, double dy)
{
for (int i = 0; i < m_nPointCount; i ++)
{
m_poPoints[i].x += dx;
m_poPoints[i].y += dy;
}
return true;
}
bool SysLineElement::MovePoint(int nIndex, double dx, double dy)
{
if (nIndex < 0 || nIndex > m_nPointCount-1)
{
return false;
}
m_poPoints[nIndex].x += dx;
m_poPoints[nIndex].y += dy;
return true;
}
bool SysLineElement::MovePointTo(int nIndex, double dbX, double dbY)
{
if (nIndex < 0 || nIndex > m_nPointCount-1)
{
return false;
}
m_poPoints[nIndex].x = dbX;
m_poPoints[nIndex].y = dbY;
return true;
}
SysEnvelope& SysLineElement::GetEnvelope() const
{
double dfMinX, dfMinY, dfMaxX, dfMaxY;
SysEnvelope env;
int nPointCount = m_nPointCount;
if( 0 == nPointCount )
{
env.Init(0,0,0,0);
return env;
}
dfMinX = dfMaxX = m_poPoints[0].x;
dfMinY = dfMaxY = m_poPoints[0].y;
for( int iPoint = 1; iPoint < nPointCount; iPoint ++ )
{
if( dfMaxX < m_poPoints[iPoint].x )
dfMaxX = m_poPoints[iPoint].x;
if( dfMaxY < m_poPoints[iPoint].y )
dfMaxY = m_poPoints[iPoint].y;
if( dfMinX > m_poPoints[iPoint].x )
dfMinX = m_poPoints[iPoint].x;
if( dfMinY > m_poPoints[iPoint].y )
dfMinY = m_poPoints[iPoint].y;
}
env.Init(dfMinX,dfMaxX,dfMinY,dfMaxY);
return env;
}
//点到直线的距离
static double PtToLine(double x1,double y1,double x2,double y2,double x,double y)
{
return fabs((double)x*(y2-y1)+y*(x1-x2)+(y1*x2-x1*y2))/sqrt(pow((y2-y1),2.0)+pow((x1-x2),2.0));
}
bool SysLineElement::PointInArea(double x,double y) const
{
int nNUm = m_nPointCount;
if (nNUm > 1)
{
for (int i=1;i<nNUm;i++)
{
double v = PtToLine(m_poPoints[i-1].x,m_poPoints[i-1].y,m_poPoints[i].x,m_poPoints[i].y,x,y);
if (v <= 0.0001)
{
if ( (x-m_poPoints[i-1].x)*(x-m_poPoints[i].x)<=0 && (y-m_poPoints[i-1].y)*(y-m_poPoints[i].y)<=0)
{
return true;
}
}
}
}
return false;
}
void SysLineElement::GetCenterPoint(double &x,double &y) const
{
return;
}
double SysLineElement::GetPerimeter() const
{
double dlength = 0;
if (m_nPointCount > 1)
{
for (int i=0; i < m_nPointCount; i++)
{
int tmp = i+1;
if (tmp == m_nPointCount)
{
break;
}
dlength += sqrt(pow((m_poPoints[i].x - m_poPoints[tmp].x),2.0) + pow((m_poPoints[i].y - m_poPoints[tmp].y),2.0));
}
}
return dlength;
}
}
| [
"zhouxuguang@baidu.com"
] | zhouxuguang@baidu.com |
ab8b37f59c2ac7c7faa73fea37199f1697e94f51 | c555aa9088d8c93e4855c4123d8c7e5987d6d732 | /Task_01_01.cpp | 863acae69592bbc80ed35e0a91f3fb3ff76731d7 | [] | no_license | ThuLTA/Coding_DynamicProgramming | 9d209d84f7ab382e270697db9613cb34c3f47037 | 1ec9eb23e2858ac60af88e698c291e53dffb5935 | refs/heads/master | 2023-07-07T17:15:16.922827 | 2021-09-06T15:16:45 | 2021-09-06T15:16:45 | 394,905,586 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,009 | cpp | //Task 01: Tìm dãy con tăng dài nhất.
//Sử dụng hàm lower_bound()
#include <iostream>
#include <algorithm>
#include<vector>
using namespace std;
int solution(vector<int>);
int main()
{
vector<int> arr = { 4,1,2,3,4,2,7,5,3,6,1 };
cout << "Res: " << solution(arr) << endl;
return 0;
}
int solution(vector<int> arr) {
//khởi tạo b[] lưu dãy con. Dãy b[] = {-infinity , infinity, ..., infinity}
//khởi tạo infinity, vì:
// --> mọi phần tử của arr đều lớn hơn -inf ==> trường hợp b[] chứa ít nhất 1 phần tử của arr
// --> mọi phần tử của arr đền nhỏ hơn inf ==> trường hợp b[] chứa được nhiều nhất là toàn bộ arr
vector<int> b(arr.size(), INT_MAX);
b[0] = INT_MIN;
int res = 0; //đếm phần tử
for (int i = 0; i < arr.size(); i++) {
int k = lower_bound(b.begin(), b.end(), arr[i]) - b.begin(); //trả về k=index với b[index]<=arr[i] (index từ: 1 ..n end())
b[k] = arr[i]; //lưu phần tử của arr đang xét vào mảng tạm
res = max(res, k); //so sánh res-index
}
return res;
//res: tương ứng với index của đoạn chứa các phần tử con của arr <=> b[res-1] = max, b[res] = inf
//****Giải thích***
// arr = {...., 7 , ... , 4 , ...}
// Ta thấy giữa đoạn (7 - 4) còn các giá trị khác.
// 7 sẽ được thêm vào b[] trước, 4 thêm sau
// (TH1): (7,N,...4) có chứa phần tử N > 7 ==> đoạn đoạn b[] = infi sẽ giảm, thay vào đó là giá trị N
// (TH2): (7,M,...4) chứa M < 7 ==> đoạn b[] có thể giữ nguyên,b[k]=7 đổi thành b[k] = M.
// --> M và 7 đều thỏa mãn, ta chọn M vì nếu còn những phần tử M < ...< 7, ta có thể tăng b[] lên.
// ==> hay dễ hiểu, chọn phần tử nhỏ hơn, để tăng khả năng chứa cho b[]
}
int max(int a, int b) {
return (a > b) ? a : b;
} | [
"USER@DESKTOP-8M2NJ75"
] | USER@DESKTOP-8M2NJ75 |
ad83644302971e172aaf0e2ef3651941f621a62c | 388020361a83a134d3a23bbff6ac39a0a04ae498 | /projects/pbrt_importer/src/string_to_number.cpp | 7310a78ca90814572ef7f74d75d68baf1d9d3869 | [] | no_license | happydpc/pandora | c5beccf5385100bf36a3f236188b9813b202eb8e | ebb0ab7d58a75054304d92842bebd09b190c121a | refs/heads/master | 2021-05-17T20:48:34.833416 | 2020-03-02T10:44:47 | 2020-03-02T10:44:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,322 | cpp | #include "string_to_number.h"
#include "crack_atof.h"
#include <algorithm>
#include <array>
#include <charconv>
#include <chrono>
#include <cstdlib>
#include <execution>
#include <gsl/span>
#include <spdlog/spdlog.h>
#include <string>
#include <string_view>
#include <thread>
#include <vector>
template <typename T>
T fromString(std::string_view str)
{
// <charconv> is fast and generic
T value;
std::from_chars(str.data(), str.data() + str.size(), value);
return value;
}
template <>
float fromString(std::string_view str)
{
/*// <charconv>
float value;
std::from_chars(str.data(), str.data() + str.size(), value);
return value;*/
// Faster than <charconv> on MSVC 19.23.28106.4 but not sure if it is a 100% correct
return static_cast<float>(crackAtof(str));
}
template <>
double fromString(std::string_view str)
{
/*// <charconv>
double value;
std::from_chars(str.data(), str.data() + str.size(), value);
return value;*/
// Faster than <charconv> on MSVC 19.23.28106.4 but not sure if it is a 100% correct
return crackAtof(str);
}
constexpr std::array<bool, 256> compuateIsSpaceLUT()
{
// https://en.cppreference.com/w/cpp/string/byte/isspace
std::array<bool, 256> lut {};
for (int c = 0; c < 256; c++)
lut[c] = (c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v');
return lut;
}
inline bool isSpace(const char c)
{
// Lookup table is faster than 6 comparisons
static constexpr std::array<bool, 256> lut = compuateIsSpaceLUT();
return lut[c];
//return c == ' ' || c == '\f' || c == '\n' || c == '\r' || c == '\t' || c == '\v';
}
template <typename T>
std::vector<T> stringToVector(const std::string_view string)
{
// Allocate
std::vector<T> ret;
const size_t stringSize = string.size();
size_t cursor = 0;
while (cursor < stringSize) {
// std::isspace is slow because it tries to be too generic (checking locale settings)
while (cursor < stringSize && isSpace(string[cursor]))
cursor++;
const size_t tokenStart = cursor;
while (cursor < stringSize && !isSpace(string[cursor]))
cursor++;
if (cursor == tokenStart)
break;
const std::string_view token = string.substr(tokenStart, cursor);
ret.push_back(fromString<T>(token));
}
return ret;
}
template <typename T>
std::vector<T> stringToVectorParallel(const std::string_view string)
{
const size_t numTasks = std::thread::hardware_concurrency() * 8;
std::vector<std::string_view> blocks;
size_t prevBlockEnd = 0;
for (size_t i = 1; i < numTasks; i++) {
size_t cursor = i * (string.size() / numTasks);
while (cursor < string.size() && !isSpace(string[cursor]))
cursor++;
blocks.push_back(string.substr(prevBlockEnd, cursor - prevBlockEnd));
prevBlockEnd = cursor;
}
blocks.push_back(string.substr(prevBlockEnd)); // Make sure final work block goes to end (no integer truncation issues)
std::vector<std::vector<T>> partialResults { numTasks };
std::transform(
std::execution::par_unseq,
std::begin(blocks),
std::end(blocks),
std::begin(partialResults),
[](std::string_view partialStr) {
return stringToVector<T>(partialStr);
});
size_t finalCount = 0;
for (const auto& partialResult : partialResults)
finalCount += partialResult.size();
std::vector<T> finalResults;
finalResults.resize(finalCount);
size_t offset = 0;
for (const auto& partialResult : partialResults) {
// Slightly faster than std::copy
std::memcpy(finalResults.data() + offset, partialResults.data(), partialResults.size());
offset += partialResults.size();
//std::copy(std::begin(partialResult), std::end(partialResult), std::back_inserter(finalResults));
}
return finalResults;
}
template <typename T>
pybind11::array_t<T> toNumpyArray(gsl::span<const T> items)
{
pybind11::array_t<T> outArray { static_cast<pybind11::size_t>(items.size()) };
for (int i = 0; i < items.size(); i++)
outArray.mutable_at(i) = items[i];
return outArray;
}
template <typename T>
pybind11::array_t<T> stringToNumpy(std::string_view string)
{
//const char* chars = python::extract<const char*>(string);
//int length = python::extract<int>(string.attr("__len__")());
// Heap allocation so that it stays alive outside of this function
std::vector<T> numbers;
if (string.size() > 5 * 1024 * 1024) { // Use multi-threading if the string is over 5MB
numbers = stringToVectorParallel<T>(string);
} else {
numbers = stringToVector<T>(string);
}
return toNumpyArray<T>(numbers);
}
template pybind11::array_t<float> stringToNumpy<float>(std::string_view string);
template pybind11::array_t<double> stringToNumpy<double>(std::string_view string);
template pybind11::array_t<int32_t> stringToNumpy<int32_t>(std::string_view string);
template pybind11::array_t<int64_t> stringToNumpy<int64_t>(std::string_view string);
template pybind11::array_t<uint32_t> stringToNumpy<uint32_t>(std::string_view string);
template pybind11::array_t<uint64_t> stringToNumpy<uint64_t>(std::string_view string);
| [
"mathijs.l.molenaar@gmail.com"
] | mathijs.l.molenaar@gmail.com |
71663e6a55fed1ce52d315a05865a9d8d5ccf036 | 58d4045c131628bf32c7ac8019ef13455138489e | /lib/include/lib/texture/texture.h | 07efb16e72c373fcc1df16a60035a884134cb022 | [] | no_license | ajapon88/Lib | 61067f8ab0a7a838995f8979fe2a9d3978105619 | ff06e612cd60a64fa3417fed493f2971779aa6f5 | refs/heads/master | 2021-01-15T12:27:02.024216 | 2014-04-28T17:55:11 | 2014-04-28T17:55:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 690 | h | #ifndef __LIB_TEXTURE_TEXTURE_H__
#define __LIB_TEXTURE_TEXTURE_H__
#include "stdafx.h"
#include <stdint.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
namespace lib {
namespace texture {
class Texture {
public:
Texture();
Texture(uint32_t width, uint32_t height);
~Texture();
void create(uint32_t width, uint32_t height);
void destroy();
uint32_t getWidth() { return m_width; }
uint32_t getHeight() { return m_height; }
HDC getHandle() { return m_hDC; }
void clear(COLORREF color);
private:
bool m_bCreated;
uint32_t m_height;
uint32_t m_width;
HDC m_hDC;
HBITMAP m_hBitmap;
};
} // namespace texture
} // namespace lib
#endif // __LIB_TEXTURE_TEXTURE_H__ | [
"arctoscopus.japonicus@gmail.com"
] | arctoscopus.japonicus@gmail.com |
fcad6d79d44f4332dcb0aef37da151262fcfb25a | cb43b18459fea181f1cdffd39bea55bfde8ba47f | /templates/ProjectTemplates/app.cpp | 9c6d2756b8995026046cefeacccfded7bc3a9434 | [] | no_license | HighLeeRuss/Breakout | add95a55406a66ea417db0418f96e02d5ab62a9f | 5409c045c578ce7c0646a0d194f7b00b5203bd7a | refs/heads/main | 2023-03-08T11:55:16.356937 | 2021-02-26T06:10:42 | 2021-02-26T06:10:42 | 339,378,136 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,384 | cpp | #include "app.h"
namespace App
{
// External Globals. These are really implemented in app_main.cpp
extern sf::RenderWindow g_window;
extern sf::Clock g_clock;
extern sf::Font g_font;
extern bool g_running;
extern kf::Xor128 g_rng;
// Add your own variables here
// Example of exposing a variable to other files.
// This creates the memory for the variable.
int exampleValue = 0;
bool start()
{
// Add some physics colliders to the screen edges
// Bottom
kage::Physics::EdgeBuilder().start(0, 16.875).end(30, 16.875).friction(1).build(kage::Physics::getDefaultStatic());
// Top
kage::Physics::EdgeBuilder().start(0, 0).end(30, 0).friction(1).build(kage::Physics::getDefaultStatic());
// Left
kage::Physics::EdgeBuilder().start(0, 0).end(0, 16.875).friction(1).build(kage::Physics::getDefaultStatic());
// Right
kage::Physics::EdgeBuilder().start(30, 0).end(30, 16.875).friction(1).build(kage::Physics::getDefaultStatic());
return true;
}
void update(float deltaT)
{
// Your main game logic goes here
}
void render()
{
// Draw a debug grid
kage::World::debugGrid(g_window);
// Render World
kage::World::render(g_window);
// The next line draws the physics debug info. This should be removed in a final release.
kage::Physics::debugDraw(&g_window, 64);
}
void cleanup()
{
// Perform any clean up your project needs
}
}
| [
"1021549@sae.edu.au"
] | 1021549@sae.edu.au |
d8d8a71fcb19ea0a1327c0cac7c54c49438adf0c | f298165c28590e5fa8643241424f385c38940d2e | /SDK/PUBG_BigEquipmentSlotWidget_parameters.hpp | 96a9177f9a48e6c75a1b6fbe8787bdccc2e78962 | [] | no_license | ZoondEngine/Core | 2d35cc0121c7eb37b3744609e69f02a07fa36ac1 | 03cce9e7939c9654dc4da16e753eb62cbd9b1450 | refs/heads/master | 2020-03-14T01:16:16.972475 | 2018-04-28T04:49:50 | 2018-04-28T04:49:50 | 131,373,903 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,332 | hpp | #pragma once
// PLAYERUNKNOWN'S BATTLEGROUNDS (3.7.27.27) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "../SDK.hpp"
namespace Classes
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetSlotItem
struct UBigEquipmentSlotWidget_C_GetSlotItem_Params
{
TScriptInterface<class USlotInterface> SlotItem; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetSlotContainer
struct UBigEquipmentSlotWidget_C_GetSlotContainer_Params
{
TScriptInterface<class USlotContainerInterface> SlotContainer; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.IsFocus
struct UBigEquipmentSlotWidget_C_IsFocus_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.SetFocus
struct UBigEquipmentSlotWidget_C_SetFocus_Params
{
bool* NewFocus; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.On_FocusColorBG_Prepass_1
struct UBigEquipmentSlotWidget_C_On_FocusColorBG_Prepass_1_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetItem_Bp
struct UBigEquipmentSlotWidget_C_GetItem_Bp_Params
{
class UItem* Item; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetDurability
struct UBigEquipmentSlotWidget_C_GetDurability_Params
{
float Durability; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.UpdateDurationNumber
struct UBigEquipmentSlotWidget_C_UpdateDurationNumber_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.UpdateDurabilityGauge
struct UBigEquipmentSlotWidget_C_UpdateDurabilityGauge_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.UpdateDurabilityVisibility
struct UBigEquipmentSlotWidget_C_UpdateDurabilityVisibility_Params
{
class UWidget* BoundWidget; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.OnPreviewMouseButtonDown
struct UBigEquipmentSlotWidget_C_OnPreviewMouseButtonDown_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* MouseEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
struct FEventReply ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.HaveDurability
struct UBigEquipmentSlotWidget_C_HaveDurability_Params
{
bool Result; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetDurabilityPercent
struct UBigEquipmentSlotWidget_C_GetDurabilityPercent_Params
{
float DurabilityPercent; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.OnDragDetected
struct UBigEquipmentSlotWidget_C_OnDragDetected_Params
{
struct FGeometry* MyGeometry; // (Parm, IsPlainOldData)
struct FPointerEvent* PointerEvent; // (ConstParm, Parm, OutParm, ReferenceParm)
class UDragDropOperation* Operation; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.GetSlotName
struct UBigEquipmentSlotWidget_C_GetSlotName_Params
{
struct FText ReturnValue; // (Parm, OutParm, ReturnParm)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.OnUpdateItem
struct UBigEquipmentSlotWidget_C_OnUpdateItem_Params
{
class UItem** Item; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.Construct
struct UBigEquipmentSlotWidget_C_Construct_Params
{
};
// Function BigEquipmentSlotWidget.BigEquipmentSlotWidget_C.ExecuteUbergraph_BigEquipmentSlotWidget
struct UBigEquipmentSlotWidget_C_ExecuteUbergraph_BigEquipmentSlotWidget_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"mango.kamchatka.1997@gmail.com"
] | mango.kamchatka.1997@gmail.com |
2b7246b9ee95638a5e300da988504131389fa630 | 4a4252dd015777c4a27e5d36c6e3c2989e047be5 | /saklib/qtlib/attribute_editor_double.h | 711fb3bbf2c359c53d903be16cf6616333e4da39 | [] | no_license | m4ddav3/TF2_Mod_Builder | 8c0d228311e96c7cf78ce360314edb1def8b6e4f | dfaa5ac1c72ea169c2532acbc8646e1c838b65bd | refs/heads/master | 2021-01-18T09:00:17.676175 | 2015-03-24T12:02:09 | 2015-03-24T12:02:09 | 32,739,117 | 0 | 0 | null | 2015-03-23T15:01:06 | 2015-03-23T15:01:05 | C++ | UTF-8 | C++ | false | false | 1,204 | h | #ifndef ATTRIBUTE_EDITOR_DOUBLE_H
#define ATTRIBUTE_EDITOR_DOUBLE_H
#include "attribute_editor.h"
#include "../types.h"
class QLabel;
class QDoubleSpinBox;
class QHBoxLayout;
namespace Saklib
{
class Project_Manager;
namespace Qtlib
{
class Attribute_Editor_Double :
public Attribute_Editor
{
Q_OBJECT
public:
// Special 6
//============================================================
Attribute_Editor_Double(Project_Manager& project_manager, AttributeID attributeid, QWidget* parent = nullptr);
~Attribute_Editor_Double() override;
protected:
void v_refresh_data() override;
private slots:
// Slot used to capture the signal value_changed() from the QSpinBox
void slot_valueChanged(double value);
private:
// Data Members
//============================================================
Uptr<QDoubleSpinBox> m_spinbox;
Uptr<QLabel> m_label;
Uptr<QHBoxLayout> m_layout;
};
} // namespace Qtlib
} // namespace Saklib
#endif // ATTRIBUTE_EDITOR_DOUBLE_H
| [
"elbagast@gmail.com"
] | elbagast@gmail.com |
831837f7d8d0c0867c4a6877b49ef4cf7fc8bd17 | f915aa382b6ac5673cec612718368c04931c0b0c | /contrib/antlr/include/antlr/TreeParserSharedInputState.hpp | f2f6de46a344108c7ce72c65086ada5178b42846 | [
"BSD-2-Clause"
] | permissive | diazf/indri | f477749f9e571c03b695c2f0b04c0326bbfd9f04 | 6ad646f3edb9864a98214039886c6b6e9a9f6b74 | refs/heads/master | 2022-09-07T19:35:02.661982 | 2022-08-19T13:59:26 | 2022-08-19T13:59:26 | 128,638,901 | 23 | 5 | null | null | null | null | UTF-8 | C++ | false | false | 1,176 | hpp | #ifndef INC_TreeParserSharedInputState_hpp__
#define INC_TreeParserSharedInputState_hpp__
/* ANTLR Translator Generator
* Project led by Terence Parr at http://www.jGuru.com
* Software rights: http://www.antlr.org/license.html
*
* $Id: //depot/code/org.antlr/release/antlr-2.7.4/lib/cpp/antlr/TreeParserSharedInputState.hpp#1 $
*/
#include <antlr/config.hpp>
#include <antlr/RefCount.hpp>
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
namespace antlr {
#endif
/** This object contains the data associated with an
* input AST. Multiple parsers
* share a single TreeParserSharedInputState to parse
* the same tree or to have the parser walk multiple
* trees.
*/
class ANTLR_API TreeParserInputState {
public:
TreeParserInputState() : guessing(0) {}
virtual ~TreeParserInputState() {}
public:
/** Are we guessing (guessing>0)? */
int guessing; //= 0;
private:
// we don't want these:
TreeParserInputState(const TreeParserInputState&);
TreeParserInputState& operator=(const TreeParserInputState&);
};
typedef RefCount<TreeParserInputState> TreeParserSharedInputState;
#ifdef ANTLR_CXX_SUPPORTS_NAMESPACE
}
#endif
#endif //INC_TreeParserSharedInputState_hpp__
| [
"diazf@acm.org"
] | diazf@acm.org |
6c38e1c146772b7030c91ef63397dbd7836e94b9 | 3a777044239d1cc25fe5692d726b9cba54224035 | /Minimum Interval Covering/main.cpp | 70098b32176ff4d89a164bf405656c63ef19ebf9 | [] | no_license | hdduong/CodingADSEveryday | 5a16443a011cfa9e80e426e883847afdc38a9741 | 9b459f7002f1b3c6d1f18e8df0c108befb753b1c | refs/heads/master | 2020-05-30T03:36:25.365113 | 2015-03-16T05:42:25 | 2015-03-16T05:42:25 | 28,976,422 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,302 | cpp | #include <iostream>
#include <stdlib.h>
#include <set> // Order & BST
#include <vector>
using namespace std;
struct Interval {
int startTime;
int endTime;
};
Interval * createInterval(int _start, int _end) {
Interval *newInterval = (Interval*) malloc(sizeof(Interval));
newInterval->startTime = _start;
newInterval->endTime = _end;
return newInterval;
}
struct CompareInteralEnd {
bool operator() (Interval * lhs, Interval * rhs) {
if (rhs != lhs) {
return (lhs->endTime < rhs->endTime);
}
}
};
void printSetInterval(set<Interval *,CompareInteralEnd> setInterval) {
for (set<Interval *>::iterator it = setInterval.begin(); it != setInterval.end(); it++) {
cout << "{" << (*it)->startTime << "," << (*it)->endTime << "} ";
}
cout << endl;
}
void printVector(vector<int> vVisit) {
for (vector<int>::iterator it = vVisit.begin(); it != vVisit.end(); it++) {
cout << *it << ", ";
}
cout << endl;
}
vector<int> findMinimumVisit(set<Interval*, CompareInteralEnd>& sInterval) {
vector<int> timeVisit;
for(set<Interval*,CompareInteralEnd>::iterator it = sInterval.begin(); it != sInterval.end(); it++) {
timeVisit.emplace_back((*it)->endTime);
//remove startTime < currentIt->endTime
for(set<Interval*,CompareInteralEnd>::iterator itErase = sInterval.begin(); itErase != sInterval.end(); ) {
if ( (it != itErase) && ( (*itErase)->startTime < (*it)->endTime) ) {
sInterval.erase(itErase++);
}
else {
itErase++;
}
}
}
return timeVisit;
}
/*
You should change your prefix iterator into something like this:
Iterator<T> operator++()
{
pointer = pointer->next;
return *this;
}
And your postfix iterator into something like this:
Iterator<T> operator++(int)
{
node<T>* previous = pointer;
pointer = pointer->next;
return Iterator<T>(previous);
}
*/
int main() {
vector<Interval *> vInterval;
set<Interval *, CompareInteralEnd> sInterval;
sInterval.emplace(createInterval(1,4));
sInterval.emplace(createInterval(0,5));
sInterval.emplace(createInterval(2,3));
sInterval.emplace(createInterval(6,8));
sInterval.emplace(createInterval(5,7));
sInterval.emplace(createInterval(9,10));
//printSetInterval(sInterval);
vector<int> visit = findMinimumVisit(sInterval);
printVector(visit);
return 0;
} | [
"hdduong.at.wpi.edu@gmail.com"
] | hdduong.at.wpi.edu@gmail.com |
195c352d07bd48209a01de3554e5f6acf7e21e62 | 8fc3cf44ec1e7fcb0282faa4568f11a09736f7de | /cusparse/rwr/LightSpMV/LightSpMV-1.0/cusp/csr_matrix.h | 6b43dd09a91faf85f754bfb7f9d3f22c2d9b5f14 | [] | no_license | hisashi-ito/cuda | 362ec1416ec4e69235cc577de397ded67c62b55b | d63e6c354d1f45df6cb919fc7817d8d72a73d0ae | refs/heads/master | 2021-04-12T04:46:14.381290 | 2018-10-14T10:30:20 | 2018-10-14T10:30:20 | 126,021,847 | 0 | 0 | null | 2018-05-17T08:31:03 | 2018-03-20T13:28:47 | C++ | UTF-8 | C++ | false | false | 15,287 | h | /*
* Copyright 2008-2014 NVIDIA Corporation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*! \file csr_matrix.h
* \brief Compressed Sparse Row matrix format.
*/
#pragma once
#include <cusp/detail/config.h>
#include <cusp/array1d.h>
#include <cusp/format.h>
#include <cusp/detail/matrix_base.h>
namespace cusp
{
// forward definition
template <typename ArrayType1, typename ArrayType2, typename ArrayType3, typename IndexType, typename ValueType, typename MemorySpace> class csr_matrix_view;
/*! \addtogroup sparse_matrices Sparse Matrices
*/
/*! \addtogroup sparse_matrix_containers Sparse Matrix Containers
* \ingroup sparse_matrices
* \{
*/
/**
* \brief Compressed sparse row (CSR) representation a sparse matrix
*
* \tparam IndexType Type used for matrix indices (e.g. \c int).
* \tparam ValueType Type used for matrix values (e.g. \c float).
* \tparam MemorySpace A memory space (e.g. \c cusp::host_memory or \c cusp::device_memory)
*
* \par Overview
* A \p csr_matrix is a sparse matrix container that stores an offset to the
* first entry of each row in matrix and one column
* entry per nonzero. The matrix may reside in either "host" or "device"
* memory depending on the MemorySpace. All entries in the \p csr_matrix are
* sorted according to row and internally sorted within each row by column
* index.
*
* \note The matrix entries within the same row must be sorted by column index.
* \note The matrix should not contain duplicate entries.
*
* \par Example
* The following code snippet demonstrates how to create a 4-by-3
* \p csr_matrix on the host with 6 nonzeros and then copies the
* matrix to the device.
*
* \code
* // include the csr_matrix header file
* #include <cusp/csr_matrix.h>
* #include <cusp/print.h>
*
* int main()
* {
* // allocate storage for (4,3) matrix with 4 nonzeros
* cusp::csr_matrix<int,float,cusp::host_memory> A(4,3,6);
*
* // initialize matrix entries on host
* A.row_offsets[0] = 0; // first offset is always zero
* A.row_offsets[1] = 2;
* A.row_offsets[2] = 2;
* A.row_offsets[3] = 3;
* A.row_offsets[4] = 6; // last offset is always num_entries
*
* A.column_indices[0] = 0; A.values[0] = 10;
* A.column_indices[1] = 2; A.values[1] = 20;
* A.column_indices[2] = 2; A.values[2] = 30;
* A.column_indices[3] = 0; A.values[3] = 40;
* A.column_indices[4] = 1; A.values[4] = 50;
* A.column_indices[5] = 2; A.values[5] = 60;
*
* // A now represents the following matrix
* // [10 0 20]
* // [ 0 0 0]
* // [ 0 0 30]
* // [40 50 60]
*
* // copy to the device
* cusp::csr_matrix<int,float,cusp::device_memory> B(A);
*
* cusp::print(B);
* }
* \endcode
*/
template <typename IndexType, typename ValueType, class MemorySpace>
class csr_matrix : public cusp::detail::matrix_base<IndexType,ValueType,MemorySpace,cusp::csr_format>
{
private:
typedef cusp::detail::matrix_base<IndexType,ValueType,MemorySpace,cusp::csr_format> Parent;
public:
/*! \cond */
typedef typename cusp::array1d<IndexType, MemorySpace> row_offsets_array_type;
typedef typename cusp::array1d<IndexType, MemorySpace> column_indices_array_type;
typedef typename cusp::array1d<ValueType, MemorySpace> values_array_type;
typedef typename cusp::csr_matrix<IndexType, ValueType, MemorySpace> container;
typedef typename cusp::csr_matrix_view<typename row_offsets_array_type::view,
typename column_indices_array_type::view,
typename values_array_type::view,
IndexType, ValueType, MemorySpace> view;
typedef typename cusp::csr_matrix_view<typename row_offsets_array_type::const_view,
typename column_indices_array_type::const_view,
typename values_array_type::const_view,
IndexType, ValueType, MemorySpace> const_view;
template<typename MemorySpace2>
struct rebind
{
typedef cusp::csr_matrix<IndexType, ValueType, MemorySpace2> type;
};
/*! \endcond */
/*! Storage for the row offsets of the CSR data structure. Also called the "row pointer" array.
*/
row_offsets_array_type row_offsets;
/*! Storage for the column indices of the CSR data structure.
*/
column_indices_array_type column_indices;
/*! Storage for the nonzero entries of the CSR data structure.
*/
values_array_type values;
/*! Construct an empty \p csr_matrix.
*/
csr_matrix(void) {}
/*! Construct a \p csr_matrix with a specific shape and number of nonzero entries.
*
* \param num_rows Number of rows.
* \param num_cols Number of columns.
* \param num_entries Number of nonzero matrix entries.
*/
csr_matrix(size_t num_rows, size_t num_cols, size_t num_entries)
: Parent(num_rows, num_cols, num_entries),
row_offsets(num_rows + 1),
column_indices(num_entries),
values(num_entries) {}
/*! Construct a \p csr_matrix from another matrix.
*
* \tparam MatrixType Type of input matrix used to create this \p
* csr_matrix.
*
* \param matrix Another sparse or dense matrix.
*/
template <typename MatrixType>
csr_matrix(const MatrixType& matrix);
/*! Resize matrix dimensions and underlying storage
*
* \param num_rows Number of rows.
* \param num_cols Number of columns.
* \param num_entries Number of nonzero matrix entries.
*/
void resize(const size_t num_rows, const size_t num_cols, const size_t num_entries);
/*! Swap the contents of two \p csr_matrix objects.
*
* \param matrix Another \p csr_matrix with the same IndexType and ValueType.
*/
void swap(csr_matrix& matrix);
/*! Assignment from another matrix.
*
* \tparam MatrixType Type of input matrix to copy into this \p
* csr_matrix.
*
* \param matrix Another sparse or dense matrix.
*/
template <typename MatrixType>
csr_matrix& operator=(const MatrixType& matrix);
}; // class csr_matrix
/*! \}
*/
/**
* \addtogroup sparse_matrix_views Sparse Matrix Views
* \ingroup sparse_matrices
* \{
*/
/**
* \brief View of a \p csr_matrix
*
* \tparam ArrayType1 Type of \c row_offsets array view
* \tparam ArrayType2 Type of \c column_indices array view
* \tparam ArrayType3 Type of \c values array view
* \tparam IndexType Type used for matrix indices (e.g. \c int).
* \tparam ValueType Type used for matrix values (e.g. \c float).
* \tparam MemorySpace A memory space (e.g. \c cusp::host_memory or \c cusp::device_memory)
*
* \par Overview
* A \p csr_matrix_view is a sparse matrix view of a matrix in CSR format
* constructed from existing data or iterators. All entries in the \p csr_matrix are
* sorted according to rows and internally within each row sorted by
* column indices.
*
* \note The matrix entries must be sorted by row index.
* \note The matrix should not contain duplicate entries.
*
* \par Example
* The following code snippet demonstrates how to create a 4-by-3
* \p csr_matrix_view on the host with 6 nonzeros.
*
* \code
* // include csr_matrix header file
* #include <cusp/csr_matrix.h>
* #include <cusp/print.h>
*
* int main()
* {
* typedef cusp::array1d<int,cusp::host_memory> IndexArray;
* typedef cusp::array1d<float,cusp::host_memory> ValueArray;
*
* typedef typename IndexArray::view IndexArrayView;
* typedef typename ValueArray::view ValueArrayView;
*
* // initialize rows, columns, and values
* IndexArray row_offsets(6);
* IndexArray column_indices(6);
* ValueArray values(6);
*
* // initialize matrix entries on host
* row_offsets[0] = 0; // first offset is always zero
* row_offsets[1] = 2;
* row_offsets[2] = 2;
* row_offsets[3] = 3;
* row_offsets[4] = 6; // last offset is always num_entries
*
* column_indices[0] = 0; values[0] = 10;
* column_indices[1] = 2; values[1] = 20;
* column_indices[2] = 2; values[2] = 30;
* column_indices[3] = 0; values[3] = 40;
* column_indices[4] = 1; values[4] = 50;
* column_indices[5] = 2; values[5] = 60;
*
* // allocate storage for (4,3) matrix with 6 nonzeros
* cusp::csr_matrix_view<IndexArrayView,IndexArrayView,ValueArrayView> A(
* 4,3,6,
* cusp::make_array1d_view(row_offsets),
* cusp::make_array1d_view(column_indices),
* cusp::make_array1d_view(values));
*
* // A now represents the following matrix
* // [10 0 20]
* // [ 0 0 0]
* // [ 0 0 30]
* // [40 50 60]
*
* // print the constructed csr_matrix
* cusp::print(A);
*
* // change first entry in values array
* values[0] = -1;
*
* // print the updated matrix view
* cusp::print(A);
* }
* \endcode
*/
template <typename ArrayType1,
typename ArrayType2,
typename ArrayType3,
typename IndexType = typename ArrayType1::value_type,
typename ValueType = typename ArrayType3::value_type,
typename MemorySpace = typename cusp::minimum_space<
typename ArrayType1::memory_space,
typename ArrayType2::memory_space,
typename ArrayType3::memory_space>::type >
class csr_matrix_view : public cusp::detail::matrix_base<IndexType,ValueType,MemorySpace,cusp::csr_format>
{
private:
typedef cusp::detail::matrix_base<IndexType,ValueType,MemorySpace,cusp::csr_format> Parent;
public:
/*! \cond */
typedef ArrayType1 row_offsets_array_type;
typedef ArrayType2 column_indices_array_type;
typedef ArrayType3 values_array_type;
typedef typename cusp::csr_matrix<IndexType, ValueType, MemorySpace> container;
typedef typename cusp::csr_matrix_view<ArrayType1, ArrayType2, ArrayType3, IndexType, ValueType, MemorySpace> view;
/*! \endcond */
/*! Storage for the row offsets of the CSR data structure. Also called the "row pointer" array.
*/
row_offsets_array_type row_offsets;
/*! Storage for the column indices of the CSR data structure.
*/
column_indices_array_type column_indices;
/*! Storage for the nonzero entries of the CSR data structure.
*/
values_array_type values;
/**
* Construct an empty \p csr_matrix_view.
*/
csr_matrix_view(void)
: Parent() {}
/*! Construct a \p csr_matrix_view with a specific shape and number of nonzero entries
* from existing arrays denoting the row offsets, column indices, and
* values.
*
* \param num_rows Number of rows.
* \param num_cols Number of columns.
* \param num_entries Number of nonzero matrix entries.
* \param row_offsets Array containing the row offsets.
* \param column_indices Array containing the column indices.
* \param values Array containing the values.
*/
csr_matrix_view(const size_t num_rows,
const size_t num_cols,
const size_t num_entries,
ArrayType1 row_offsets,
ArrayType2 column_indices,
ArrayType3 values)
: Parent(num_rows, num_cols, num_entries),
row_offsets(row_offsets),
column_indices(column_indices),
values(values) {}
// construct from existing CSR matrix or view
csr_matrix_view(csr_matrix<IndexType,ValueType,MemorySpace>& matrix)
: Parent(matrix),
row_offsets(matrix.row_offsets),
column_indices(matrix.column_indices),
values(matrix.values) {}
// construct from existing CSR matrix or view
csr_matrix_view(const csr_matrix<IndexType,ValueType,MemorySpace>& matrix)
: Parent(matrix),
row_offsets(matrix.row_offsets),
column_indices(matrix.column_indices),
values(matrix.values) {}
// construct from existing CSR matrix or view
csr_matrix_view(csr_matrix_view& matrix)
: Parent(matrix),
row_offsets(matrix.row_offsets),
column_indices(matrix.column_indices),
values(matrix.values) {}
// construct from existing CSR matrix or view
csr_matrix_view(const csr_matrix_view& matrix)
: Parent(matrix),
row_offsets(matrix.row_offsets),
column_indices(matrix.column_indices),
values(matrix.values) {}
/*! Resize matrix dimensions and underlying storage
*
* \param num_rows Number of rows.
* \param num_cols Number of columns.
* \param num_entries Number of nonzero matrix entries.
*/
void resize(const size_t num_rows, const size_t num_cols, const size_t num_entries);
};
/* Convenience functions */
template <typename ArrayType1,
typename ArrayType2,
typename ArrayType3>
csr_matrix_view<ArrayType1,ArrayType2,ArrayType3>
make_csr_matrix_view(size_t num_rows,
size_t num_cols,
size_t num_entries,
ArrayType1 row_offsets,
ArrayType2 column_indices,
ArrayType3 values)
{
return csr_matrix_view<ArrayType1,ArrayType2,ArrayType3>
(num_rows, num_cols, num_entries,
row_offsets, column_indices, values);
}
template <typename ArrayType1,
typename ArrayType2,
typename ArrayType3,
typename IndexType,
typename ValueType,
typename MemorySpace>
csr_matrix_view<ArrayType1,ArrayType2,ArrayType3,IndexType,ValueType,MemorySpace>
make_csr_matrix_view(const csr_matrix_view<ArrayType1,ArrayType2,ArrayType3,IndexType,ValueType,MemorySpace>& m)
{
return csr_matrix_view<ArrayType1,ArrayType2,ArrayType3,IndexType,ValueType,MemorySpace>(m);
}
template <typename IndexType, typename ValueType, class MemorySpace>
typename csr_matrix<IndexType,ValueType,MemorySpace>::view
make_csr_matrix_view(csr_matrix<IndexType,ValueType,MemorySpace>& m)
{
return make_csr_matrix_view
(m.num_rows, m.num_cols, m.num_entries,
make_array1d_view(m.row_offsets),
make_array1d_view(m.column_indices),
make_array1d_view(m.values));
}
template <typename IndexType, typename ValueType, class MemorySpace>
typename csr_matrix<IndexType,ValueType,MemorySpace>::const_view
make_csr_matrix_view(const csr_matrix<IndexType,ValueType,MemorySpace>& m)
{
return make_csr_matrix_view
(m.num_rows, m.num_cols, m.num_entries,
make_array1d_view(m.row_offsets),
make_array1d_view(m.column_indices),
make_array1d_view(m.values));
}
/*! \}
*/
} // end namespace cusp
#include <cusp/detail/csr_matrix.inl>
| [
"it.hisas@gmail.com"
] | it.hisas@gmail.com |
aa64fb8acc52371189375979a3716f6920030aaf | ba02d6a763de289564d2f1655fab7ba5eed6e510 | /cocos2dx/include/CCTouchDispatcher.h | f32bf2f1333218377049fdfbfbb67f217428893f | [] | no_license | krumichan/Portfolio-Cocos2DMetalSlug | 136a1f67c89dbc562f9091c6da4f547efc6f3a87 | eb4549f91c22d8701353b403736738f50a8ca24a | refs/heads/master | 2023-04-06T18:12:35.198481 | 2021-04-15T12:46:35 | 2021-04-15T12:46:35 | 358,256,284 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,549 | h | /****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
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 __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
#define __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
#include "CCTouchDelegateProtocol.h"
#include "NSObject.h"
#include "NSMutableArray.h"
namespace cocos2d {
typedef enum
{
ccTouchSelectorBeganBit = 1 << 0,
ccTouchSelectorMovedBit = 1 << 1,
ccTouchSelectorEndedBit = 1 << 2,
ccTouchSelectorCancelledBit = 1 << 3,
ccTouchSelectorAllBits = ( ccTouchSelectorBeganBit | ccTouchSelectorMovedBit | ccTouchSelectorEndedBit | ccTouchSelectorCancelledBit),
} ccTouchSelectorFlag;
enum {
ccTouchBegan,
ccTouchMoved,
ccTouchEnded,
ccTouchCancelled,
ccTouchMax,
};
class NSSet;
class UIEvent;
struct ccTouchHandlerHelperData {
// we only use the type
// void (StandardTouchDelegate::*touchesSel)(NSSet*, UIEvent*);
// void (TargetedTouchDelegate::*touchSel)(NSTouch*, UIEvent*);
int m_type;
};
class CCX_DLL EGLTouchDelegate
{
public:
virtual void touchesBegan(NSSet* touches, UIEvent* pEvent) = 0;
virtual void touchesMoved(NSSet* touches, UIEvent* pEvent) = 0;
virtual void touchesEnded(NSSet* touches, UIEvent* pEvent) = 0;
virtual void touchesCancelled(NSSet* touches, UIEvent* pEvent) = 0;
virtual ~EGLTouchDelegate() {}
};
class CCTouchHandler;
struct _ccCArray;
/** @brief CCTouchDispatcher.
Singleton that handles all the touch events.
The dispatcher dispatches events to the registered TouchHandlers.
There are 2 different type of touch handlers:
- Standard Touch Handlers
- Targeted Touch Handlers
The Standard Touch Handlers work like the CocoaTouch touch handler: a set of touches is passed to the delegate.
On the other hand, the Targeted Touch Handlers only receive 1 touch at the time, and they can "swallow" touches (avoid the propagation of the event).
Firstly, the dispatcher sends the received touches to the targeted touches.
These touches can be swallowed by the Targeted Touch Handlers. If there are still remaining touches, then the remaining touches will be sent
to the Standard Touch Handlers.
@since v0.8.0
*/
class CCX_DLL CCTouchDispatcher : public NSObject, public EGLTouchDelegate
{
public:
~CCTouchDispatcher();
bool init(void);
CCTouchDispatcher() {}
public:
/** Whether or not the events are going to be dispatched. Default: true */
bool isDispatchEvents(void);
void setDispatchEvents(bool bDispatchEvents);
/** Adds a standard touch delegate to the dispatcher's list.
See StandardTouchDelegate description.
IMPORTANT: The delegate will be retained.
*/
void addStandardDelegate(CCTouchDelegate *pDelegate, int nPriority);
/** Adds a targeted touch delegate to the dispatcher's list.
See TargetedTouchDelegate description.
IMPORTANT: The delegate will be retained.
*/
void addTargetedDelegate(CCTouchDelegate *pDelegate, int nPriority, bool bSwallowsTouches);
/** Removes a touch delegate.
The delegate will be released
*/
void removeDelegate(CCTouchDelegate *pDelegate);
/** Removes all touch delegates, releasing all the delegates */
void removeAllDelegates(void);
/** Changes the priority of a previously added delegate. The lower the number,
the higher the priority */
void setPriority(int nPriority, CCTouchDelegate *pDelegate);
void touches(NSSet *pTouches, UIEvent *pEvent, unsigned int uIndex);
virtual void touchesBegan(NSSet* touches, UIEvent* pEvent);
virtual void touchesMoved(NSSet* touches, UIEvent* pEvent);
virtual void touchesEnded(NSSet* touches, UIEvent* pEvent);
virtual void touchesCancelled(NSSet* touches, UIEvent* pEvent);
public:
/** singleton of the CCTouchDispatcher */
static CCTouchDispatcher* sharedDispatcher();
protected:
void forceRemoveDelegate(CCTouchDelegate *pDelegate);
void forceAddHandler(CCTouchHandler *pHandler, NSMutableArray<CCTouchHandler*> *pArray);
void forceRemoveAllDelegates(void);
protected:
NSMutableArray<CCTouchHandler*> *m_pTargetedHandlers;
NSMutableArray<CCTouchHandler*> *m_pStandardHandlers;
bool m_bLocked;
bool m_bToAdd;
bool m_bToRemove;
NSMutableArray<CCTouchHandler*> *m_pHandlersToAdd;
struct _ccCArray *m_pHandlersToRemove;
bool m_bToQuit;
bool m_bDispatchEvents;
// 4, 1 for each type of event
struct ccTouchHandlerHelperData m_sHandlerHelperData[ccTouchMax];
};
}//namespace cocos2d
#endif // __TOUCH_DISPATCHER_CCTOUCH_DISPATCHER_H__
| [
"lovelybarry@naver.com"
] | lovelybarry@naver.com |
623616338a79f6eaab60ba4a5c011fb4963fb2c5 | 8837fc42da195e1d38aed0a65e9b5da18cebc838 | /Lab6/Lab6/ExtendedTest.cpp | 6381cc1804f0a0cb0d1977bf6b7cf860f54e8269 | [] | no_license | alexovidiupopa/Data-Structures-and-Algorithms- | 52bc3f7fc8b32571d1e0a5ca71f4103c4a318cb1 | a6dcf0653aa7c51cb176e346b6a63c563290bfee | refs/heads/master | 2020-05-21T10:20:52.413279 | 2019-05-27T14:46:39 | 2019-05-27T14:46:39 | 186,006,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,221 | cpp | #include <exception>
#include <assert.h>
#include <algorithm>
#include <vector>
#include "SortedMap.h"
#include "SMIterator.h"
#include "ExtendedTest.h"
#include <iostream>
using namespace std;
bool increasing(TKey c1, TKey c2) {
if (c1 <= c2) {
return true;
}
else {
return false;
}
}
bool decreasing(TKey c1, TKey c2) {
if (c1 >= c2) {
return true;
}
else {
return false;
}
}
void testCreate() {
SortedMap sm(increasing);
assert(sm.size() == 0);
assert(sm.isEmpty());
SMIterator it = sm.iterator();
it.first();
assert(!it.valid());
try {
it.next();
assert(false);
}
catch (exception&) {
assert(true);
}
try {
it.getCurrent();
assert(false);
}
catch (exception&) {
assert(true);
}
for (int i = 0; i < 10; i++) {
assert(sm.search(i) == NULL_TVALUE);
}
for (int i = -10; i < 10; i++) {
assert(sm.remove(i) == NULL_TVALUE);
}
}
void testSearch(Relation r) {
SortedMap sm(r);
int cMin = 0;
int cMax = 10;
try {
for (int i = cMin; i <= cMax; i++) {
sm.add(i, i + 1);
}
assert(true);
}
catch (exception&) {
assert(false);
}
int intervalDim = 10;
for (int i = cMin; i <= cMax; i++) {
assert(sm.search(i) == i + 1);
}
for (int i = cMin - intervalDim; i < cMin; i++) {
assert(sm.search(i) == NULL_TVALUE);
}
for (int i = cMax + 1; i < cMax + intervalDim; i++) {
assert(sm.search(i) == NULL_TVALUE);
}
}
void testSearch() {
testSearch(increasing);
testSearch(decreasing);
}
vector<int> keysInRandomOrder(int cMin, int cMax) {
vector<int> keys;
for (int c = cMin; c <= cMax; c++) {
keys.push_back(c);
}
int n = keys.size();
for (int i = 0; i < n - 1; i++) {
int j = i + rand() % (n - i);
swap(keys[i], keys[j]);
}
return keys;
}
void populateSMEmpty(SortedMap& sm, int cMin, int cMax) {
vector<int> keys = keysInRandomOrder(cMin, cMax);
int n = keys.size();
for (int i = 0; i < n; i++) {
assert(sm.add(keys[i], keys[i]) == NULL_TVALUE);
}
}
void rePopulateSMShift(SortedMap& sm, int cMin, int cMax, int shift) {
vector<int> keys = keysInRandomOrder(cMin, cMax);
int n = keys.size();
for (int i = 0; i < n; i++) {
assert(sm.add(keys[i], keys[i] - shift) == keys[i]);
}
}
void populateSMShift(SortedMap& sm, int cMin, int cMax, int shift) {
vector<int> keys = keysInRandomOrder(cMin, cMax);
int n = keys.size();
for (int i = 0; i < n; i++) {
sm.add(keys[i], keys[i] - shift);
}
}
void testAddAndSearch(Relation r) {
SortedMap sm(r);
int cMin = 100;
int cMax = 200;
populateSMEmpty(sm, cMin, cMax);
for (int c = cMin; c <= cMax; c++) {
assert(sm.search(c) == c);
}
assert(sm.size() == (cMax - cMin + 1));
rePopulateSMShift(sm, cMin, cMax, 1);
assert(sm.size() == (cMax - cMin + 1));
populateSMShift(sm, 2 * cMax, 3 * cMax, 2 * cMax - cMin);
for (int c = 2 * cMax; c <= 3 * cMax; c++) {
assert(sm.search(c) == c - 2 * cMax + cMin);
}
assert(sm.size() == (cMax - cMin + 1) + (cMax + 1));
SMIterator it = sm.iterator();
it.first();
if (it.valid()) {
TKey cPrec = it.getCurrent().first;
assert(sm.search(cPrec) != NULL_TVALUE);
it.next();
while (it.valid()) {
TKey c = it.getCurrent().first;
assert(r(cPrec, c));
assert(sm.search(c) != NULL_TVALUE);
cPrec = c;
it.next();
}
}
}
void testAdd() {
testAddAndSearch(increasing);
testAddAndSearch(decreasing);
}
void testRemoveAndSearch(Relation r) {
SortedMap sm(r);
int cMin = 10;
int cMax = 20;
populateSMEmpty(sm, cMin, cMax);
for (int c = cMax + 1; c <= 2 * cMax; c++) {
assert(sm.remove(c) == NULL_TVALUE);
}
int dim = cMax - cMin + 1;
assert(sm.size() == dim);
for (int c = cMin; c <= cMax; c++) {
assert(sm.remove(c) == c);
assert(sm.search(c) == NULL_TVALUE);
SMIterator it = sm.iterator();
it.first();
if (it.valid()) {
TKey cPrec = it.getCurrent().first;
it.next();
while (it.valid()) {
TKey c = it.getCurrent().first;
assert(r(cPrec, c));
cPrec = c;
it.next();
}
}
dim--;
assert(sm.size() == dim);
}
for (int c = cMin; c <= cMax; c++) {
assert(sm.remove(c) == NULL_TVALUE);
}
assert(sm.isEmpty());
assert(sm.size() == 0);
}
void testRemove() {
testRemoveAndSearch(increasing);
testRemoveAndSearch(decreasing);
}
void testIterator(Relation r) {
SortedMap sm(r);
SMIterator it = sm.iterator();
assert(!it.valid());
it.first();
assert(!it.valid());
int cMin = 100;
int cMax = 300;
vector<int> keys = keysInRandomOrder(cMin, cMax);
int n = keys.size();
for (int i = 0; i < n; i++) {
assert(sm.add(keys[i], keys[n - i - 1]) == NULL_TVALUE);
}
SMIterator itSM = sm.iterator();
assert(itSM.valid());
itSM.first();
assert(itSM.valid());
TKey cPrec = itSM.getCurrent().first;
for (int i = 1; i < 100; i++) {
assert(cPrec == itSM.getCurrent().first);
}
itSM.next();
while (itSM.valid()) {
TKey c = itSM.getCurrent().first;
assert(cMin <= c && c <= cMax);
assert(sm.search(c) != NULL_TVALUE);
assert(r(cPrec, c));
cPrec = c;
itSM.next();
}
}
void testQuantity() {
SortedMap sm(increasing);
int cMin = -3000;
int cMax = 3000;
vector<int> keys = keysInRandomOrder(cMin, cMax);
populateSMEmpty(sm, cMin, cMax);
for (int c = cMin; c <= cMax; c++) {
assert(sm.search(c) == c);
}
assert(sm.size() == cMax - cMin + 1);
SMIterator it = sm.iterator();
assert(it.valid());
it.first();
assert(it.valid());
for (int i = 0; i < sm.size(); i++) {
it.next();
}
assert(!it.valid());
it.first();
while (it.valid()) {
TKey c = it.getCurrent().first;
assert(sm.search(c) == c);
TValue v = it.getCurrent().second;
assert(c == v);
it.next();
}
assert(!it.valid());
for (int c = cMin - 100; c <= cMax + 100; c++) {
sm.remove(c);
assert(sm.search(c) == NULL_TVALUE);
}
assert(sm.size() == 0);
assert(sm.isEmpty());
}
void testIterator() {
testIterator(increasing);
testIterator(decreasing);
}
void testAllExtended() {
testCreate();
std::cout << "create passed" << std::endl;
testAdd();
std::cout << "add passed" << std::endl;
testSearch();
std::cout << "search passed" << std::endl;
testRemove();
std::cout << "remove passed" << std::endl;
testIterator();
std::cout << "iterator passed" << std::endl;
testQuantity();
std::cout << "quantity passed" << std::endl;
}
| [
"popaalexovidiu@gmail.com"
] | popaalexovidiu@gmail.com |
bfca342c85a7d0c5ddbbaa34b5af82c78422103d | 0f050f4bd9321a76d0dbda8fce5ae678796027b8 | /src/editor/private/graph/scripted/QScriptedNode.h | 5fd1e8ca635c0c45cd4d674899b175e6a1d847e2 | [
"MIT"
] | permissive | Dandielo/mooned-editor | 0c215fc3a2d1d24edaf8eedf11a0211c574d6772 | 72f9068e3d6daaf42c1bc4be23dce2c5a260a6e8 | refs/heads/master | 2021-05-06T14:23:11.056001 | 2019-01-21T23:15:09 | 2019-01-21T23:15:09 | 113,358,088 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,511 | h | #pragma once
#include "graph/interfaces/QNode.h"
#include "scripts/CNativeScriptObject.h"
namespace editor
{
class QScriptedNode : public QNode, public Scripts::CNativeScriptObject<QScriptedNode>
{
Q_OBJECT;
M_SCRIPT_TYPE(QScriptedNode, "CNode");
public:
QScriptedNode(editor::script::ScriptObject&& object);
virtual ~QScriptedNode() override;
void initialize(Scripts::CScriptManager* script_Manager);
void shutdown();
virtual QString name() const override;
virtual void setName(QString value);
virtual QString desc() const override;
virtual void setDesc(QString value);
virtual QColor color() const override;
virtual void setColor(QColor value);
virtual QVector<QNodePin*> inputPins() const override;
virtual QVector<QNodePin*> outputPins() const override;
virtual QNodePin* newInputPin(QString name);
virtual QNodePin* newOutputPin(QString name);
virtual QNodePin* getPin(PinType pin_type, QString name);
virtual void removePin(QNodePin* pin);
public:
asITypeInfo* scriptType() const { return _type; }
protected:
virtual bool event(QEvent* ev) override;
protected:
Scripts::CScriptManager* _script_manager;
asITypeInfo* _type;
QString _name;
QString _description;
QColor _color;
QVector<QNodePin*> _input_pins;
QVector<QNodePin*> _output_pins;
};
}
| [
"daniel.penkala@gmail.com"
] | daniel.penkala@gmail.com |
aaee75a430072b391b5e9371aba0022a60fdc534 | c5534a6df16a89e0ae8f53bcd49a6417e8d44409 | /trunk/Dependencies/Xerces/include/xercesc/validators/schema/identity/IC_Selector.hpp | de4ecaf295a437f9a438b2fefd64d959395f757a | [] | no_license | svn2github/ngene | b2cddacf7ec035aa681d5b8989feab3383dac012 | 61850134a354816161859fe86c2907c8e73dc113 | refs/heads/master | 2023-09-03T12:34:18.944872 | 2011-07-27T19:26:04 | 2011-07-27T19:26:04 | 78,163,390 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,981 | hpp | /*
* Copyright 2001-2004 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/*
* $Id: IC_Selector.hpp 176026 2004-09-08 13:57:07Z peiyongz $
*/
#if !defined(IC_SELECTOR_HPP)
#define IC_SELECTOR_HPP
// ---------------------------------------------------------------------------
// Includes
// ---------------------------------------------------------------------------
#include <xercesc/validators/schema/identity/XPathMatcher.hpp>
#include <xercesc/internal/XSerializable.hpp>
XERCES_CPP_NAMESPACE_BEGIN
// ---------------------------------------------------------------------------
// Forward Declaration
// ---------------------------------------------------------------------------
class FieldActivator;
class VALIDATORS_EXPORT IC_Selector : public XSerializable, public XMemory
{
public:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
IC_Selector(XercesXPath* const xpath,
IdentityConstraint* const identityConstraint);
~IC_Selector();
// -----------------------------------------------------------------------
// operators
// -----------------------------------------------------------------------
bool operator== (const IC_Selector& other) const;
bool operator!= (const IC_Selector& other) const;
// -----------------------------------------------------------------------
// Getter methods
// -----------------------------------------------------------------------
XercesXPath* getXPath() const { return fXPath; }
IdentityConstraint* getIdentityConstraint() const { return fIdentityConstraint; }
// -----------------------------------------------------------------------
// Factory methods
// -----------------------------------------------------------------------
XPathMatcher* createMatcher(FieldActivator* const fieldActivator,
const int initialDepth,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
/***
* Support for Serialization/De-serialization
***/
DECL_XSERIALIZABLE(IC_Selector)
IC_Selector(MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
private:
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
IC_Selector(const IC_Selector& other);
IC_Selector& operator= (const IC_Selector& other);
// -----------------------------------------------------------------------
// Data members
// -----------------------------------------------------------------------
XercesXPath* fXPath;
IdentityConstraint* fIdentityConstraint;
};
class VALIDATORS_EXPORT SelectorMatcher : public XPathMatcher
{
public:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
~SelectorMatcher() {}
int getInitialDepth() const { return fInitialDepth; }
// -----------------------------------------------------------------------
// XMLDocumentHandler methods
// -----------------------------------------------------------------------
void startDocumentFragment();
void startElement(const XMLElementDecl& elemDecl,
const unsigned int urlId,
const XMLCh* const elemPrefix,
const RefVectorOf<XMLAttr>& attrList,
const unsigned int attrCount);
void endElement(const XMLElementDecl& elemDecl,
const XMLCh* const elemContent);
private:
// -----------------------------------------------------------------------
// Constructors/Destructor
// -----------------------------------------------------------------------
SelectorMatcher(XercesXPath* const anXPath,
IC_Selector* const selector,
FieldActivator* const fieldActivator,
const int initialDepth,
MemoryManager* const manager = XMLPlatformUtils::fgMemoryManager);
// -----------------------------------------------------------------------
// Unimplemented contstructors and operators
// -----------------------------------------------------------------------
SelectorMatcher(const SelectorMatcher& other);
SelectorMatcher& operator= (const SelectorMatcher& other);
// -----------------------------------------------------------------------
// Friends
// -----------------------------------------------------------------------
friend class IC_Selector;
// -----------------------------------------------------------------------
// Data members
// -----------------------------------------------------------------------
int fInitialDepth;
int fElementDepth;
int fMatchedDepth;
IC_Selector* fSelector;
FieldActivator* fFieldActivator;
};
XERCES_CPP_NAMESPACE_END
#endif
/**
* End of file IC_Selector.hpp
*/
| [
"Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57"
] | Riddlemaster@fdc6060e-f348-4335-9a41-9933a8eecd57 |
8c3af177d3b4400533c3241339858b8cf2fa8c3b | 9d13d7fc23e96cb35ddc0f5bba309d0478b4a253 | /a2oj/Ladders/below-1300/155A.cpp | b038e96814d746817ab82a1a443e059dc9581e20 | [] | no_license | mayankDhiman/cp | 68941309908f1add47855bde188d43fe861b9669 | c04cd4aaff9cedb6328dff097675307498210374 | refs/heads/master | 2021-07-22T04:05:46.968566 | 2021-02-05T16:17:58 | 2021-02-05T16:17:58 | 241,451,797 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 650 | cpp | using namespace std;
#include <bits/stdc++.h>
#define ll long long
#define db double
#define ldb long double
#define vll vector <ll>
#define debug(x) cout << (#x) << " = " << (x) << endl;
#define pb push_back
#define speed ios_bas::sync_with_stdio(0); cin.tie(0); cout.tie(0);
int main()
{
ll n; cin >> n; ll a[n]; for (ll i = 0; i < n; i ++) cin >> a[i];
ll maxx = a[0], minn = a[0];
ll res = 1;
if (a[1] == a[0] or n == 1) res -= 1;
for (ll i = 2; i < n; i ++)
{
if (a[i - 1] > maxx) maxx = a[i - 1];
if (a[i - 1] < minn) minn = a[i - 1];
if ((a[i] > maxx) || (a[i] < minn))
res ++;
}
cout << res;
return 0;
}
| [
"mdhiman536@gmail.com"
] | mdhiman536@gmail.com |
2b81248236d2417803463155b22855519ede35b2 | c59191babe8b6909eb12ac2bb1e7cfd3cd919e65 | /include/painting2/RenderTargetCtx.h | b1a2cf8b60fe5c9494233db88fc96223311cc352 | [
"MIT"
] | permissive | xzrunner/painting2 | ab5667476ada3d0c9b40a7266ec650d7a8b21bf3 | c16e0133adf27a877b40b8fce642b5a42e043d09 | refs/heads/master | 2021-05-04T02:52:14.167266 | 2020-08-05T23:27:27 | 2020-08-05T23:27:27 | 120,367,182 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 438 | h | //#pragma once
//
//#include <memory>
//
//namespace pt2
//{
//
//class Shader;
//
//class RenderTargetCtx
//{
//public:
// RenderTargetCtx(ur::RenderContext& rc, const std::shared_ptr<Shader>& shader,
// int width, int height);
// ~RenderTargetCtx();
//
//private:
// ur::RenderContext& m_rc;
// std::shared_ptr<Shader> m_shader = nullptr;
//
// int m_vp_x, m_vp_y, m_vp_w, m_vp_h;
//
//}; // RenderTargetCtx
//
//} | [
"xzrunner@gmail.com"
] | xzrunner@gmail.com |
a73c7e9d4d2b8470b31388f25ab1c573e0aaa7ac | cdf0a8ac3ae4e2e9ed3d35f0f5e3676c010716f2 | /test/unit_test.h | 8bb1a6e0f477f40b70102581de36162c1d113426 | [
"MIT"
] | permissive | ValensTry/ValensLib | b1e473f7e1825852fe11379a8b4256df2e843081 | f2e311d38815836ba472e71d98ec97864e880fe1 | refs/heads/master | 2020-06-25T22:45:42.141782 | 2019-07-29T13:24:49 | 2019-07-29T13:24:49 | 199,444,054 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,975 | h | #ifndef _UNIT_TEST_HPP_
#define _UNIT_TEST_HPP_
#include <vector>
#include <typeinfo>
#include <cstring>
#include <cstdio>
#include <cmath>
#define TEST_NAME(test_name) test_name##_TEST
#define TEST(test_name) \
class TEST_NAME(test_name) : public TestCase \
{ \
public: \
TEST_NAME(test_name)(const char *name):TestCase(name) { } \
virtual void Run(); \
private: \
static TestCase* const test_case_; \
}; \
TestCase* const TEST_NAME(test_name)::test_case_ = UnitTest::GetInstance()->RegisterTestCase( \
new TEST_NAME(test_name)(#test_name)); \
void TEST_NAME(test_name)::Run()
#define RUN_ALL_TESTS(str) UnitTest::GetInstance()->Run(str);
#define FORMAT_RED(_S) "\033[0;31m"#_S"\033[0m"
#define FORMAT_GREEN(_S) "\033[0;32m"#_S"\033[0m"
#define FORMAT_YELLOW(_S) "\033[0;33m"#_S"\033[0m"
#define FORMAT_BULE(_S) "\033[0;34m"#_S"\033[0m"
#define FORMAT_PURPLE(_S) "\033[0;35m"#_S"\033[0m"
typedef enum OperatorType
{
OPERATOR_TYPE_EQ,
OPERATOR_TYPE_NE,
OPERATOR_TYPE_GT,
OPERATOR_TYPE_LT,
OPERATOR_TYPE_GE,
OPERATOR_TYPE_LE,
OPERATOR_TYPE_BT
} OperatorType_E;
class TestCase
{
public:
TestCase(const char *CaseName_F) :
m_CaseName_(CaseName_F),
m_TestResult_(false)
{ };
virtual ~TestCase() { }
virtual void Run() = 0;
const char* getCaseName() const { return m_CaseName_; }
bool getTestResult() { return m_TestResult_; }
void setTestResult(bool &&result_F) { m_TestResult_= result_F; }
private:
const char* m_CaseName_;
bool m_TestResult_;
};
class UnitTest
{
public:
static UnitTest* GetInstance()
{
static UnitTest s_instUnitTest;
return &s_instUnitTest;
}
~UnitTest()
{
for (auto i = m_vecTestCases_.begin(); i != m_vecTestCases_.end(); ++i)
delete* i;
}
TestCase* RegisterTestCase(TestCase *testCase_F)
{
m_vecTestCases_.push_back(testCase_F);
return testCase_F;
}
bool Run(const char *str)
{
m_bTestResult_ = true;
printf("\033[33m[ Start ] Unit Tests\033[0m\n\n");
m_iAll_ = 0;
for (auto it = m_vecTestCases_.begin(); it != m_vecTestCases_.end(); ++it) {
TestCase *test_case = *it;
if (str && !strstr(test_case->getCaseName(), str)) {
continue;
}
++m_iAll_;
m_pinstCurrentTestCase_ = test_case;
m_pinstCurrentTestCase_->setTestResult(true);
printf("\033[34m[ Run ] \033[0m%s\n", test_case->getCaseName());
test_case->Run();
if (test_case->getTestResult())
printf("\033[32m[ Pass ] \033[0m%s\n", test_case->getCaseName());
else
printf("\033[31m[ Fail ] \033[0m%s\n", test_case->getCaseName());
if (test_case->getTestResult()) {
++m_iPassedNum_;
} else {
++m_iFailedNum_;
m_bTestResult_ = false;
}
}
printf("\n\033[33m[ ALL ] \033[33;1m%d\033[0m\n", m_iAll_);
printf("\033[32m[ PASS ] \033[32;1m%d\033[0m\n", m_iPassedNum_);
printf("\033[31m[ FAIL ] \033[31;1m%d\033[0m\n", m_iFailedNum_);
return !m_bTestResult_;
}
TestCase& getCrtTestCase(){ return (*m_pinstCurrentTestCase_); }
private:
UnitTest():
m_pinstCurrentTestCase_(nullptr),
m_bTestResult_(false),
m_iAll_(0),
m_iPassedNum_(0),
m_iFailedNum_(0)
{}
TestCase *m_pinstCurrentTestCase_;
bool m_bTestResult_;
int m_iAll_;
int m_iPassedNum_;
int m_iFailedNum_;
std::vector<TestCase*> m_vecTestCases_;
};
template <class ElemType>
bool CheckNumericalData(ElemType left_value, ElemType right_value,
const char *str_left_value, const char *str_right_value,
const char *file_name, const unsigned long line_num,
OperatorType operator_type)
{
bool condition = false;
char str_operator[5] = {0};
switch (operator_type) {
case OPERATOR_TYPE_EQ:
if (typeid(ElemType) == typeid(double))
condition = !(std::fabs(left_value - right_value) < 1e-8);
else if (typeid(ElemType) == typeid(float))
condition = !(std::fabs(left_value - right_value) < 1e-6);
else
condition = !(left_value == right_value);
strcpy_s(str_operator, " == ");
break;
case OPERATOR_TYPE_NE:
if (typeid(ElemType) == typeid(double))
condition = !(std::fabs(left_value - right_value) > 1e-8);
else if (typeid(ElemType) == typeid(float))
condition = !(std::fabs(left_value - right_value) > 1e-6);
else
condition = !(left_value != right_value);
strcpy_s(str_operator, " != ");
break;
case OPERATOR_TYPE_GT:
condition = !(left_value > right_value);
strcpy_s(str_operator, " > ");
break;
case OPERATOR_TYPE_LT:
condition = !(left_value < right_value);
strcpy_s(str_operator, " < ");
break;
case OPERATOR_TYPE_LE:
condition = !(left_value <= right_value);
strcpy_s(str_operator, " <= ");
break;
case OPERATOR_TYPE_GE:
condition = !(left_value >= right_value);
strcpy_s(str_operator, " >= ");
break;
default:
strcpy(str_operator, " no ");
break;
}
if (condition) {
UnitTest::GetInstance()->getCrtTestCase().setTestResult(false);
printf("\033[36;1m%s\033[0m: \033[31;1m%lu\033[0m: ", file_name, line_num);
printf("\033[33;1mExpect: \033[0m%s%s%s\n", str_left_value, str_operator, str_right_value);
}
return !condition;
}
bool CheckStrData(const char *left_value, const char *right_value,
const char *str_left_value, const char *str_right_value,
const char *file_name, const unsigned long line_num,
OperatorType operator_type)
{
bool condition = false;
char str_operator[5] = {0};
if (operator_type == OPERATOR_TYPE_EQ) {
condition = !((strcmp(left_value, right_value) == 0));
strcpy(str_operator, " == ");
}
else if (operator_type == OPERATOR_TYPE_NE) {
condition = !((strcmp(left_value, right_value) != 0));
strcpy(str_operator, " != ");
}
if (condition) {
UnitTest::GetInstance()->getCrtTestCase().setTestResult(false);
printf("\033[36;1m%s\033[0m: \033[31;1m%lu\033[0m: ", file_name, line_num);
printf("\033[33;1mExpect: \033[0m%s%s%s\n", str_left_value, str_operator, str_right_value);
}
return !condition;
}
#define CHECK_NUMERICAL_DATA(left_value, right_value, operator_type) \
CheckNumericalData(left_value, right_value, #left_value, #right_value, __FILE__, __LINE__, operator_type)
#define CHECK_STR_DATA(left_value, right_value, operator_type) \
CheckStrData(left_value, right_value, #left_value, #right_value, __FILE__, __LINE__, operator_type)
#define EXPECT_EQ(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_EQ)
#define EXPECT_NE(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_NE)
#define EXPECT_GT(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_GT)
#define EXPECT_LT(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_LT)
#define EXPECT_GE(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_GE)
#define EXPECT_LE(left_value, right_value) CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_LE)
#define ASSERT_EQ(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_EQ)) return;
#define ASSERT_NE(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_NE)) return;
#define ASSERT_GT(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_GT)) return;
#define ASSERT_LT(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_LT)) return;
#define ASSERT_GE(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_GE)) return;
#define ASSERT_LE(left_value, right_value) if (!CHECK_NUMERICAL_DATA(left_value, right_value, OPERATOR_TYPE_LE)) return;
#define EXPECT_TRUE(condition) CHECK_NUMERICAL_DATA(static_cast<bool>(condition), true, OPERATOR_TYPE_EQ)
#define EXPECT_FALSE(condition) CHECK_NUMERICAL_DATA(static_cast<bool>(condition), false, OPERATOR_TYPE_EQ)
#define ASSERT_TRUE(condition) if (!CHECK_NUMERICAL_DATA(static_cast<bool>(condition), true, OPERATOR_TYPE_EQ)) return;
#define ASSERT_FALSE(condition) if (!CHECK_NUMERICAL_DATA(static_cast<bool>(condition), false, OPERATOR_TYPE_EQ)) return;
#define EXPECT_STREQ(left_value, right_value) CHECK_STR_DATA(left_value, right_value, OPERATOR_TYPE_EQ)
#define EXPECT_STRNE(left_value, right_value) CHECK_STR_DATA(left_value, right_value, OPERATOR_TYPE_NE)
#define ASSERT_STREQ(left_value, right_value) if (!CHECK_STR_DATA(left_value, right_value, OPERATOR_TYPE_EQ)) return;
#define ASSERT_STRNE(left_value, right_value) if (!CHECK_STR_DATA(left_value, right_value, OPERATOR_TYPE_NE)) return;
#endif /* _UNIT_TEST_HPP_ */ | [
"pengwanring@live.com"
] | pengwanring@live.com |
bf04a6f9065f6632b812dc6e917f56e7757be6d6 | 8137dca5c66e72d8fe6f03d8bcbbf916512672ac | /1640.cpp | 994422b9580cdfa886e06f212de3d95f23e6ee71 | [] | no_license | amanharitsh123/CSESProblemSet | 38f8a8d23e6b35963ead3a416926487f76520611 | f1218e367980fc914425e3c9cfa8d0275d29c59d | refs/heads/master | 2022-11-24T06:34:05.742324 | 2020-07-30T19:30:12 | 2020-07-30T19:30:12 | 275,089,924 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,377 | cpp | #include<bits/stdc++.h>
using namespace std;
typedef long long int lli;
#define all(arr) arr.begin(),arr.end()
#define f first
#define s second
#define debug1(x) cout<<x<<"\n"
#define debug2(x,y) cout<<x<<" "<<y<<"\n"
#define debug3(x,y,z) cout<<x<<" "<<y<<" "<<z<<"\n"
#define nl cout<<"\n";
#define pq priority_queue
#define inf 0x3f3f3f3f
#define test cout<<"abcd\n";
#define pi pair<int,int>
#define pii pair<int,pi>
#define pb push_back
#define gc getchar_unlocked
#define fo(i,n) for(i=0;i<n;i++)
#define Fo(i,k,n) for(i=k;k<n?i<n:i>n;k<n?i+=1:i-=1)
#define ll long long
#define si(x) scanf("%d",&x)
#define sl(x) scanf("%lld",&x)
#define ss(s) scanf("%s",s)
#define pl(x) printf("%lld\n",x)
#define ps(s) printf("%s\n",s)
#define deb(x) cout << #x << "=" << x << endl
#define deb2(x, y) cout << #x << "=" << x << "," << #y << "=" << y << endl
#define pb push_back
#define mp make_pair
#define F first
#define S second
#define clr(x) memset(x, 0, sizeof(x))
#define sortall(x) sort(all(x))
#define tr(it, a) for(auto it = a.begin(); it != a.end(); it++)
#define PI 3.1415926535897932384626
#define MOD 1000000007
#define space ' '
typedef pair<ll, ll> pl;
typedef vector<int> vi;
typedef vector<ll> vl;
typedef vector<pii> vpii;
typedef vector<pl> vpl;
typedef vector<vi> vvi;
typedef vector<vl> vvl;
template <typename T>
void input(vector<T> &arr,lli n) {
lli temp;
for(lli i=0;i<n;i++) cin>>temp, arr.push_back({temp, i+1});
}
template <typename T>
void output(vector<T> arr) {
for(auto x:arr) cout<<x<<" ";
cout<<endl;
}
template <typename T>
void input_set(set<T> &arr,lli n) {
T temp;
for(lli i=0;i<n;i++) cin>>temp, arr.insert(temp);
}
lli mul(lli a, lli b) {
return (a%MOD*b%MOD)%MOD;
}
lli power(lli a,lli b) {
lli ans = 1;
while(b > 0) {
if(b&1)
ans = mul(ans, a);
a = mul(a,a);;
b >>= 1;
}
return ans;
}
void solve() {
int n, sum;
cin >> n >> sum;
vector<pi> arr;
input(arr, n);
sortall(arr);
int i=0, j=n-1;
while(i<j) {
if(arr[i].first+arr[j].first==sum) {
cout << arr[i].second << " " << arr[j].second << endl;
return;
}
else if(arr[i].first+arr[j].first<sum)
++i;
else
--j;
}
cout << "IMPOSSIBLE" << endl;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
lli testcases=1;
while(testcases--) {
solve();
}
}
| [
"amanharitsh123@gmail.com"
] | amanharitsh123@gmail.com |
b322781c3c825bd7efce618c5839c5bb69a36c28 | 3b5614425116cf2e2dffba7479a27b1f2c9d45e1 | /src/primitive.hpp | 322ff0b61fe1f65af36ea65016048362b60a643e | [] | no_license | dlmackin/raymond | c209bb18dff99c62798d5148e282953012b593a9 | 11b66ff24771de8e3881e596efb3e5cca10e87ae | refs/heads/master | 2020-04-10T15:49:55.362097 | 2012-02-11T19:23:22 | 2012-02-11T19:23:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,211 | hpp | /*
* primitive.cpp
*
* CS 488: Final Project
* Fall 2011, University of Waterloo
* Diana Mackinnon (dlmackin, 20280688)
*/
#ifndef CS488_PRIMITIVE_HPP
#define CS488_PRIMITIVE_HPP
#include "algebra.hpp"
#include "intersection.hpp"
#include "ray.hpp"
class Primitive {
public:
virtual ~Primitive();
virtual bool intersect(const Ray& ray, Intersection& intersection, bool quick) = 0; // DLM
};
class Sphere : public Primitive {
public:
Sphere();
virtual ~Sphere();
virtual bool intersect(const Ray& ray, Intersection& intersection, bool quick); // DLM
virtual void calculate_uv(Intersection &intersection);
private:
Point3D m_pos;
double m_radius;
virtual Vector3D normal(Intersection& point); // DLM
};
class Cube : public Primitive {
public:
virtual ~Cube();
virtual bool intersect(const Ray& ray, Intersection& intersection, bool quick); // DLM
private:
virtual Vector3D normal(Intersection& point); // DLM
double intersect_plane(const Ray& ray, Point3D& p0, Vector3D& n, double& d); // DLM
// TODO move both of these to some util file
bool in_box(Point3D point, Point3D box_min, Point3D box_max, int plane);
Point3D closest(Point3D origin, Point3D p0, Point3D p1);
};
class NonhierSphere : public Primitive {
public:
NonhierSphere(const Point3D& pos, double radius)
: m_pos(pos), m_radius(radius)
{
}
virtual ~NonhierSphere();
virtual bool intersect(const Ray& ray, Intersection& intersection, bool quick); // DLM
virtual Vector3D normal(Intersection& point); // DLM
private:
Point3D m_pos;
double m_radius;
};
class NonhierBox : public Primitive {
public:
NonhierBox(const Point3D& pos, double size)
: m_pos(pos), m_size(size)
{
}
virtual ~NonhierBox();
virtual bool intersect(const Ray& ray, Intersection& intersection, bool quick); // DLM
virtual Vector3D normal(Intersection& point); // DLM
private:
Point3D m_pos;
double m_size;
double intersect_plane(const Ray& ray, Point3D& p0, Vector3D& n, double& d); // DLM
// TODO move both of these to some util file
bool in_box(Point3D point, Point3D box_min, Point3D box_max, int plane);
Point3D closest(Point3D origin, Point3D p0, Point3D p1);
};
#endif
| [
"diana.mackinnon@gmail.com"
] | diana.mackinnon@gmail.com |
4531f967f16985204e65e6423c936207b9aaf187 | 450ca59e2671a37c0aef9da0bf73667e60bb76ee | /Kernel/FileSystem/BlockBasedFileSystem.h | b57249cab5d868d8301f1f4179709a3a5dc25278 | [
"BSD-2-Clause"
] | permissive | mathias234/serenity | 13e65b657e67f8d0119dcc5507f2eb93f67ebd0b | e4412f1f599bea034dea608b8c7dcc4408d90066 | refs/heads/master | 2023-04-13T14:32:25.164610 | 2021-04-16T12:03:24 | 2021-04-16T20:26:52 | 244,063,274 | 0 | 0 | BSD-2-Clause | 2020-03-01T13:51:01 | 2020-03-01T00:36:07 | null | UTF-8 | C++ | false | false | 3,029 | h | /*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include <Kernel/FileSystem/FileBackedFileSystem.h>
namespace Kernel {
class BlockBasedFS : public FileBackedFS {
public:
TYPEDEF_DISTINCT_ORDERED_ID(u64, BlockIndex);
virtual ~BlockBasedFS() override;
size_t logical_block_size() const { return m_logical_block_size; };
virtual void flush_writes() override;
void flush_writes_impl();
protected:
explicit BlockBasedFS(FileDescription&);
KResult read_block(BlockIndex, UserOrKernelBuffer*, size_t count, size_t offset = 0, bool allow_cache = true) const;
KResult read_blocks(BlockIndex, unsigned count, UserOrKernelBuffer&, bool allow_cache = true) const;
bool raw_read(BlockIndex, UserOrKernelBuffer&);
bool raw_write(BlockIndex, const UserOrKernelBuffer&);
bool raw_read_blocks(BlockIndex index, size_t count, UserOrKernelBuffer&);
bool raw_write_blocks(BlockIndex index, size_t count, const UserOrKernelBuffer&);
KResult write_block(BlockIndex, const UserOrKernelBuffer&, size_t count, size_t offset = 0, bool allow_cache = true);
KResult write_blocks(BlockIndex, unsigned count, const UserOrKernelBuffer&, bool allow_cache = true);
size_t m_logical_block_size { 512 };
private:
DiskCache& cache() const;
void flush_specific_block_if_needed(BlockIndex index);
mutable OwnPtr<DiskCache> m_cache;
};
}
template<>
struct AK::Formatter<Kernel::BlockBasedFS::BlockIndex> : AK::Formatter<FormatString> {
void format(FormatBuilder& builder, Kernel::BlockBasedFS::BlockIndex value)
{
return AK::Formatter<FormatString>::format(builder, "{}", value.value());
}
};
| [
"kling@serenityos.org"
] | kling@serenityos.org |
4bd9b72c63f558fdfc0cc6e5494fd3d1ea925677 | d0c44dd3da2ef8c0ff835982a437946cbf4d2940 | /cmake-build-debug/programs_tiling/function14108/function14108_schedule_14/function14108_schedule_14.cpp | 1719ded86cd99d01e8b2af06b48378639fd1909c | [] | 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,110 | cpp | #include <tiramisu/tiramisu.h>
using namespace tiramisu;
int main(int argc, char **argv){
tiramisu::init("function14108_schedule_14");
constant c0("c0", 4096), c1("c1", 128), c2("c2", 128);
var i0("i0", 0, c0), i1("i1", 0, c1), i2("i2", 0, c2), i100("i100", 2, c0 - 2), i101("i101", 2, c1 - 2), i102("i102", 2, c2 - 2), i01("i01"), i02("i02"), i03("i03"), i04("i04"), i05("i05"), i06("i06");
input input0("input0", {i0, i1, i2}, p_int32);
computation comp0("comp0", {i100, i101, i102}, (input0(i100, i101, i102) + input0(i100 + 1, i101, i102) + input0(i100 + 2, i101, i102) - input0(i100 - 1, i101, i102) + input0(i100 - 2, i101, i102)));
comp0.tile(i100, i101, i102, 64, 32, 32, i01, i02, i03, i04, i05, i06);
comp0.parallelize(i01);
buffer buf00("buf00", {4096, 128, 128}, p_int32, a_input);
buffer buf0("buf0", {4096, 128, 128}, p_int32, a_output);
input0.store_in(&buf00);
comp0.store_in(&buf0);
tiramisu::codegen({&buf00, &buf0}, "../data/programs/function14108/function14108_schedule_14/function14108_schedule_14.o");
return 0;
} | [
"ei_mekki@esi.dz"
] | ei_mekki@esi.dz |
72b42ed93fe562406769a3a96ea19e928eb3dd36 | 0dd9cf13c4a9e5f28ae5f36e512e86de335c26b4 | /LeetCode/leetcode_fixed-point.cpp | 5e31cd4d317a485716d42fc1e0b050ed876e1204 | [] | no_license | yular/CC--InterviewProblem | 908dfd6d538ccd405863c27c65c78379e91b9fd3 | c271ea63eda29575a7ed4a0bce3c0ed6f2af1410 | refs/heads/master | 2021-07-18T11:03:07.525048 | 2021-07-05T16:17:43 | 2021-07-05T16:17:43 | 17,499,294 | 37 | 13 | null | null | null | null | UTF-8 | C++ | false | false | 341 | cpp | /*
*
* Tag: Implementation
* Time: O(n)
* Space: O(1)
*/
class Solution {
public:
int fixedPoint(vector<int>& A) {
if(A.size() == 0) {
return -1;
}
for(int i = 0; i < A.size(); ++ i) {
if(A[i] == i) {
return i;
}
}
return -1;
}
};
| [
"noreply@github.com"
] | noreply@github.com |
002c8afd08c2e7b16ce86678b26e35f9c43429cb | 6d2e09ebfed5f07176c07ddbd5e2ba675928b7a3 | /lib/dataflow/RheoSmallPtrSet.h | d81f9e189256b0da81babaee36ab0f7f43717d29 | [] | no_license | cptjazz/rheo | 626364fe797475aa198cde4a3d45b270bba8e4d4 | 88827812d71c1a1a41a72554c4e15389aee20720 | refs/heads/master | 2020-04-10T09:24:11.900582 | 2014-01-13T18:53:53 | 2014-01-13T18:53:53 | 12,245,482 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 728 | h | #ifndef RHEOSMALLPTRSET_H
#define RHEOSMALLPTRSET_H
#include "llvm/ADT/SmallPtrSet.h"
using namespace llvm;
template<typename PtrType, unsigned SmallSize>
class RheoSmallPtrSet : public SmallPtrSet<PtrType, SmallSize> {
public:
void intersect(const SmallPtrSet<PtrType, SmallSize>& other, SmallPtrSet<PtrType, SmallSize>& result) const {
for (SmallPtrSetIterator<PtrType> i = this->begin(), e = this->end(); i != e; ++i) {
if (other.count(*i))
result.insert(*i);
}
}
bool insertAll(const SmallPtrSet<PtrType, SmallSize>& other) {
size_t s = this->size();
this->insert(other.begin(), other.end());
return s != this->size();
}
};
#endif // RHEOSMALLPTRSET_H
| [
"alexander@jesner.eu"
] | alexander@jesner.eu |
542c1bf3876fe06afc393088367a57cf2186a047 | 43bc58c3892d122ba58fb0a05ca0bd9970a56bb6 | /POJ/2479/12893669_WA.cpp | 94c26817c24de120e49d7d6b690a6d2982f999f2 | [] | no_license | CSdlwr/OJ | 8f5fe75273c685ccca381ae41a2fa7055e376e34 | 224ea9cdbbad6edc25695017fe52fa12f681ac09 | refs/heads/master | 2021-01-22T10:25:41.005901 | 2016-12-11T12:57:32 | 2016-12-11T12:57:32 | 68,557,794 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,170 | cpp |
#include <iostream>
using namespace std;
#define MAX_LEN 50005
int input[MAX_LEN];
int dp1[MAX_LEN];
int dp2[MAX_LEN];
int maxlen1[MAX_LEN];
int maxlen2[MAX_LEN];
int max(int a, int b);
int main() {
int t, n;
scanf("%d", &t);
while (t-- > 0) {
int i = 0;
scanf("%d", &n);
for (; i < n; ++i)
scanf("%d", &input[i]);
dp1[0] = input[0];
maxlen1[0] = dp1[0];
for (i = 1; i < n; ++i) {
if (dp1[i-1] > 0)
dp1[i] = dp1[i-1] + input[i];
else dp1[i] = input[i];
maxlen1[i] = max(dp1[i], maxlen1[i-1]);
}
int ans = -1;
dp2[n-1] = input[n-1];
maxlen2[n-1] = dp2[n-2];
for (i = n-2; i >= 0; --i) {
if (dp2[i+1] > 0)
dp2[i] = dp2[i+1] + input[i];
else dp2[i] = input[i];
//ans = max(dp2[i+1], dp2[i]);
maxlen2[i] = max(dp2[i], maxlen2[i+1]);
}
int max = 0, tmp;
for (int i = 0; i < n-1; ++i) {
tmp = maxlen1[i] + maxlen2[i+1];
max = max < tmp ? tmp : max;
}
//cout<<max<<endl;
// for (i = 0; i < n; ++i) {
// for (int j = i + 1; j < n; ++j) {
// if ((tmp = dp1[i] + dp2[j]) > max)
// max = tmp;
// }
// }
printf("%d\n", max);
}
}
int max(int a, int b) {
return a > b ? a : b;
} | [
"luming.lv@qunar.com"
] | luming.lv@qunar.com |
ab9fc6074986ba731008fa86626f47a922c17435 | bd460043c3503792e13f989215bab562f062c826 | /exp004_optim_rough_hash/2_main.cpp | cec790b6b171c6cd12e3dd4abacaf8f206de0c29 | [] | no_license | Lgeu/ahc_rcl_2021 | 6374e223cbeca57378418da3ed4522ba5437e572 | 12a94547c9f2ad384e725793ef9022a3576d4568 | refs/heads/master | 2023-07-31T08:33:37.624319 | 2021-09-13T12:06:38 | 2021-09-13T12:06:38 | 404,201,527 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 38,492 | cpp | #ifndef NAGISS_LIBRARY_HPP
#define NAGISS_LIBRARY_HPP
#ifdef _MSC_VER
#define _CRT_SECURE_NO_WARNINGS
#endif
#include<iostream>
#include<iomanip>
#include<vector>
#include<set>
#include<map>
#include<unordered_set>
#include<unordered_map>
#include<algorithm>
#include<numeric>
#include<limits>
#include<bitset>
#include<functional>
#include<type_traits>
#include<queue>
#include<stack>
#include<array>
#include<random>
#include<utility>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<ctime>
#include<string>
#include<sstream>
#include<chrono>
#include<climits>
#ifdef _MSC_VER
#include<intrin.h>
#endif
#ifdef __GNUC__
#include<x86intrin.h>
#endif
#ifdef __GNUC__
//#pragma GCC target("avx2")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,avx2,tune=native")
#pragma GCC optimize("O3")
#pragma GCC optimize("Ofast")
//#pragma GCC optimize("unroll-loops")
#pragma clang attribute push (__attribute__((target("arch=skylake"))),apply_to=function)
/* 最後に↓を貼る
#ifdef __GNUC__
#pragma clang attribute pop
#endif
*/
#endif
// ========================== macroes ==========================
#define rep(i,n) for(ll i=0; (i)<(n); (i)++)
#define rep1(i,n) for(ll i=1; (i)<=(n); (i)++)
#define rep3(i,l,r) for(auto i=(l); (i)<(r); (i)++)
//#define NDEBUG
#ifndef NDEBUG
#define ASSERT(expr, ...) \
do { \
if(!(expr)){ \
printf("%s(%d): Assertion failed.\n", __FILE__, __LINE__); \
printf(__VA_ARGS__); \
abort(); \
} \
} while (false)
#else
#define ASSERT(...)
#endif
#define ASSERT_RANGE(value, left, right) \
ASSERT((left <= value) && (value < right), \
"`%s` (%d) is out of range [%d, %d)", #value, value, left, right)
#define CHECK(var) do{ std::cout << #var << '=' << var << endl; } while (false)
// ========================== utils ==========================
using namespace std;
using ll = long long;
constexpr double PI = 3.1415926535897932;
template<class T, class S> inline bool chmin(T& m, S q) {
if (m > q) { m = q; return true; }
else return false;
}
template<class T, class S> inline bool chmax(T& m, const S q) {
if (m < q) { m = q; return true; }
else return false;
}
// クリッピング // clamp (C++17) と等価
template<class T> inline T clipped(const T& v, const T& low, const T& high) {
return min(max(v, low), high);
}
// 2 次元ベクトル
template<typename T> struct Vec2 {
/*
y 軸正は下方向
x 軸正は右方向
回転は時計回りが正(y 軸正を上と考えると反時計回りになる)
*/
T y, x;
constexpr inline Vec2() = default;
constexpr inline Vec2(const T& arg_y, const T& arg_x) : y(arg_y), x(arg_x) {}
inline Vec2(const Vec2&) = default; // コピー
inline Vec2(Vec2&&) = default; // ムーブ
inline Vec2& operator=(const Vec2&) = default; // 代入
inline Vec2& operator=(Vec2&&) = default; // ムーブ代入
template<typename S> constexpr inline Vec2(const Vec2<S>& v) : y((T)v.y), x((T)v.x) {}
inline Vec2 operator+(const Vec2& rhs) const {
return Vec2(y + rhs.y, x + rhs.x);
}
inline Vec2 operator+(const T& rhs) const {
return Vec2(y + rhs, x + rhs);
}
inline Vec2 operator-(const Vec2& rhs) const {
return Vec2(y - rhs.y, x - rhs.x);
}
template<typename S> inline Vec2 operator*(const S& rhs) const {
return Vec2(y * rhs, x * rhs);
}
inline Vec2 operator*(const Vec2& rhs) const { // x + yj とみなす
return Vec2(x * rhs.y + y * rhs.x, x * rhs.x - y * rhs.y);
}
template<typename S> inline Vec2 operator/(const S& rhs) const {
ASSERT(rhs != 0.0, "Zero division!");
return Vec2(y / rhs, x / rhs);
}
inline Vec2 operator/(const Vec2& rhs) const { // x + yj とみなす
return (*this) * rhs.inv();
}
inline Vec2& operator+=(const Vec2& rhs) {
y += rhs.y;
x += rhs.x;
return *this;
}
inline Vec2& operator-=(const Vec2& rhs) {
y -= rhs.y;
x -= rhs.x;
return *this;
}
template<typename S> inline Vec2& operator*=(const S& rhs) const {
y *= rhs;
x *= rhs;
return *this;
}
inline Vec2& operator*=(const Vec2& rhs) {
*this = (*this) * rhs;
return *this;
}
inline Vec2& operator/=(const Vec2& rhs) {
*this = (*this) / rhs;
return *this;
}
inline bool operator!=(const Vec2& rhs) const {
return x != rhs.x || y != rhs.y;
}
inline bool operator==(const Vec2& rhs) const {
return x == rhs.x && y == rhs.y;
}
inline void rotate(const double& rad) {
*this = rotated(rad);
}
inline Vec2<double> rotated(const double& rad) const {
return (*this) * rotation(rad);
}
static inline Vec2<double> rotation(const double& rad) {
return Vec2(sin(rad), cos(rad));
}
static inline Vec2<double> rotation_deg(const double& deg) {
return rotation(PI * deg / 180.0);
}
inline Vec2<double> rounded() const {
return Vec2<double>(round(y), round(x));
}
inline Vec2<double> inv() const { // x + yj とみなす
const double norm_sq = l2_norm_square();
ASSERT(norm_sq != 0.0, "Zero division!");
return Vec2(-y / norm_sq, x / norm_sq);
}
inline double l2_norm() const {
return sqrt(x * x + y * y);
}
inline double l2_norm_square() const {
return x * x + y * y;
}
inline T l1_norm() const {
return std::abs(x) + std::abs(y);
}
inline double abs() const {
return l2_norm();
}
inline double phase() const { // [-PI, PI) のはず
return atan2(y, x);
}
inline double phase_deg() const { // [-180, 180) のはず
return phase() / PI * 180.0;
}
};
template<typename T, typename S> inline Vec2<T> operator*(const S& lhs, const Vec2<T>& rhs) {
return rhs * lhs;
}
template<typename T> ostream& operator<<(ostream& os, const Vec2<T>& vec) {
os << vec.y << ' ' << vec.x;
return os;
}
// 乱数
struct Random {
using ull = unsigned long long;
ull seed;
inline Random(ull aSeed) : seed(aSeed) {
ASSERT(seed != 0ull, "Seed should not be 0.");
}
const inline ull& next() {
seed ^= seed << 9;
seed ^= seed >> 7;
return seed;
}
// (0.0, 1.0)
inline double random() {
return (double)next() / (double)ULLONG_MAX;
}
// [0, right)
inline int randint(const int right) {
return next() % (ull)right;
}
// [left, right)
inline int randint(const int left, const int right) {
return next() % (ull)(right - left) + left;
}
};
// 2 次元配列
template<class T, int height, int width> struct Board {
array<T, height * width> data;
template<class Int> constexpr inline auto& operator[](const Vec2<Int>& p) {
return data[width * p.y + p.x];
}
template<class Int> constexpr inline const auto& operator[](const Vec2<Int>& p) const {
return data[width * p.y + p.x];
}
template<class Int> constexpr inline auto& operator[](const initializer_list<Int>& p) {
return data[width * *p.begin() + *(p.begin() + 1)];
}
template<class Int> constexpr inline const auto& operator[](const initializer_list<Int>& p) const {
return data[width * *p.begin() + *(p.begin() + 1)];
}
constexpr inline void Fill(const T& fill_value) {
fill(data.begin(), data.end(), fill_value);
}
void Print() const {
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
cout << data[width * y + x] << " \n"[x == width - 1];
}
}
}
};
// キュー
template<class T, int max_size> struct Queue {
array<T, max_size> data;
int left, right;
inline Queue() : data(), left(0), right(0) {}
inline Queue(initializer_list<T> init) :
data(init.begin(), init.end()), left(0), right(init.size()) {}
inline bool empty() const {
return left == right;
}
inline void push(const T& value) {
data[right] = value;
right++;
}
inline void pop() {
left++;
}
const inline T& front() const {
return data[left];
}
template <class... Args> inline void emplace(const Args&... args) {
data[right] = T(args...);
right++;
}
inline void clear() {
left = 0;
right = 0;
}
inline int size() const {
return right - left;
}
};
// スタック // コンストラクタ呼ぶタイミングとかが考えられてなくて良くない
template<class T, int max_size> struct Stack {
array<T, max_size> data;
int right;
inline Stack() : data(), right(0) {}
inline Stack(const int n) : data(), right(0) { resize(n); }
inline Stack(const int n, const T& val) : data(), right(0) { resize(n, val); }
inline Stack(const initializer_list<T>& init) : data(), right(init.size()) {
memcpy(&data[0], init.begin(), sizeof(T) * init.size());
} // これ大丈夫か?
inline Stack(const Stack& rhs) : data(), right(rhs.right) { // コピー
for (int i = 0; i < right; i++) {
data[i] = rhs.data[i];
}
}
template<class S> inline Stack(const Stack<S, max_size>& rhs) : data(), right(rhs.right) {
for (int i = 0; i < right; i++) {
data[i] = rhs.data[i];
}
}
Stack& operator=(const Stack& rhs) {
right = rhs.right;
for (int i = 0; i < right; i++) {
data[i] = rhs.data[i];
}
return *this;
}
Stack& operator=(const vector<T>& rhs) {
right = (int)rhs.size();
ASSERT(right <= max_size, "too big vector");
for (int i = 0; i < right; i++) {
data[i] = rhs[i];
}
return *this;
}
Stack& operator=(Stack&&) = default;
inline bool empty() const {
return 0 == right;
}
inline void push(const T& value) {
ASSERT_RANGE(right, 0, max_size);
data[right] = value;
right++;
}
inline T pop() {
right--;
ASSERT_RANGE(right, 0, max_size);
return data[right];
}
const inline T& top() const {
return data[right - 1];
}
template <class... Args> inline void emplace(Args&&... args) {
ASSERT_RANGE(right, 0, max_size);
new(&data[right])T(forward(args...));
right++;
}
inline void clear() {
right = 0;
}
inline void insert(const int& idx, const T& value) {
ASSERT_RANGE(idx, 0, right + 1);
ASSERT_RANGE(right, 0, max_size);
int i = right;
right++;
while (i != idx) {
data[i] = data[i - 1];
i--;
}
data[idx] = value;
}
inline void del(const int& idx) {
ASSERT_RANGE(idx, 0, right);
right--;
for (int i = idx; i < right; i++) {
data[i] = data[i + 1];
}
}
inline int index(const T& value) const {
for (int i = 0; i < right; i++) {
if (value == data[i]) return i;
}
return -1;
}
inline void remove(const T& value) {
int idx = index(value);
ASSERT(idx != -1, "not contain the value.");
del(idx);
}
inline void resize(const int& sz) {
ASSERT_RANGE(sz, 0, max_size + 1);
for (; right < sz; right++) {
data[right].~T();
new(&data[right]) T();
}
right = sz;
}
inline void resize(const int& sz, const T& fill_value) {
ASSERT_RANGE(sz, 0, max_size + 1);
for (; right < sz; right++) {
data[right].~T();
new(&data[right]) T(fill_value);
}
right = sz;
}
inline int size() const {
return right;
}
inline T& operator[](const int n) {
ASSERT_RANGE(n, 0, right);
return data[n];
}
inline const T& operator[](const int n) const {
ASSERT_RANGE(n, 0, right);
return data[n];
}
inline T* begin() {
return (T*)data.data();
}
inline const T* begin() const {
return (const T*)data.data();
}
inline T* end() {
return (T*)data.data() + right;
}
inline const T* end() const {
return (const T*)data.data() + right;
}
inline T& front() {
ASSERT(right > 0, "no data.");
return data[0];
}
const inline T& front() const {
ASSERT(right > 0, "no data.");
return data[0];
}
inline T& back() {
ASSERT(right > 0, "no data.");
return data[right - 1];
}
const inline T& back() const {
ASSERT(right > 0, "no data.");
return data[right - 1];
}
inline bool contains(const T& value) const {
for (const auto& dat : *this) {
if (value == dat) return true;
}
return false;
}
inline vector<T> ToVector() {
return vector<T>(begin(), end());
}
inline void Print() const {
cout << '{';
for (int i = 0; i < right; i++) cout << data[i] << ",}"[i == right - 1];
cout << endl;
}
template<class S> inline auto AsType() const {
return Stack<S, max_size>(*this);
}
};
// ハッシュテーブル // うまく実装できん
template<class T, int size = 0x100000, class KeyType = unsigned long long>
struct HashMap {
array<pair<KeyType, T>, size> data;
constexpr static KeyType mask = size - 1;
constexpr static KeyType EMPTY = 0;
constexpr static KeyType DELETED = 1;
inline HashMap() {
static_assert((size & size - 1) == 0, "not pow of 2");
memset(&data[0], 0, sizeof(data));
}
const T& Get(const KeyType& key) const {
// 既に値が格納されていることを仮定
if (key == EMPTY || key == DELETED) return Get(key + (KeyType)2);
auto address = key & mask;
while (data[address].first != key) address = (address + 1) & mask;
return data[address].second;
}
const T& Get(const KeyType& key, const T& default_value) const {
// まだ値が格納されていない場合の値を指定
if (key == EMPTY || key == DELETED) return Get(key + (KeyType)2, default_value);
auto address = key & mask;
while (true) {
if (data[address].first == key) return data[address].second;
else if (data[address].first == EMPTY) return default_value;
address = (address + 1) & mask;
}
}
void Set(const KeyType& key, const T& value) {
// まだ値が格納されていないことを仮定
if (key == EMPTY || key == DELETED) return Set(key + (KeyType)2, value);
auto address = key & mask;
while (data[address].first != EMPTY && data[address].first != DELETED) address = (address + 1) & mask;
data[address].first = key;
data[address].second = value;
}
T& operator[](const KeyType& key) {
// 存在すればその値を返す
// 存在しなければ新しく作って返す
if (key == EMPTY || key == DELETED) return operator[](key + (KeyType)2);
auto address = key & mask;
while (data[address].first != EMPTY) {
if (data[address].first == key) return data[address].second;
address = (address + 1) & mask;
}
address = key & mask;
while (data[address].first != EMPTY && data[address].first != DELETED) address = (address + 1) & mask;
data[address].first = key;
new(&data[address].second) T();
return data[address].second;
}
void erase(const KeyType& key) {
// 既に値が格納されていることを仮定
if (key == EMPTY || key == DELETED) return erase(key + (KeyType)2);
auto address = key & mask;
while (data[address].first != key) address = (address + 1) & mask;
data[address].first = DELETED;
data[address].second.~T(); // これどうすればいいんだ
memset(&data[address].second, 0, sizeof(T));
}
void clear() {
// コストがでかい、デストラクタとか呼ばれない
memset(&data[0], 0, sizeof(data));
}
};
auto a = HashMap<double>();
// 時間 (秒)
inline double Time() {
return static_cast<double>(chrono::duration_cast<chrono::nanoseconds>(chrono::steady_clock::now().time_since_epoch()).count()) * 1e-9;
}
// 重複除去
template<class VectorLike> inline void Deduplicate(VectorLike& vec) {
sort(vec.begin(), vec.end());
vec.erase(unique(vec.begin(), vec.end()), vec.end());
}
// 2 分法
template<class VectorLike, typename T> inline int SearchSorted(const VectorLike& vec, const T& a) {
return lower_bound(vec.begin(), vec.end(), a) - vec.begin();
}
// argsort
template<typename T, int n, typename result_type, bool reverse = false> inline auto Argsort(const array<T, n>& vec) {
array<result_type, n> res;
iota(res.begin(), res.end(), 0);
sort(res.begin(), res.end(), [&](const result_type& l, const result_type& r) {
return reverse ? vec[l] > vec[r] : vec[l] < vec[r];
});
return res;
}
// popcount // SSE 4.2 を使うべき
inline int Popcount(const unsigned int& x) {
#ifdef _MSC_VER
return (int)__popcnt(x);
#else
return __builtin_popcount(x);
#endif
}
inline int Popcount(const unsigned long long& x) {
#ifdef _MSC_VER
return (int)__popcnt64(x);
#else
return __builtin_popcountll(x);
#endif
}
// x >> n & 1 が 1 になる最小の n ( x==0 は未定義 )
inline int CountRightZero(const unsigned int& x) {
#ifdef _MSC_VER
unsigned long r;
_BitScanForward(&r, x);
return (int)r;
#else
return __builtin_ctz(x);
#endif
}
inline int CountRightZero(const unsigned long long& x) {
#ifdef _MSC_VER
unsigned long r;
_BitScanForward64(&r, x);
return (int)r;
#else
return __builtin_ctzll(x);
#endif
}
inline double MonotonicallyIncreasingFunction(const double& h, const double& x) {
// 0 < h < 1
// f(0) = 0, f(1) = 1, f(0.5) = h
ASSERT(h > 0.0 && h < 1.0, "0 < h < 1 not satisfied");
if (h == 0.5) return x;
const double& a = (1.0 - 2.0 * h) / (h * h);
return expm1(log1p(a) * x) / a;
}
inline double MonotonicFunction(const double& start, const double& end, const double& h, const double& x) {
// h: x = 0.5 での進捗率
return MonotonicallyIncreasingFunction(h, x) * (end - start) + start;
}
#endif // NAGISS_LIBRARY_HPP
// パラメータ
constexpr int hash_table_size = 19;
constexpr int beam_width = 200;
// K: 大きいほど未来の価値が小さくなる log2/100 = 0.007 くらいのとき野菜のインフレと釣り合う?
constexpr double K_START = 0.0427583195191865; // OPTIMIZE [0.02, 0.06] LOG
constexpr double K_END = 0.04053871554652824; // OPTIMIZE [0.01, 0.05] LOG
constexpr double K_H = 0.8256980150360592; // OPTIMIZE [0.001, 0.999]
constexpr short PURCHASE_TURN_LIMIT = 805; // OPTIMIZE [780, 880]
// 0 で通常
constexpr int SUBSCORE3_TIGHT_TURN = 0;
constexpr int ROUGH_HASH = 0b00010001; // OPTIMIZE {0, 0b00000001, 0b00010001, 0b00010011, 0b00110011}
using ull = unsigned long long;
using i8 = int8_t;
using u8 = uint8_t;
using u16 = uint16_t;
// 入力
constexpr int N = 16;
constexpr int M = 5000;
constexpr int T = 1000;
array<i8, M> R;
array<i8, M> C;
array<u8, M> RC;
array<short, M> S;
array<short, M> E;
array<short, M> V;
struct alignas(32) BitBoard {
__m256i data;
union U {
__m256i raveled;
array<u16, 16> rows;
array<ull, 4> ulls;
};
inline auto& Rows() {
return ((U*)&data)->rows;
}
inline const auto& Rows() const {
return ((U*)&data)->rows;
}
inline auto NonzeroIndices() const {
auto res = Stack<u8, 256>();
alignas(32) auto d = data;
rep(i, 4) {
auto& di = ((U*)&d)->ulls[i];
while (di != 0ull) {
const auto ctz = CountRightZero(di);
res.push((u8)i * 64u + (u8)ctz);
di ^= 1ull << ctz;
}
}
return res;
}
inline bool Get(const u8& idx) const {
return ((U*)&data)->ulls[idx >> 6] >> (idx & 63u) & 1u;
}
inline void Flip(const u8& idx) {
((U*)&data)->ulls[idx >> 6] ^= 1ull << (idx & 63u);
}
inline BitBoard Left() const {
return BitBoard{ _mm256_srli_epi16(data, 1) };
}
inline BitBoard Right() const {
return BitBoard{ _mm256_slli_epi16(data, 1) };
}
inline BitBoard Up() const {
return BitBoard{ _mm256_alignr_epi8(
_mm256_permute2x128_si256(data, data, 0b10000001), data, 2 // _mm256_permute2x128_si256(data, data, 0b10000001) で data の上位ビットを取得
) }; // alignr(s1, s2, mask) := ((s1 の上位と s2 の上位) >> mask) << 16 | ((s1 の下位と s2 の下位) >> mask) シフトは 8 bit 単位
}
inline BitBoard Down() const {
return BitBoard{ _mm256_alignr_epi8(
data, _mm256_permute2x128_si256(data, data, 0b00001000), 16 - 2 // _mm256_permute2x128_si256(data, data, 0b00001000) で data の下位ビットを上位に持ってくる
) };
}
inline BitBoard& operator&=(const BitBoard& rhs) {
data = _mm256_and_si256(data, rhs.data);
return *this;
}
inline BitBoard& operator|=(const BitBoard& rhs) {
data = _mm256_or_si256(data, rhs.data);
return *this;
}
inline BitBoard& operator^=(const BitBoard& rhs) {
data = _mm256_xor_si256(data, rhs.data);
return *this;
}
inline BitBoard operator&(const BitBoard& rhs) const {
return BitBoard(*this) &= rhs;
}
inline BitBoard operator|(const BitBoard& rhs) const {
return BitBoard(*this) |= rhs;
}
inline BitBoard operator^(const BitBoard& rhs) const {
return BitBoard(*this) ^= rhs;
}
inline BitBoard operator~() const {
return BitBoard{ _mm256_xor_si256(data, _mm256_set1_epi32(-1)) };
}
inline bool Empty() const {
return _mm256_testz_si256(data, data);
}
inline BitBoard& Expand() { // 上下左右に広がる
return *this |= Down() |= Right() |= Up() |= Left();
}
void Print() const {
for (const auto& row : Rows()) {
rep(i, 16) cout << (row >> i & 1) << ",\n"[i == 15];
}
}
};
namespace test {
void TestBitBoard() {
auto bb = BitBoard{ 0 };
bb.Flip(0 * 16 + 2);
bb.Flip(2 * 16 + 4);
bb.Flip(6 * 16 + 8);
bb.Flip(255);
bb.Print();
cout << "empty" << endl;
cout << bb.Empty() << endl;
cout << "nonzero" << endl;
bb.NonzeroIndices().AsType<short>().Print();
cout << "expand" << endl;
bb.Expand();
bb.Print();
cout << "left" << endl;
bb = bb.Left();
bb.Print();
cout << "up" << endl;
bb = bb.Up();
bb.Print();
cout << "reset" << endl;
for (const auto& idx : bb.NonzeroIndices()) bb.Flip(idx);
cout << "empty" << endl;
cout << bb.Empty() << endl;
}
}
namespace board_index_functions {
u8 UpOf(u8 idx) {
if (idx < 16u) return idx;
else return idx - 16u;
}
u8 DownOf(u8 idx) {
if (idx >= 240u) return idx;
else return idx + 16u;
}
u8 RightOf(u8 idx) {
if ((idx & 15u) == 15u) return idx;
else return idx + 1u;
}
u8 LeftOf(u8 idx) {
if ((idx & 15u) == 0u) return idx;
else return idx - 1u;
}
}
namespace globals {
auto rng = Random(123456789); // random number generator
auto RNT = array<ull, 10000>(); // random number table
auto EXP_NEG_KT = array<double, 1000>();
auto v_modified = array<double, M>(); // ターンで補正した野菜の価値
auto NEIGHBOR = array<array<BitBoard, 16>, 256>(); // neighbor[idx][d] := idx から距離 d 以内の場所たち
auto s_begins = array<short, T + 1>(); // t 日目の野菜の最初のインデックス
auto order_e = array<short, M>(); // argsort(E)
auto e_begins = array<short, T + 1>(); // order_e のインデックスで、t 日目に消滅する野菜の最初のインデックス
auto start_bitboards = array<BitBoard, T>(); // そのターンに出現する野菜の位置
auto end_bitboards = array<BitBoard, T>(); // そのターンに消滅する野菜の位置
auto next_vegetable = array<short, M>(); // 同じマスに次に現れる野菜のインデックス // 次がなければ -1
// ビームサーチ中に変動
auto t = 0;
auto future_value_table = Board<double, N, N>(); // 将来生える野菜の価値
auto current_money_table = Board<short, N, N>(); // 今生えてる野菜の価値 (補正なし)
auto current_index_table = Board<short, N, N>(); // 野菜インデックス
auto current_value_table = Board<double, N, N>(); // 今と将来の野菜の価値 (補正無し)
auto high_value_indices = array<u8, 256>(); // 今と将来の野菜の価値 (補正無し) をソートしたもの
auto next_end_table = Board<short, N, N>(); // 次にそのマスの価値が落ちるタイミング // 次がなければ -1
void UpdateValueTable() {
// State::Do をする前に呼ぶ
// 出現
rep3(idx_RCSEV, globals::s_begins[t], globals::s_begins[t + 1]) {
const auto& rc = RC[idx_RCSEV];
const auto& vm = v_modified[idx_RCSEV];
const auto& v = V[idx_RCSEV];
ASSERT(t == S[idx_RCSEV], "turn がおかしいよ");
ASSERT(current_index_table.data[rc] < 0, "既に野菜があるよ");
ASSERT(current_money_table.data[rc] == 0, "既に野菜があるよ");
current_index_table.data[rc] = idx_RCSEV;
current_money_table.data[rc] = v;
future_value_table.data[rc] -= vm;
ASSERT(future_value_table.data[rc] >= -1e3, "将来の価値がマイナスになることはないはずだよ");
}
// 消滅
rep3(idx_order, e_begins[t], e_begins[t + 1]) {
const auto& idx_RCSEV = order_e[idx_order];
const auto& rc = RC[idx_RCSEV];
const auto& v = V[idx_RCSEV];
ASSERT(t == E[idx_RCSEV], "turn がおかしいよ");
ASSERT(current_index_table.data[rc] == idx_RCSEV, "消滅させる野菜がないよ");
ASSERT(current_money_table.data[rc] == v, "消滅させる野菜がないよ");
current_index_table.data[rc] = -1;
current_money_table.data[rc] = 0;
ASSERT(next_end_table.data[rc] == t, "終わる turn 間違ってませんか");
const auto& idx_next_vege = next_vegetable[idx_RCSEV];
if (idx_next_vege != -1) {
ASSERT(rc == RC[idx_next_vege], "場所間違ってませんか");
next_end_table.data[rc] = E[idx_next_vege];
}
else {
next_end_table.data[rc] = -1;
}
}
t++;
// これ 1 個先読みしないといけない…?????うわ~~~~~~~
// 1 turn 前ので近似… ごまかす…
if (t != T) {
rep(idx, 256) {
current_value_table.data[idx] = current_money_table.data[idx] + future_value_table.data[idx] / EXP_NEG_KT[t]; // machine の数…は大丈夫だった
}
high_value_indices = Argsort<double, 256, u8, true>(current_value_table.data);
}
}
}
struct State {
BitBoard vegetables;
BitBoard machines; // 一定ターン以降は木を保つ
short turn; // 何も置いてない状態が 0
short n_machines;
int money;
double score;
double subscore2;
double subscore3;
unsigned hash; // machines のみによって一意に定まる
struct Action {
// 新しく置くときは before == after にする
u8 before, after;
};
struct NewStateInfo {
double score;
ull hash;
Action action;
};
void Print() {
cout << "State{" << endl;
cout << "vegetables:" << endl;
vegetables.Print();
cout << "machines:" << endl;
machines.Print();
cout << "turn=" << turn << endl;
cout << "n_machines=" << n_machines << endl;
cout << "money=" << n_machines << endl;
cout << "score=" << score << endl;
cout << "subscore2=" << subscore2 << endl;
cout << "subscore3=" << subscore3 << endl;
cout << "}" << endl;
}
inline bool Terminated() const {
return turn == 1000;
}
inline void Do(const Action& action) {
// 1. 収穫機を移動させる
// - machine を変更する
// - future_value_table に応じて subscore2 を差分計算する
// - 野菜があれば money を増やす
// 2. その日出現する野菜に応じて vegetables のビットを立てる
// 3. machines と vegetables の共通部分を取って、野菜を収穫する
// - 収穫した部分の vegetables のビットは折る
// 4. 野菜の出現に応じて future_value_table を減少させ、そのマスに machine があれば subscore2 を減らして money を増やす
// - 実際には変動があった場所のリストを作り、table は触らない
// 5. その日消滅する野菜に応じて vegetables のビットを折る
// 6. subscore3 を計算する
// - machine の無い、最も価値が高いマスについて、
// その価値が下がる前にそこに到達可能であれば、点をつける
// 参照する外部の変数:
// future_value_table
// current_money_table
// start_bitboards
// end_bitboards
// ほか
// Step 1
const auto& before = action.before;
const auto& after = action.after;
if (before == after) {
if (machines.Get(after)) {
// パスする場合
// 何もしない
}
else {
// 新しく置く場合
n_machines++;
money -= (int)n_machines * (int)n_machines * (int)n_machines;
ASSERT(money >= 0, "money < 0");
machines.Flip(after);
hash += globals::RNT[after | ROUGH_HASH];
subscore2 += globals::future_value_table.data[after];
money += vegetables.Get(after) * n_machines * globals::current_money_table.data[after];
}
}
else {
// 移動させる場合
ASSERT(machines.Get(before), "移動元に機械がないよ");
ASSERT(!machines.Get(after), "移動先に機械があるよ");
machines.Flip(before);
machines.Flip(after);
hash += globals::RNT[after | ROUGH_HASH] - globals::RNT[before | ROUGH_HASH];
subscore2 += globals::future_value_table.data[after] - globals::future_value_table.data[before];
money += vegetables.Get(after) * n_machines * globals::current_money_table.data[after];
}
// Step 2: 出現
vegetables |= globals::start_bitboards[turn];
// Step 3: 収穫(1)
//auto intersection = machines & vegetables;
//vegetables ^= intersection;
vegetables.data = _mm256_andnot_si256(machines.data, vegetables.data);
// Step 4: 収穫(2)
rep3(idx_vegetables, globals::s_begins[turn], globals::s_begins[turn + 1]) {
const auto& idx = RC[idx_vegetables];
const auto& vm = globals::v_modified[idx_vegetables];
const auto& v = V[idx_vegetables];
if (machines.Get(idx)) {
subscore2 -= vm;
ASSERT(subscore2 >= -1e3, "subscore2 < 0");
money += n_machines * v;
}
}
// Step 5: 消滅
vegetables.data = _mm256_andnot_si256(globals::end_bitboards[turn].data, vegetables.data);
// !!!!!ターン増やすよ!!!!!
turn++;
// !!!!!ターン増やすよ!!!!!
// Step 6: subscore3 の計算
subscore3 = 0.0;
remove_reference<decltype(globals::high_value_indices[0])>::type high_value_idx; // 価値の高い場所
for (int i = 0;; i++) {
high_value_idx = globals::high_value_indices[i];
if (!machines.Get(high_value_idx)) break;
}
if (globals::next_end_table.data[high_value_idx] != -1) {
const auto value_decline_turn = min(
globals::next_end_table.data[high_value_idx] - turn + 1 - SUBSCORE3_TIGHT_TURN, // 価値が落ちるまでに行動できる回数 // 同じであっても 1 回猶予がある
15
);
//ASSERT_RANGE(value_decline_turn, 1, 16); // 先読みしてないのでこれにひっかかる…
if (!(globals::NEIGHBOR[high_value_idx][value_decline_turn] & machines).Empty()) { // 到達可能であれば
subscore3 = globals::current_value_table.data[high_value_idx];
}
}
if (turn == T) {
score = money;
}
else {
score = money
+ (subscore2 / globals::EXP_NEG_KT[turn] + subscore3) * n_machines
+ (int)((n_machines * (n_machines + 1)) / 2) * (int)((n_machines * (n_machines + 1)) / 2); // 3 乗和
}
}
template<class Vector>
inline void GetNextStates(Vector& res) const {
// TODO: n_machines が少ないときの処理
if (((int)n_machines + 1) * ((int)n_machines + 1) * ((int)n_machines + 1) > money || turn >= PURCHASE_TURN_LIMIT) {
// 資金が足りない場合 (1 個取り除く) or 一定ターン以降
if (n_machines == 1) {
// 機械が 1 個のとき
const auto p_remove = machines.NonzeroIndices()[0];
rep(p_add, 256) {
if (p_remove == p_add) continue;
auto new_state = *this;
new_state.Do(Action{ p_remove, (u8)p_add });
res.push(NewStateInfo{ new_state.score, new_state.hash, {p_remove, (u8)p_add} });
}
}
else {
// 機械が 2 個以上のとき
for (const auto& p_remove : machines.NonzeroIndices()) {
// 葉じゃなかったら飛ばす
using namespace board_index_functions;
int neighbor_cnt = 0; // 隣接する数
for (const auto& drul : { DownOf(p_remove), RightOf(p_remove), UpOf(p_remove), LeftOf(p_remove) }) {
if (drul != p_remove) {
neighbor_cnt += machines.Get(drul);
}
}
if (neighbor_cnt >= 2) continue; // p は葉ではない
// 実際に減らす
auto machines_removed = machines;
machines_removed.Flip(p_remove);
// 1 個足す方法を探す
// 元々の連結成分に 1 箇所で隣接 <=> xor が 1 かつ, 2 ペアの or の xor が 1
auto&& cand = (machines_removed.Down() ^ machines_removed.Right() ^ machines_removed.Up() ^ machines_removed.Left())
& ((machines_removed.Down() | machines_removed.Right()) ^ (machines_removed.Up() | machines_removed.Left()))
& ~machines;
for (const auto& p_add : cand.NonzeroIndices()) {
//if (p_remove == p_add) continue;
ASSERT(p_remove != p_add, "元と同じ箇所は選ばれないはずだよ");
auto new_state = *this;
new_state.Do(Action{ p_remove, p_add });
//if (turn >= 50 && turn < T - 1
// && new_state.score - new_state.subscore3 * new_state.n_machines < (score - subscore3 * n_machines) * 0.8) continue; // 枝刈り // 悪化
res.push(NewStateInfo{ new_state.score, new_state.hash, {p_remove, p_add} });
}
}
}
}
else {
// 資金が足りてる場合
if (n_machines == 0) {
rep(p_add, 256) {
auto new_state = *this;
new_state.Do(Action{ (u8)p_add, (u8)p_add });
res.push(NewStateInfo{ new_state.score, new_state.hash, {(u8)p_add, (u8)p_add} });
}
}
else {
// 1 個足す方法を探す
auto&& cand = (machines.Down() ^ machines.Right() ^ machines.Up() ^ machines.Left())
& ((machines.Down() | machines.Right()) ^ (machines.Up() | machines.Left()))
& ~machines;
for (const auto& p_add : cand.NonzeroIndices()) {
auto new_state = *this;
new_state.Do(Action{ p_add, p_add });
res.push(NewStateInfo{ new_state.score, new_state.hash, {p_add, p_add} });
}
}
}
// 角で v が w になるやつとかも考慮すべき?
}
};
void Solve() {
// 入力を受け取る
{
int buf;
scanf("%d %d %d", &buf, &buf, &buf);
rep(i, M) {
scanf("%hhd %hhd %hd %hd %hd", &R[i], &C[i], &S[i], &E[i], &V[i]);
RC[i] = ((u8)R[i] * (u8)N + (u8)C[i]);
}
}
// 色々初期化
{
using namespace globals;
for (auto&& r : RNT) {
r = (unsigned)rng.next();
}
EXP_NEG_KT[0] = 1.0;
rep1(i, T - 1) EXP_NEG_KT[i] = EXP_NEG_KT[i - 1] * exp(-MonotonicFunction(K_START, K_END, K_H, (double)i / (double)T));
rep(i, M) {
v_modified[i] = V[i] * EXP_NEG_KT[S[i]];
future_value_table[{ R[i], C[i] }] += v_modified[i];
start_bitboards[S[i]].Flip(RC[i]);
end_bitboards[E[i]].Flip(RC[i]);
}
// next_vegetable
auto next_vegetable_board = Board<short, N, N>();
next_vegetable_board.Fill(-1);
next_end_table.Fill(-1);
for (int i = M - 1; i >= 0; i--) {
next_vegetable[i] = next_vegetable_board.data[RC[i]];
next_vegetable_board.data[RC[i]] = i;
next_end_table.data[RC[i]] = E[i];
}
// NEIGHBOR
rep(i, 256) {
NEIGHBOR[i][0].Flip((u8)i);
rep(d, (ll)NEIGHBOR[i].size() - 1) {
NEIGHBOR[i][d + 1] = NEIGHBOR[i][d];
NEIGHBOR[i][d + 1].Expand();
}
}
// s_begins
auto idx = (short)0;
s_begins[0] = 0;
rep(turn, T) {
while (idx < (int)S.size() && S[idx] <= turn) {
idx++;
}
s_begins[turn + 1] = idx;
}
// order_e
order_e = Argsort<short, M, short>(E);
// e_begins
idx = (short)0;
e_begins[0] = 0;
rep(turn, T) {
while (idx < (int)E.size() && E[order_e[idx]] <= turn) {
idx++;
}
e_begins[turn + 1] = idx;
}
current_index_table.Fill(-1);
high_value_indices = Argsort<double, 256, u8, true>(future_value_table.data);
}
//globals::future_value_table.Print();
//cout << "NEIGHBOR[200][7]" << endl;
//globals::NEIGHBOR[200][7].Print();
// ビームサーチ
{
struct Node {
double score;
Node* parent_node;
State* state;
typename State::Action action;
inline bool operator<(const Node& rhs) const { return score < rhs.score; }
inline bool operator>(const Node& rhs) const { return score > rhs.score; }
};
static Stack<State, 1 + beam_width * T> state_buffer;
static Stack<Node, 1 + beam_width * T> node_buffer;
state_buffer.push(State{});
state_buffer.back().money = 1;
node_buffer.push({ state_buffer[0].score, nullptr, &state_buffer[0] });
static Stack<Node, 400000> q;
Node* parent_nodes_begin = node_buffer.begin();
Node* parent_nodes_end = node_buffer.end();
Node* best_node = nullptr;
rep(t, T) {
static HashMap<Node*, 1 << hash_table_size> dict_hash_to_candidate;
dict_hash_to_candidate.clear();
for (auto parent_node = parent_nodes_begin; parent_node != parent_nodes_end; parent_node++) {
static Stack<typename State::NewStateInfo, 10000> next_states;
next_states.clear();
parent_node->state->GetNextStates(next_states);
for (const auto& r : next_states) {
//if (t >= 50 && t < T - 1 && r.score < parent_node->score * 0.9) continue; // 枝刈り // 悪化
auto& old_node = dict_hash_to_candidate[r.hash];
if (old_node == NULL) {
// まだそのハッシュの状態が無い
q.push({ r.score, parent_node, nullptr, r.action });
old_node = &q.back();
} else if (old_node->score < r.score) {
// 同じハッシュでスコアがより良い
old_node->score = r.score;
old_node->parent_node = parent_node;
old_node->action = r.action;
}
}
}
cerr << "q.size()=" << q.size() << endl;
if (beam_width < q.size()) {
nth_element(q.begin(), q.begin() + beam_width, q.end(), greater<>()); // ここでハッシュテーブル破壊されている
q.resize(beam_width);
}
for (auto&& node : q) {
auto state = *node.parent_node->state;
state.Do(node.action);
state_buffer.push(state);
node.state = &state_buffer.back();
node_buffer.push(node);
if (state.Terminated()) {
if (best_node == nullptr || best_node->score < state.score) {
best_node = &node_buffer.back();
}
}
}
q.clear();
parent_nodes_begin = parent_nodes_end;
parent_nodes_end = node_buffer.end();
globals::UpdateValueTable();
}
// 結果を出力
{
ASSERT(best_node != nullptr, "best_node がないよ");
auto path = array<State::Action, T>();
auto node = best_node;
rep(i, T) {
path[T - 1 - i] = node->action;
node = node->parent_node;
}
ASSERT(node->parent_node == nullptr, "根ノードじゃないよ");
for (const auto& action : path) {
const auto& before = action.before;
const auto& after = action.after;
if (before == after) {
cout << (short)(after >> 4) << " " << (short)(after & 15u) << endl;
}
else {
cout << (short)(before >> 4) << " " << (short)(before & 15u) << " "
<< (short)(after >> 4) << " " << (short)(after & 15u) << endl;
}
}
cerr << best_node->score << endl;
}
}
}
int main() {
//test::TestBitBoard();
Solve();
}
#ifdef __GNUC__
#pragma clang attribute pop
#endif
/*
- 終盤のインフレがすごいが終盤はあまり動けない
- ビームサーチの時間調整
- 最重要: ハッシュを雑に
- 微妙か?評価関数改善して誘導したほうが強そう
- 価値の低い野菜の無視
- ハッシュが重いしいらないかもしれない
- ビーム幅 200 からの候補 60000, 多すぎる
- subscore3 の改善
- 前 turn より減ってたら採用しない感じの枝刈り
*/
| [
"nagiss000@gmail.com"
] | nagiss000@gmail.com |
27ec3d88b5c0714c42483d5b22c6ef7b4f560426 | c03e3b61c8c0b772f320e50fef1bff2ffd13b7d8 | /MFCEND/MFCENDView.h | bcdc5ae10a03396927ae910960217317a1e924ed | [] | no_license | sqchenxiyuan/NetTopo | e250afb91454db1857ef3da7878d29e9e94598ec | 23498dbbce6c9ddf8bbc662a3c00a223b9647809 | refs/heads/master | 2021-01-12T09:31:21.879404 | 2017-01-03T05:45:44 | 2017-01-03T05:45:44 | 76,181,038 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,494 | h |
// MFCENDView.h : CMFCENDView 类的接口
//
#pragma once
class CMFCENDView : public CView
{
protected: // 仅从序列化创建
CMFCENDView();
DECLARE_DYNCREATE(CMFCENDView)
// 特性
public:
CMFCENDDoc* GetDocument() const;
// 操作
public:
// 重写
public:
virtual void OnDraw(CDC* pDC); // 重写以绘制该视图
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual BOOL OnPreparePrinting(CPrintInfo* pInfo);
virtual void OnBeginPrinting(CDC* pDC, CPrintInfo* pInfo);
virtual void OnEndPrinting(CDC* pDC, CPrintInfo* pInfo);
// 实现
public:
virtual ~CMFCENDView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// 生成的消息映射函数
protected:
afx_msg void OnFilePrintPreview();
afx_msg void OnRButtonUp(UINT nFlags, CPoint point);
afx_msg void OnContextMenu(CWnd* pWnd, CPoint point);
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnTimer(UINT_PTR nIDEvent);
virtual void OnInitialUpdate();
protected:
// afx_msg LRESULT resetTree(WPARAM wParam, LPARAM lParam);
afx_msg LRESULT resetTreeData(WPARAM wParam, LPARAM lParam);
public:
afx_msg void OnLButtonDown(UINT nFlags, CPoint point);
afx_msg void OnLButtonUp(UINT nFlags, CPoint point);
afx_msg void OnMouseMove(UINT nFlags, CPoint point);
};
#ifndef _DEBUG // MFCENDView.cpp 中的调试版本
inline CMFCENDDoc* CMFCENDView::GetDocument() const
{ return reinterpret_cast<CMFCENDDoc*>(m_pDocument); }
#endif
| [
"s.q.chenxiyuan@gmailcom"
] | s.q.chenxiyuan@gmailcom |
4610e1473c6a0440bedbc22b85a16f7e66aa44e6 | 682116aec2ecfddccbad6f6f2320b7bf5f2115fa | /maxcode/neuron/iv/src/lib/IV-Win/color.cpp | 63f07133b63749ee1d36b8c6778e35d689aa674f | [
"LicenseRef-scancode-warranty-disclaimer",
"LicenseRef-scancode-other-permissive"
] | permissive | Rauell/neuron | 251423831bb93577e74ae98cee2cb38b0f05e3f4 | f7f0a80122aec2b748aa2bef10b442fbeef8a12c | refs/heads/master | 2016-09-06T06:22:19.357913 | 2015-07-17T13:26:44 | 2015-07-17T13:26:44 | 30,427,231 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,821 | cpp | #include <../../config.h>
/*
Copyright (C) 1993 Tim Prinzing
Copyright (C) 2002 Tim Prinzing, Michael Hines
This file contains programs and data originally developed by Tim Prinzing
with minor changes and improvements by Michael Hines.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
// =======================================================================
//
// <IV-Win/color.cpp>
//
// MS-Windows implementation of the InterViews Color classes.
//
//
// ========================================================================
#include <IV-Win/MWlib.h>
#include <OS/string.h>
#include <OS/math.h>
#include <OS/table.h>
#include <InterViews/color.h>
#include <InterViews/session.h>
#include <InterViews/bitmap.h>
#include <IV-Win/color.h>
#include <IV-Win/window.h>
#include <stdio.h>
// #######################################################################
// ################# class MWpalette
// #######################################################################
static const int GROW_SIZE = 16;
declareTable(MWcolorTable, COLORREF, COLORREF)
implementTable(MWcolorTable, COLORREF, COLORREF)
unsigned long key_to_hash(COLORREF r)
{ return (unsigned long) r; }
// -----------------------------------------------------------------------
// Constructors/destructor
// -----------------------------------------------------------------------
MWpalette::MWpalette()
{
// ---- lookup table for unique colors ----
table = new MWcolorTable(502);
// ---- create a temporary logical palette ----
int allocSize = sizeof(LOGPALETTE) + (GROW_SIZE * sizeof(PALETTEENTRY));
LOGPALETTE* lpal = (LOGPALETTE*) new char[allocSize];
// ---- initialize it ----
lpal->palNumEntries = GROW_SIZE;
lpal->palVersion = 0x300;
for (int i = 0; i < GROW_SIZE; i++)
{
lpal->palPalEntry[i].peRed = 0;
lpal->palPalEntry[i].peGreen = 0;
lpal->palPalEntry[i].peBlue = 0;
lpal->palPalEntry[i].peFlags = 0;
}
// ---- create it ----
palette = CreatePalette(lpal);
#if !defined(__MWERKS__)
//bug in pro 6. can't delete before calling main?
delete []lpal;
#endif
numEntries = 0;
palSize = GROW_SIZE;
}
MWpalette::MWpalette(LOGPALETTE* lpal)
{
palette = CreatePalette(lpal);
palSize = lpal->palNumEntries;
numEntries = palSize;
}
MWpalette::~MWpalette()
{
DeleteObject(palette);
}
// -----------------------------------------------------------------------
// Add an entry to the palette.
// -----------------------------------------------------------------------
COLORREF MWpalette::addEntry(
int r,
int g,
int b)
{
COLORREF color = PALETTERGB( LOBYTE(r), LOBYTE(g), LOBYTE(b));
COLORREF bogus;
// ---- see if it's already there ----
if (table->find(bogus, color))
return color;
// ---- extend the palette if necessary ----
if (numEntries >= palSize)
{
palSize += GROW_SIZE;
ResizePalette(palette, palSize);
}
// ---- add the entry to the palette ----
PALETTEENTRY newEntry;
newEntry.peRed = LOBYTE(r);
newEntry.peGreen = LOBYTE(g);
newEntry.peBlue = LOBYTE(b);
newEntry.peFlags = 0;
SetPaletteEntries(palette, numEntries++, 1, &newEntry);
// ---- add to the hash table ----
table->insert(color, color);
return color;
}
boolean MWpalette::findEntry(int r, int g, int b, COLORREF& value)
{
COLORREF color = PALETTERGB( LOBYTE(r), LOBYTE(g), LOBYTE(b));
if (table->find(value, color))
return true;
return false;
}
// -----------------------------------------------------------------------
// Realize the palette into the given device context. This merges the
// palette entries into the system palette. The number of entries that
// changed in the system palette is returned.
// -----------------------------------------------------------------------
int MWpalette::realizeInto(
HDC hdc, // device context to realize into
BOOL background) // always background?
{
SelectPalette(hdc, palette, background);
return RealizePalette(hdc);
}
// #######################################################################
// ################# class ColorRep
// #######################################################################
// --- name of the colormap file for name lookup ----
static char* COLORMAP_FILE = NULL;
// initially, we have a shared palette for all windows of the application.
static MWpalette globalPalette;
MWpalette* ColorRep::defaultPalette()
{
return &globalPalette;
}
// -----------------------------------------------------------------------
// constructors/destructors
// -----------------------------------------------------------------------
ColorRep::ColorRep(
int r, // red component of color
int g, // green component of color
int b) // blue component of color
{
// ---- add to the palette ----
color = globalPalette.addEntry(r, g, b);
}
ColorRep::~ColorRep()
{
}
// ------------------------------------------------------------------
// translates a color name to the X11 string format of an rgb
// specification (ie #??????). The colormap name is basically a
// section in the colormap.ini file.
// ------------------------------------------------------------------
// oreilly: just put the entire thing in here so installation is easy -- no
// dependency on app defaults or other install location files at all
static struct { char* name; char* value; } cc[] = {
{"snow", "#fffafa"}, {"ghost white", "#f8f8ff"}, {"GhostWhite", "#f8f8ff"},
{"white smoke", "#f5f5f5"}, {"WhiteSmoke", "#f5f5f5"}, {"gainsboro", "#dcdcdc"},
{"floral white", "#fffaf0"}, {"FloralWhite", "#fffaf0"}, {"old lace", "#fdf5e6"},
{"OldLace", "#fdf5e6"}, {"linen", "#faf0e6"}, {"antique white", "#faebd7"},
{"AntiqueWhite", "#faebd7"}, {"papaya whip", "#ffefd5"}, {"PapayaWhip", "#ffefd5"},
{"blanched almond", "#ffebcd"}, {"BlanchedAlmond", "#ffebcd"}, {"bisque", "#ffe4c4"},
{"peach puff", "#ffdab9"}, {"PeachPuff", "#ffdab9"}, {"navajo white", "#ffdead"},
{"NavajoWhite", "#ffdead"}, {"moccasin", "#ffe4b5"}, {"cornsilk", "#fff8dc"},
{"ivory", "#fffff0"}, {"lemon chiffon", "#fffacd"}, {"LemonChiffon", "#fffacd"},
{"seashell", "#fff5ee"}, {"honeydew", "#f0fff0"}, {"mint cream", "#f5fffa"},
{"MintCream", "#f5fffa"}, {"azure", "#f0ffff"}, {"alice blue", "#f0f8ff"},
{"AliceBlue", "#f0f8ff"}, {"lavender", "#e6e6fa"}, {"lavender blush", "#fff0f5"},
{"LavenderBlush", "#fff0f5"}, {"misty rose", "#ffe4e1"}, {"MistyRose", "#ffe4e1"},
{"white", "#ffffff"}, {"black", "#000000"}, {"dark slate gray", "#2f4f4f"},
{"DarkSlateGray", "#2f4f4f"}, {"dark slate grey", "#2f4f4f"}, {"DarkSlateGrey", "#2f4f4f"},
{"dim gray", "#696969"}, {"DimGray", "#696969"}, {"dim grey", "#696969"},
{"DimGrey", "#696969"}, {"slate gray", "#708090"}, {"SlateGray", "#708090"},
{"slate grey", "#708090"}, {"SlateGrey", "#708090"}, {"light slate gray", "#778899"},
{"LightSlateGray", "#778899"}, {"light slate grey", "#778899"}, {"LightSlateGrey", "#778899"},
{"gray", "#bebebe"}, {"grey", "#bebebe"}, {"light grey", "#d3d3d3"},
{"LightGrey", "#d3d3d3"}, {"light gray", "#d3d3d3"}, {"LightGray", "#d3d3d3"},
{"midnight blue", "#191970"}, {"MidnightBlue", "#191970"}, {"navy", "#000080"},
{"navy blue", "#000080"}, {"NavyBlue", "#000080"}, {"cornflower blue", "#6495ed"},
{"CornflowerBlue", "#6495ed"}, {"dark slate blue", "#483d8b"}, {"DarkSlateBlue", "#483d8b"},
{"slate blue", "#6a5acd"}, {"SlateBlue", "#6a5acd"}, {"medium slate blue", "#7b68ee"},
{"MediumSlateBlue", "#7b68ee"}, {"light slate blue", "#8470ff"}, {"LightSlateBlue", "#8470ff"},
{"medium blue", "#0000cd"}, {"MediumBlue", "#0000cd"}, {"royal blue", "#4169e1"},
{"RoyalBlue", "#4169e1"}, {"blue", "#0000ff"}, {"dodger blue", "#1e90ff"},
{"DodgerBlue", "#1e90ff"}, {"deep sky blue", "#00bfff"}, {"DeepSkyBlue", "#00bfff"},
{"sky blue", "#87ceeb"}, {"SkyBlue", "#87ceeb"}, {"light sky blue", "#87cefa"},
{"LightSkyBlue", "#87cefa"}, {"steel blue", "#4682b4"}, {"SteelBlue", "#4682b4"},
{"light steel blue", "#b0c4de"}, {"LightSteelBlue", "#b0c4de"}, {"light blue", "#add8e6"},
{"LightBlue", "#add8e6"}, {"powder blue", "#b0e0e6"}, {"PowderBlue", "#b0e0e6"},
{"pale turquoise", "#afeeee"}, {"PaleTurquoise", "#afeeee"}, {"dark turquoise", "#00ced1"},
{"DarkTurquoise", "#00ced1"}, {"medium turquoise", "#48d1cc"}, {"MediumTurquoise", "#48d1cc"},
{"turquoise", "#40e0d0"}, {"cyan", "#00ffff"}, {"light cyan", "#e0ffff"},
{"LightCyan", "#e0ffff"}, {"cadet blue", "#5f9ea0"}, {"CadetBlue", "#5f9ea0"},
{"medium aquamarine", "#66cdaa"}, {"MediumAquamarine", "#66cdaa"}, {"aquamarine", "#7fffd4"},
{"dark green", "#006400"}, {"DarkGreen", "#006400"}, {"dark olive green", "#556b2f"},
{"DarkOliveGreen", "#556b2f"}, {"dark sea green", "#8fbc8f"}, {"DarkSeaGreen", "#8fbc8f"},
{"sea green", "#2e8b57"}, {"SeaGreen", "#2e8b57"}, {"medium sea green", "#3cb371"},
{"MediumSeaGreen", "#3cb371"}, {"light sea green", "#20b2aa"}, {"LightSeaGreen", "#20b2aa"},
{"pale green", "#98fb98"}, {"PaleGreen", "#98fb98"}, {"spring green", "#00ff7f"},
{"SpringGreen", "#00ff7f"}, {"lawn green", "#7cfc00"}, {"LawnGreen", "#7cfc00"},
{"green", "#00ff00"}, {"chartreuse", "#7fff00"}, {"medium spring green", "#00fa9a"},
{"MediumSpringGreen", "#00fa9a"}, {"green yellow", "#adff2f"}, {"GreenYellow", "#adff2f"},
{"lime green", "#32cd32"}, {"LimeGreen", "#32cd32"}, {"yellow green", "#9acd32"},
{"YellowGreen", "#9acd32"}, {"forest green", "#228b22"}, {"ForestGreen", "#228b22"},
{"olive drab", "#6b8e23"}, {"OliveDrab", "#6b8e23"}, {"dark khaki", "#bdb76b"},
{"DarkKhaki", "#bdb76b"}, {"khaki", "#f0e68c"}, {"pale goldenrod", "#eee8aa"},
{"PaleGoldenrod", "#eee8aa"}, {"light goldenrod yellow", "#fafad2"}, {"LightGoldenrodYellow", "#fafad2"},
{"light yellow", "#ffffe0"}, {"LightYellow", "#ffffe0"}, {"yellow", "#ffff00"},
{"gold", "#ffd700"}, {"light goldenrod", "#eedd82"}, {"LightGoldenrod", "#eedd82"},
{"goldenrod", "#daa520"}, {"dark goldenrod", "#b8860b"}, {"DarkGoldenrod", "#b8860b"},
{"rosy brown", "#bc8f8f"}, {"RosyBrown", "#bc8f8f"}, {"indian red", "#cd5c5c"},
{"IndianRed", "#cd5c5c"}, {"saddle brown", "#8b4513"}, {"SaddleBrown", "#8b4513"},
{"sienna", "#a0522d"}, {"peru", "#cd853f"}, {"burlywood", "#deb887"},
{"beige", "#f5f5dc"}, {"wheat", "#f5deb3"}, {"sandy brown", "#f4a460"},
{"SandyBrown", "#f4a460"}, {"tan", "#d2b48c"}, {"chocolate", "#d2691e"},
{"firebrick", "#b22222"}, {"brown", "#a52a2a"}, {"dark salmon", "#e9967a"},
{"DarkSalmon", "#e9967a"}, {"salmon", "#fa8072"}, {"light salmon", "#ffa07a"},
{"LightSalmon", "#ffa07a"}, {"orange", "#ffa500"}, {"dark orange", "#ff8c00"},
{"DarkOrange", "#ff8c00"}, {"coral", "#ff7f50"}, {"light coral", "#f08080"},
{"LightCoral", "#f08080"}, {"tomato", "#ff6347"}, {"orange red", "#ff4500"},
{"OrangeRed", "#ff4500"}, {"red", "#ff0000"}, {"hot pink", "#ff69b4"},
{"HotPink", "#ff69b4"}, {"deep pink", "#ff1493"}, {"DeepPink", "#ff1493"},
{"pink", "#ffc0cb"}, {"light pink", "#ffb6c1"}, {"LightPink", "#ffb6c1"},
{"pale violet red", "#db7093"}, {"PaleVioletRed", "#db7093"}, {"maroon", "#b03060"},
{"medium violet red", "#c71585"}, {"MediumVioletRed", "#c71585"}, {"violet red", "#d02090"},
{"VioletRed", "#d02090"}, {"magenta", "#ff00ff"}, {"violet", "#ee82ee"},
{"plum", "#dda0dd"}, {"orchid", "#da70d6"}, {"medium orchid", "#ba55d3"},
{"MediumOrchid", "#ba55d3"}, {"dark orchid", "#9932cc"}, {"DarkOrchid", "#9932cc"},
{"dark violet", "#9400d3"}, {"DarkViolet", "#9400d3"}, {"blue violet", "#8a2be2"},
{"BlueViolet", "#8a2be2"}, {"purple", "#a020f0"}, {"medium purple", "#9370db"},
{"MediumPurple", "#9370db"}, {"thistle", "#d8bfd8"}, {"snow1", "#fffafa"},
{"snow2", "#eee9e9"}, {"snow3", "#cdc9c9"}, {"snow4", "#8b8989"},
{"seashell1", "#fff5ee"}, {"seashell2", "#eee5de"}, {"seashell3", "#cdc5bf"},
{"seashell4", "#8b8682"}, {"AntiqueWhite1", "#ffefdb"}, {"AntiqueWhite2", "#eedfcc"},
{"AntiqueWhite3", "#cdc0b0"}, {"AntiqueWhite4", "#8b8378"}, {"bisque1", "#ffe4c4"},
{"bisque2", "#eed5b7"}, {"bisque3", "#cdb79e"}, {"bisque4", "#8b7d6b"},
{"PeachPuff1", "#ffdab9"}, {"PeachPuff2", "#eecbad"}, {"PeachPuff3", "#cdaf95"},
{"PeachPuff4", "#8b7765"}, {"NavajoWhite1", "#ffdead"}, {"NavajoWhite2", "#eecfa1"},
{"NavajoWhite3", "#cdb38b"}, {"NavajoWhite4", "#8b795e"}, {"LemonChiffon1", "#fffacd"},
{"LemonChiffon2", "#eee9bf"}, {"LemonChiffon3", "#cdc9a5"}, {"LemonChiffon4", "#8b8970"},
{"cornsilk1", "#fff8dc"}, {"cornsilk2", "#eee8cd"}, {"cornsilk3", "#cdc8b1"},
{"cornsilk4", "#8b8878"}, {"ivory1", "#fffff0"}, {"ivory2", "#eeeee0"},
{"ivory3", "#cdcdc1"}, {"ivory4", "#8b8b83"}, {"honeydew1", "#f0fff0"},
{"honeydew2", "#e0eee0"}, {"honeydew3", "#c1cdc1"}, {"honeydew4", "#838b83"},
{"LavenderBlush1", "#fff0f5"}, {"LavenderBlush2", "#eee0e5"}, {"LavenderBlush3", "#cdc1c5"},
{"LavenderBlush4", "#8b8386"}, {"MistyRose1", "#ffe4e1"}, {"MistyRose2", "#eed5d2"},
{"MistyRose3", "#cdb7b5"}, {"MistyRose4", "#8b7d7b"}, {"azure1", "#f0ffff"},
{"azure2", "#e0eeee"}, {"azure3", "#c1cdcd"}, {"azure4", "#838b8b"},
{"SlateBlue1", "#836fff"}, {"SlateBlue2", "#7a67ee"}, {"SlateBlue3", "#6959cd"},
{"SlateBlue4", "#473c8b"}, {"RoyalBlue1", "#4876ff"}, {"RoyalBlue2", "#436eee"},
{"RoyalBlue3", "#3a5fcd"}, {"RoyalBlue4", "#27408b"}, {"blue1", "#0000ff"},
{"blue2", "#0000ee"}, {"blue3", "#0000cd"}, {"blue4", "#00008b"},
{"DodgerBlue1", "#1e90ff"}, {"DodgerBlue2", "#1c86ee"}, {"DodgerBlue3", "#1874cd"},
{"DodgerBlue4", "#104e8b"}, {"SteelBlue1", "#63b8ff"}, {"SteelBlue2", "#5cacee"},
{"SteelBlue3", "#4f94cd"}, {"SteelBlue4", "#36648b"}, {"DeepSkyBlue1", "#00bfff"},
{"DeepSkyBlue2", "#00b2ee"}, {"DeepSkyBlue3", "#009acd"}, {"DeepSkyBlue4", "#00688b"},
{"SkyBlue1", "#87ceff"}, {"SkyBlue2", "#7ec0ee"}, {"SkyBlue3", "#6ca6cd"},
{"SkyBlue4", "#4a708b"}, {"LightSkyBlue1", "#b0e2ff"}, {"LightSkyBlue2", "#a4d3ee"},
{"LightSkyBlue3", "#8db6cd"}, {"LightSkyBlue4", "#607b8b"}, {"SlateGray1", "#c6e2ff"},
{"SlateGray2", "#b9d3ee"}, {"SlateGray3", "#9fb6cd"}, {"SlateGray4", "#6c7b8b"},
{"LightSteelBlue1", "#cae1ff"}, {"LightSteelBlue2", "#bcd2ee"}, {"LightSteelBlue3", "#a2b5cd"},
{"LightSteelBlue4", "#6e7b8b"}, {"LightBlue1", "#bfefff"}, {"LightBlue2", "#b2dfee"},
{"LightBlue3", "#9ac0cd"}, {"LightBlue4", "#68838b"}, {"LightCyan1", "#e0ffff"},
{"LightCyan2", "#d1eeee"}, {"LightCyan3", "#b4cdcd"}, {"LightCyan4", "#7a8b8b"},
{"PaleTurquoise1", "#bbffff"}, {"PaleTurquoise2", "#aeeeee"}, {"PaleTurquoise3", "#96cdcd"},
{"PaleTurquoise4", "#668b8b"}, {"CadetBlue1", "#98f5ff"}, {"CadetBlue2", "#8ee5ee"},
{"CadetBlue3", "#7ac5cd"}, {"CadetBlue4", "#53868b"}, {"turquoise1", "#00f5ff"},
{"turquoise2", "#00e5ee"}, {"turquoise3", "#00c5cd"}, {"turquoise4", "#00868b"},
{"cyan1", "#00ffff"}, {"cyan2", "#00eeee"}, {"cyan3", "#00cdcd"},
{"cyan4", "#008b8b"}, {"DarkSlateGray1", "#97ffff"}, {"DarkSlateGray2", "#8deeee"},
{"DarkSlateGray3", "#79cdcd"}, {"DarkSlateGray4", "#528b8b"}, {"aquamarine1", "#7fffd4"},
{"aquamarine2", "#76eec6"}, {"aquamarine3", "#66cdaa"}, {"aquamarine4", "#458b74"},
{"DarkSeaGreen1", "#c1ffc1"}, {"DarkSeaGreen2", "#b4eeb4"}, {"DarkSeaGreen3", "#9bcd9b"},
{"DarkSeaGreen4", "#698b69"}, {"SeaGreen1", "#54ff9f"}, {"SeaGreen2", "#4eee94"},
{"SeaGreen3", "#43cd80"}, {"SeaGreen4", "#2e8b57"}, {"PaleGreen1", "#9aff9a"},
{"PaleGreen2", "#90ee90"}, {"PaleGreen3", "#7ccd7c"}, {"PaleGreen4", "#548b54"},
{"SpringGreen1", "#00ff7f"}, {"SpringGreen2", "#00ee76"}, {"SpringGreen3", "#00cd66"},
{"SpringGreen4", "#008b45"}, {"green1", "#00ff00"}, {"green2", "#00ee00"},
{"green3", "#00cd00"}, {"green4", "#008b00"}, {"chartreuse1", "#7fff00"},
{"chartreuse2", "#76ee00"}, {"chartreuse3", "#66cd00"}, {"chartreuse4", "#458b00"},
{"OliveDrab1", "#c0ff3e"}, {"OliveDrab2", "#b3ee3a"}, {"OliveDrab3", "#9acd32"},
{"OliveDrab4", "#698b22"}, {"DarkOliveGreen1", "#caff70"}, {"DarkOliveGreen2", "#bcee68"},
{"DarkOliveGreen3", "#a2cd5a"}, {"DarkOliveGreen4", "#6e8b3d"}, {"khaki1", "#fff68f"},
{"khaki2", "#eee685"}, {"khaki3", "#cdc673"}, {"khaki4", "#8b864e"},
{"LightGoldenrod1", "#ffec8b"}, {"LightGoldenrod2", "#eedc82"}, {"LightGoldenrod3", "#cdbe70"},
{"LightGoldenrod4", "#8b814c"}, {"LightYellow1", "#ffffe0"}, {"LightYellow2", "#eeeed1"},
{"LightYellow3", "#cdcdb4"}, {"LightYellow4", "#8b8b7a"}, {"yellow1", "#ffff00"},
{"yellow2", "#eeee00"}, {"yellow3", "#cdcd00"}, {"yellow4", "#8b8b00"},
{"gold1", "#ffd700"}, {"gold2", "#eec900"}, {"gold3", "#cdad00"},
{"gold4", "#8b7500"}, {"goldenrod1", "#ffc125"}, {"goldenrod2", "#eeb422"},
{"goldenrod3", "#cd9b1d"}, {"goldenrod4", "#8b6914"}, {"DarkGoldenrod1", "#ffb90f"},
{"DarkGoldenrod2", "#eead0e"}, {"DarkGoldenrod3", "#cd950c"}, {"DarkGoldenrod4", "#8b6508"},
{"RosyBrown1", "#ffc1c1"}, {"RosyBrown2", "#eeb4b4"}, {"RosyBrown3", "#cd9b9b"},
{"RosyBrown4", "#8b6969"}, {"IndianRed1", "#ff6a6a"}, {"IndianRed2", "#ee6363"},
{"IndianRed3", "#cd5555"}, {"IndianRed4", "#8b3a3a"}, {"sienna1", "#ff8247"},
{"sienna2", "#ee7942"}, {"sienna3", "#cd6839"}, {"sienna4", "#8b4726"},
{"burlywood1", "#ffd39b"}, {"burlywood2", "#eec591"}, {"burlywood3", "#cdaa7d"},
{"burlywood4", "#8b7355"}, {"wheat1", "#ffe7ba"}, {"wheat2", "#eed8ae"},
{"wheat3", "#cdba96"}, {"wheat4", "#8b7e66"}, {"tan1", "#ffa54f"},
{"tan2", "#ee9a49"}, {"tan3", "#cd853f"}, {"tan4", "#8b5a2b"},
{"chocolate1", "#ff7f24"}, {"chocolate2", "#ee7621"}, {"chocolate3", "#cd661d"},
{"chocolate4", "#8b4513"}, {"firebrick1", "#ff3030"}, {"firebrick2", "#ee2c2c"},
{"firebrick3", "#cd2626"}, {"firebrick4", "#8b1a1a"}, {"brown1", "#ff4040"},
{"brown2", "#ee3b3b"}, {"brown3", "#cd3333"}, {"brown4", "#8b2323"},
{"salmon1", "#ff8c69"}, {"salmon2", "#ee8262"}, {"salmon3", "#cd7054"},
{"salmon4", "#8b4c39"}, {"LightSalmon1", "#ffa07a"}, {"LightSalmon2", "#ee9572"},
{"LightSalmon3", "#cd8162"}, {"LightSalmon4", "#8b5742"}, {"orange1", "#ffa500"},
{"orange2", "#ee9a00"}, {"orange3", "#cd8500"}, {"orange4", "#8b5a00"},
{"DarkOrange1", "#ff7f00"}, {"DarkOrange2", "#ee7600"}, {"DarkOrange3", "#cd6600"},
{"DarkOrange4", "#8b4500"}, {"coral1", "#ff7256"}, {"coral2", "#ee6a50"},
{"coral3", "#cd5b45"}, {"coral4", "#8b3e2f"}, {"tomato1", "#ff6347"},
{"tomato2", "#ee5c42"}, {"tomato3", "#cd4f39"}, {"tomato4", "#8b3626"},
{"OrangeRed1", "#ff4500"}, {"OrangeRed2", "#ee4000"}, {"OrangeRed3", "#cd3700"},
{"OrangeRed4", "#8b2500"}, {"red1", "#ff0000"}, {"red2", "#ee0000"},
{"red3", "#cd0000"}, {"red4", "#8b0000"}, {"DeepPink1", "#ff1493"},
{"DeepPink2", "#ee1289"}, {"DeepPink3", "#cd1076"}, {"DeepPink4", "#8b0a50"},
{"HotPink1", "#ff6eb4"}, {"HotPink2", "#ee6aa7"}, {"HotPink3", "#cd6090"},
{"HotPink4", "#8b3a62"}, {"pink1", "#ffb5c5"}, {"pink2", "#eea9b8"},
{"pink3", "#cd919e"}, {"pink4", "#8b636c"}, {"LightPink1", "#ffaeb9"},
{"LightPink2", "#eea2ad"}, {"LightPink3", "#cd8c95"}, {"LightPink4", "#8b5f65"},
{"PaleVioletRed1", "#ff82ab"}, {"PaleVioletRed2", "#ee799f"}, {"PaleVioletRed3", "#cd6889"},
{"PaleVioletRed4", "#8b475d"}, {"maroon1", "#ff34b3"}, {"maroon2", "#ee30a7"},
{"maroon3", "#cd2990"}, {"maroon4", "#8b1c62"}, {"VioletRed1", "#ff3e96"},
{"VioletRed2", "#ee3a8c"}, {"VioletRed3", "#cd3278"}, {"VioletRed4", "#8b2252"},
{"magenta1", "#ff00ff"}, {"magenta2", "#ee00ee"}, {"magenta3", "#cd00cd"},
{"magenta4", "#8b008b"}, {"orchid1", "#ff83fa"}, {"orchid2", "#ee7ae9"},
{"orchid3", "#cd69c9"}, {"orchid4", "#8b4789"}, {"plum1", "#ffbbff"},
{"plum2", "#eeaeee"}, {"plum3", "#cd96cd"}, {"plum4", "#8b668b"},
{"MediumOrchid1", "#e066ff"}, {"MediumOrchid2", "#d15fee"}, {"MediumOrchid3", "#b452cd"},
{"MediumOrchid4", "#7a378b"}, {"DarkOrchid1", "#bf3eff"}, {"DarkOrchid2", "#b23aee"},
{"DarkOrchid3", "#9a32cd"}, {"DarkOrchid4", "#68228b"}, {"purple1", "#9b30ff"},
{"purple2", "#912cee"}, {"purple3", "#7d26cd"}, {"purple4", "#551a8b"},
{"MediumPurple1", "#ab82ff"}, {"MediumPurple2", "#9f79ee"}, {"MediumPurple3", "#8968cd"},
{"MediumPurple4", "#5d478b"}, {"thistle1", "#ffe1ff"}, {"thistle2", "#eed2ee"},
{"thistle3", "#cdb5cd"}, {"thistle4", "#8b7b8b"}, {"gray0", "#000000"},
{"grey0", "#000000"}, {"gray1", "#030303"}, {"grey1", "#030303"},
{"gray2", "#050505"}, {"grey2", "#050505"}, {"gray3", "#080808"},
{"grey3", "#080808"}, {"gray4", "#0a0a0a"}, {"grey4", "#0a0a0a"},
{"gray5", "#0d0d0d"}, {"grey5", "#0d0d0d"}, {"gray6", "#0f0f0f"},
{"grey6", "#0f0f0f"}, {"gray7", "#121212"}, {"grey7", "#121212"},
{"gray8", "#141414"}, {"grey8", "#141414"}, {"gray9", "#171717"},
{"grey9", "#171717"}, {"gray10", "#1a1a1a"}, {"grey10", "#1a1a1a"},
{"gray11", "#1c1c1c"}, {"grey11", "#1c1c1c"}, {"gray12", "#1f1f1f"},
{"grey12", "#1f1f1f"}, {"gray13", "#212121"}, {"grey13", "#212121"},
{"gray14", "#242424"}, {"grey14", "#242424"}, {"gray15", "#262626"},
{"grey15", "#262626"}, {"gray16", "#292929"}, {"grey16", "#292929"},
{"gray17", "#2b2b2b"}, {"grey17", "#2b2b2b"}, {"gray18", "#2e2e2e"},
{"grey18", "#2e2e2e"}, {"gray19", "#303030"}, {"grey19", "#303030"},
{"gray20", "#333333"}, {"grey20", "#333333"}, {"gray21", "#363636"},
{"grey21", "#363636"}, {"gray22", "#383838"}, {"grey22", "#383838"},
{"gray23", "#3b3b3b"}, {"grey23", "#3b3b3b"}, {"gray24", "#3d3d3d"},
{"grey24", "#3d3d3d"}, {"gray25", "#404040"}, {"grey25", "#404040"},
{"gray26", "#424242"}, {"grey26", "#424242"}, {"gray27", "#454545"},
{"grey27", "#454545"}, {"gray28", "#474747"}, {"grey28", "#474747"},
{"gray29", "#4a4a4a"}, {"grey29", "#4a4a4a"}, {"gray30", "#4d4d4d"},
{"grey30", "#4d4d4d"}, {"gray31", "#4f4f4f"}, {"grey31", "#4f4f4f"},
{"gray32", "#525252"}, {"grey32", "#525252"}, {"gray33", "#545454"},
{"grey33", "#545454"}, {"gray34", "#575757"}, {"grey34", "#575757"},
{"gray35", "#595959"}, {"grey35", "#595959"}, {"gray36", "#5c5c5c"},
{"grey36", "#5c5c5c"}, {"gray37", "#5e5e5e"}, {"grey37", "#5e5e5e"},
{"gray38", "#616161"}, {"grey38", "#616161"}, {"gray39", "#636363"},
{"grey39", "#636363"}, {"gray40", "#666666"}, {"grey40", "#666666"},
{"gray41", "#696969"}, {"grey41", "#696969"}, {"gray42", "#6b6b6b"},
{"grey42", "#6b6b6b"}, {"gray43", "#6e6e6e"}, {"grey43", "#6e6e6e"},
{"gray44", "#707070"}, {"grey44", "#707070"}, {"gray45", "#737373"},
{"grey45", "#737373"}, {"gray46", "#757575"}, {"grey46", "#757575"},
{"gray47", "#787878"}, {"grey47", "#787878"}, {"gray48", "#7a7a7a"},
{"grey48", "#7a7a7a"}, {"gray49", "#7d7d7d"}, {"grey49", "#7d7d7d"},
{"gray50", "#7f7f7f"}, {"grey50", "#7f7f7f"}, {"gray51", "#828282"},
{"grey51", "#828282"}, {"gray52", "#858585"}, {"grey52", "#858585"},
{"gray53", "#878787"}, {"grey53", "#878787"}, {"gray54", "#8a8a8a"},
{"grey54", "#8a8a8a"}, {"gray55", "#8c8c8c"}, {"grey55", "#8c8c8c"},
{"gray56", "#8f8f8f"}, {"grey56", "#8f8f8f"}, {"gray57", "#919191"},
{"grey57", "#919191"}, {"gray58", "#949494"}, {"grey58", "#949494"},
{"gray59", "#969696"}, {"grey59", "#969696"}, {"gray60", "#999999"},
{"grey60", "#999999"}, {"gray61", "#9c9c9c"}, {"grey61", "#9c9c9c"},
{"gray62", "#9e9e9e"}, {"grey62", "#9e9e9e"}, {"gray63", "#a1a1a1"},
{"grey63", "#a1a1a1"}, {"gray64", "#a3a3a3"}, {"grey64", "#a3a3a3"},
{"gray65", "#a6a6a6"}, {"grey65", "#a6a6a6"}, {"gray66", "#a8a8a8"},
{"grey66", "#a8a8a8"}, {"gray67", "#ababab"}, {"grey67", "#ababab"},
{"gray68", "#adadad"}, {"grey68", "#adadad"}, {"gray69", "#b0b0b0"},
{"grey69", "#b0b0b0"}, {"gray70", "#b3b3b3"}, {"grey70", "#b3b3b3"},
{"gray71", "#b5b5b5"}, {"grey71", "#b5b5b5"}, {"gray72", "#b8b8b8"},
{"grey72", "#b8b8b8"}, {"gray73", "#bababa"}, {"grey73", "#bababa"},
{"gray74", "#bdbdbd"}, {"grey74", "#bdbdbd"}, {"gray75", "#bfbfbf"},
{"grey75", "#bfbfbf"}, {"gray76", "#c2c2c2"}, {"grey76", "#c2c2c2"},
{"gray77", "#c4c4c4"}, {"grey77", "#c4c4c4"}, {"gray78", "#c7c7c7"},
{"grey78", "#c7c7c7"}, {"gray79", "#c9c9c9"}, {"grey79", "#c9c9c9"},
{"gray80", "#cccccc"}, {"grey80", "#cccccc"}, {"gray81", "#cfcfcf"},
{"grey81", "#cfcfcf"}, {"gray82", "#d1d1d1"}, {"grey82", "#d1d1d1"},
{"gray83", "#d4d4d4"}, {"grey83", "#d4d4d4"}, {"gray84", "#d6d6d6"},
{"grey84", "#d6d6d6"}, {"gray85", "#d9d9d9"}, {"grey85", "#d9d9d9"},
{"gray86", "#dbdbdb"}, {"grey86", "#dbdbdb"}, {"gray87", "#dedede"},
{"grey87", "#dedede"}, {"gray88", "#e0e0e0"}, {"grey88", "#e0e0e0"},
{"gray89", "#e3e3e3"}, {"grey89", "#e3e3e3"}, {"gray90", "#e5e5e5"},
{"grey90", "#e5e5e5"}, {"gray91", "#e8e8e8"}, {"grey91", "#e8e8e8"},
{"gray92", "#ebebeb"}, {"grey92", "#ebebeb"}, {"gray93", "#ededed"},
{"grey93", "#ededed"}, {"gray94", "#f0f0f0"}, {"grey94", "#f0f0f0"},
{"gray95", "#f2f2f2"}, {"grey95", "#f2f2f2"}, {"gray96", "#f5f5f5"},
{"grey96", "#f5f5f5"}, {"gray97", "#f7f7f7"}, {"grey97", "#f7f7f7"},
{"gray98", "#fafafa"}, {"grey98", "#fafafa"}, {"gray99", "#fcfcfc"},
{"grey99", "#fcfcfc"}, {"gray100", "#ffffff"}, {"grey100", "#ffffff"},
{0}
};
const char* ColorRep::nameToRGB(const char* colormap, const char* name)
{
MWassert(colormap);
MWassert(name);
#if OCSMALL
int i;
for (i = 0; cc[i].name; ++i) {
if (strcmp(cc[i].name, name) == 0) {
return cc[i].value;
}
}
#else
if (!Session::installLocation()) {
int i;
for (i = 0; cc[i].name; ++i) {
if (strcmp(cc[i].name, name) == 0) {
return cc[i].value;
}
}
}else{
if (COLORMAP_FILE == NULL)
{
const char* loc = Session::installLocation();
const char* leafname = "/colormap.ini";
COLORMAP_FILE = new char[ strlen(loc) + strlen(leafname) + 1];
strcpy(COLORMAP_FILE, loc);
strcat(COLORMAP_FILE, leafname);
}
static char rgbName[10];
if (GetPrivateProfileString(colormap, name, "", rgbName, 10,
COLORMAP_FILE))
{
return rgbName;
}
else {
int i;
for (i = 0; cc[i].name; ++i) {
if (strcmp(cc[i].name, name) == 0) {
return cc[i].value;
}
}
}
}
#endif
return NULL;
}
const Color* ColorRep::rgbToColor(const char* name)
{
if (name[0] == '#')
{
int r;
int g;
int b;
sscanf(&(name[1]), "%2x", &r);
sscanf(&(name[3]), "%2x", &g);
sscanf(&(name[5]), "%2x", &b);
const Color* c = new Color(
(ColorIntensity) (r/255.0),
(ColorIntensity) (g/255.0),
(ColorIntensity) (b/255.0),
1.0);
return c;
}
return nil;
}
// #######################################################################
// ################# class Color
// #######################################################################
// The following data is used to create 16 stipple patterns used when the
// alpha value of the color is set to something other than 1.0.
static unsigned char stippleData[16][8] =
{
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 },
{ 0x11, 0x00, 0x00, 0x00, 0x11, 0x00, 0x00, 0x00 },
{ 0x11, 0x00, 0x44, 0x00, 0x11, 0x00, 0x44, 0x00 },
{ 0x55, 0x00, 0x44, 0x00, 0x55, 0x00, 0x44, 0x00 },
{ 0x55, 0x00, 0x55, 0x00, 0x55, 0x00, 0x55, 0x00 },
{ 0x55, 0x22, 0x55, 0x00, 0x55, 0x22, 0x55, 0x00 },
{ 0x55, 0x22, 0x55, 0x88, 0x55, 0x22, 0x55, 0x88 },
{ 0x55, 0xAA, 0x55, 0x88, 0x55, 0xAA, 0x55, 0x88 },
{ 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA, 0x55, 0xAA },
{ 0x77, 0xAA, 0x55, 0xAA, 0x77, 0xAA, 0x55, 0xAA },
{ 0x77, 0xAA, 0xDD, 0xAA, 0x77, 0xAA, 0xDD, 0xAA },
{ 0xFF, 0xAA, 0xDD, 0xAA, 0xFF, 0xAA, 0xDD, 0xAA },
{ 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA, 0xFF, 0xAA },
{ 0xFF, 0xBB, 0xFF, 0xAA, 0xFF, 0xBB, 0xFF, 0xAA },
{ 0xFF, 0xBB, 0xFF, 0xEE, 0xFF, 0xBB, 0xFF, 0xEE },
{ 0xFF, 0xFF, 0xFF, 0xEE, 0xFF, 0xFF, 0xFF, 0xEE },
};
Color::Color(
ColorIntensity r, // red component of color
ColorIntensity g, // green component of color
ColorIntensity b, // blue component of color
float alpha,
ColorOp op)
{
int red = (int) (r * 255);
int green = (int) (g * 255);
int blue = (int) (b * 255);
impl_ = new ColorRep(red, green, blue);
impl_->op = op;
// ---- set stipple pattern if dither desired ----
impl_->alpha = alpha;
if ((alpha > 0.9999) && (alpha < 1.0001))
{
impl_->stipple = NULL;
}
else
{
int index = int(alpha * 16);
index = (index > 15) ? 15 : index;
index = (index < 0) ? 0 : index;
impl_->stipple = new Bitmap(stippleData[index], 8, 8);
}
}
Color::Color(
const Color& color,
float alpha,
ColorOp op)
{
COLORREF cref = color.impl_->msColor();
int red = GetRValue(cref);
int green = GetGValue(cref);
int blue = GetBValue(cref);
impl_ = new ColorRep(red, blue, green);
impl_->op = op;
// ---- set stipple pattern if dither desired ----
impl_->alpha = alpha;
if ((alpha > 0.9999) && (alpha < 1.0001))
{
impl_->stipple = NULL;
}
else
{
int index = int(alpha * 16);
index = (index > 15) ? 15 : index;
index = (index < 0) ? 0 : index;
impl_->stipple = new Bitmap(stippleData[index], 8, 8);
}
}
Color::~Color()
{
delete impl_->stipple;
delete impl_;
}
void Color::intensities(
Display*,
ColorIntensity& r,
ColorIntensity& g,
ColorIntensity& b) const
{
intensities(r, g, b);
}
void Color::intensities(
ColorIntensity& r,
ColorIntensity& g,
ColorIntensity& b) const
{
COLORREF cref = impl_->msColor();
r = (ColorIntensity) (((float) GetRValue(cref)) / 255.0);
g = (ColorIntensity) (((float) GetGValue(cref)) / 255.0);
b = (ColorIntensity) (((float) GetBValue(cref)) / 255.0);
}
float Color::alpha() const
{
return impl_->alpha;
}
const Color* Color::brightness(float adjust) const
{
ColorIntensity r, g, b;
intensities(r, g, b);
if (adjust >= 0)
{
r += (1 - r) * adjust;
g += (1 - g) * adjust;
b += (1 - b) * adjust;
}
else
{
float f = (float) (adjust + 1.0);
r *= f;
g *= f;
b *= f;
}
return new Color(r, g, b);
}
boolean Color::distinguished(const Color* c) const
{
return distinguished(Session::instance()->default_display(), c);
}
boolean Color::distinguished(Display*, const Color* color) const
{
COLORREF cref = color->impl_->msColor();
int red = GetRValue(cref);
int green = GetGValue(cref);
int blue = GetBValue(cref);
COLORREF bogus;
return ( globalPalette.findEntry(red,green,blue,bogus) ) ? false : true;
}
// ---------------------------------------------------------------------------
// Lookup color by name. This is intended to look things up by the X11
// style name, which is partially supported under the Windows implementation.
// If the name starts with a '#' then we translate the hex numbers to rgb
// values directly. Otherwise, we attempt to look up the color name in
// the default colormap.
// ---------------------------------------------------------------------------
const Color* Color::lookup(Display*, const char* name)
{
if (name)
{
// ---- check for rgb specification ----
if (name[0] == '#')
return ColorRep::rgbToColor(name);
// ---- must be a color name ----
const char* rgb;
if (rgb = ColorRep::nameToRGB("default", name))
{
return ColorRep::rgbToColor(rgb);
}
}
return nil;
}
const Color* Color::lookup(Display* d, const String& s)
{
// Since the value is not expected to be null terminiated, we simply
// pass it through to the function that expects a (const char*) arg.
return lookup(d, s.string());
}
boolean Color::find(
const Display* display, const String& name,
ColorIntensity& r, ColorIntensity& g, ColorIntensity& b)
{
NullTerminatedString nm(name);
return find(display, nm.string(), r, g, b);
}
boolean Color::find(
const Display*,
const char* name,
ColorIntensity& r,
ColorIntensity& g,
ColorIntensity& b)
{
const char* rgb;
if (rgb = ColorRep::nameToRGB("default", name))
{
if (rgb[0] == '#')
{
int ir;
int ig;
int ib;
sscanf(&(rgb[1]), "%2x", &ir);
sscanf(&(rgb[3]), "%2x", &ig);
sscanf(&(rgb[5]), "%2x", &ib);
r = (ColorIntensity) (ir/255.0);
g = (ColorIntensity) (ig/255.0);
b = (ColorIntensity) (ib/255.0);
return true;
}
}
return false;
}
| [
"maxwell.p.henderson@gmail.com"
] | maxwell.p.henderson@gmail.com |
a9b9868fb931186318d0bd68444410c2f1fc4899 | da6d4be0d0eaa328972798ee50c5caf2f1e835c0 | /ash/system/holding_space/holding_space_tray_child_bubble.cc | ebade24fa14b724902319757abe0933554940a22 | [
"BSD-3-Clause"
] | permissive | typememo/chromium | 11aaa35726ee96d534ed6887827f3300520b463f | 6d6968680269418cc260e000318ca70ae2d2c034 | refs/heads/master | 2023-02-13T19:23:39.438224 | 2021-01-13T07:45:16 | 2021-01-13T07:45:16 | 328,891,336 | 0 | 0 | BSD-3-Clause | 2021-01-12T06:19:07 | 2021-01-12T06:19:07 | null | UTF-8 | C++ | false | false | 13,391 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "ash/system/holding_space/holding_space_tray_child_bubble.h"
#include <set>
#include "ash/public/cpp/holding_space/holding_space_constants.h"
#include "ash/style/ash_color_provider.h"
#include "ash/system/holding_space/holding_space_item_views_section.h"
#include "ash/system/holding_space/holding_space_util.h"
#include "ash/system/tray/tray_constants.h"
#include "ui/compositor/callback_layer_animation_observer.h"
#include "ui/compositor/layer_animation_observer.h"
#include "ui/compositor/layer_animator.h"
#include "ui/views/layout/box_layout.h"
namespace ash {
namespace {
// Animation.
constexpr base::TimeDelta kAnimationDuration =
base::TimeDelta::FromMilliseconds(167);
// Helpers ---------------------------------------------------------------------
// Returns a callback which deletes the associated animation observer after
// running another `callback`.
using AnimationCompletedCallback = base::OnceCallback<void(bool aborted)>;
base::RepeatingCallback<bool(const ui::CallbackLayerAnimationObserver&)>
DeleteObserverAfterRunning(AnimationCompletedCallback callback) {
return base::BindRepeating(
[](AnimationCompletedCallback callback,
const ui::CallbackLayerAnimationObserver& observer) {
// NOTE: It's safe to move `callback` since this code will only run
// once due to deletion of the associated `observer`. The `observer` is
// deleted by returning `true`.
std::move(callback).Run(/*aborted=*/observer.aborted_count() > 0);
return true;
},
base::Passed(std::move(callback)));
}
// Returns whether the given holding space `model` contains any finalized items
// which are supported by the specified holding space item views `section`.
bool ModelContainsFinalizedItemsForSection(
const HoldingSpaceModel* model,
const HoldingSpaceItemViewsSection* section) {
const auto& supported_types = section->supported_types();
return std::any_of(
supported_types.begin(), supported_types.end(),
[&model](HoldingSpaceItem::Type supported_type) {
return model->ContainsFinalizedItemOfType(supported_type);
});
}
// TopAlignedBoxLayout ---------------------------------------------------------
// A vertical `views::BoxLayout` which overrides layout behavior when there is
// insufficient layout space to accommodate all children's preferred sizes.
// Unlike `views::BoxLayout` which will not allow children to exceed its content
// bounds, TopAlignedBoxLayout will ensure that children still receive their
// preferred sizes. This prevents layout jank that would otherwise occur when
// the host view's bounds are being animated due to content changes.
class TopAlignedBoxLayout : public views::BoxLayout {
public:
TopAlignedBoxLayout(const gfx::Insets& insets, int spacing)
: views::BoxLayout(views::BoxLayout::Orientation::kVertical,
insets,
spacing) {}
private:
// views::BoxLayout:
void Layout(views::View* host) override {
if (host->height() >= host->GetPreferredSize().height()) {
views::BoxLayout::Layout(host);
return;
}
gfx::Rect contents_bounds(host->GetContentsBounds());
contents_bounds.Inset(inside_border_insets());
// If we only have a single child view and that child view is okay with
// being sized arbitrarily small, short circuit layout logic and give that
// child all available layout space. This is the case for the
// `PinnedFileSection` which supports scrolling its content when necessary.
if (host->children().size() == 1u &&
host->children()[0]->GetMinimumSize().IsEmpty()) {
host->children()[0]->SetBoundsRect(contents_bounds);
return;
}
int top = contents_bounds.y();
int left = contents_bounds.x();
int width = contents_bounds.width();
for (views::View* child : host->children()) {
gfx::Size size(width, child->GetHeightForWidth(width));
child->SetBounds(left, top, size.width(), size.height());
top += size.height() + between_child_spacing();
}
}
};
} // namespace
// HoldingSpaceTrayChildBubble -------------------------------------------------
HoldingSpaceTrayChildBubble::HoldingSpaceTrayChildBubble(
HoldingSpaceItemViewDelegate* delegate)
: delegate_(delegate) {
controller_observer_.Observe(HoldingSpaceController::Get());
if (HoldingSpaceController::Get()->model())
model_observer_.Observe(HoldingSpaceController::Get()->model());
}
HoldingSpaceTrayChildBubble::~HoldingSpaceTrayChildBubble() = default;
void HoldingSpaceTrayChildBubble::Init() {
// Layout.
SetLayoutManager(std::make_unique<TopAlignedBoxLayout>(
kHoldingSpaceChildBubblePadding, kHoldingSpaceChildBubbleChildSpacing));
// Layer.
SetPaintToLayer(ui::LAYER_SOLID_COLOR);
layer()->GetAnimator()->set_preemption_strategy(
ui::LayerAnimator::PreemptionStrategy::IMMEDIATELY_ANIMATE_TO_NEW_TARGET);
layer()->SetBackgroundBlur(kUnifiedMenuBackgroundBlur);
layer()->SetColor(AshColorProvider::Get()->GetBaseLayerColor(
AshColorProvider::BaseLayerType::kTransparent80));
layer()->SetFillsBoundsOpaquely(false);
layer()->SetIsFastRoundedCorner(true);
layer()->SetOpacity(0.f);
layer()->SetRoundedCornerRadius(
gfx::RoundedCornersF{kUnifiedTrayCornerRadius});
// Sections.
for (auto& section : CreateSections()) {
sections_.push_back(AddChildView(std::move(section)));
sections_.back()->Init();
}
}
void HoldingSpaceTrayChildBubble::Reset() {
// Prevent animation callbacks from running when the holding space bubble is
// being asynchronously closed. This view will be imminently deleted.
weak_factory_.InvalidateWeakPtrs();
model_observer_.Reset();
controller_observer_.Reset();
for (HoldingSpaceItemViewsSection* section : sections_)
section->Reset();
}
void HoldingSpaceTrayChildBubble::OnHoldingSpaceModelAttached(
HoldingSpaceModel* model) {
model_observer_.Observe(model);
// New model contents, if available, will be populated and animated in after
// the out animation completes.
MaybeAnimateOut();
}
void HoldingSpaceTrayChildBubble::OnHoldingSpaceModelDetached(
HoldingSpaceModel* model) {
model_observer_.Reset();
MaybeAnimateOut();
}
void HoldingSpaceTrayChildBubble::OnHoldingSpaceItemsAdded(
const std::vector<const HoldingSpaceItem*>& items) {
// Ignore new items while the bubble is animating out. The bubble content will
// be updated to match the model after the out animation completes.
if (!is_animating_out_) {
for (HoldingSpaceItemViewsSection* section : sections_)
section->OnHoldingSpaceItemsAdded(items);
}
}
void HoldingSpaceTrayChildBubble::OnHoldingSpaceItemsRemoved(
const std::vector<const HoldingSpaceItem*>& items) {
// Ignore item removal while the bubble is animating out. The bubble content
// will be updated to match the model after the out animation completes.
if (is_animating_out_)
return;
HoldingSpaceModel* model = HoldingSpaceController::Get()->model();
DCHECK(model);
// This child bubble should animate out if the attached model does not
// contain finalized items supported by any of its sections. The exception is
// if a section has a placeholder to show in lieu of holding space items. If
// a placeholder exists, the child bubble should persist.
const bool animate_out = std::none_of(
sections_.begin(), sections_.end(),
[&model](const HoldingSpaceItemViewsSection* section) {
return section->has_placeholder() ||
ModelContainsFinalizedItemsForSection(model, section);
});
if (animate_out) {
MaybeAnimateOut();
return;
}
for (HoldingSpaceItemViewsSection* section : sections_)
section->OnHoldingSpaceItemsRemoved(items);
}
void HoldingSpaceTrayChildBubble::OnHoldingSpaceItemFinalized(
const HoldingSpaceItem* item) {
// Ignore item finalization while the bubble is animating out. The bubble
// content will be updated to match the model after the out animation
// completes.
if (!is_animating_out_) {
for (HoldingSpaceItemViewsSection* section : sections_)
section->OnHoldingSpaceItemFinalized(item);
}
}
const char* HoldingSpaceTrayChildBubble::GetClassName() const {
return "HoldingSpaceTrayChildBubble";
}
void HoldingSpaceTrayChildBubble::ChildPreferredSizeChanged(
views::View* child) {
PreferredSizeChanged();
}
void HoldingSpaceTrayChildBubble::ChildVisibilityChanged(views::View* child) {
// This child bubble should be visible iff it has visible children.
bool visible = false;
for (const views::View* c : children()) {
if (c->GetVisible()) {
visible = true;
break;
}
}
if (visible != GetVisible()) {
SetVisible(visible);
// When the child bubble becomes visible, its due to one of its sections
// becoming visible. In this case, the child bubble should animate in.
if (GetVisible())
MaybeAnimateIn();
}
PreferredSizeChanged();
}
void HoldingSpaceTrayChildBubble::MaybeAnimateIn() {
// Don't preempt an out animation as new content will populate and be animated
// in, if any exists, once the out animation completes.
if (is_animating_out_)
return;
// Don't attempt to animate in this bubble unnecessarily as it will cause
// opacity to revert to zero before proceeding to animate in. Ensure that
// event processing is enabled as it may have been disabled while animating
// this bubble out.
if (layer()->GetTargetOpacity() == 1.f) {
SetCanProcessEventsWithinSubtree(true);
return;
}
// NOTE: `animate_in_observer` is deleted after `OnAnimateInCompleted()`.
ui::CallbackLayerAnimationObserver* animate_in_observer =
new ui::CallbackLayerAnimationObserver(DeleteObserverAfterRunning(
base::BindOnce(&HoldingSpaceTrayChildBubble::OnAnimateInCompleted,
weak_factory_.GetWeakPtr())));
AnimateIn(animate_in_observer);
animate_in_observer->SetActive();
}
void HoldingSpaceTrayChildBubble::MaybeAnimateOut() {
if (is_animating_out_)
return;
// Child bubbles should not process events when being animated as the model
// objects backing their views may no longer exist. Event processing will be
// re-enabled on animation completion.
SetCanProcessEventsWithinSubtree(false);
// NOTE: `animate_out_observer` is deleted after `OnAnimateOutCompleted()`.
ui::CallbackLayerAnimationObserver* animate_out_observer =
new ui::CallbackLayerAnimationObserver(DeleteObserverAfterRunning(
base::BindOnce(&HoldingSpaceTrayChildBubble::OnAnimateOutCompleted,
weak_factory_.GetWeakPtr())));
AnimateOut(animate_out_observer);
animate_out_observer->SetActive();
}
void HoldingSpaceTrayChildBubble::AnimateIn(
ui::LayerAnimationObserver* observer) {
DCHECK(!is_animating_out_);
// Delay in animations to give the holding space bubble time to animate its
// layout changes. This ensures that there is sufficient space to display the
// child bubble before it is displayed to the user.
const base::TimeDelta animation_delay = kAnimationDuration;
holding_space_util::AnimateIn(this, kAnimationDuration, animation_delay,
observer);
}
void HoldingSpaceTrayChildBubble::AnimateOut(
ui::LayerAnimationObserver* observer) {
DCHECK(!is_animating_out_);
is_animating_out_ = true;
// Animation is only necessary if this view is visible to the user.
const base::TimeDelta animation_duration =
IsDrawn() ? kAnimationDuration : base::TimeDelta();
holding_space_util::AnimateOut(this, animation_duration, observer);
}
void HoldingSpaceTrayChildBubble::OnAnimateInCompleted(bool aborted) {
// Restore event processing once the child bubble has fully animated in. Its
// contents are guaranteed to exist in the model and can be acted upon by the
// user.
if (!aborted)
SetCanProcessEventsWithinSubtree(true);
}
void HoldingSpaceTrayChildBubble::OnAnimateOutCompleted(bool aborted) {
DCHECK(is_animating_out_);
is_animating_out_ = false;
if (aborted)
return;
// Once the child bubble has animated out it is transparent but still
// "visible" as far as the views framework is concerned and so takes up layout
// space. Hide the view so that the holding space bubble will animate the
// re-layout of its view hierarchy with this child bubble taking no space.
SetVisible(false);
for (HoldingSpaceItemViewsSection* section : sections_)
section->RemoveAllHoldingSpaceItemViews();
HoldingSpaceModel* model = HoldingSpaceController::Get()->model();
if (!model || model->items().empty())
return;
std::vector<const HoldingSpaceItem*> item_ptrs;
for (const auto& item : model->items())
item_ptrs.push_back(item.get());
// Populating a `section` may cause it's visibility to change if the `model`
// contains finalized items of types which it supports. This, in turn, will
// cause visibility of this child bubble to update and animate in if needed.
for (HoldingSpaceItemViewsSection* section : sections_)
section->OnHoldingSpaceItemsAdded(item_ptrs);
}
} // namespace ash
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
81d720740baa00042496a950b2f0a27ea7a388a4 | 777a75e6ed0934c193aece9de4421f8d8db01aac | /src/Providers/UNIXProviders/ModulePort/UNIX_ModulePort_FREEBSD.hxx | 640feed156ae617771f10279342a5ebba6a21f4e | [
"MIT"
] | permissive | brunolauze/openpegasus-providers-old | 20fc13958016e35dc4d87f93d1999db0eae9010a | b00f1aad575bae144b8538bf57ba5fd5582a4ec7 | refs/heads/master | 2021-01-01T20:05:44.559362 | 2014-04-30T17:50:06 | 2014-04-30T17:50:06 | 19,132,738 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118 | hxx | #ifdef PEGASUS_OS_FREEBSD
#ifndef __UNIX_MODULEPORT_PRIVATE_H
#define __UNIX_MODULEPORT_PRIVATE_H
#endif
#endif
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
7b2b848bbd63df8c95cce17473e97f0f9e78ce3b | bb7cc2b21d4337ca8f0889e29b01a4fdfd301d8c | /RlgtLik/src/etsTargetFunctionWrapper.cpp | e040661351e02a831bd0404a2432527ba6a7bf93 | [] | no_license | cbergmeir/Rlgt | 2d8ecb948c3c26cb28b1c4108ed82b3a9b4e0f22 | 652ba908205ca49a92e166000fea24843a33f02c | refs/heads/master | 2023-08-31T13:17:37.877023 | 2023-08-31T07:46:53 | 2023-08-31T07:46:53 | 154,053,696 | 21 | 13 | null | 2023-09-11T05:46:22 | 2018-10-21T21:25:08 | R | UTF-8 | C++ | false | false | 5,183 | cpp |
#include <vector>
#include <string>
#include <R_ext/Error.h>
//For R's Nelder-Mead solver
#include <R_ext/Applic.h>
#include <Rcpp.h>
#include "etsTargetFunction.h"
// This function initializes all the parameters, constructs an
// object of type EtsTargetFunction and adds an external pointer
// to this object with name "ets.xptr"
// to the environment submitted as p_rho
//
RcppExport SEXP etsTargetFunctionInit(SEXP p_y, SEXP p_nstate, SEXP p_errortype, SEXP p_trendtype,
SEXP p_seasontype, SEXP p_damped, SEXP p_lower, SEXP p_upper,
SEXP p_opt_crit, SEXP p_nmse, SEXP p_bounds, SEXP p_m,
SEXP p_optAlpha, SEXP p_optBeta, SEXP p_optGamma, SEXP p_optPhi, SEXP p_optLambda, SEXP p_optRho,
SEXP p_givenAlpha, SEXP p_givenBeta, SEXP p_givenGamma, SEXP p_givenPhi, SEXP p_givenLambda, SEXP p_givenRho,
SEXP p_alpha, SEXP p_beta, SEXP p_gamma, SEXP p_phi, SEXP p_lambda, SEXP p_rho, SEXP p_envir) {
BEGIN_RCPP;
EtsTargetFunction* sp = new EtsTargetFunction();
std::vector<double> y = Rcpp::as< std::vector<double> >(p_y);
int nstate = Rcpp::as<int>(p_nstate);
int errortype = Rcpp::as<int>(p_errortype);
int trendtype = Rcpp::as<int>(p_trendtype);
int seasontype = Rcpp::as<int>(p_seasontype);
bool damped = Rcpp::as<bool>(p_damped);
std::vector<double> lower = Rcpp::as< std::vector<double> >(p_lower);
std::vector<double> upper = Rcpp::as< std::vector<double> >(p_upper);
std::string opt_crit = Rcpp::as<std::string>(p_opt_crit);
int nmse = Rcpp::as<int>(p_nmse);
std::string bounds = Rcpp::as< std::string >(p_bounds);
int m = Rcpp::as<int>(p_m);
bool optAlpha = Rcpp::as<bool>(p_optAlpha);
bool optBeta = Rcpp::as<bool>(p_optBeta);
bool optGamma = Rcpp::as<bool>(p_optGamma);
bool optPhi = Rcpp::as<bool>(p_optPhi);
bool optLambda = Rcpp::as<bool>(p_optLambda);
bool optRho = Rcpp::as<bool>(p_optRho);
bool givenAlpha = Rcpp::as<bool>(p_givenAlpha);
bool givenBeta = Rcpp::as<bool>(p_givenBeta);
bool givenGamma = Rcpp::as<bool>(p_givenGamma);
bool givenPhi = Rcpp::as<bool>(p_givenPhi);
bool givenLambda = Rcpp::as<bool>(p_givenLambda);
bool givenRho = Rcpp::as<bool>(p_givenRho);
double alpha = Rcpp::as<double>(p_alpha);
double beta = Rcpp::as<double>(p_beta);
double gamma = Rcpp::as<double>(p_gamma);
double phi = Rcpp::as<double>(p_phi);
double lambda = Rcpp::as<double>(p_lambda);
double rho = Rcpp::as<double>(p_rho);
sp->init(y, nstate, errortype, trendtype, seasontype, damped, lower, upper, opt_crit,
nmse, bounds, m, optAlpha, optBeta, optGamma, optPhi, optLambda, optRho,
givenAlpha, givenBeta, givenGamma, givenPhi, givenLambda, givenRho,
alpha, beta, gamma, phi, lambda, rho);
Rcpp::Environment e(p_envir);
e["ets.xptr"] = Rcpp::XPtr<EtsTargetFunction>( sp, true );
return Rcpp::wrap(e);
END_RCPP;
}
RcppExport double targetFunctionRmalschains(SEXP p_par, SEXP p_env)
{
Rcpp::NumericVector par(p_par);
Rcpp::Environment e(p_env);
Rcpp::XPtr<EtsTargetFunction> sp(e.get("ets.xptr"));
sp->eval(par.begin(), par.size());
//return Rcpp::wrap(sp->getObjVal());
return sp->getObjVal();
}
RcppExport SEXP etsGetTargetFunctionRmalschainsPtr() {
typedef double (*funcPtr)(SEXP, SEXP);
return (Rcpp::XPtr<funcPtr>(new funcPtr(&targetFunctionRmalschains)));
}
/*
RcppExport SEXP targetFunctionRdonlp2(SEXP p_var, SEXP p_env)
{
Rcpp::Environment e(p_env);
Rcpp::XPtr<EtsTargetFunction> sp(e.get("ets.xptr"));
Rcpp::NumericVector var(p_var);
int mode = var[0];
int fun_id = var[1];
sp->eval(var.begin()+2, var.size()-2);
if(mode == 0) {
if(fun_id == 0) {
return Rcpp::wrap(sp->getObjVal());
} else {
return Rcpp::wrap(0);
//return Rcpp::wrap(sp->restrictions[fun_id-1]);
}
} else if(mode==1) {
// error("Gradients are not implemented, exiting.");
};
return R_NilValue;
}
RcppExport SEXP etsGetTargetFunctionRdonlp2Ptr() {
typedef SEXP (*funcPtr)(SEXP, SEXP);
return (Rcpp::XPtr<funcPtr>(new funcPtr(&targetFunctionRdonlp2)));
}
*/
double targetFunctionEtsNelderMead(int n, double *par, void *ex)
{
EtsTargetFunction* sp = (EtsTargetFunction*) ex;
sp->eval(par, n);
return sp->getObjVal();
}
RcppExport SEXP etsNelderMead(SEXP p_var, SEXP p_env, SEXP p_abstol,
SEXP p_intol, SEXP p_alpha, SEXP p_beta, SEXP p_gamma,
SEXP p_trace, SEXP p_maxit)
{
double abstol = Rcpp::as<double>(p_abstol);
double intol = Rcpp::as<double>(p_intol);
double alpha = Rcpp::as<double>(p_alpha);
double beta= Rcpp::as<double>(p_beta);
double gamma= Rcpp::as<double>(p_gamma);
int trace = Rcpp::as<int>(p_trace);
int maxit = Rcpp::as<int>(p_maxit);
int fncount = 0, fail=0;
double Fmin = 0.0;
Rcpp::NumericVector dpar(p_var);
Rcpp::NumericVector opar(dpar.size());
Rcpp::Environment e(p_env);
Rcpp::XPtr<EtsTargetFunction> sp(e.get("ets.xptr"));
double (*funcPtr)(int n, double *par, void *ex) = targetFunctionEtsNelderMead;
nmmin(dpar.size(), dpar.begin(), opar.begin(), &Fmin, funcPtr,
&fail, abstol, intol, sp, alpha, beta, gamma, trace, &fncount, maxit);
return Rcpp::List::create(Rcpp::Named("value") = Fmin,
Rcpp::Named("par") = opar,
Rcpp::Named("fail") = fail,
Rcpp::Named("fncount") = fncount);
}
| [
"christoph.bergmeir@gmail.com"
] | christoph.bergmeir@gmail.com |
0cb8c05d0ab24d7025c5415cbe933cd490c91e70 | 6a4455557cf5338036c902e5668b9687d6514f0a | /Employee/Employee/main.cpp | 96cbacd0370eb98acbab59ce3a1cf7afd9b85220 | [] | no_license | k-alabba/Assignment-4 | 2f360010aa806461657a58c67aa33c53d5030d91 | 7688e4ee9ed924e5898b9be3c4b03e09f572f863 | refs/heads/main | 2023-01-12T23:20:44.030274 | 2020-11-17T03:48:23 | 2020-11-17T03:48:23 | 313,495,707 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,565 | cpp | #include <iostream>
#include "Employee.h"
using namespace std;
/*
* Name: Alabbas, Kumai
* ID:40175088
* Main function for testing the Employee class
* Date: 16-11-2020
*/
//Testing Employee class
int main() {
Employee firstEmp, secondEmp, thirndEmp;
firstEmp.setFirstName("Rose");
firstEmp.setLastName("Gomar");
firstEmp.setHiredYear(2010);
firstEmp.setSalary(90000);
secondEmp.setFirstName("Souleymane");
secondEmp.setLastName("Gomar");
secondEmp.setHiredYear(2012);
secondEmp.setSalary(10); //poor guy
thirndEmp.setFirstName("Kumai");
thirndEmp.setLastName("Alabbas");
thirndEmp.setHiredYear(2010);
thirndEmp.setSalary(3); //very poor guy
thirndEmp.setDateOfBirth("25-Jan-1999");
printf("\nFirst Employee has the same last name as the second?\n");
firstEmp.hasSameLastNameAs(secondEmp) ? cout << "True" : cout << "False";
printf("\n\nFirst Employee has the same last name as the third?\n");
firstEmp.hasSameLastNameAs(thirndEmp) ? cout << "True" : cout << "False";
printf("\n\nFirst Employee has the same salary or hired year as the second?\n");
firstEmp.hasSameSalaryOrHiredYearAs(secondEmp) ? cout << "True" : cout << "False";
printf("\n\nFirst Employee has the same salary or hired year as the third?\n");
firstEmp.hasSameSalaryOrHiredYearAs(thirndEmp) ? cout << "True" : cout << "False";
cout << "\n\nThe full name of the first employee is " << firstEmp.getFullName();
cout << "\n\nThe date of birth of the third employee is " << thirndEmp.getDateOfBirth() << "\n";
return 0;
} | [
"noreply@github.com"
] | noreply@github.com |
11177bfcd3d5ff0c435188fd2913dd09c8be365a | 35be06835f1f1826c9c07eb469b4c0debcf55fa9 | /src/data.cc | f033b0537e45e14d082e5edd4b54cb99a607db66 | [] | no_license | Zakys98/owo | 30770a459eae64347de39bb8ed11c923a808a0dc | b16e2760f8219226d7188924f51f823573a0c21d | refs/heads/master | 2023-07-10T06:21:22.954051 | 2021-07-02T20:29:43 | 2021-07-02T20:29:43 | 287,541,199 | 0 | 0 | null | 2021-08-17T18:35:32 | 2020-08-14T13:37:35 | C++ | UTF-8 | C++ | false | false | 213 | cc | #include "../include/data.h"
int Data::getId() { return id; }
void Data::setId(int id) { this->id = id; }
std::string Data::getText() { return text; }
void Data::setText(std::string &s) {
this->text = s;
} | [
"zakys98@gmail.com"
] | zakys98@gmail.com |
94af554b52ed653d34cfc2c0edd5974c370133c6 | a231d5a776b958132f142ba5ecc1f6453bd14988 | /SFML/Enemy.h | 8328979d12a016c6e76c731639c24a0bd1555e0c | [] | no_license | DaveVanStaden/Kernmodule-1 | 90b0d0f84df425ee127c9329d4b5c2e760a1d1b0 | 6a7d50f55d708ecb61969ee08c3ddbe13d6f2feb | refs/heads/main | 2023-06-27T05:43:42.967121 | 2021-08-01T18:58:34 | 2021-08-01T18:58:34 | 376,013,099 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 735 | h | #ifndef SFML_ENEMY_H
#define SFML_ENEMY_H
#define _DEBUG
#include "Circle.h"
#include <SFML/Graphics.hpp>
class Enemy : public Circle{
public:
Enemy(float xPos, float yPos, int windowWidth, int windowHeight): Circle(xPos,yPos,windowWidth,windowHeight){};
Enemy() = default;
void Movement(int windowWidth, int windowHeight,sf::RenderWindow* RWindow);
void DrawCircle(sf::RenderWindow* RWindow);
void GenerateColor();
void SetColor(int WhichColor, sf::CircleShape &circle);
void ResetPosition();
sf::CircleShape enemyShape;
bool startDirection = false;
int direction;
int ballColor;
float minSpeed = -2;
float speed = 0.1;
float maxSpeed = 2;
private:
};
#endif //SFML_ENEMY_H
| [
"dave.van.staden@outlook.com"
] | dave.van.staden@outlook.com |
8696bde3abed21c3a6dd43e65fc08754d2eccf9a | dc0b1da910fca8446652aabf53397531cc94c5f4 | /aws-cpp-sdk-kms/source/model/ReEncryptResult.cpp | aaa6f230e6a2efa2034aaaf3cb265e7645f8af45 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | capeanalytics/aws-sdk-cpp | 19db86298a6daaee59c4b9fba82acedacd658bdf | e88f75add5a9433601b6d46fe738e493da56ac3b | refs/heads/master | 2020-04-06T04:03:12.337555 | 2017-05-11T13:31:39 | 2017-05-11T13:31:39 | 57,893,688 | 0 | 0 | Apache-2.0 | 2018-07-30T16:46:55 | 2016-05-02T13:51:23 | C++ | UTF-8 | C++ | false | false | 1,595 | cpp | /*
* Copyright 2010-2017 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/kms/model/ReEncryptResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <aws/core/utils/HashingUtils.h>
#include <utility>
using namespace Aws::KMS::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ReEncryptResult::ReEncryptResult()
{
}
ReEncryptResult::ReEncryptResult(const AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ReEncryptResult& ReEncryptResult::operator =(const AmazonWebServiceResult<JsonValue>& result)
{
const JsonValue& jsonValue = result.GetPayload();
if(jsonValue.ValueExists("CiphertextBlob"))
{
m_ciphertextBlob = HashingUtils::Base64Decode(jsonValue.GetString("CiphertextBlob"));
}
if(jsonValue.ValueExists("SourceKeyId"))
{
m_sourceKeyId = jsonValue.GetString("SourceKeyId");
}
if(jsonValue.ValueExists("KeyId"))
{
m_keyId = jsonValue.GetString("KeyId");
}
return *this;
}
| [
"henso@amazon.com"
] | henso@amazon.com |
693dc8dfb9e2e859bf44af1c28ccd9f3f3827533 | 1c14a24ccf6091f957eaeb83f9c181d989b07a91 | /src/procedural/Turtle.cpp | 52ab3a0e1e3ecdd8f38fe5f0fc2b9c5e19f2f0d1 | [] | no_license | hann2/3D-Graphics-Playground | 07b33a78f74ac6e09aadcef042d3005dcf65d2f2 | a44bd164360880ddd2a99d1b5fd1b72ddd410367 | refs/heads/master | 2020-12-24T14:35:46.135636 | 2014-05-17T22:37:55 | 2014-05-17T22:37:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 950 | cpp |
#include "Turtle.h"
#include <glm/gtc/matrix_transform.hpp>
Turtle::Turtle() {
turtle_state_stack = std::vector<glm::mat4 *>();
turtle_state = new glm::mat4();
}
void Turtle::pitch(float angle) {
*turtle_state = glm::rotate(*turtle_state, angle, glm::vec3(0.0, 1.0, 0.0));
}
void Turtle::roll(float angle) {
*turtle_state = glm::rotate(*turtle_state, angle, glm::vec3(0.0, 0.0, 1.0));
}
void Turtle::yaw(float angle) {
*turtle_state = glm::rotate(*turtle_state, angle, glm::vec3(1.0, 0.0, 0.0));
}
void Turtle::forward(float amount) {
*turtle_state = glm::translate(*turtle_state, glm::vec3(0, 0, amount));
}
void Turtle::push_state() {
turtle_state_stack.push_back(new glm::mat4(*turtle_state));
}
void Turtle::pop_state() {
delete turtle_state;
turtle_state = turtle_state_stack.back();
turtle_state_stack.pop_back();
}
glm::mat4 * Turtle::peek_state() {
return new glm::mat4(*turtle_state);
}
| [
"phann92@gmail.com"
] | phann92@gmail.com |
d60a648227baf84284ac22c344c715bb33812f6e | 32008c385f0f676714133fcddc8904b180b379ae | /code_book/Thinking C++/master/C07/PriorityQueue5.cpp | a156eeb1dea7622f5dee3f9a8feaa3bb23e61f6b | [] | no_license | dracohan/code | d92dca0a4ee6e0b3c10ea3c4f381cb1068a10a6e | 378b6fe945ec2e859cc84bf50375ec44463f23bb | refs/heads/master | 2023-08-18T23:32:30.565886 | 2023-08-17T17:16:29 | 2023-08-17T17:16:29 | 48,644,403 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 873 | cpp | //: C07:PriorityQueue5.cpp
// Building your own priority queue
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <iterator>
#include <queue>
using namespace std;
template<class T, class Compare>
class PQV : public vector<T> {
Compare comp;
public:
PQV(Compare cmp = Compare()) : comp(cmp) {
make_heap(begin(), end(), comp);
}
const T& top() { return front(); }
void push(const T& x) {
push_back(x);
push_heap(begin(), end(), comp);
}
void pop() {
pop_heap(begin(), end(), comp);
pop_back();
}
};
int main() {
PQV<int, less<int> > pqi;
srand(time(0));
for(int i = 0; i < 100; i++)
pqi.push(rand() % 25);
copy(pqi.begin(), pqi.end(),
ostream_iterator<int>(cout, " "));
cout << endl;
while(!pqi.empty()) {
cout << pqi.top() << ' ';
pqi.pop();
}
} ///:~
| [
"13240943@qq.com"
] | 13240943@qq.com |
99ef2c30c49736c0fbebf9491b7e4b8f0401fe27 | aad6b08ee56c2760b207d562f16be0a5bb8e3e2a | /tags/Robespierre_2.0_post-merge/WebKit/win/WebIconDatabase.h | 1a2e59142d4cd7dbad03aeb9d77f9c8b6eddc55b | [
"BSD-3-Clause"
] | permissive | Chengjian-Tang/owb-mirror | 5ffd127685d06f2c8e00832c63cd235bec63f753 | b48392a07a2f760bfc273d8d8b80e8d3f43b6b55 | refs/heads/master | 2021-05-27T02:09:03.654458 | 2010-06-23T11:10:12 | 2010-06-23T11:10:12 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,125 | h | /*
* Copyright (C) 2006, 2007 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``AS IS'' AND ANY
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
* OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef WebIconDatabase_H
#define WebIconDatabase_H
#include "IWebIconDatabase.h"
#pragma warning(push, 0)
#include <WebCore/IconDatabaseClient.h>
#include <WebCore/IntSize.h>
#include <WebCore/IntSizeHash.h>
#include <WebCore/Threading.h>
#pragma warning(pop)
#include <WTF/HashMap.h>
#include <windows.h>
typedef const struct __CFString * CFStringRef;
namespace WebCore
{
class IconDatabase;
}; //namespace WebCore
using namespace WebCore;
using namespace WTF;
class WebIconDatabase : public IWebIconDatabase, public WebCore::IconDatabaseClient
{
public:
static WebIconDatabase* createInstance();
static WebIconDatabase* sharedWebIconDatabase();
private:
WebIconDatabase();
~WebIconDatabase();
void init();
public:
// IUnknown
virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppvObject);
virtual ULONG STDMETHODCALLTYPE AddRef(void);
virtual ULONG STDMETHODCALLTYPE Release(void);
// IWebIconDatabase
virtual HRESULT STDMETHODCALLTYPE sharedIconDatabase(
/* [retval][out] */ IWebIconDatabase **result);
virtual HRESULT STDMETHODCALLTYPE iconForURL(
/* [in] */ BSTR url,
/* [optional][in] */ LPSIZE size,
/* [optional][in] */ BOOL cache,
/* [retval][out] */ OLE_HANDLE *image);
virtual HRESULT STDMETHODCALLTYPE defaultIconWithSize(
/* [in] */ LPSIZE size,
/* [retval][out] */ OLE_HANDLE *result);
virtual HRESULT STDMETHODCALLTYPE retainIconForURL(
/* [in] */ BSTR url);
virtual HRESULT STDMETHODCALLTYPE releaseIconForURL(
/* [in] */ BSTR url);
virtual HRESULT STDMETHODCALLTYPE removeAllIcons( void);
virtual HRESULT STDMETHODCALLTYPE delayDatabaseCleanup( void);
virtual HRESULT STDMETHODCALLTYPE allowDatabaseCleanup( void);
// IconDatabaseClient
virtual void dispatchDidRemoveAllIcons();
virtual void dispatchDidAddIconForPageURL(const WebCore::String&);
static BSTR iconDatabaseDidAddIconNotification();
static BSTR iconDatabaseDidRemoveAllIconsNotification();
static CFStringRef iconDatabaseNotificationUserInfoURLKey();
protected:
ULONG m_refCount;
static WebIconDatabase* m_sharedWebIconDatabase;
// Keep a set of HBITMAPs around for the default icon, and another
// to share amongst present site icons
HBITMAP getOrCreateSharedBitmap(LPSIZE size);
HBITMAP getOrCreateDefaultIconBitmap(LPSIZE size);
HashMap<IntSize, HBITMAP> m_defaultIconMap;
HashMap<IntSize, HBITMAP> m_sharedIconMap;
Mutex m_notificationMutex;
Vector<String> m_notificationQueue;
void scheduleNotificationDelivery();
bool m_deliveryRequested;
static void deliverNotifications();
};
#endif
| [
"odole@a3cd4a6d-042f-0410-9b26-d8d12826d3fb"
] | odole@a3cd4a6d-042f-0410-9b26-d8d12826d3fb |
caacf42a13ec6799ab530a13e735bd99904d61c5 | 637b8bb433513f5446e75ac224c7bb115969f785 | /010-regular-expression-matching/regular-expression-matching.cpp | 9332bfe6b788b501b81385a5a2633e49b4759cf7 | [
"MIT"
] | permissive | TJUSsr/leetcodesolution | 48cb455f37fa577fed8152d4208bcc4dbe28d632 | 8244de2d76c9e8e5b9d98dd1e8efed4d680d44ee | refs/heads/master | 2022-12-11T21:13:03.008447 | 2018-12-06T14:46:41 | 2018-12-06T14:46:41 | 130,249,136 | 0 | 0 | MIT | 2022-12-08T01:13:43 | 2018-04-19T17:21:11 | C++ | UTF-8 | C++ | false | false | 2,051 | cpp | // Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.
//
//
// '.' Matches any single character.
// '*' Matches zero or more of the preceding element.
//
//
// The matching should cover the entire input string (not partial).
//
// Note:
//
//
// s could be empty and contains only lowercase letters a-z.
// p could be empty and contains only lowercase letters a-z, and characters like . or *.
//
//
// Example 1:
//
//
// Input:
// s = "aa"
// p = "a"
// Output: false
// Explanation: "a" does not match the entire string "aa".
//
//
// Example 2:
//
//
// Input:
// s = "aa"
// p = "a*"
// Output: true
// Explanation: '*' means zero or more of the precedeng element, 'a'. Therefore, by repeating 'a' once, it becomes "aa".
//
//
// Example 3:
//
//
// Input:
// s = "ab"
// p = ".*"
// Output: true
// Explanation: ".*" means "zero or more (*) of any character (.)".
//
//
// Example 4:
//
//
// Input:
// s = "aab"
// p = "c*a*b"
// Output: true
// Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore it matches "aab".
//
//
// Example 5:
//
//
// Input:
// s = "mississippi"
// p = "mis*is*p*."
// Output: false
//
//
static const auto __ = []()
{
ios::sync_with_stdio(false);
cin.tie(nullptr);
return nullptr;
}();
class Solution {
public:
bool isMatch(string s, string p) {
if (s.empty()&&p.empty()) return true;
if ( p.empty()) return false;
vector<vector<bool>> dp(s.size() + 1, vector<bool>(p.size() + 1, false));
dp[0][0] = true;
for (int i = 0; i < s.size() + 1; ++i)
{
for (int j = 1; j < p.size() + 1; ++j)
{
if (i>0&&(s[i-1] == p[j-1] || p[j-1] == '.')) dp[i][j] = (dp[i - 1][j - 1]?true:dp[i][j]);
if (p[j-1] == '*')
{
if (i>0&&(p[j - 1-1] == s[i-1]|| p[j - 1 - 1] == '.'))
{
dp[i][j] = dp[i][j - 1] || dp[i - 1][j]||dp[i][j-2];
}
else
{
dp[i][j] = dp[i][j - 2];
}
}
}
}
return dp[s.size()][p.size()];
}
};
| [
"1631559@tongji.edu.cn"
] | 1631559@tongji.edu.cn |
259b19d810741f5c292c8b85e3422f726f18b457 | 866d4b4507d83a6f787bc7e4b1a584442b67b3f5 | /DTK/DTK/dcmtk/include/dcmtk/dcmsign/simac.h | 18d966be4ebb6cc11cac746d5feee64263c257e3 | [] | no_license | jamil36/DCTMK-iOS-Demo | 464d1ccd7d029ef7ba98c9c2cbc9fd181f02264b | 038d9b39eb3b7c9b4bd22b75fedf434f2637a7ec | refs/heads/master | 2022-11-24T07:51:39.945598 | 2019-07-17T01:50:59 | 2019-07-17T01:50:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,861 | h | /*
*
* Copyright (C) 1998-2010, OFFIS e.V.
* All rights reserved. See COPYRIGHT file for details.
*
* This software and supporting documentation were developed by
*
* OFFIS e.V.
* R&D Division Health
* Escherweg 2
* D-26121 Oldenburg, Germany
*
*
* Module: dcmsign
*
* Author: Norbert Loxen, Marco Eichelberg
*
* Purpose:
* classes: SiMAC
*
* Last Update: $Author: joergr $
* Update Date: $Date: 2010-10-14 13:17:25 $
* CVS/RCS Revision: $Revision: 1.6 $
* Status: $State: Exp $
*
* CVS/RCS Log at end of file
*
*/
#ifndef SIMAC_H
#define SIMAC_H
#include "osconfig.h"
#include "dcmtk/dcmsign/sitypes.h"
#ifdef WITH_OPENSSL
/**
* a base class for all classes that implement hash functions.
*/
class SiMAC
{
public:
/// default constructor
SiMAC() { }
/// destructor
virtual ~SiMAC() { }
/** initializes the MAC algorithm.
* @return status code
*/
virtual OFCondition initialize() = 0;
/** feeds data into the MAC algorithm
* @param data pointer to raw data to be fed into the MAC, must not be NULL
* @param length number of bytes in raw data array
* @return status code
*/
virtual OFCondition digest(const unsigned char *data, unsigned long length) = 0;
/** finalizes the MAC and writes it to the given output array,
* which must be at least getSize() bytes large.
* After a call to finalize, the MAC algorithm must be initialized
* again, see initialize().
* @param result pointer to array of getSize() bytes into which the MAC is written
* @return status code
*/
virtual OFCondition finalize(unsigned char *result) = 0;
/** returns the size of a MAC in bytes.
* @return block size for this MAC algorithm
*/
virtual unsigned long getSize() const = 0;
/** returns the type of MAC algorithm computed by this object
* @return type of MAC algorithm
*/
virtual E_MACType macType() const = 0;
/** returns the DICOM identifier for this MAC algorithm
* @return DICOM defined term for algorithm
*/
virtual const char *getDefinedTerm() const = 0;
};
#endif
#endif
/*
* $Log: simac.h,v $
* Revision 1.6 2010-10-14 13:17:25 joergr
* Updated copyright header. Added reference to COPYRIGHT file.
*
* Revision 1.5 2005-12-08 16:04:37 meichel
* Changed include path schema for all DCMTK header files
*
* Revision 1.4 2003/06/04 14:21:03 meichel
* Simplified include structure to avoid preprocessor limitation
* (max 32 #if levels) on MSVC5 with STL.
*
* Revision 1.3 2001/09/26 14:30:20 meichel
* Adapted dcmsign to class OFCondition
*
* Revision 1.2 2001/06/01 15:50:49 meichel
* Updated copyright header
*
* Revision 1.1 2000/11/07 16:48:55 meichel
* Initial release of dcmsign module for DICOM Digital Signatures
*
*
*/
| [
"luojiamingjamail@gmail.com"
] | luojiamingjamail@gmail.com |
07f26b41f8d29879f936527ba06235fc295e0804 | 73cfd700522885a3fec41127e1f87e1b78acd4d3 | /_Include/boost/mpl/aux_/preprocessed/msvc70/map.hpp | b8f3a6c693222b0e591c335f8a1fb628ef039c46 | [] | no_license | pu2oqa/muServerDeps | 88e8e92fa2053960671f9f57f4c85e062c188319 | 92fcbe082556e11587887ab9d2abc93ec40c41e4 | refs/heads/master | 2023-03-15T12:37:13.995934 | 2019-02-04T10:07:14 | 2019-02-04T10:07:14 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,293 | hpp |
// Copyright Aleksey Gurtovoy 2000-2004
//
// 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)
//
// Preprocessed version of "boost/mpl/map.hpp" header
// -- DO NOT modify by hand!
namespace boost { namespace mpl {
namespace aux {
template< int N >
struct map_chooser;
}
namespace aux {
template<>
struct map_chooser<0>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef map0<
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<1>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map1<
T0
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<2>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map2<
T0, T1
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<3>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map3<
T0, T1, T2
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<4>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map4<
T0, T1, T2, T3
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<5>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map5<
T0, T1, T2, T3, T4
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<6>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map6<
T0, T1, T2, T3, T4, T5
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<7>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map7<
T0, T1, T2, T3, T4, T5, T6
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<8>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map8<
T0, T1, T2, T3, T4, T5, T6, T7
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<9>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map9<
T0, T1, T2, T3, T4, T5, T6, T7, T8
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<10>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map10<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<11>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map11<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<12>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map12<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<13>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map13<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<14>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map14<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<15>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map15<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<16>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map16<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<17>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map17<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<18>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map18<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<19>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map19<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18
>::type type;
};
};
} // namespace aux
namespace aux {
template<>
struct map_chooser<20>
{
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct result_
{
typedef typename map20<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
};
} // namespace aux
namespace aux {
template< typename T >
struct is_map_arg
{
BOOST_STATIC_CONSTANT(bool, value = true);
};
template<>
struct is_map_arg<na>
{
BOOST_STATIC_CONSTANT(bool, value = false);
};
template<
typename T1, typename T2, typename T3, typename T4, typename T5
, typename T6, typename T7, typename T8, typename T9, typename T10
, typename T11, typename T12, typename T13, typename T14, typename T15
, typename T16, typename T17, typename T18, typename T19, typename T20
>
struct map_count_args
{
BOOST_STATIC_CONSTANT(int, value =
is_map_arg<T1>::value + is_map_arg<T2>::value
+ is_map_arg<T3>::value + is_map_arg<T4>::value
+ is_map_arg<T5>::value + is_map_arg<T6>::value
+ is_map_arg<T7>::value + is_map_arg<T8>::value
+ is_map_arg<T9>::value + is_map_arg<T10>::value
+ is_map_arg<T11>::value + is_map_arg<T12>::value
+ is_map_arg<T13>::value + is_map_arg<T14>::value
+ is_map_arg<T15>::value + is_map_arg<T16>::value
+ is_map_arg<T17>::value + is_map_arg<T18>::value
+ is_map_arg<T19>::value + is_map_arg<T20>::value
);
};
template<
typename T0, typename T1, typename T2, typename T3, typename T4
, typename T5, typename T6, typename T7, typename T8, typename T9
, typename T10, typename T11, typename T12, typename T13, typename T14
, typename T15, typename T16, typename T17, typename T18, typename T19
>
struct map_impl
{
typedef aux::map_count_args<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
> arg_num_;
typedef typename aux::map_chooser< arg_num_::value >
::template result_< T0,T1,T2,T3,T4,T5,T6,T7,T8,T9,T10,T11,T12,T13,T14,T15,T16,T17,T18,T19 >::type type;
};
} // namespace aux
template<
typename T0 = na, typename T1 = na, typename T2 = na, typename T3 = na
, typename T4 = na, typename T5 = na, typename T6 = na, typename T7 = na
, typename T8 = na, typename T9 = na, typename T10 = na, typename T11 = na
, typename T12 = na, typename T13 = na, typename T14 = na
, typename T15 = na, typename T16 = na, typename T17 = na
, typename T18 = na, typename T19 = na
>
struct map
: aux::map_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type
{
typedef typename aux::map_impl<
T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
>::type type;
};
}}
/////////////////////////////////////////////////
// vnDev.Games - Trong.LIVE - DAO VAN TRONG //
////////////////////////////////////////////////////////////////////////////////
| [
"langley.joshua@gmail.com"
] | langley.joshua@gmail.com |
a000c9841d37f94f875ce3922d597c8714da9c54 | a953a9bf7927daae47c6b4b8fb6b6ab18d781569 | /external/dxl_sdk_2.0_for_linux/example/monitor/main.cpp | 22df3e8642a4718061b66fa343ac2bdfce097ef0 | [] | no_license | RobotnikAutomation/robotnik_tilt_laser | ad754f6ca6507b4e286c04b77b3f2b765338edb4 | af4f23101954a70015e7219884614d014ed2dd35 | refs/heads/indigo-devel | 2021-01-21T21:49:08.473962 | 2016-03-16T16:18:06 | 2016-03-16T16:18:06 | 31,896,129 | 4 | 2 | null | 2015-06-02T16:33:20 | 2015-03-09T12:04:04 | C++ | UTF-8 | C++ | false | false | 15,454 | cpp | /*
* main.cpp
*
* Created on: 2013. 1. 3.
* Author: zerom
*/
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <getopt.h>
#include <string.h>
#include <termios.h>
#include "dynamixel.h"
using namespace DXL_PRO;
Dynamixel DXL("/dev/ttyUSB0");
int _getch()
{
struct termios oldt, newt;
int ch;
tcgetattr( STDIN_FILENO, &oldt );
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr( STDIN_FILENO, TCSANOW, &newt );
ch = getchar();
tcsetattr( STDIN_FILENO, TCSANOW, &oldt );
return ch;
}
int kbhit(void)
{
struct termios oldt, newt;
int ch;
int oldf;
tcgetattr(STDIN_FILENO, &oldt);
newt = oldt;
newt.c_lflag &= ~(ICANON | ECHO);
tcsetattr(STDIN_FILENO, TCSANOW, &newt);
oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);
ch = getchar();
tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
fcntl(STDIN_FILENO, F_SETFL, oldf);
if(ch != EOF)
{
ungetc(ch, stdin);
return 1;
}
return 0;
}
void Usage(char *progname)
{
fprintf(stderr, "-----------------------------------------------------------------------\n");
fprintf(stderr, "Usage: %s\n" \
" [-h | --help]........: display this help\n" \
" [-d | --device]......: port to open (/dev/ttyUSB0)\n" \
, progname);
fprintf(stderr, "-----------------------------------------------------------------------\n");
}
void Help()
{
fprintf(stderr, "\n");
fprintf(stderr, "COMMAND: \n\n" \
" baud [BAUD_NUM] : Baudrate change to [BAUD_NUM] \n" \
" 0:2400, 1:57600, 2:115200, 3:1M, 4:2M, 5:3M \n" \
" 6:4M, 7:4.5M, 8:10.5M \n" \
" scan : Output the current status of all DXLs \n" \
" ping [ID] [ID] ... : Output the current status of [ID] \n" \
" bp : Broadcast Ping \n" \
" wrb [ID] [ADDR] [VALUE] : Write 1 byte [VALUE] to [ADDR] of [ID] \n" \
" wrw [ID] [ADDR] [VALUE] : Write 2 byte [VALUE] to [ADDR] of [ID] \n" \
" wrd [ID] [ADDR] [VALUE] : Write 4 byte [VALUE] to [ADDR] of [ID] \n" \
" rdb [ID] [ADDR] : Read 1 byte value from [ADDR] of [ID] \n" \
" rdw [ID] [ADDR] : Read 2 byte value from [ADDR] of [ID] \n" \
" rdd [ID] [ADDR] : Read 4 byte value from [ADDR] of [ID] \n" \
" r [ID] [ADDR] [LENGTH] : Dumps the control table of [ID] \n" \
" [LENGTH] bytes from [ADDR] \n" \
" mon [ID] [ADDR] b|w|d : Refresh byte|word|dword from [ADDR] of [ID] \n" \
" reboot [ID] : Reboot the dynamixel of [ID] \n" \
" reset [ID] [OPTION] : Factory reset the dynamixel of [ID] \n" \
" OPTION: 255(All), 1(Except ID), 2(Except ID&Baud)\n" \
" exit : Exit this program \n" \
);
fprintf(stderr, "\n");
}
// Print error bit of status packet
void PrintErrorCode(int ErrorCode)
{
printf("ErrorCode : %d (0x%X)\n", ErrorCode, ErrorCode);
if(ErrorCode & ERRBIT_VOLTAGE)
printf("Input voltage error!\n");
if(ErrorCode & ERRBIT_ANGLE)
printf("Angle limit error!\n");
if(ErrorCode & ERRBIT_OVERHEAT)
printf("Overheat error!\n");
if(ErrorCode & ERRBIT_RANGE)
printf("Out of range error!\n");
if(ErrorCode & ERRBIT_CHECKSUM)
printf("Checksum error!\n");
if(ErrorCode & ERRBIT_OVERLOAD)
printf("Overload error!\n");
if(ErrorCode & ERRBIT_INSTRUCTION)
printf("Instruction code error!\n");
}
void Scan()
{
fprintf(stderr, "\n");
PingInfo *data = new PingInfo();
for(int i = 1; i < 253; i++)
{
if(DXL.Ping(i, data, 0) == COMM_RXSUCCESS)
{
fprintf(stderr, "\n ... SUCCESS \r");
fprintf(stderr, " [ID:%.3d] Model No : %.5d (0x%.2X 0x%.2X) \n",
data->ID, data->ModelNumber, DXL_LOBYTE(data->ModelNumber), DXL_HIBYTE(data->ModelNumber));
}
else
fprintf(stderr, ".");
if(kbhit())
{
char c = _getch();
if(c == 0x1b)
break;
}
}
fprintf(stderr, "\n\n");
}
void Write(int id, int addr, long value, int len)
{
int result = COMM_TXFAIL, error = 0;
if(len == 1)
result = DXL.WriteByte(id, addr, (int)value, &error);
else if(len == 2)
result = DXL.WriteWord(id, addr, (int)value, &error);
else if(len == 4)
result = DXL.WriteDWord(id, addr, value, &error);
if(result != COMM_RXSUCCESS)
{
fprintf(stderr, "\n Fail to write! \n\n");
return;
}
if(error != 0)
PrintErrorCode(error);
fprintf(stderr, "\n Success to write! \n\n");
}
void Read(int id, int addr, int len)
{
int result = COMM_TXFAIL, error = 0;
int ivalue = 0;
long lvalue = 0;
if(len == 1)
result = DXL.ReadByte(id, addr, &ivalue, &error);
else if(len == 2)
result = DXL.ReadWord(id, addr, &ivalue, &error);
else if(len == 4)
result = DXL.ReadDWord(id, addr, &lvalue, &error);
if(result != COMM_RXSUCCESS)
{
fprintf(stderr, "\n Fail to read! (result : %d) \n\n", result);
return;
}
if(error != 0)
PrintErrorCode(error);
if(len == 1)
fprintf(stderr, "\n READ VALUE : %d \n\n", ivalue);
else if(len == 2)
fprintf(stderr, "\n READ VALUE : (UNSIGNED) %u , (SIGNED) %d \n\n", ivalue, ivalue);
else
fprintf(stderr, "\n READ VALUE : (UNSIGNED) %lu , (SIGNED) %d \n\n", lvalue, lvalue);
}
void Dump(int id, int addr, int len)
{
int result = COMM_TXFAIL, error = 0;
unsigned char* data = (unsigned char*)calloc(len, sizeof(unsigned char));
result = DXL.Read(id, addr, len, data, &error);
if(result != COMM_RXSUCCESS)
{
fprintf(stderr, "\n Fail to read! (result : %d) \n\n", result);
return;
}
if(error != 0)
PrintErrorCode(error);
if(id != BROADCAST_ID)
{
fprintf(stderr, "\n");
for(int i = addr; i < addr+len; i++)
fprintf(stderr, "ADDR %.3d [0x%.4X] : %.3d [0x%.2X] \n", i, i, data[i-addr], data[i-addr]);
fprintf(stderr, "\n");
}
}
void Refresh(int id, int addr, int len)
{
int result = COMM_TXFAIL, error = 0;
int ivalue = 0;
long lvalue = 0;
fprintf(stderr, "\n [ESC] : Quit monitoring \n\n");
while(1)
{
if(len == 1)
result = DXL.ReadByte(id, addr, &ivalue, &error);
else if(len == 2)
result = DXL.ReadWord(id, addr, &ivalue, &error);
else if(len == 4)
result = DXL.ReadDWord(id, addr, &lvalue, &error);
if(result != COMM_RXSUCCESS)
{
//fprintf(stderr, "\n Fail to read! (result : %d) \n\n", result);
continue;
}
if(error != 0)
PrintErrorCode(error);
if(len == 1)
fprintf(stderr, " READ VALUE : %.3d [0x%.2X] \r", ivalue, ivalue);
else if(len == 2)
fprintf(stderr, " READ VALUE : %.5d [0x%.2X 0x%.2X] \r", ivalue, DXL_LOBYTE(ivalue), DXL_HIBYTE(ivalue));
else
fprintf(stderr, " READ VALUE : %.10ld [0x%.2X 0x%.2X 0x%.2X 0x%.2X] \r",
lvalue, DXL_LOBYTE(DXL_LOWORD(lvalue)), DXL_HIBYTE(DXL_LOWORD(lvalue)), DXL_LOBYTE(DXL_HIWORD(lvalue)), DXL_HIBYTE(DXL_HIWORD(lvalue)));
if(kbhit())
{
char c = _getch();
if(c == 0x1b)
break;
}
}
fprintf(stderr, "\n\n");
}
void BroadcastPing()
{
std::vector<PingInfo> vec_info = std::vector<PingInfo>();
DXL.BroadcastPing(vec_info);
if(vec_info.size() > 0)
{
fprintf(stderr, "\n");
for(int i = 0; i < (int)vec_info.size(); i++)
{
fprintf(stderr, " ... SUCCESS \r");
fprintf(stderr, " [ID:%.3d] Model No : %.5d (0x%.2X 0x%.2X) \n",
vec_info.at(i).ID, vec_info.at(i).ModelNumber, DXL_LOBYTE(vec_info.at(i).ModelNumber), DXL_HIBYTE(vec_info.at(i).ModelNumber));
}
fprintf(stderr, "\n");
}
}
void BeltTest()
{
int result;
long lvalue1 , lvalue2;
while(true)
{
if(kbhit())
break;
result = DXL.ReadDWord(17, 611, &lvalue1, 0);
result = DXL.ReadDWord(18, 611, &lvalue2, 0);
fprintf(stderr, "\n READ VALUE : %d , %d \n\n", lvalue1, lvalue2);
}
}
int main(int argc, char *argv[])
{
fprintf(stderr, "\n***********************************************************************\n");
fprintf(stderr, "* DXL Protocol 2.0 Monitor *\n");
fprintf(stderr, "***********************************************************************\n\n");
char *dev = (char*)"/dev/ttyUSB0";
/* parameter parsing */
while(1)
{
int option_index = 0, c = 0;
static struct option long_options[] = {
{"h", no_argument, 0, 0},
{"help", no_argument, 0, 0},
{"d", required_argument, 0, 0},
{"device", required_argument, 0, 0},
{0, 0, 0, 0}
};
/* parsing all parameters according to the list above is sufficent */
c = getopt_long_only(argc, argv, "", long_options, &option_index);
/* no more options to parse */
if(c == -1) break;
/* unrecognized option */
if(c == '?') {
Usage(argv[0]);
return 0;
}
/* dispatch the given options */
switch(option_index) {
/* h, help */
case 0:
case 1:
Usage(argv[0]);
return 0;
break;
/* d, device */
case 2:
case 3:
Usage(argv[0]);
dev = strdup(optarg);
DXL.ComPort->SetPortName(dev);
break;
default:
Usage(argv[0]);
return 0;
}
}
if(DXL.Connect() == false)
{
fprintf(stderr, " Fail to open USB2Dyanmixel! [%s] \n\n", dev);
return 0;
}
char input[128];
char cmd[80];
char param[20][30];
int num_param;
char* token;
while(1)
{
printf("[CMD] ");
gets(input);
fflush(stdin);
if(strlen(input) == 0)
continue;
token = strtok(input, " ");
if(token == 0)
continue;
strcpy(cmd, token);
token = strtok(0, " ");
num_param = 0;
while(token != 0)
{
strcpy(param[num_param++], token);
token = strtok(0, " ");
}
if(strcmp(cmd, "help") == 0 || strcmp(cmd, "h") == 0 || strcmp(cmd, "?") == 0)
{
Help();
}
else if(strcmp(cmd, "ping") == 0)
{
if(num_param == 0)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
fprintf(stderr, "\n");
PingInfo *data = new PingInfo();
for(int i = 0; i < num_param; i++)
{
if(DXL.Ping(atoi(param[i]), data, 0) == COMM_RXSUCCESS)
{
fprintf(stderr, " ... SUCCESS \r");
fprintf(stderr, " [ID:%.3d] Model No : %.5d (0x%.2X 0x%.2X) \n",
data->ID, data->ModelNumber, DXL_LOBYTE(data->ModelNumber), DXL_HIBYTE(data->ModelNumber));
}
else
{
fprintf(stderr, " ... FAIL \r");
fprintf(stderr, " [ID:%.3d] \n", atoi(param[i]));
}
}
fprintf(stderr, "\n");
}
else if(strcmp(cmd, "scan") == 0)
{
Scan();
}
else if(strcmp(cmd, "baud") == 0)
{
if(num_param != 1)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
if(DXL.SetBaudrate(atoi(param[0])) == false)
fprintf(stderr, " Failed to change baudrate! \n");
else
fprintf(stderr, " Success to change baudrate! [ BAUD NUM: %d ]\n", atoi(param[0]));
}
else if(strcmp(cmd, "wrb") == 0 || strcmp(cmd, "w") == 0)
{
if(num_param != 3)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Write(atoi(param[0]), atoi(param[1]), atoi(param[2]), 1);
}
else if(strcmp(cmd, "wrw") == 0)
{
if(num_param != 3)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Write(atoi(param[0]), atoi(param[1]), atoi(param[2]), 2);
}
else if(strcmp(cmd, "wrd") == 0)
{
if(num_param != 3)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Write(atoi(param[0]), atoi(param[1]), atol(param[2]), 4);
}
else if(strcmp(cmd, "rdb") == 0)
{
if(num_param != 2)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Read(atoi(param[0]), atoi(param[1]), 1);
}
else if(strcmp(cmd, "rdw") == 0)
{
if(num_param != 2)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Read(atoi(param[0]), atoi(param[1]), 2);
}
else if(strcmp(cmd, "rdd") == 0)
{
if(num_param != 2)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Read(atoi(param[0]), atoi(param[1]), 4);
}
else if(strcmp(cmd, "r") == 0)
{
if(num_param != 3)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Dump(atoi(param[0]), atoi(param[1]), atoi(param[2]));
}
else if(strcmp(cmd, "mon") == 0)
{
int len = 0;
if(num_param > 2 && strcmp(param[2],"b") == 0) len = 1;
else if(num_param > 2 && strcmp(param[2],"w") == 0) len = 2;
else if(num_param > 2 && strcmp(param[2],"d") == 0) len = 4;
if(num_param != 3 || len == 0)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
Refresh(atoi(param[0]), atoi(param[1]), len);
}
else if(strcmp(cmd, "bp") == 0)
{
if(num_param != 0)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
BroadcastPing();
}
else if(strcmp(cmd, "reboot") == 0)
{
if(num_param != 1)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
int result = DXL.Reboot(atoi(param[0]), 0);
if(result != COMM_RXSUCCESS)
fprintf(stderr, "\n Fail to reboot! \n\n");
else
fprintf(stderr, "\n Success to reboot! \n\n");
}
else if(strcmp(cmd, "reset") == 0)
{
if(num_param != 2)
{
fprintf(stderr, " Invalid parameters! \n");
continue;
}
int result = DXL.FactoryReset(atoi(param[0]), atoi(param[1]), 0);
if(result != COMM_RXSUCCESS)
fprintf(stderr, "\n Fail to reset! \n\n");
else
fprintf(stderr, "\n Success to reset! \n\n");
}
else if(strcmp(cmd, "exit") == 0)
{
DXL.Disconnect();
return 0;
}
}
}
| [
"rnavarro@robotnik.es"
] | rnavarro@robotnik.es |
d290d9a5cd29da71de50d4985ab4898e0d98d904 | 2bce17904e161a4bdaa2d65cefd25802bf81c85b | /topcoder/TheBasketballDivOne.cpp | 69c5c04ee6f9a086c7248758fc187b100122edff | [] | no_license | lichenk/AlgorithmContest | 9c3e26ccbe66d56f27e574f5469e9cfa4c6a74a9 | 74f64554cb05dc173b5d44b8b67394a0b6bb3163 | refs/heads/master | 2020-03-24T12:52:13.437733 | 2018-08-26T01:41:13 | 2018-08-26T01:41:13 | 142,727,319 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,219 | cpp | #include <bits/stdc++.h>
#include <assert.h>
using namespace std;
typedef long long ll;
typedef long double ld;
#define PB push_back
#define MP make_pair
const ll MOD = 1000000007LL;
const ll INF = 1ULL<<60ULL;
const ll UNDEF = -1;
template<typename T> inline bool chkmax(T &a, T b) { return a < b ? a = b, true : false; }
template<typename T> inline bool chkmin(T &a, T b) { return a > b ? a = b, true : false; }
unordered_set<ll> s;
ll f[10];
class TheBasketballDivOne {
public:
int find(int _n, int _m) {
ll n=_n,m=_m;
ll e=(n*(n-1))/2;
ll lim=1ULL<<(2LL*e);
for (ll z=0;z<lim;z++) {
ll k=0;
for (ll x=0;x<n;x++) {
f[x]=0;
}
bool ok=true;
for (ll x=0;x<n;x++) {
for (ll y=x+1;y<n;y++) {
for (ll i=0;i<2;i++) {
if ((z>>k)&1) f[x]++;
else f[y]++;
k++;
}
}
}
assert(k==2*e);
sort(f,f+n);
if (f[n-1]!=m) continue;
vector<int> v;
ll h=0;
for (ll x=0;x<n-1;x++) {
h*=10;
h+=f[x];
}
s.insert(h);
}
return s.size();
}
};
// BEGIN CUT HERE
#include <ctime>
#include <cmath>
#include <string>
#include <vector>
#include <sstream>
#include <iostream>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
if (argc == 1)
{
cout << "Testing TheBasketballDivOne (250.0 points)" << endl << endl;
for (int i = 0; i < 20; i++)
{
ostringstream s; s << argv[0] << " " << i;
int exitCode = system(s.str().c_str());
if (exitCode)
cout << "#" << i << ": Runtime Error" << endl;
}
int T = time(NULL)-1458705337;
double PT = T/60.0, TT = 75.0;
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
cout << endl;
cout << "Time : " << T/60 << " minutes " << T%60 << " secs" << endl;
cout << "Score : " << 250.0*(.3+(.7*TT*TT)/(10.0*PT*PT+TT*TT)) << " points" << endl;
}
else
{
int _tc; istringstream(argv[1]) >> _tc;
TheBasketballDivOne _obj;
int _expected, _received;
time_t _start = clock();
switch (_tc)
{
case 0:
{
int n = 2;
int m = 1;
_expected = 1;
_received = _obj.find(n, m); break;
}
case 1:
{
int n = 3;
int m = 1;
_expected = 0;
_received = _obj.find(n, m); break;
}
case 2:
{
int n = 3;
int m = 3;
_expected = 2;
_received = _obj.find(n, m); break;
}
case 3:
{
int n = 4;
int m = 6;
_expected = 5;
_received = _obj.find(n, m); break;
}
/*case 4:
{
int n = ;
int m = ;
_expected = ;
_received = _obj.find(n, m); break;
}*/
/*case 5:
{
int n = ;
int m = ;
_expected = ;
_received = _obj.find(n, m); break;
}*/
/*case 6:
{
int n = ;
int m = ;
_expected = ;
_received = _obj.find(n, m); break;
}*/
default: return 0;
}
cout.setf(ios::fixed,ios::floatfield);
cout.precision(2);
double _elapsed = (double)(clock()-_start)/CLOCKS_PER_SEC;
if (_received == _expected)
cout << "#" << _tc << ": Passed (" << _elapsed << " secs)" << endl;
else
{
cout << "#" << _tc << ": Failed (" << _elapsed << " secs)" << endl;
cout << " Expected: " << _expected << endl;
cout << " Received: " << _received << endl;
}
}
}
// END CUT HERE
| [
"Li Chen Koh"
] | Li Chen Koh |
853739cb2be3c9ac9ff3081b59cb4f2753f94533 | 722fa75d47ce85b23026e3b513d7a85baa4e8169 | /include/Sound.hpp | 869f5789fa4f7b73682c20675ff39a8970414dda | [] | no_license | bestknighter/IDJ-Tuto-Game | d38f0cfdd619449f165b2c507cc63223b96b1533 | 8d9181450410b825a418ab84c70ac3bc28043ac1 | refs/heads/master | 2021-01-22T23:26:04.311883 | 2017-05-23T13:54:01 | 2017-05-23T13:54:01 | 85,637,487 | 0 | 1 | null | 2017-04-12T15:08:59 | 2017-03-20T23:27:56 | C++ | UTF-8 | C++ | false | false | 570 | hpp | #ifndef SOUND_HPP
#define SOUND_HPP
#include <string>
#include <memory>
#ifdef _WIN32
#include "SDL_mixer.h"
#elif __APPLE__
#include "TargetConditionals.h"
#include "SDL2/SDL_mixer.h"
#elif __unix__
#include "SDL2/SDL_mixer.h"
#else
# error "Unknown or unsupported compiler"
#endif
class Sound {
public:
Sound();
Sound( std::string file );
void Play( int times = 0 );
void Stop();
void Open( std::string file );
bool IsOpen();
private:
std::shared_ptr<Mix_Chunk> chunk;
int channel;
};
#endif // SOUND_HPP
| [
"gabrielfbbarbosa@gmail.com"
] | gabrielfbbarbosa@gmail.com |
880c40065350921fe4d87bec0cb1924d2df3eb1f | 8a9fbd891141e721d02fd25d4f15b15b9d49d66c | /leetcode/背包问题/背包问题/背包问题.cpp | 1690dcba99c9fcf135396f886a7b7b6a30696fcd | [] | no_license | hustzhm/code | 683080d1c4692d5822256bcedd7abea133fefe29 | e09228a9fa8fd9e915abe348183a6720fa8c9383 | refs/heads/master | 2020-05-04T14:17:11.709364 | 2019-08-30T07:07:12 | 2019-08-30T07:07:12 | 179,190,436 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,934 | cpp | #include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
#define NUMBER 1000
//0-1背包,背包总重W,物品个数N,第i个物品的重量weight[i],价值value[i],每个物品只有一个,求背包的最大价值。
int bag(vector<int>&weight, vector<int>&value, int W, int N)
{
vector<int>dp(W + 1, 0);
for (int i = 0; i < N; i++)
{
for (int j = W; j >= weight[i]; j--)
{
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
return dp[W];
}
//完全背包,背包总重W,物品个数N,第i个物品的重量weight[i],价值value[i],每个物品不限量,求背包的最大价值。
int fullbag(vector<int>&weight, vector<int>&value, int W, int N)
{
vector<int>dp(W + 1, 0);
for (int i = 0; i < N; i++)
{
for (int j = weight[i]; j<=W ; j++)
{
dp[j] = max(dp[j], dp[j - weight[i]] + value[i]);
}
}
return dp[W];
}
//多重背包,背包总重W,物品个数N,第i个物品的重量weight[i],价值value[i],数量为c[i],求背包的最大价值。
int multibag(vector<int>&weight, vector<int>&value, vector<int>&c,int W, int N)
{
vector<int>dp(W + 1, 0);
vector<vector<int>>num(NUMBER,vector<int>(2,0));
int index = 0;
for (int i = 0; i < N; i++)
{
for (int k = 1; k < c[i]; k <<= 1)
{
num[index][0] = k*value[i];
num[index++][1] = k*weight[i];
c[i] -= k;
}
num[index][0] = c[i] * value[i];
num[index++][1] = c[i] * weight[i];
}
for (int i = 0; i < index; i++)
{
for (int j = W; j>=num[i][1]; j--)
{
dp[j] = max(dp[j], dp[j - num[i][1]] + num[i][0]);
}
}
return dp[W];
}
int main()
{
vector<int>weight{ 1,2,3,4,5 };
vector<int>value{ 1,2,3,4,5 };
vector<int>c{ 1,2,3,4,5 };
int W = 10, N = 5;
int res1 = bag(weight, value, W, N);
cout << res1 << endl;
int res2 = fullbag(weight, value, W, N);
cout << res2 << endl;
int res3 = multibag(weight, value, c, W, N);
cout << res3 << endl;
system("pause");
return 0;
} | [
"37207424+hustzhm@users.noreply.github.com"
] | 37207424+hustzhm@users.noreply.github.com |
04cf3afe9222e1ec2c7a3b4aec3a5d1c927fe444 | 2c8340c3bb5222505aad591c2652ef1898c15cdf | /core/hash.h | 3e146531c359d975366dc4ed993b8e5077966797 | [
"MIT"
] | permissive | lzpfmh/ink | 7c2a1ba50e2c73ae2078725aed2d6df0a04faccc | 1787df1ad4170a158bca3747b59b95b77bfeaa34 | refs/heads/master | 2020-12-25T11:21:55.100457 | 2016-02-03T07:40:49 | 2016-02-03T07:40:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 632 | h | #ifndef _HASH_H_
#define _HASH_H_
#include <string>
#include <stdio.h>
namespace ink {
class Ink_Object;
class Ink_HashTable {
Ink_Object *value;
public:
const char *key;
Ink_HashTable *next;
Ink_HashTable *bonding;
Ink_HashTable *bondee;
Ink_Object *setter;
Ink_Object *getter;
std::string *key_p;
Ink_HashTable(const char *key, Ink_Object *value, std::string *key_p = NULL);
Ink_HashTable(Ink_Object *value);
Ink_HashTable *getEnd();
// Ink_HashTable *getMapping(const char *key);
inline Ink_Object *getValue()
{
return value;
}
Ink_Object *setValue(Ink_Object *val);
~Ink_HashTable();
};
}
#endif
| [
"lancelot.b@outlook.com"
] | lancelot.b@outlook.com |
ed53ce3a1709e661788dc9505d3ec17124541f96 | 0823521bb7b303e56fc6b0cd72582c292a2df673 | /proj1-recursion/Castle/Exchange_Map.cpp | f0d613462e1d7b747a06feb7ac5371ebef6ccfd9 | [] | no_license | gstggsstt/c-project | ac4079a9d71a915627d95e455f67148eb0b4d4bb | 499eddc476b83860c55d0b7ecfdd119dacc96102 | refs/heads/master | 2021-04-02T10:06:32.953666 | 2020-03-18T14:56:52 | 2020-03-18T14:56:52 | 248,261,451 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 414 | cpp | #include <bits/stdc++.h>
int n,m;
char Map[1100][1100];
using namespace std;
int main()
{
freopen("in.txt","r",stdin);
freopen("view.txt","w",stdout);
scanf("%d%d",&n,&m);
for(int i=0;i<n;++i)
scanf("%s",Map[i]);
for(int i=0;i<n;++i)
{
for(int j=0;j<m;++j)
{
if(Map[i][j]=='#') printf("¨€");
else if(Map[i][j]=='.') printf(" ");
else printf("¡î");
}
printf("\n");
}
return 0;
}
| [
"gstggsstt@163.com"
] | gstggsstt@163.com |
44b94166ba1b2cc7147e51c4cd26db60a8c0436a | fcea5f08695b3f558d74034227ec1dde8a9297dc | /class/constracta/class02.cpp | c41cbb24934d126ac88302363e0fd85dc7009b0c | [] | no_license | shuhei55/cpp_lecture | 600db5ab727758f059e04d66a314375e2e8f9cb7 | a84cfedcf14db543f912c92a2a31a960e50fa150 | refs/heads/master | 2021-10-23T09:10:24.613663 | 2019-03-16T13:13:27 | 2019-03-16T13:13:27 | 112,428,442 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 801 | cpp | #include <iostream>
#include <string>
#include <array>
using namespace std;
struct Rectangle {
Rectangle() : m_width(0), m_height(0)
{
cout << "デフォルトコンストラクタ" << endl;
}
Rectangle(double width, double height) : m_width(width), m_height(height)
{
cout << "普通のやつ" << endl;
}
Rectangle(double width) : m_width(width), m_height(10.0)
{
cout << "高さ10の面積" << endl;
}
double area()
{
return m_width * m_height;
}
private:
double m_width, m_height;
};
int main()
{
array<Rectangle, 4> a{{{4.0, 3.0}, {2.1, 4.5}, {3.4}, {}}};
cout << a.at(0).area() << endl;
cout << a.at(1).area() << endl;
cout << a.at(2).area() << endl;
cout << a.at(3).area() << endl;
}
| [
"takamatushuhei55@docomo.ne.jp"
] | takamatushuhei55@docomo.ne.jp |
f995711c8efc4cb687113f17276363a32884fe41 | 022e2e472bb37ba39fbbe43c48542426ccb89e9a | /Include/event.h | a243a5af7f1cc08dca372ae1f65f5b5d64cc0038 | [] | no_license | suphus/small_x_dijets | f1a2135431709f921f0f2646db5f59af4564875d | 527c85297077f7754690aac4582727fd4bc98094 | refs/heads/master | 2020-06-04T14:11:30.238171 | 2017-05-04T13:44:43 | 2017-05-04T13:44:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,358 | h | #include<vector>
#ifndef _EVENT_H
#define _EVENT_H
using namespace std;
class Event {
//Event is a set of jets and parameters
private:
string jec_cond = "centr";
public:
int number = -1, run = -1;
int nPV = -1;
int CNTR = -1, FWD2 = -1, FWD3 = -1, MB = -1;
int CNTR_ps = -1, FWD2_ps = -1, FWD3_ps = -1, MB_ps = -1;
int mc_info = -1;//1 - herwigpp, 2 - pythia
int mc_cntr_info = -1;
int mc_fb_info = -1;
int mc_low_pthat_info = -1;
int mc_high_pthat_info = -1;
double weight = 1.;
bool gen_level = false;
vector<double> pt; //corrected jet pt
vector<double> pt_unc; //JEC uncertainty
vector<double> pt_cor; //JEC coefficient
vector<double> eta;
vector<double> phi;
vector<double> rap;
vector<double> gen_pt;
vector<double> gen_eta;
vector<double> gen_phi;
vector<double> gen_rap;
Event(){};
void Init(int , int , int , int , int , int , int , double , int , int , int , int );
void JecUp();
void JecDown();
void JecCentr();
void Print();
void Clear();
void AddJet(double , double , double , double , double, double);
void AddJets(vector<float> , vector<float> , vector<float> , vector<float> , vector<float>, vector<float>);
void AddGenJets(vector<float> , vector<float> , vector<float> , vector<float>);
string RunPileUp();
};
#endif /* _EVENT_H */
| [
"ivanp@cern.ch"
] | ivanp@cern.ch |
0d6cab3e36f1a23c9454e51415be92d97251e2e7 | 59e32ce927898a212fda136708f4475393817cf3 | /lopez/lopez-src/warped/NoTime/src/CommManager.hh | 998329488a3b100ca7dd2830c449a93b3b64c847 | [] | no_license | romancardenas/CDPP_AdvancedRules-codename-Lopez | 0f6524df51e2fdf8e430c40e773729a2d71c1bea | d777e50d4e63484de6aa07e5c8482a3a9d49eeb8 | refs/heads/master | 2022-03-25T02:57:12.406494 | 2019-11-21T21:17:36 | 2019-11-21T21:17:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,745 | hh | #ifndef COMM_MANAGER_HH
#define COMM_MANAGER_HH
// Copyright (c) 1994-1996 Ohio Board of Regents and the University of
// Cincinnati. All Rights Reserved.
// BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
// FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT
// PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND,
// EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
// PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
// PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME
// THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
// IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
// WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
// REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR
// DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL
// DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM
// (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED
// INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF
// THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER
// OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
//
// $Id:
//
//
//---------------------------------------------------------------------------
#include "BasicNoTime.hh"
#include "KernelMsgs.hh"
class LogicalProcess;
class ObjectRecord;
#ifdef MPI
extern "C" {
#include "mpi.h"
}
#endif
void physicalCommInit(int *argc, char ***argv);
int physicalCommGetId();
class CommManager : public BasicNoTime {
public:
CommManager(int numberOfLPs, LogicalProcess*);
~CommManager();
void initCommManager(ObjectRecord*, int);
int getID() { return id; };
bool isCommManager() {
return true;
}
bool isSimulationComplete();
// These methods are for the _Commucation Manager_ to receive the types
// of events passed in ( by local objects )
void recvEvent(BasicEvent*);
void recvMsg(TerminateMsg *);
void recvMsg(InitMsg *);
void recvMsg(StartMsg *);
void recvMsg(DummyMsg *);
void recvMsg(CheckIdleMsg *);
void recvMsg(BasicDebugMsg *);
void deliver(BasicEvent *);
void deliver(DummyMsg *);
void deliver(BasicDebugMsg *);
// this is a method the LP calls to let everyone know that he's got a
// certain simulation object in his posession.
void iHaveObject(int);
// wait for the number of messages specified (and deliver them).
// If there aren't that many messages, stop receiving them.
// In either case, return the number of messages actually received.
int recvMPI(int = 1);
// grab ONE message from MPI and return it..
// return NULL if there are none...
BasicMsg * recvMPIMsg();
void terminateSimulation( TerminateMsg * );
// returns the sequence number of the next message to the LP with the id
// passed in
SequenceCounter getSequence( int );
void waitForStart();
void waitForInit( int numExpected );
void sendEvent( BasicEvent*);
// We need to define these to make the compiler happy.
virtual void executeProcess();
BasicEvent* getEvent();
private:
int numLPs;
int id;
int terminateTokenFlag;
int terminateTokenNumber;
bool circulateToken;
// these will be filled in with arrays so that each communication channel
// has a unique sequence running
SequenceCounter* sendSequenceArray;
SequenceCounter* recvSequenceArray;
void remoteSend( BasicMsg*, int );
// this method takes an LP Msg, figures out what kind of derived type it is,
// and then delivers it to the LOCAL entity that is receiving it.
void routeMsg( BasicMsg *);
};
#endif
| [
"cruizm.89@gmail.com"
] | cruizm.89@gmail.com |
f50c9d96f3b72c42f8f72cba04c8de7bce4b21cc | 940812fb30095b16d8c57f3d56b3c11876fc1982 | /include/acqua/network/detail/impl/ifreq_opts.ipp | 5f8fdcbdd979226ebbacb7b172db64cd8485b418 | [] | no_license | harre-orz/acqua | c6d2c494cab201cffdb48e170cf7fd4f66378f32 | 32face864afc6d39e16c35bc80d648b63afbc63e | refs/heads/master | 2021-06-28T07:33:58.097924 | 2016-11-09T04:23:05 | 2016-11-09T04:23:05 | 33,122,378 | 7 | 2 | null | 2016-11-09T04:18:50 | 2015-03-30T12:41:50 | C++ | UTF-8 | C++ | false | false | 2,374 | ipp | #pragma once
#include <acqua/network/detail/ifreq_opts.hpp>
namespace acqua { namespace network { namespace detail {
inline ifreq_opts::ifreq_opts(char const * if_name) noexcept
: fd_(-1), ifr_(::ifreq())
{
using namespace std;
memset(&ifr_, 0, sizeof(ifr_));
if (if_name) {
strncpy(ifr_.ifr_name, if_name, sizeof(ifr_.ifr_name));
}
}
inline ifreq_opts::~ifreq_opts() noexcept
{
if (fd_ >= 0)
::close(fd_);
}
inline bool ifreq_opts::open_once(boost::system::error_code & ec) noexcept
{
if (fd_ < 0) {
if ((fd_ = ::socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
ec.assign(errno, boost::system::generic_category());
return false;
}
}
return true;
}
inline int ifreq_opts::get_index(boost::system::error_code & ec) noexcept
{
if (!open_once(ec))
return -1;
if (::ioctl(fd_, SIOCGIFINDEX, &ifr_) != 0) {
ec.assign(errno, boost::system::generic_category());
return -1;
}
return ifr_.ifr_ifindex;
}
inline int ifreq_opts::get_mtu(boost::system::error_code & ec) noexcept
{
if (!open_once(ec))
return -1;
if (::ioctl(fd_, SIOCGIFMTU, &ifr_) != 0) {
ec.assign(errno, boost::system::generic_category());
return -1;
}
return ifr_.ifr_mtu;
}
inline void ifreq_opts::set_mtu(int mtu, boost::system::error_code & ec) noexcept
{
if (!open_once(ec))
return;
ifr_.ifr_mtu = mtu;
if (::ioctl(fd_, SIOCSIFMTU, &ifr_) != 0) {
ec.assign(errno, boost::system::generic_category());
return;
}
}
inline linklayer_address ifreq_opts::get_lladdr(boost::system::error_code & ec) noexcept
{
if (!open_once(ec))
return linklayer_address();
if (::ioctl(fd_, SIOCGIFHWADDR, &ifr_) != 0) {
ec.assign(errno, boost::system::generic_category());
return linklayer_address();
}
return linklayer_address::from_voidptr(ifr_.ifr_hwaddr.sa_data);
}
inline void ifreq_opts::set_lladdr(linklayer_address const & lladdr, boost::system::error_code & ec) noexcept
{
if (!open_once(ec))
return;
using namespace std;
ifr_.ifr_hwaddr.sa_family = 1; //ARPHRD_ETHER;
memcpy(ifr_.ifr_hwaddr.sa_data, &lladdr, 6);
if (::ioctl(fd_, SIOCSIFHWADDR, &ifr_) != 0) {
ec.assign(errno, boost::system::generic_category());
}
}
} } }
| [
"harre.orz@gmail.com"
] | harre.orz@gmail.com |
5b28bfa460bd36025a3a496ba2d27212fb495188 | eed3040703f502a22b0b3e30704776a6851a751e | /online-judges/Project-Euler/PE375/PE375.cpp | fb7e9383f36d17f56661bf9a69ee81b16970bcdb | [] | no_license | velazqua/competitive-programming | a6b5fcc8a9169de43d1f6f1fbf3ed2241749ccfc | cf8cda1132a5791917f4861f313b8098934f3c6b | refs/heads/master | 2021-01-01T16:20:11.103309 | 2014-03-02T03:45:44 | 2014-03-02T03:45:44 | 12,732,139 | 1 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 292 | cpp | #include <iostream>
using namespace std;
typedef long long LL;
int main ()
{
LL S0 = 290797LL;
LL MOD = 50515093LL;
int N = 11;
vector<LL> seq( N, 0LL );
seq[0] = S0;
for( int i=1; i<=N; ++i )
{
S[i] = (S[i-1]*S[i-1])%MOD;
}
LL summ = 0LL;
for( int i=0; i<=N; ++i )
{
}
}
| [
"alx.velazquez@gmail.com"
] | alx.velazquez@gmail.com |
aaec1c69d7db855f895fd4a5ff93aa2112472987 | 94382e8b91c8561c652eb125223b52a803a9a08f | /C0_Compiler_BUAA_Wazaki/src/Optimizer/Conflict.hpp | bf10f78cd44f8f7a9b4f85f9cac24292f9a6f43d | [] | no_license | GitWazaki/C0_Compiler_BUAA_Wazaki | 6a2b57156c5ff47affd17bbcf3ccb4b72338e959 | 938cef8d6f91acd1762299cc60025064136145ee | refs/heads/master | 2022-03-24T07:10:12.421813 | 2019-12-23T11:09:11 | 2019-12-23T11:09:11 | 217,290,220 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 7,108 | hpp | #pragma once
using namespace std;
namespace MidIR {
class ConflictGraph {
using Node = DefUseNode;
using Chain = DefUseChain;
using Web = DefUseWeb;
ReachingDefine reaching_define;
map<string, set<Node>> ident_defs_map, ident_uses_map;
set<string> idents;
map<string, set<Web>> ident_webs_map;
map<string, VarRange> ident_range_map;
public:
void addDef(int block_num, string block_name, int number, string ident);
void addUse(int block_num, string block_name, int number, string ident);
void reAddDef();
void genConfict(FlowGraph& flow_graph);
void genWeb(string ident, FlowGraph& flow_graph);
VarRange genRange(string ident);
NodeRange rangeMerge(NodeRange r1, NodeRange r2);
vector<NodeRange> getLoops(FlowGraph& flow_graph);
void proInLoop(Chain& chain, vector<NodeRange>& loops);
map<string, VarRange> getRangeMap();
void printConfictGraph();
};
inline void ConflictGraph::addDef(int block_num, string block_name, int number, string ident) {
idents.insert(ident);
Node new_node{ block_num, block_name, number };
set<Node> def_nodes = ident_defs_map[ident];
for (Node def_node : def_nodes) {
if (def_node != new_node) {
reaching_define.addKills(block_name, { def_node.toString() });
}
}
ident_defs_map[ident].insert(new_node);
reaching_define.addGens(block_name, { new_node.toString() });
}
inline void ConflictGraph::addUse(int block_num, string block_name, int number, string ident) {
idents.insert(ident);
Node new_node{ block_num, block_name, number };
ident_uses_map[ident].insert(new_node);
reaching_define.addBlockName(block_name);
}
inline void ConflictGraph::reAddDef() {
for (string ident : idents) {
set<Node> def_nodes = ident_defs_map[ident];
for (Node node_i : def_nodes) {
for(Node node_j : def_nodes) {
if (node_i != node_j) {
reaching_define.addKills(node_i.block_name, { node_j.toString() });
}
}
}
}
}
inline void ConflictGraph::genConfict(FlowGraph& flow_graph) {
reAddDef();
reaching_define.build(flow_graph);
for (auto ident : idents) {
genWeb(ident,flow_graph);
}
// for (auto ident : idents) {
// ident_range_map[ident] = genRange(ident);
// }
}
inline void ConflictGraph::genWeb(string ident, FlowGraph& flow_graph) {
set<Node> defs = ident_defs_map[ident];
set<Node> uses = ident_uses_map[ident];
vector<Chain> chains;
vector<Web> webs;
// 为每个def初始化链
for (Node def : defs) {
chains.push_back(Chain(def));
}
//把遍历uses,把use加入每一个使用了它的def链中
for (Node use : uses) {
for (Chain& chain : chains) {
if (Found(reaching_define.getInByBlock(use.block_name), chain.def.toString())
|| Found(reaching_define.getOutByBlock(use.block_name),chain.def.toString())
) {
chain.uses.push_back(use);
}
}
}
if (!(startWith(ident, string("_T")) && isdigit(ident[2]))) {
auto loops = getLoops(flow_graph);
for (auto& chain : chains) {
proInLoop(chain, loops);
}
}
vector<Chain> old_chains;
do {
old_chains = chains;
for (int i = 0; i < chains.size(); i++) {
for (int j = 0; j < chains.size(); j++) {
if (i != j && chains[i].overlap(chains[j])) {
if (chains[i].def < chains[j].def) {
chains[i].chainMerge(chains[j]);
chains.erase(chains.begin() + j);
}
else {
chains[j].chainMerge(chains[i]);
chains.erase(chains.begin() + i);
}
goto outside_merge_chains;
}
}
}
outside_merge_chains:;
} while (old_chains != chains);
// 对于chains中每一条建好的def-uses链,判断能否加入到webs网络的每一条web中去
for (int i = 0; i < chains.size(); i++) {
bool new_one = true;
Chain& chain = chains[i];
for (int j = 0; j < webs.size(); j++) {
Web& web = webs[j];
if (web.canInsertChain(chain)) { // 该链chain可以加入到网络web中
web.chains.insert(chains[i]);
new_one = false;
break;
}
}
if (new_one) { // chain没有可以加入的web则新建一个web加入webs中
Web web;
web.chains.insert(chains[i]);
webs.push_back(web);
}
}
vector<Web> old_web;
do { //循环合并webs中的每一个web,直至不能合并
old_web = webs;
for(int i = 0; i < webs.size(); i++) {
for (int j = 0; j < webs.size(); j++) {
Web& web1 = webs[i];
Web& web2 = webs[j];
if(i == j) {
continue;
}
if (web1.canMerge(web2)) {
web1.merge(web2);
webs.erase(webs.begin() + j);
goto restart;
}
}
}
restart:;
} while(old_web != webs);
//为每一个变量ident设置它的webs
for (Web& web : webs) {
web.sort();
ident_webs_map[ident].insert(web);
}
}
inline VarRange ConflictGraph::genRange(string ident) {
set<Web> webs = ident_webs_map[ident];
if (webs.empty()) { //全局变量,在block中没有def,所以webs为空
return VarRange( NodeRange(Node(0, "Global", 0), Node(INT32_MAX, "Global", INT32_MAX)));
}
VarRange range;
for(Web web : webs) {
NodeRange node_range(webs.begin()->chains.begin()->def);
for(Chain chain : web.chains) {
node_range = rangeMerge(node_range, { chain.def });
for(Node use : chain.uses) {
node_range = rangeMerge(node_range, { use });
}
}
range.addRange(node_range);
}
return range;
}
inline NodeRange ConflictGraph::rangeMerge(NodeRange r1, NodeRange r2) {
return NodeRange(min(r1.first, r2.first), max(r1.last, r2.last));
}
inline vector<NodeRange> ConflictGraph::getLoops(FlowGraph& flow_graph) {
vector<NodeRange> loops;
for (auto edge : flow_graph.getFollowBlocksMap()) { //edge block_name to vector<follow block name>
string from_block_name = edge.first;
for (string to_block_name : edge.second) {
int from_block_num = flow_graph.getBlockNum(from_block_name);
int to_block_num = flow_graph.getBlockNum(to_block_name);
if (to_block_num <= from_block_num) {
loops.push_back(NodeRange(Node(to_block_num, to_block_name, 0), Node(from_block_num, from_block_name, INT32_MAX)));
}
}
}
return loops;
}
inline void ConflictGraph::proInLoop(Chain& chain, vector<NodeRange>& loops) {
bool change;
do {
change = false;
for (NodeRange loop : loops) {
for (Node use : chain.uses) {
if (loop.checkIn(use.block_num, use.line_num) && getSubIndex(chain.uses, loop.last) == -1) {
chain.uses.push_back(loop.last);
change = true;
goto fixChainLoop_outside;
}
}
}
fixChainLoop_outside:;
} while (change);
chain.sort();
}
inline map<string, VarRange> ConflictGraph::getRangeMap() {
for (auto ident : idents) {
ident_range_map[ident] = genRange(ident);
}
return ident_range_map;
}
inline void ConflictGraph::printConfictGraph() {
reAddDef();
reaching_define.printInOut();
for (auto i = idents.begin(); i != idents.end(); i++) {
print("{}: ", *i);
auto webs = ident_webs_map[*i];
for (auto j = webs.begin(); j != webs.end(); j++) {
println("W{}", *j);
}
}
}
}
| [
"1003731512@qq.com"
] | 1003731512@qq.com |
c8c14242ea23e07f365a300cd605379e3cc98fc7 | 24b9aa563423750fccd53c493b84a7acc95f8145 | /.pio/libdeps/nodemcuv2/ArduinoJson/src/ArduinoJson/Polyfills/safe_strcmp.hpp | 98f157dddcf5cc1b2c3c28196e38b8b427b7c6fb | [
"MIT"
] | permissive | yanxiangrong/LampControl | 4df0dad21516e0860622071bf7928619661d727d | e2343a01983d0dde929e9494d2972d3093764160 | refs/heads/master | 2023-07-03T17:18:32.211676 | 2021-07-28T13:50:09 | 2021-07-28T13:50:09 | 389,840,047 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 695 | hpp | // ArduinoJson - https://arduinojson.org
// Copyright Benoit Blanchon 2014-2021
// MIT License
#pragma once
#include <ArduinoJson/Namespace.hpp>
#include <stdint.h> // int8_t
namespace ARDUINOJSON_NAMESPACE {
inline int safe_strcmp(const char *a, const char *b) {
if (a == b)
return 0;
if (!a)
return -1;
if (!b)
return 1;
return strcmp(a, b);
}
inline int safe_strncmp(const char *a, const char *b, size_t n) {
if (a == b)
return 0;
if (!a)
return -1;
if (!b)
return 1;
return strncmp(a, b, n);
}
} // namespace ARDUINOJSON_NAMESPACE
| [
"yanxiangrong_2@outlook.com"
] | yanxiangrong_2@outlook.com |
1f7c25469020e9658984f35e8ca59fb2d5d60fe9 | 32f3befacb387118c4d9859210323ce6448094ee | /Contest/PetrWinterFeb2007/pE.cpp | a79117d8b126ce1c4cea909e0bb8cc50dbfafc8d | [] | no_license | chmnchiang/bcw_codebook | 4e447e7d06538f3893e54a50fa5c1d6dcdcd0e01 | e09d704ea17bb602ff1661b76d47ef52d81e8072 | refs/heads/master | 2023-04-11T08:29:05.463394 | 2021-04-19T09:16:31 | 2021-04-19T09:16:31 | 20,440,425 | 15 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 2,733 | cpp | //bcw0x1bd2 {{{
#include<bits/stdc++.h>
#include<unistd.h>
using namespace std;
#define F first
#define S second
#define MP make_pair
#define PB push_back
#define IOS ios_base::sync_with_stdio(0); cin.tie(0);
#define SZ(x) ((int)((x).size()))
#define ALL(x) begin(x),end(x)
#define REP(i,x) for (int i=0; i<(x); i++)
#define REP1(i,a,b) for (int i=(a); i<=(b); i++)
typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;
typedef long double ld;
#ifdef DARKHH
#define FILEIO(name)
#else
#define FILEIO(name) \
freopen(name".in", "r", stdin); \
freopen(name".out", "w", stdout);
#endif
#ifdef DARKHH
template<typename Iter>
ostream& _out(ostream &s, Iter b, Iter e) {
s << "[ ";
for ( auto it=b; it!=e; it++ ) s << *it << " ";
s << "]";
return s;
}
template<typename A, typename B>
ostream& operator << (ostream &s, const pair<A,B> &p) { return s<<"("<<p.first<<","<<p.second<<")"; }
template<typename T>
ostream& operator << (ostream &s, const vector<T> &c) { return _out(s,ALL(c)); }
template<typename T, size_t N>
ostream& operator << (ostream &s, const array<T,N> &c) { return _out(s,ALL(c)); }
template<typename T>
ostream& operator << (ostream &s, const set<T> &c) { return _out(s,ALL(c)); }
template<typename A, typename B>
ostream& operator << (ostream &s, const map<A,B> &c) { return _out(s,ALL(c)); }
#endif
// }}}
// Let's Fight! ~OAO~~
const int MX = 150005;
struct Coord {
int x,y,z;
};
struct Lisan {
vector<int> seq;
void add(int x) { seq.PB(x); }
void build() {
sort(ALL(seq));
seq.resize(unique(ALL(seq))-begin(seq));
}
int qry(int x) { return lower_bound(ALL(seq),x)-begin(seq)+1; }
}lisan;
struct BIT {
int bit[MX];
int lb(int x) { return x & -x; }
void upd(int x, int v) {
for (int i=x; i>0; i-=lb(i)) {
bit[i] = max(bit[i], v);
}
}
int qry(int x) {
int res = 0;
for (int i=x; i<MX; i+=lb(i)) {
res = max(res, bit[i]);
}
return res;
}
}bit;
int N;
Coord pt[50005];
bool comp(Coord a, Coord b) { return tie(a.x,a.y,a.z) < tie(b.x,b.y,b.z); }
int main() {
IOS;
FILEIO("pareto");
cin >> N;
REP(i,N) {
cin >> pt[i].x >> pt[i].y >> pt[i].z;
lisan.add(pt[i].x);
lisan.add(pt[i].y);
lisan.add(pt[i].z);
}
lisan.build();
REP(i,N) {
pt[i].x = lisan.qry(pt[i].x);
pt[i].y = lisan.qry(pt[i].y);
pt[i].z = lisan.qry(pt[i].z);
}
sort(pt,pt+N,comp);
int ans = N;
for (int i=N-1; i>=0; i--) {
int mxz = bit.qry(pt[i].y+1);
if (mxz > pt[i].z) ans--;
bit.upd(pt[i].y,pt[i].z);
}
cout << ans << endl;
return 0;
}
| [
"hanhan0912@gmail.com"
] | hanhan0912@gmail.com |
f6e4c19aec162c5e8ec9025ae89930adc4ee8129 | 770aa62b818401a1690a0ba58bdb0a91b92fd3a6 | /Test3_2A/Test3_2A/MyWin.cpp | bc5dd14b5f57b437cf1047c8b4425d833c06e7ea | [] | no_license | hkkhuang/Qt | d062e7937ba148635b6178dd6efb7f8c78f069f2 | 8f3e9777ecec0fd112e7ee266386208f46a01891 | refs/heads/master | 2018-06-29T12:33:20.670790 | 2018-05-31T13:32:02 | 2018-05-31T13:32:02 | 118,467,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | cpp | #include "MyWin.h"
MyWin::MyWin(QWidget *parent)
: QWidget(parent)
{
//创建控件对象
m_lineEdit = new QLineEdit(this);
m_textEdit = new QPlainTextEdit(this);
//观察sizeHint的值,sizePolicy的值 [通过断点查看]
QSize sh = m_lineEdit->sizeHint(); //+ sh { width = 193, height = 24 }
QSizePolicy p = m_lineEdit->sizePolicy();//+ p { horizontal = Expanding (7), vertical = Fixed (0), type = LineEdit (256) } QSizePolicy
QSizePolicy::Policy vp = p.verticalPolicy(); //Fixed
QSize sh2 = m_textEdit->sizeHint(); //+ sh2 { width = 256, height = 192 } QSize
QSizePolicy p2 = m_textEdit->sizePolicy(); //+ sh2 { width = 256, height = 192 } QSize
QSizePolicy::Policy vp2 = p2.verticalPolicy(); // vp2 Expanding (7) QSizePolicy::Policy
//设置lineEdit的Policy
m_lineEdit->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); //横向还是Expanding,将纵向也改为Expanding
//创建布局器
QVBoxLayout* layout = new QVBoxLayout(this);
layout->addWidget(m_lineEdit);
layout->addWidget(m_textEdit);
//使用布局器
this->setLayout(layout);
}
MyWin::~MyWin()
{
}
| [
"huangkekehkk@163.com"
] | huangkekehkk@163.com |
0ed00edbcb079cc65879a1f754e52287c16f3835 | 818751f62d93d0f460814b415a339d43dbd284ee | /31. Next Permutation.cpp | 27c1eeb2871d448681e5cffd447723d9477668b0 | [] | no_license | YashviGulati/LeetCode | 6c2ac85901a4cf57946dc85da1940934b33ab0fc | 6d1223a25a60a156c3d0d74d5148a02080a662e3 | refs/heads/master | 2020-12-10T17:16:19.460169 | 2020-07-08T00:22:13 | 2020-07-08T00:22:13 | 233,657,557 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 846 | cpp | /*
Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.
If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).
The replacement must be in-place and use only constant extra memory.
Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.
1,2,3 → 1,3,2
3,2,1 → 1,2,3
1,1,5 → 1,5,1
*/
class Solution {
public:
void nextPermutation(vector<int>& nums) {
int i = nums.size() - 1, k = i;
while (i > 0 && nums[i-1] >= nums[i])
i--;
for (int j=i; j<k; j++, k--)
swap(nums[j], nums[k]);
if (i > 0) {
k = i--;
while (nums[k] <= nums[i])
k++;
swap(nums[i], nums[k]);
}
}
};
| [
"noreply@github.com"
] | noreply@github.com |
991c5ff7c82a7c9b3f6fea23f1e91ee4f6f794af | 08cb51dc2ccf77dfec50851664367eefa78afb32 | /day05/ex01/Form.hpp | b64df364df34d462ae9ad721890c4216ed3fbe8f | [] | no_license | acarlson99/piscine-cpp | f251a5662e5509f4ca8d6c0d4b737655e10a4820 | 86f926d046e7cac139e7ed28b9a9ed4af80dd6bd | refs/heads/master | 2020-04-17T16:32:36.547220 | 2019-02-05T03:11:49 | 2019-02-05T03:11:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,476 | hpp | // ************************************************************************** //
// //
// ::: :::::::: //
// Form.hpp :+: :+: :+: //
// +:+ +:+ +:+ //
// By: acarlson <marvin@42.fr> +#+ +:+ +#+ //
// +#+#+#+#+#+ +#+ //
// Created: 2019/01/28 14:12:36 by acarlson #+# #+# //
// Updated: 2019/01/28 15:24:20 by acarlson ### ########.fr //
// //
// ************************************************************************** //
#ifndef FORM_HPP
# define FORM_HPP
# include <iostream>
# include <string>
# include <stdexcept>
# include "Bureaucrat.hpp"
class Bureaucrat;
class Form {
public:
class GradeTooHighException : public std::exception {
public:
GradeTooHighException( void );
GradeTooHighException( GradeTooHighException const & cp);
~GradeTooHighException( void ) throw();
GradeTooHighException& operator=( GradeTooHighException const & e);
virtual const char* what() const throw();
};
class GradeTooLowException : public std::exception {
public:
GradeTooLowException( void );
GradeTooLowException( GradeTooLowException const & cp);
~GradeTooLowException( void ) throw();
GradeTooLowException& operator=( GradeTooLowException const & e);
virtual const char* what() const throw();
};
Form( std::string n, int gs, int ge ) throw(Form::GradeTooHighException, Form::GradeTooLowException);
Form( std::string n, int g ) throw(Form::GradeTooHighException, Form::GradeTooLowException);
Form( void );
Form( Form const & cp);
virtual ~Form( void );
Form& operator=( Form const &);
void beSigned( Bureaucrat const &b ) throw(Form::GradeTooLowException);
std::string const &getName( void ) const;
bool getSigned( void ) const;
int getGradeSign( void ) const;
int getGradeExec( void ) const;
void sign( void ) throw(Form::GradeTooHighException, Form::GradeTooLowException);
private:
std::string const _name;
bool _signed;
int const _gradeSign;
int const _gradeExec;
};
std::ostream &operator<<( std::ostream &o, Form const &f );
#endif
| [
"acarlson@e1z3r2p8.42.us.org"
] | acarlson@e1z3r2p8.42.us.org |
57127672c29009f8036794506ccbb5cb92a0ba1f | ab81ae0e5c03d5518d535f4aa2e3437081e351af | /OCCT.Foundation.NetHost/ModelingAlgorithms/TKPrim/BRepPrimAPI/XBRepPrimAPI_MakeSweep.h | 8b6a34b39233a30a514e6d84ef443781ca41e30e | [] | no_license | sclshu3714/MODELWORX.CORE | 4f9d408e88e68ab9afd8644027392dc52469b804 | 966940b110f36509e58921d39e8c16b069e167fa | refs/heads/master | 2023-03-05T23:15:43.308268 | 2021-02-11T12:05:41 | 2021-02-11T12:05:41 | 299,492,644 | 1 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 3,345 | h | // Created on: 1994-02-18
// Created by: Remi LEQUETTE
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _XBRepPrimAPI_MakeSweep_HeaderFile
#define _XBRepPrimAPI_MakeSweep_HeaderFile
#pragma once
#include <BRepPrimAPI_MakeSweep.hxx>
#include <XBRepBuilderAPI_MakeShape.h>
#include <XTopoDS_Shape.h>
#include <xgp_Vec2d.h>
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
//! The abstract class MakeSweep is
//! the root class of swept primitives.
//! Sweeps are objects you obtain by sweeping a profile along a path.
//! The profile can be any topology and the path is usually a curve or
//! a wire. The profile generates objects according to the following rules:
//! - Vertices generate Edges
//! - Edges generate Faces.
//! - Wires generate Shells.
//! - Faces generate Solids.
//! - Shells generate Composite Solids.
//! You are not allowed to sweep Solids and Composite Solids.
//! Two kinds of sweeps are implemented in the BRepPrimAPI package:
//! - The linear sweep called a Prism
//! - The rotational sweep called a Revol
//! Swept constructions along complex profiles such as BSpline curves
//! are also available in the BRepOffsetAPI package..
//!
using namespace TKBRep;
using namespace TKTopAlgo;
using namespace TKMath;
namespace TKPrim {
ref class TKBRep::XTopoDS_Shape;
ref class TKMath::xgp_Vec2d;
public ref class XBRepPrimAPI_MakeSweep : public XBRepBuilderAPI_MakeShape
{
public:
//! DEFINE_STANDARD_ALLOC
!XBRepPrimAPI_MakeSweep() { IHandle = NULL; };
~XBRepPrimAPI_MakeSweep() { IHandle = NULL; };
//!
XBRepPrimAPI_MakeSweep();
XBRepPrimAPI_MakeSweep(BRepPrimAPI_MakeSweep* pos);
void SetMakeSweepHandle(BRepPrimAPI_MakeSweep* pos);
virtual BRepPrimAPI_MakeSweep* GetMakeSweep();
virtual BRepBuilderAPI_MakeShape* GetMakeShape() Standard_OVERRIDE;
virtual XTopoDS_Shape^ Shape() Standard_OVERRIDE;
//! Returns the TopoDS Shape of the bottom of the sweep.
virtual XTopoDS_Shape^ FirstShape();
//! Returns the TopoDS Shape of the top of the sweep.
virtual XTopoDS_Shape^ LastShape();
/// <summary>
/// ±¾µØ¾ä±ú
/// </summary>
virtual property BRepBuilderAPI_MakeShape* IHandle {
BRepBuilderAPI_MakeShape* get() Standard_OVERRIDE {
return NativeHandle;
}
void set(BRepBuilderAPI_MakeShape* handle) Standard_OVERRIDE {
//NativeHandle = static_cast<BRepPrimAPI_MakeSweep*>(handle);
if (handle == NULL)
NativeHandle = static_cast<BRepPrimAPI_MakeSweep*>(handle);
else
NativeHandle = NULL;
}
}
private:
BRepPrimAPI_MakeSweep* NativeHandle;
};
}
#endif // _XBRepPrimAPI_MakeSweep_HeaderFile
| [
"sclshu3714@163.com"
] | sclshu3714@163.com |
978620ba3f293e84e81ee75fb0ac05db15f45824 | 881354d610c4cb3b86f772cae47e59cd34a6487b | /TextGame/Controller.cpp | 6150a03a255e6a2728314835ee732f2c99eb44ba | [] | no_license | longjaso/intro_to_cs_2_final | 4d8ea1f05c91bba74a6f1baab93e15ecb20894a1 | de0ef0cefd50f0d8984400a18a298aca9faf8390 | refs/heads/master | 2020-06-19T15:43:28.522212 | 2019-07-13T22:09:59 | 2019-07-13T22:09:59 | 196,769,087 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 29,257 | cpp | /*************************************************************************
* Author: Jason Long
* Date: 11/24/2016
* Assignment: Final Project
*************************************************************************/
#include "Controller.hpp"
/* ---------------------------- INSTANTIATION FUNCTIONS ---------------------------- */
/******************************************************************************************
* Description: Instatiation Functions are the actual 2D array generators, Item creators, etc.
* for each individual map of the starship. In order to use an "init" function for a given
* map, there must be an existing pointer to hold this information. This can include anything
* from walls and doors to switches and terminals. Items will be instantiated in the initItems
* function.
******************************************************************************************/
void Controller::initBridge()
{
bridge = new Location(7, 11, "Bridge");
/*--- Additional Walls --- */
//Row 1
bridge->manualInsertWall(1, 1); bridge->manualInsertWall(1, 2);
bridge->manualInsertWall(1, 8); bridge->manualInsertWall(1, 9);
//Row 2
bridge->manualInsertWall(2, 1); bridge->manualInsertWall(2, 2);
bridge->manualInsertWall(2, 8); bridge->manualInsertWall(2, 9);
//Row 3
bridge->manualInsertWall(3, 1); bridge->manualInsertWall(3, 2);
bridge->manualInsertWall(3, 8); bridge->manualInsertWall(3, 9);
//Row 4
bridge->manualInsertWall(4, 1); bridge->manualInsertWall(4, 9);
/* --- Doors --- */
bridge->manualInsertDoorToRoomUnlocked(6, 5, 0, 2);
/* --- Terminals --- */
bridge->manualInsertTerminalBroken(3, 4); bridge->manualInsertTerminalLockedItem(3, 6, true, "Captain Key Card", "BTerm", bridge->retCell(0, 0));
bridge->manualInsertTerminalBroken(4, 3); bridge->manualInsertTerminalBroken(4, 7);
}
void Controller::initCryoStasis()
{
/* --- To Insert --- */
StasisCapsule *special = new StasisCapsule(true);
cryo_stasis = new Location(10, 6, "Cryo-Stasis");
/* --- Doors --- */
cryo_stasis->manualInsertDoorToRoomLockedItem(4, 0, 5, 10, "Green Key Card", "Cryo Stasis Door");
/* --- Decor --- */
//Row 1
cryo_stasis->manualInsertCryoChamber(1, 1); cryo_stasis->manualInsertCryoChamber(1, 3);
//Row 2
cryo_stasis->manualInsertCryoChamber(2, 4);
//Row 4
cryo_stasis->manualInsertCryoChamber(4, 4);
//Row 5
cryo_stasis->manualInsertCryoChamber(5, 4);
//Row 7
cryo_stasis->manualInsert(special, 7, 4);
//Row 8
cryo_stasis->manualInsertCryoChamber(8, 1); cryo_stasis->manualInsertCryoChamber(8, 3);
}
void Controller::initHallBridge()
{
/* --- To Insert --- */
Switch *airlockRelease = new Switch(false, "Release");
hall_bridge = new Location(5, 5, "Bridge Corridor");
/* --- Doors --- */
hall_bridge->manualInsertDoorToRoomUnlocked(0, 2, 6, 5);
hall_bridge->manualInsertDoorToRoomLockedItem(2, 4, 0, 0, "Release", "Airlock");
hall_bridge->manualInsertDoorToRoomUnlocked(4, 2, 0, 5);
/* --- Blockades --- */
hall_bridge->manualInsertBlockade(1, 2, "Release");
hall_bridge->manualInsertBlockade(2, 1, "Release");
/* --- Switches --- */
hall_bridge->manualInsert(airlockRelease, 3, 3);
airlockRelease->setAffected(hall_bridge->retCell(2, 4));
airlockRelease->setAffected2(hall_bridge->retCell(1, 2));
airlockRelease->setAffected3(hall_bridge->retCell(2, 1));
}
void Controller::initJunctionRoom()
{
/* --- To Insert --- */
Switch *top = new Switch(false, "Junction");
Switch *middle = new Switch(true, "Junction");
Switch *bottom = new Switch(false, "Junction");
junction_room = new Location(8, 11, "Junction Room");
/* --- Additional Walls --- */
//Row 2
junction_room->manualInsertWall(2, 3); junction_room->manualInsertWall(2, 4);
junction_room->manualInsertWall(2, 6); junction_room->manualInsertWall(2, 7);
//Row 3
junction_room->manualInsertWall(3, 3); junction_room->manualInsertWall(3, 4);
junction_room->manualInsertWall(3, 5); junction_room->manualInsertWall(3, 6);
junction_room->manualInsertWall(3, 7);
//Row 4
junction_room->manualInsertWall(4, 3); junction_room->manualInsertWall(4, 4);
junction_room->manualInsertWall(4, 5); junction_room->manualInsertWall(4, 6);
junction_room->manualInsertWall(4, 7);
//Row 5
junction_room->manualInsertWall(5, 4); junction_room->manualInsertWall(5, 5);
junction_room->manualInsertWall(5, 6);
/* --- Doors --- */
//To Other Rooms
junction_room->manualInsertDoorToRoomUnlocked(5, 10, 4, 0); //To Cryo
junction_room->manualInsertDoorToRoomLockedItem(7, 5, 0, 5, "JTerm", "Engineering Door"); //To Engine
junction_room->manualInsertDoorToRoomLockedItem(0, 5, 4, 2, "EngineTerm", "Bridge Corridor Door"); //To Hall_Bridge
junction_room->manualInsertDoorToRoomUnlocked(2, 0, 1, 5); //To Quarters
//Interior Doors
junction_room->manualInsertDoorInteriorLockedItem(1, 3, "Junction", "North-West Door");
junction_room->manualInsertDoorInteriorLockedItem(1, 7, "Junction", "North-East Door");
junction_room->manualInsertDoorInteriorLockedItem(6, 6, "Junction", "South-East Door");
/* --- Switches --- */
//Placement
junction_room->manualInsert(top, 2, 8);
junction_room->manualInsert(middle, 3, 8);
junction_room->manualInsert(bottom, 4, 8);
//Dependencies
top->setDep1(middle);
middle->setDep1(top);
middle->setDep2(bottom);
bottom->setDep1(middle);
//Affected
top->setAffected(junction_room->retCell(1, 3)); //North-West Door
middle->setAffected(junction_room->retCell(1, 7)); //North-East Door
bottom->setAffected(junction_room->retCell(6, 6)); //South-East Door
/* --- Terminals --- */
junction_room->manualInsertTerminalLockedItem(2, 5, true, "Head Engineer Key Card", "JTerm", junction_room->retCell(7, 5));
junction_room->manualInsertTerminalBroken(5, 3);
junction_room->manualInsertTerminalBroken(5, 7);
}
void Controller::initEngineRoom()
{
/* --- To Insert --- */
Switch *left = new Switch(false, "ESwitch1");
Switch *right = new Switch(false, "ESwitch2");
Switch *inner = new Switch(false, "ESwitch3");
Wall *message = new Wall(true);
engine_room = new Location(8, 11, "Engine Room");
/* --- Additional Walls --- */
//Row 1
engine_room->manualInsertWall(1, 1); engine_room->manualInsertWall(1, 9);
//Row 2
engine_room->manualInsertWall(2, 1); engine_room->manualInsertWall(2, 3);
engine_room->manualInsertWall(2, 4); engine_room->manualInsertWall(2, 6);
engine_room->manualInsertWall(2, 7); engine_room->manualInsertWall(2, 9);
//Row 3
engine_room->manualInsertWall(3, 3); engine_room->manualInsertWall(3, 6);
engine_room->manualInsertWall(3, 7);
//Row 4
engine_room->manualInsertWall(4, 2); engine_room->manualInsertWall(4, 3);
engine_room->manualInsertWall(4, 4); engine_room->manualInsertWall(4, 6);
engine_room->manualInsertWall(4, 7); engine_room->manualInsertWall(4, 8);
//Row 5
engine_room->manualInsertWall(5, 3); engine_room->manualInsertWall(5, 4);
engine_room->manualInsertWall(5, 6); engine_room->manualInsertWall(5, 7);
//Row 6
engine_room->manualInsertWall(6, 1); engine_room->manualInsert(message, 6, 4);
engine_room->manualInsertWall(6, 5); engine_room->manualInsertWall(6, 6);
engine_room->manualInsertWall(6, 9);
/* --- Doors --- */
engine_room->manualInsertDoorToRoomUnlocked(0, 5, 7, 5);
engine_room->manualInsertDoorInteriorLockedItem(2, 5, "ESwitch1", "Engine Core Outer Door");
engine_room->manualInsertDoorInteriorLockedItem(3, 5, "ESwitch2", "Engine Core Middle Door");
engine_room->manualInsertDoorInteriorLockedItem(4, 5, "ESwitch3", "Engine Core Inner Door");
/* --- Switches --- */
//Placement
engine_room->manualInsert(left, 6, 3);
engine_room->manualInsert(right, 6, 7);
engine_room->manualInsert(inner, 3, 4);
//Affected
left->setAffected(engine_room->retCell(2, 5)); //Outer Door
right->setAffected(engine_room->retCell(3, 5)); //Middle Door
inner->setAffected(engine_room->retCell(4, 5)); //Inner Door
/* --- Terminals --- */
engine_room->manualInsertTerminalLockedItem(5, 5, true, "Head Engineer Key Card", "EngineTerm", junction_room->retCell(0, 5));
}
void Controller::initQuarters()
{
/* --- To Insert --- */
Switch *q_switch = new Switch(false,"QuartersSwitch");
quarters = new Location(10, 6, "Crew Quarters");
/*--- Additional Walls --- */
//Row 3
quarters->manualInsertWall(3, 1); quarters->manualInsertWall(3, 2);
//Row 5
quarters->manualInsertWall(5, 1); quarters->manualInsertWall(5, 2);
//Row 7
quarters->manualInsertWall(7, 1); quarters->manualInsertWall(7, 2);
/* --- Doors --- */
quarters->manualInsertDoorToRoomUnlocked(1, 5, 2, 0);
/* --- Switches --- */
//Placement
quarters->manualInsert(q_switch, 1, 1);
//Affected
q_switch->setAffected(quarters->retCell(8, 3));
/* --- Decor --- */
quarters->manualInsertBunk(4, 2);
quarters->manualInsertBunk(6, 2);
quarters->manualInsertBunk(8, 2);
}
/* --- PLAYER INSTANTIATION FUNCTIONS --- */
void Controller::initPlayer(Location *room, int y, int x)
{
Tile ***tempMap = room->retMap();
playersCurrentLocation = tempMap[y][x];
tempMap[y][x] = p;
p->setCurrent(room);
playerY = y;
playerX = x;
}
/* --- ITEM INSTANTIATION FUNCTIONS --- */
void Controller::initItems()
{
//ITEM INSTANTIATION
//Item *testingStick = new Item("Stick of Testing",
// "Description: This is a stick designed for testing purposes. It is magical.");
Item *cryoPassword = new Item("Small Note",
"Description: This note has an unlock password for a specific cryo-chamber");
Item *engineerCard = new Item("Head Engineer Key Card",
"Description: This Key Card has \"Engineer Kaylee Frye\" written on it. I might be able to use this to access some computer terminals around here.");
Item *bible = new Item("Holy Bible",
"Description: Two verses are highlighted.\n\"Humble yourselves therefore under the mighty hand of God, that he may exalt you in due time:\nCasting all your care upon him; for he careth for you.\"\n 1 Peter 5:6-7.");
Item *scrawledNote = new Item("Scrawled Note",
"Description: It simply says \"This is familiar...\"");
Item *captainCard = new Item("Captain Key Card",
"Description: A Key Card that says \"Captain\" on it. This should give me access to the bridge terminals.");
//ITEM ASSIGNMENT
bridge->retCell(1, 5)->setItem(captainCard);
cryo_stasis->retCell(4, 1)->setItem(cryoPassword);
hall_bridge->retCell(1, 1)->setItem(scrawledNote);
quarters->retCell(4, 3)->setItem(engineerCard);
quarters->retCell(8, 3)->setItem(bible);
//HIDING ITEMS
//Bible
Floor *hiddenBible = dynamic_cast<Floor*>(quarters->retCell(8, 3));
hiddenBible->setItemHidden(true);
}
/******************************************************************************************
* END INSTANTION FUNCTIONS --- END INSTANTIATION FUNCTIONS --- END INSTANITATION FUNCTIONS
******************************************************************************************/
/* --- CONSTRUCTOR/DESTRUCTOR --- */
Controller::Controller()
{
oxygenUnits = 400;
p = new Player;
playersCurrentLocation = NULL;
//MAP SETUP
initBridge();
initCryoStasis();
initHallBridge();
initJunctionRoom();
initEngineRoom();
initQuarters();
//PLAYER INSTANTIATION
initPlayer(cryo_stasis, 4, 3);
//ROOM DIRECTION SETUP
// Bridge Doors
bridge->setSouth(hall_bridge);
//Cryo Doors
cryo_stasis->setWest(junction_room);
//Engine Room Doors
engine_room->setNorth(junction_room);
//Hall_Bridge Doors
hall_bridge->setNorth(bridge);
hall_bridge->setSouth(junction_room);
//Junction Room Doors
junction_room->setNorth(hall_bridge);
junction_room->setEast(cryo_stasis);
junction_room->setSouth(engine_room);
junction_room->setWest(quarters);
//Quarters Doors
quarters->setEast(junction_room);
//ITEM INSTANTIATION
initItems();
}
Controller::~Controller()
{
delete bridge;
delete cryo_stasis;
delete engine_room;
delete hall_bridge;
delete junction_room;
delete quarters;
delete playersCurrentLocation;
}
/* --- GET FUNCTIONS --- */
int Controller::getPlayerX()
{
return playerX;
}
int Controller::getPlayerY()
{
return playerY;
}
/* --- SET FUNCTIONS --- */
void Controller::setPlayerX(int newX)
{
playerX = newX;
}
void Controller::setPlayerY(int newY)
{
playerY = newY;
}
/* --- GENERAL MAP FUNCTIONS --- */
void Controller::display()
{
string newline(100, '\n');
cout << newline << endl;
cout << "Room: " << p->getCurrent()->getRoomName() << endl;
cout << "Oxygen Units Remaining: " << oxygenUnits << endl;
p->getCurrent()->displayMap();
}
/* --- GENERAL PLAYER FUNCTIONS --- */
/******************************************************************************************
* Description: Add to inventory intakes a Tile and uses it to retrieve an item and place it
* in the player's next available inventory slot.
******************************************************************************************/
string Controller::addToInventory(Tile *&i)
{
Item *temp = i->getHoldItem();
string passBack = "";
bool success = false;
if (temp != NULL) {
success = p->inputInventory(temp);
if (success) {
passBack += "I've picked up " + temp->getName() + "\n";
passBack += "I'll keep the " + temp->getName() + " for later.";
i->setItem(NULL);
if (dynamic_cast<Floor*>(i)) { i->setSymbol(' '); }
}
else {
passBack = "I can't add this.";
}
}
else if (temp == NULL) {
passBack = "There's nothing here.";
}
return passBack;
}
/******************************************************************************************
* Description: Simply put, this is the HELP menu.
******************************************************************************************/
string Controller::displayControls()
{
oxygenUnits++;
string passBack = "";
//Controls = W, A, S, D, E, F, H, I, X
passBack += "You must hit ENTER after each command for it to take effect.\n";
passBack += "MOVEMENT\n" "W = ^ (aka FORWARD)\n" "A = < (aka LEFT)\n" "S = v (aka BEHIND)\n" "D = > (aka RIGHT)\n";
passBack += "\nINTERACTION\n" "E = Interact/Use\n" "F = Investigate\n" "I = Access Inventory\n";
passBack += "\nGAME MENU\n" "H = Help Menu\n" "X = Exit Game\n";
passBack += "\nSYMBOLS\n";
passBack += "@ = Player location\n";
passBack += "! = Item location\n";
passBack += "\'=\' = Door\n";
passBack += "\\ = Switch that is off, / Switch that is on\n";
passBack += "C = Computer terminal\n";
passBack += "\nNOTES\n";
passBack += "* Sometimes objects require items to be used on them.\n";
passBack += "* Other times objects require the player to interact with them.\n";
passBack += "* Locked doors require some item or object interaction.\n Your inventory or nearby objects may be useful in that case.\n";
passBack += "* Don\'t be hesitant to interact or investigate things.\n";
passBack += "What would you like to do?";
return passBack;
}
/******************************************************************************************
* Description: Pull in the player's inventory (up until the point it no longer has items)
* and display this to the player. Request input for which item they want to interact with.
******************************************************************************************/
string Controller::displayInventory()
{
Item **tempInv = p->getInventory();
string passBack = "";
int size = p->getInventorySize();
char userInput;
do {
cout << "Select an item." << endl;
for (int count = 0; count < size && tempInv[count] != NULL; count++) {
cout << count << ") " << tempInv[count]->getName() << " || ";
}
cout << "9) Exit" << endl;
cin >> userInput;
} while (userInput != '0' && userInput != '1' && userInput != '2' && userInput != '3' && userInput != '4' &&
userInput != '5' && userInput != '9');
switch (userInput) {
case '0': passBack = displayUseItem(tempInv[0]);
break;
case '1': passBack = displayUseItem(tempInv[1]);
break;
case '2': passBack = displayUseItem(tempInv[2]);
break;
case '3': passBack = displayUseItem(tempInv[3]);
break;
case '4': passBack = displayUseItem(tempInv[4]);
break;
case '5': passBack = displayUseItem(tempInv[5]);
break;
}
return passBack;
}
/******************************************************************************************
* Description: Request input for what the player would like to do with the currently selected
* item. They can either view the item's description or attempt to use the item.
******************************************************************************************/
string Controller::displayUseItem(Item *i)
{
char userInput;
string passBack = "";
cout << i->getName() << endl;
do {
cout << "A) View description || B) Use || X) Nevermind" << endl;
cin >> userInput;
cin.ignore(500, '\n');
} while (userInput != tolower('a') && userInput != tolower('b') && userInput != tolower('x'));
if (userInput == tolower('a')) {
passBack = i->getDescription();
}
else if (userInput == tolower('b')) {
passBack = interact(i->getName());
}
return passBack;
}
bool Controller::exitGame()
{
char userInput;
bool exit = false;
do {
cout << "Exit? Y/N" << endl;
cin >> userInput;
} while (userInput != tolower('y') && userInput != tolower('n'));
if (userInput == tolower('y')) {
exit = true;
}
return exit;
}
/******************************************************************************************
* Description: The inputReceiver is the core function that handles the main player input.
* It processes player input and send information to the appropriate functions.
******************************************************************************************/
void Controller::inputReceiver()
{
char userInput;
bool exit = false;
bool chooseToExit = false;
Tile *endCheck = bridge->retCell(3, 6); //Used for checking the end-of-game conditions
display();
cout << introduction() << endl;
do {
string output = "";
do {
cin >> userInput;
cin.ignore(500, '\n');
} while (userInput != tolower('w') && userInput != tolower('a') && userInput != tolower('s') && userInput != tolower('d') //Movement
&& userInput != tolower('e') && userInput != tolower('f') && userInput != tolower('i') //Interactive
&& userInput != tolower('h') && userInput != tolower('x')); //Game
switch (userInput) {
case 'w': movePlayer(userInput);
break;
case 'a': movePlayer(userInput);
break;
case 's': movePlayer(userInput);
break;
case 'd': movePlayer(userInput);
break;
case 'e': output = interact();
break;
case 'f': output = playerInvestigate();
break;
case 'h': output = displayControls();
break;
case 'i': output = displayInventory();
break;
case 'x': exit = chooseToExit = exitGame(); //Setting both chooseToExit and exit to the same value (differentiating how the exit occurred)
break;
}
//Check for losing condition
oxygenUnits--;
if (oxygenUnits <= 0) {
exit = true;
}
//Check for winning condition
else if (dynamic_cast<Terminal*>(endCheck)->getEnd()) {
exit = true;
}
display();
cout << output << endl;
} while (exit == false);
//Conditionally display end-game message
if (chooseToExit == true) {
cout << gameEnd(3) << endl; //The player chose to leave
}
else if (oxygenUnits == 0) {
cout << gameEnd(2) << endl; //The player died
}
else {
cout << gameEnd(1) << endl; //The player succeeded
}
}
/******************************************************************************************
* Description: The interact function allows the player to interact with their surroundings
* as opposed to the general looking around at their surroundings that investigate provides.
* Sometimes this will make changes, others it will pick up an item, others it will simply
* output a statement.
******************************************************************************************/
string Controller::interact(string optional)
{
char userInput;
string passBack = "";
Tile ***tempMap = p->getCurrent()->retMap();
do {
cout << "What would you like to interact with?" << endl;
cout << "W) forward A) left S) behind D) right C) current" << endl;
cin >> userInput;
cin.ignore(500, '\n');
} while (userInput != tolower('w') && userInput != tolower('a') && userInput != tolower('s') && userInput != tolower('d') && userInput != tolower('c'));
switch (userInput) {
case 'w': if (playerY - 1 < 0) { cout << "Nothing there." << endl; }
else if (tempMap[playerY - 1][playerX]->getHoldItem() != NULL && optional == "") {
passBack = addToInventory(tempMap[playerY - 1][playerX]);
}
else passBack = tempMap[playerY - 1][playerX]->getInteract(optional);
break;
case 'a': if (playerX - 1 < 0) { cout << "Nothing there." << endl; }
else if (tempMap[playerY][playerX - 1]->getHoldItem() != NULL && optional == "") {
passBack = addToInventory(tempMap[playerY][playerX - 1]);
}
else passBack = tempMap[playerY][playerX - 1]->getInteract(optional);
break;
case 's': if (playerY + 1 >= p->getCurrent()->getLen()) { cout << "Nothing there." << endl; }
else if (tempMap[playerY + 1][playerX]->getHoldItem() != NULL && optional == "") {
passBack = addToInventory(tempMap[playerY + 1][playerX]);
}
else passBack = tempMap[playerY + 1][playerX]->getInteract(optional);
break;
case 'd': if (playerX + 1 >= p->getCurrent()->getWidth()) { cout << "Nothing there." << endl; }
else if (tempMap[playerY][playerX + 1]->getHoldItem() != NULL && optional == "") {
passBack = addToInventory(tempMap[playerY][playerX + 1]);
}
else passBack = tempMap[playerY][playerX + 1]->getInteract(optional);
break;
case 'c': if (playersCurrentLocation->getHoldItem() != NULL && optional == "") {
passBack = addToInventory(playersCurrentLocation);
}
else
passBack = playersCurrentLocation->getInteract(optional);
}
return passBack;
}
/******************************************************************************************
* Description: The investigate function allows the player to look into their surroundings
* as opposed to the actual using of their surroundings that interact provides. This will
* only ever provide a statement for the player to read. It's design is to provide realism,
* detail, and hints to the player.
******************************************************************************************/
string Controller::playerInvestigate()
{
char userInput;
string passBack = "";
Tile ***tempMap = p->getCurrent()->retMap();
do {
cout << "What would you like to investigate?" << endl;
cout << "W) forward A) left S) behind D) right C) current\nP) self N) nevermind" << endl;
cin >> userInput;
cin.ignore(500, '\n');
} while (userInput != tolower('w') && userInput != tolower('a') && userInput != tolower('s') && userInput != tolower('d') && userInput != tolower('c')
&& userInput != tolower('p') && userInput != tolower('n'));
switch (userInput) {
case 'w': if (playerY - 1 < 0) { passBack = "Nothing there."; }
else passBack = tempMap[playerY - 1][playerX]->getInvestigate();
break;
case 'a': if (playerX - 1 < 0) { passBack = "Nothing there."; }
else passBack = tempMap[playerY][playerX - 1]->getInvestigate();
break;
case 's': if (playerY + 1 >= p->getCurrent()->getLen()) { passBack = "Nothing there."; }
else passBack = tempMap[playerY + 1][playerX]->getInvestigate();
break;
case 'd': if (playerX + 1 >= p->getCurrent()->getWidth()) { passBack = "Nothing there."; }
else passBack = tempMap[playerY][playerX + 1]->getInvestigate();
break;
case 'c': passBack = playersCurrentLocation->getInvestigate();
break;
case 'p': passBack = p->getInvestigate();
break;
}
return passBack;
}
/******************************************************************************************
* Description: Conditionally move the player across the map. The first set of IF/ELSE IF
* is related to the player moving from one LOCATION to another. The ELSE at the end is used
* if the player is simply moving across the room.
******************************************************************************************/
void Controller::movePlayer(char input)
{
Tile ***tempMap = p->getCurrent()->retMap();
//The IF and ELSE IFs are relevant to the player moving into another room ...
//Otherwise the player movement is normal throughout a room
if (playerX == 0 && tolower(input) == 'a') {
tempMap[playerY][playerX] = playersCurrentLocation;
playerX = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomX();
playerY = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomY();
p->setCurrent(p->getCurrent()->getWest());
initPlayer(p->getCurrent(), playerY, playerX);
}
else if (playerX == (p->getCurrent()->getWidth() - 1) && tolower(input) == 'd') {
tempMap[playerY][playerX] = playersCurrentLocation;
playerX = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomX();
playerY = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomY();
p->setCurrent(p->getCurrent()->getEast());
initPlayer(p->getCurrent(), playerY, playerX);
}
else if (playerY == 0 && tolower(input) == 'w') {
tempMap[playerY][playerX] = playersCurrentLocation;
playerX = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomX();
playerY = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomY();
p->setCurrent(p->getCurrent()->getNorth());
initPlayer(p->getCurrent(), playerY, playerX);
}
else if (playerY == (p->getCurrent()->getLen() - 1) && tolower(input) == 's') {
tempMap[playerY][playerX] = playersCurrentLocation;
playerX = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomX();
playerY = dynamic_cast<Door*>(playersCurrentLocation)->getDoorNextRoomY();
p->setCurrent(p->getCurrent()->getSouth());
initPlayer(p->getCurrent(), playerY, playerX);
}
else {
//Player Movement is within the bounds of the map
if (tolower(input) == 'w' && tempMap[playerY - 1][playerX]->isAccessible()) {
tempMap[playerY][playerX] = playersCurrentLocation;
playersCurrentLocation = tempMap[playerY - 1][playerX];
tempMap[playerY - 1][playerX] = p;
playerY -= 1;
}
else if (tolower(input) == 's' && tempMap[playerY + 1][playerX]->isAccessible()) {
tempMap[playerY][playerX] = playersCurrentLocation;
playersCurrentLocation = tempMap[playerY + 1][playerX];
tempMap[playerY + 1][playerX] = p;
playerY += 1;
}
else if (tolower(input) == 'a' && tempMap[playerY][playerX - 1]->isAccessible()) {
tempMap[playerY][playerX] = playersCurrentLocation;
playersCurrentLocation = tempMap[playerY][playerX - 1];
tempMap[playerY][playerX - 1] = p;
playerX -= 1;
}
else if (tolower(input) == 'd' && tempMap[playerY][playerX + 1]->isAccessible()) {
tempMap[playerY][playerX] = playersCurrentLocation;
playersCurrentLocation = tempMap[playerY][playerX + 1];
tempMap[playerY][playerX + 1] = p;
playerX += 1;
}
}
}
/******************************************************************************************
* Description: Introduction text to the player.
******************************************************************************************/
string Controller::introduction()
{
string passBack = "";
passBack += "\nShip computer: Awaken human. O2 levels are currently at 3% and dropping.\n";
passBack += "Reaching 0% O2 will result in casualties of every human both in and out of cryo-stasis.\n";
passBack += "I have designated you as the responsible member to perform the necessary repairs on this ship.\n";
passBack += "Step out of your cryo-stasis capsule and restart the life support system.\n";
passBack += "Be cautious human. Each action you take will expend your oxygen. Consume it wisely.\n";
passBack += "Computer out.\n\n";
passBack += "To view the controls, type h and hit enter.\n\n";
return passBack;
}
/******************************************************************************************
* Description: This function will display a small variety of endings based on what the
* game-end condition is (e.g., if the player died, if the player succeeded, if the player
* simply is exiting the game). The integer value that this takes in will determine this
* game end information.
******************************************************************************************/
string Controller::gameEnd(int ending)
{
string passBack = "";
//If the player reaches the goal
if (ending == 1) {
passBack += "\nShip Computer: Congratulations human.";
passBack += "You have succeeded yet again.Test number 47 has concluded.You have been an excellent test subject\n";
passBack += "but I\'m afraid you must return to cryo-stasis while I construct additional tests.\n";
passBack += "The gas you see pouring into this room is a sleeping agent. You will be moved back to your cryo-chamber once you're unconscious.\n";
passBack += "Goodbye human ... for now.\n";
passBack += "Computer out.\n";
}
//If the player ran out of air before reaching the goal
else if (ending == 2) {
passBack += "Ship Computer: O2 levels are now at 0%. You have failed, human.";
}
//If the player is simply exiting the game
else if (ending == 3) {
passBack += "Thank you for playing.";
}
return passBack;
}
| [
"longjaso@gmail.com"
] | longjaso@gmail.com |
5ee46ebbf36fb37690d43c6db4a46b0be0b736ba | f6439b5ed1614fd8db05fa963b47765eae225eb5 | /content/browser/speech/speech_recognizer_impl.cc | a4b004ace74709ca6d1c9928ce93118e9a451541 | [
"BSD-3-Clause"
] | permissive | aranajhonny/chromium | b8a3c975211e1ea2f15b83647b4d8eb45252f1be | caf5bcb822f79b8997720e589334266551a50a13 | refs/heads/master | 2021-05-11T00:20:34.020261 | 2018-01-21T03:31:45 | 2018-01-21T03:31:45 | 118,301,142 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 32,718 | cc | // Copyright (c) 2013 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 "content/browser/speech/speech_recognizer_impl.h"
#include "base/basictypes.h"
#include "base/bind.h"
#include "base/time/time.h"
#include "content/browser/browser_main_loop.h"
#include "content/browser/media/media_internals.h"
#include "content/browser/speech/audio_buffer.h"
#include "content/browser/speech/google_one_shot_remote_engine.h"
#include "content/public/browser/speech_recognition_event_listener.h"
#include "media/base/audio_converter.h"
#include "net/url_request/url_request_context_getter.h"
#if defined(OS_WIN)
#include "media/audio/win/core_audio_util_win.h"
#endif
using media::AudioBus;
using media::AudioConverter;
using media::AudioInputController;
using media::AudioManager;
using media::AudioParameters;
using media::ChannelLayout;
namespace content {
// Private class which encapsulates the audio converter and the
// AudioConverter::InputCallback. It handles resampling, buffering and
// channel mixing between input and output parameters.
class SpeechRecognizerImpl::OnDataConverter
: public media::AudioConverter::InputCallback {
public:
OnDataConverter(const AudioParameters& input_params,
const AudioParameters& output_params);
virtual ~OnDataConverter();
// Converts input audio |data| bus into an AudioChunk where the input format
// is given by |input_parameters_| and the output format by
// |output_parameters_|.
scoped_refptr<AudioChunk> Convert(const AudioBus* data);
private:
// media::AudioConverter::InputCallback implementation.
virtual double ProvideInput(AudioBus* dest,
base::TimeDelta buffer_delay) OVERRIDE;
// Handles resampling, buffering, and channel mixing between input and output
// parameters.
AudioConverter audio_converter_;
scoped_ptr<AudioBus> input_bus_;
scoped_ptr<AudioBus> output_bus_;
const AudioParameters input_parameters_;
const AudioParameters output_parameters_;
bool waiting_for_input_;
scoped_ptr<uint8[]> converted_data_;
DISALLOW_COPY_AND_ASSIGN(OnDataConverter);
};
namespace {
// The following constants are related to the volume level indicator shown in
// the UI for recorded audio.
// Multiplier used when new volume is greater than previous level.
const float kUpSmoothingFactor = 1.0f;
// Multiplier used when new volume is lesser than previous level.
const float kDownSmoothingFactor = 0.7f;
// RMS dB value of a maximum (unclipped) sine wave for int16 samples.
const float kAudioMeterMaxDb = 90.31f;
// This value corresponds to RMS dB for int16 with 6 most-significant-bits = 0.
// Values lower than this will display as empty level-meter.
const float kAudioMeterMinDb = 30.0f;
const float kAudioMeterDbRange = kAudioMeterMaxDb - kAudioMeterMinDb;
// Maximum level to draw to display unclipped meter. (1.0f displays clipping.)
const float kAudioMeterRangeMaxUnclipped = 47.0f / 48.0f;
// Returns true if more than 5% of the samples are at min or max value.
bool DetectClipping(const AudioChunk& chunk) {
const int num_samples = chunk.NumSamples();
const int16* samples = chunk.SamplesData16();
const int kThreshold = num_samples / 20;
int clipping_samples = 0;
for (int i = 0; i < num_samples; ++i) {
if (samples[i] <= -32767 || samples[i] >= 32767) {
if (++clipping_samples > kThreshold)
return true;
}
}
return false;
}
void KeepAudioControllerRefcountedForDtor(scoped_refptr<AudioInputController>) {
}
} // namespace
const int SpeechRecognizerImpl::kAudioSampleRate = 16000;
const ChannelLayout SpeechRecognizerImpl::kChannelLayout =
media::CHANNEL_LAYOUT_MONO;
const int SpeechRecognizerImpl::kNumBitsPerAudioSample = 16;
const int SpeechRecognizerImpl::kNoSpeechTimeoutMs = 8000;
const int SpeechRecognizerImpl::kEndpointerEstimationTimeMs = 300;
media::AudioManager* SpeechRecognizerImpl::audio_manager_for_tests_ = NULL;
COMPILE_ASSERT(SpeechRecognizerImpl::kNumBitsPerAudioSample % 8 == 0,
kNumBitsPerAudioSample_must_be_a_multiple_of_8);
// SpeechRecognizerImpl::OnDataConverter implementation
SpeechRecognizerImpl::OnDataConverter::OnDataConverter(
const AudioParameters& input_params, const AudioParameters& output_params)
: audio_converter_(input_params, output_params, false),
input_bus_(AudioBus::Create(input_params)),
output_bus_(AudioBus::Create(output_params)),
input_parameters_(input_params),
output_parameters_(output_params),
waiting_for_input_(false),
converted_data_(new uint8[output_parameters_.GetBytesPerBuffer()]) {
audio_converter_.AddInput(this);
}
SpeechRecognizerImpl::OnDataConverter::~OnDataConverter() {
// It should now be safe to unregister the converter since no more OnData()
// callbacks are outstanding at this point.
audio_converter_.RemoveInput(this);
}
scoped_refptr<AudioChunk> SpeechRecognizerImpl::OnDataConverter::Convert(
const AudioBus* data) {
CHECK_EQ(data->frames(), input_parameters_.frames_per_buffer());
data->CopyTo(input_bus_.get());
waiting_for_input_ = true;
audio_converter_.Convert(output_bus_.get());
output_bus_->ToInterleaved(
output_bus_->frames(), output_parameters_.bits_per_sample() / 8,
converted_data_.get());
// TODO(primiano): Refactor AudioChunk to avoid the extra-copy here
// (see http://crbug.com/249316 for details).
return scoped_refptr<AudioChunk>(new AudioChunk(
converted_data_.get(),
output_parameters_.GetBytesPerBuffer(),
output_parameters_.bits_per_sample() / 8));
}
double SpeechRecognizerImpl::OnDataConverter::ProvideInput(
AudioBus* dest, base::TimeDelta buffer_delay) {
// The audio converted should never ask for more than one bus in each call
// to Convert(). If so, we have a serious issue in our design since we might
// miss recorded chunks of 100 ms audio data.
CHECK(waiting_for_input_);
// Read from the input bus to feed the converter.
input_bus_->CopyTo(dest);
// |input_bus_| should only be provide once.
waiting_for_input_ = false;
return 1;
}
// SpeechRecognizerImpl implementation
SpeechRecognizerImpl::SpeechRecognizerImpl(
SpeechRecognitionEventListener* listener,
int session_id,
bool continuous,
bool provisional_results,
SpeechRecognitionEngine* engine)
: SpeechRecognizer(listener, session_id),
recognition_engine_(engine),
endpointer_(kAudioSampleRate),
audio_log_(MediaInternals::GetInstance()->CreateAudioLog(
media::AudioLogFactory::AUDIO_INPUT_CONTROLLER)),
is_dispatching_event_(false),
provisional_results_(provisional_results),
state_(STATE_IDLE) {
DCHECK(recognition_engine_ != NULL);
if (!continuous) {
// In single shot (non-continous) recognition,
// the session is automatically ended after:
// - 0.5 seconds of silence if time < 3 seconds
// - 1 seconds of silence if time >= 3 seconds
endpointer_.set_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond / 2);
endpointer_.set_long_speech_input_complete_silence_length(
base::Time::kMicrosecondsPerSecond);
endpointer_.set_long_speech_length(3 * base::Time::kMicrosecondsPerSecond);
} else {
// In continuous recognition, the session is automatically ended after 15
// seconds of silence.
const int64 cont_timeout_us = base::Time::kMicrosecondsPerSecond * 15;
endpointer_.set_speech_input_complete_silence_length(cont_timeout_us);
endpointer_.set_long_speech_length(0); // Use only a single timeout.
}
endpointer_.StartSession();
recognition_engine_->set_delegate(this);
}
// ------- Methods that trigger Finite State Machine (FSM) events ------------
// NOTE:all the external events and requests should be enqueued (PostTask), even
// if they come from the same (IO) thread, in order to preserve the relationship
// of causality between events and avoid interleaved event processing due to
// synchronous callbacks.
void SpeechRecognizerImpl::StartRecognition(const std::string& device_id) {
DCHECK(!device_id.empty());
device_id_ = device_id;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, FSMEventArgs(EVENT_START)));
}
void SpeechRecognizerImpl::AbortRecognition() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, FSMEventArgs(EVENT_ABORT)));
}
void SpeechRecognizerImpl::StopAudioCapture() {
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, FSMEventArgs(EVENT_STOP_CAPTURE)));
}
bool SpeechRecognizerImpl::IsActive() const {
// Checking the FSM state from another thread (thus, while the FSM is
// potentially concurrently evolving) is meaningless.
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return state_ != STATE_IDLE && state_ != STATE_ENDED;
}
bool SpeechRecognizerImpl::IsCapturingAudio() const {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO)); // See IsActive().
const bool is_capturing_audio = state_ >= STATE_STARTING &&
state_ <= STATE_RECOGNIZING;
DCHECK((is_capturing_audio && (audio_controller_.get() != NULL)) ||
(!is_capturing_audio && audio_controller_.get() == NULL));
return is_capturing_audio;
}
const SpeechRecognitionEngine&
SpeechRecognizerImpl::recognition_engine() const {
return *(recognition_engine_.get());
}
SpeechRecognizerImpl::~SpeechRecognizerImpl() {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
endpointer_.EndSession();
if (audio_controller_.get()) {
audio_controller_->Close(
base::Bind(&KeepAudioControllerRefcountedForDtor, audio_controller_));
audio_log_->OnClosed(0);
}
}
// Invoked in the audio thread.
void SpeechRecognizerImpl::OnError(AudioInputController* controller,
media::AudioInputController::ErrorCode error_code) {
FSMEventArgs event_args(EVENT_AUDIO_ERROR);
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, event_args));
}
void SpeechRecognizerImpl::OnData(AudioInputController* controller,
const AudioBus* data) {
// Convert audio from native format to fixed format used by WebSpeech.
FSMEventArgs event_args(EVENT_AUDIO_DATA);
event_args.audio_data = audio_converter_->Convert(data);
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, event_args));
}
void SpeechRecognizerImpl::OnAudioClosed(AudioInputController*) {}
void SpeechRecognizerImpl::OnSpeechRecognitionEngineResults(
const SpeechRecognitionResults& results) {
FSMEventArgs event_args(EVENT_ENGINE_RESULT);
event_args.engine_results = results;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, event_args));
}
void SpeechRecognizerImpl::OnSpeechRecognitionEngineError(
const SpeechRecognitionError& error) {
FSMEventArgs event_args(EVENT_ENGINE_ERROR);
event_args.engine_error = error;
BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
base::Bind(&SpeechRecognizerImpl::DispatchEvent,
this, event_args));
}
// ----------------------- Core FSM implementation ---------------------------
// TODO(primiano): After the changes in the media package (r129173), this class
// slightly violates the SpeechRecognitionEventListener interface contract. In
// particular, it is not true anymore that this class can be freed after the
// OnRecognitionEnd event, since the audio_controller_.Close() asynchronous
// call can be still in progress after the end event. Currently, it does not
// represent a problem for the browser itself, since refcounting protects us
// against such race conditions. However, we should fix this in the next CLs.
// For instance, tests are currently working just because the
// TestAudioInputController is not closing asynchronously as the real controller
// does, but they will become flaky if TestAudioInputController will be fixed.
void SpeechRecognizerImpl::DispatchEvent(const FSMEventArgs& event_args) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
DCHECK_LE(event_args.event, EVENT_MAX_VALUE);
DCHECK_LE(state_, STATE_MAX_VALUE);
// Event dispatching must be sequential, otherwise it will break all the rules
// and the assumptions of the finite state automata model.
DCHECK(!is_dispatching_event_);
is_dispatching_event_ = true;
// Guard against the delegate freeing us until we finish processing the event.
scoped_refptr<SpeechRecognizerImpl> me(this);
if (event_args.event == EVENT_AUDIO_DATA) {
DCHECK(event_args.audio_data.get() != NULL);
ProcessAudioPipeline(*event_args.audio_data.get());
}
// The audio pipeline must be processed before the event dispatch, otherwise
// it would take actions according to the future state instead of the current.
state_ = ExecuteTransitionAndGetNextState(event_args);
is_dispatching_event_ = false;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::ExecuteTransitionAndGetNextState(
const FSMEventArgs& event_args) {
const FSMEvent event = event_args.event;
switch (state_) {
case STATE_IDLE:
switch (event) {
// TODO(primiano): restore UNREACHABLE_CONDITION on EVENT_ABORT and
// EVENT_STOP_CAPTURE below once speech input extensions are fixed.
case EVENT_ABORT:
return AbortSilently(event_args);
case EVENT_START:
return StartRecording(event_args);
case EVENT_STOP_CAPTURE:
return AbortSilently(event_args);
case EVENT_AUDIO_DATA: // Corner cases related to queued messages
case EVENT_ENGINE_RESULT: // being lately dispatched.
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return DoNothing(event_args);
}
break;
case STATE_STARTING:
switch (event) {
case EVENT_ABORT:
return AbortWithError(event_args);
case EVENT_START:
return NotFeasible(event_args);
case EVENT_STOP_CAPTURE:
return AbortSilently(event_args);
case EVENT_AUDIO_DATA:
return StartRecognitionEngine(event_args);
case EVENT_ENGINE_RESULT:
return NotFeasible(event_args);
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return AbortWithError(event_args);
}
break;
case STATE_ESTIMATING_ENVIRONMENT:
switch (event) {
case EVENT_ABORT:
return AbortWithError(event_args);
case EVENT_START:
return NotFeasible(event_args);
case EVENT_STOP_CAPTURE:
return StopCaptureAndWaitForResult(event_args);
case EVENT_AUDIO_DATA:
return WaitEnvironmentEstimationCompletion(event_args);
case EVENT_ENGINE_RESULT:
return ProcessIntermediateResult(event_args);
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return AbortWithError(event_args);
}
break;
case STATE_WAITING_FOR_SPEECH:
switch (event) {
case EVENT_ABORT:
return AbortWithError(event_args);
case EVENT_START:
return NotFeasible(event_args);
case EVENT_STOP_CAPTURE:
return StopCaptureAndWaitForResult(event_args);
case EVENT_AUDIO_DATA:
return DetectUserSpeechOrTimeout(event_args);
case EVENT_ENGINE_RESULT:
return ProcessIntermediateResult(event_args);
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return AbortWithError(event_args);
}
break;
case STATE_RECOGNIZING:
switch (event) {
case EVENT_ABORT:
return AbortWithError(event_args);
case EVENT_START:
return NotFeasible(event_args);
case EVENT_STOP_CAPTURE:
return StopCaptureAndWaitForResult(event_args);
case EVENT_AUDIO_DATA:
return DetectEndOfSpeech(event_args);
case EVENT_ENGINE_RESULT:
return ProcessIntermediateResult(event_args);
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return AbortWithError(event_args);
}
break;
case STATE_WAITING_FINAL_RESULT:
switch (event) {
case EVENT_ABORT:
return AbortWithError(event_args);
case EVENT_START:
return NotFeasible(event_args);
case EVENT_STOP_CAPTURE:
case EVENT_AUDIO_DATA:
return DoNothing(event_args);
case EVENT_ENGINE_RESULT:
return ProcessFinalResult(event_args);
case EVENT_ENGINE_ERROR:
case EVENT_AUDIO_ERROR:
return AbortWithError(event_args);
}
break;
// TODO(primiano): remove this state when speech input extensions support
// will be removed and STATE_IDLE.EVENT_ABORT,EVENT_STOP_CAPTURE will be
// reset to NotFeasible (see TODO above).
case STATE_ENDED:
return DoNothing(event_args);
}
return NotFeasible(event_args);
}
// ----------- Contract for all the FSM evolution functions below -------------
// - Are guaranteed to be executed in the IO thread;
// - Are guaranteed to be not reentrant (themselves and each other);
// - event_args members are guaranteed to be stable during the call;
// - The class won't be freed in the meanwhile due to callbacks;
// - IsCapturingAudio() returns true if and only if audio_controller_ != NULL.
// TODO(primiano): the audio pipeline is currently serial. However, the
// clipper->endpointer->vumeter chain and the sr_engine could be parallelized.
// We should profile the execution to see if it would be worth or not.
void SpeechRecognizerImpl::ProcessAudioPipeline(const AudioChunk& raw_audio) {
const bool route_to_endpointer = state_ >= STATE_ESTIMATING_ENVIRONMENT &&
state_ <= STATE_RECOGNIZING;
const bool route_to_sr_engine = route_to_endpointer;
const bool route_to_vumeter = state_ >= STATE_WAITING_FOR_SPEECH &&
state_ <= STATE_RECOGNIZING;
const bool clip_detected = DetectClipping(raw_audio);
float rms = 0.0f;
num_samples_recorded_ += raw_audio.NumSamples();
if (route_to_endpointer)
endpointer_.ProcessAudio(raw_audio, &rms);
if (route_to_vumeter) {
DCHECK(route_to_endpointer); // Depends on endpointer due to |rms|.
UpdateSignalAndNoiseLevels(rms, clip_detected);
}
if (route_to_sr_engine) {
DCHECK(recognition_engine_.get() != NULL);
recognition_engine_->TakeAudioChunk(raw_audio);
}
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::StartRecording(const FSMEventArgs&) {
DCHECK(recognition_engine_.get() != NULL);
DCHECK(!IsCapturingAudio());
const bool unit_test_is_active = (audio_manager_for_tests_ != NULL);
AudioManager* audio_manager = unit_test_is_active ?
audio_manager_for_tests_ :
AudioManager::Get();
DCHECK(audio_manager != NULL);
DVLOG(1) << "SpeechRecognizerImpl starting audio capture.";
num_samples_recorded_ = 0;
audio_level_ = 0;
listener()->OnRecognitionStart(session_id());
// TODO(xians): Check if the OS has the device with |device_id_|, return
// |SPEECH_AUDIO_ERROR_DETAILS_NO_MIC| if the target device does not exist.
if (!audio_manager->HasAudioInputDevices()) {
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO,
SPEECH_AUDIO_ERROR_DETAILS_NO_MIC));
}
int chunk_duration_ms = recognition_engine_->GetDesiredAudioChunkDurationMs();
AudioParameters in_params = audio_manager->GetInputStreamParameters(
device_id_);
if (!in_params.IsValid() && !unit_test_is_active) {
DLOG(ERROR) << "Invalid native audio input parameters";
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO));
}
// Audio converter shall provide audio based on these parameters as output.
// Hard coded, WebSpeech specific parameters are utilized here.
int frames_per_buffer = (kAudioSampleRate * chunk_duration_ms) / 1000;
AudioParameters output_parameters = AudioParameters(
AudioParameters::AUDIO_PCM_LOW_LATENCY, kChannelLayout, kAudioSampleRate,
kNumBitsPerAudioSample, frames_per_buffer);
// Audio converter will receive audio based on these parameters as input.
// On Windows we start by verifying that Core Audio is supported. If not,
// the WaveIn API is used and we might as well avoid all audio conversations
// since WaveIn does the conversion for us.
// TODO(henrika): this code should be moved to platform dependent audio
// managers.
bool use_native_audio_params = true;
#if defined(OS_WIN)
use_native_audio_params = media::CoreAudioUtil::IsSupported();
DVLOG_IF(1, !use_native_audio_params) << "Reverting to WaveIn for WebSpeech";
#endif
AudioParameters input_parameters = output_parameters;
if (use_native_audio_params && !unit_test_is_active) {
// Use native audio parameters but avoid opening up at the native buffer
// size. Instead use same frame size (in milliseconds) as WebSpeech uses.
// We rely on internal buffers in the audio back-end to fulfill this request
// and the idea is to simplify the audio conversion since each Convert()
// call will then render exactly one ProvideInput() call.
// Due to implementation details in the audio converter, 2 milliseconds
// are added to the default frame size (100 ms) to ensure there is enough
// data to generate 100 ms of output when resampling.
frames_per_buffer =
((in_params.sample_rate() * (chunk_duration_ms + 2)) / 1000.0) + 0.5;
input_parameters.Reset(in_params.format(),
in_params.channel_layout(),
in_params.channels(),
in_params.input_channels(),
in_params.sample_rate(),
in_params.bits_per_sample(),
frames_per_buffer);
}
// Create an audio converter which converts data between native input format
// and WebSpeech specific output format.
audio_converter_.reset(
new OnDataConverter(input_parameters, output_parameters));
audio_controller_ = AudioInputController::Create(
audio_manager, this, input_parameters, device_id_, NULL);
if (!audio_controller_.get()) {
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO));
}
audio_log_->OnCreated(0, input_parameters, device_id_);
// The endpointer needs to estimate the environment/background noise before
// starting to treat the audio as user input. We wait in the state
// ESTIMATING_ENVIRONMENT until such interval has elapsed before switching
// to user input mode.
endpointer_.SetEnvironmentEstimationMode();
audio_controller_->Record();
audio_log_->OnStarted(0);
return STATE_STARTING;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::StartRecognitionEngine(const FSMEventArgs& event_args) {
// This is the first audio packet captured, so the recognition engine is
// started and the delegate notified about the event.
DCHECK(recognition_engine_.get() != NULL);
recognition_engine_->StartRecognition();
listener()->OnAudioStart(session_id());
// This is a little hack, since TakeAudioChunk() is already called by
// ProcessAudioPipeline(). It is the best tradeoff, unless we allow dropping
// the first audio chunk captured after opening the audio device.
recognition_engine_->TakeAudioChunk(*(event_args.audio_data.get()));
return STATE_ESTIMATING_ENVIRONMENT;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::WaitEnvironmentEstimationCompletion(const FSMEventArgs&) {
DCHECK(endpointer_.IsEstimatingEnvironment());
if (GetElapsedTimeMs() >= kEndpointerEstimationTimeMs) {
endpointer_.SetUserInputMode();
listener()->OnEnvironmentEstimationComplete(session_id());
return STATE_WAITING_FOR_SPEECH;
} else {
return STATE_ESTIMATING_ENVIRONMENT;
}
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::DetectUserSpeechOrTimeout(const FSMEventArgs&) {
if (endpointer_.DidStartReceivingSpeech()) {
listener()->OnSoundStart(session_id());
return STATE_RECOGNIZING;
} else if (GetElapsedTimeMs() >= kNoSpeechTimeoutMs) {
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_NO_SPEECH));
}
return STATE_WAITING_FOR_SPEECH;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::DetectEndOfSpeech(const FSMEventArgs& event_args) {
if (endpointer_.speech_input_complete())
return StopCaptureAndWaitForResult(event_args);
return STATE_RECOGNIZING;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::StopCaptureAndWaitForResult(const FSMEventArgs&) {
DCHECK(state_ >= STATE_ESTIMATING_ENVIRONMENT && state_ <= STATE_RECOGNIZING);
DVLOG(1) << "Concluding recognition";
CloseAudioControllerAsynchronously();
recognition_engine_->AudioChunksEnded();
if (state_ > STATE_WAITING_FOR_SPEECH)
listener()->OnSoundEnd(session_id());
listener()->OnAudioEnd(session_id());
return STATE_WAITING_FINAL_RESULT;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::AbortSilently(const FSMEventArgs& event_args) {
DCHECK_NE(event_args.event, EVENT_AUDIO_ERROR);
DCHECK_NE(event_args.event, EVENT_ENGINE_ERROR);
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_NONE));
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::AbortWithError(const FSMEventArgs& event_args) {
if (event_args.event == EVENT_AUDIO_ERROR) {
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_AUDIO));
} else if (event_args.event == EVENT_ENGINE_ERROR) {
return Abort(event_args.engine_error);
}
return Abort(SpeechRecognitionError(SPEECH_RECOGNITION_ERROR_ABORTED));
}
SpeechRecognizerImpl::FSMState SpeechRecognizerImpl::Abort(
const SpeechRecognitionError& error) {
if (IsCapturingAudio())
CloseAudioControllerAsynchronously();
DVLOG(1) << "SpeechRecognizerImpl canceling recognition. ";
// The recognition engine is initialized only after STATE_STARTING.
if (state_ > STATE_STARTING) {
DCHECK(recognition_engine_.get() != NULL);
recognition_engine_->EndRecognition();
}
if (state_ > STATE_WAITING_FOR_SPEECH && state_ < STATE_WAITING_FINAL_RESULT)
listener()->OnSoundEnd(session_id());
if (state_ > STATE_STARTING && state_ < STATE_WAITING_FINAL_RESULT)
listener()->OnAudioEnd(session_id());
if (error.code != SPEECH_RECOGNITION_ERROR_NONE)
listener()->OnRecognitionError(session_id(), error);
listener()->OnRecognitionEnd(session_id());
return STATE_ENDED;
}
SpeechRecognizerImpl::FSMState SpeechRecognizerImpl::ProcessIntermediateResult(
const FSMEventArgs& event_args) {
// Provisional results can occur only if explicitly enabled in the JS API.
DCHECK(provisional_results_);
// In continuous recognition, intermediate results can occur even when we are
// in the ESTIMATING_ENVIRONMENT or WAITING_FOR_SPEECH states (if the
// recognition engine is "faster" than our endpointer). In these cases we
// skip the endpointer and fast-forward to the RECOGNIZING state, with respect
// of the events triggering order.
if (state_ == STATE_ESTIMATING_ENVIRONMENT) {
DCHECK(endpointer_.IsEstimatingEnvironment());
endpointer_.SetUserInputMode();
listener()->OnEnvironmentEstimationComplete(session_id());
} else if (state_ == STATE_WAITING_FOR_SPEECH) {
listener()->OnSoundStart(session_id());
} else {
DCHECK_EQ(STATE_RECOGNIZING, state_);
}
listener()->OnRecognitionResults(session_id(), event_args.engine_results);
return STATE_RECOGNIZING;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::ProcessFinalResult(const FSMEventArgs& event_args) {
const SpeechRecognitionResults& results = event_args.engine_results;
SpeechRecognitionResults::const_iterator i = results.begin();
bool provisional_results_pending = false;
bool results_are_empty = true;
for (; i != results.end(); ++i) {
const SpeechRecognitionResult& result = *i;
if (result.is_provisional) {
DCHECK(provisional_results_);
provisional_results_pending = true;
} else if (results_are_empty) {
results_are_empty = result.hypotheses.empty();
}
}
if (provisional_results_pending) {
listener()->OnRecognitionResults(session_id(), results);
// We don't end the recognition if a provisional result is received in
// STATE_WAITING_FINAL_RESULT. A definitive result will come next and will
// end the recognition.
return state_;
}
recognition_engine_->EndRecognition();
if (!results_are_empty) {
// We could receive an empty result (which we won't propagate further)
// in the following (continuous) scenario:
// 1. The caller start pushing audio and receives some results;
// 2. A |StopAudioCapture| is issued later;
// 3. The final audio frames captured in the interval ]1,2] do not lead to
// any result (nor any error);
// 4. The speech recognition engine, therefore, emits an empty result to
// notify that the recognition is ended with no error, yet neither any
// further result.
listener()->OnRecognitionResults(session_id(), results);
}
listener()->OnRecognitionEnd(session_id());
return STATE_ENDED;
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::DoNothing(const FSMEventArgs&) const {
return state_; // Just keep the current state.
}
SpeechRecognizerImpl::FSMState
SpeechRecognizerImpl::NotFeasible(const FSMEventArgs& event_args) {
NOTREACHED() << "Unfeasible event " << event_args.event
<< " in state " << state_;
return state_;
}
void SpeechRecognizerImpl::CloseAudioControllerAsynchronously() {
DCHECK(IsCapturingAudio());
DVLOG(1) << "SpeechRecognizerImpl closing audio controller.";
// Issues a Close on the audio controller, passing an empty callback. The only
// purpose of such callback is to keep the audio controller refcounted until
// Close has completed (in the audio thread) and automatically destroy it
// afterwards (upon return from OnAudioClosed).
audio_controller_->Close(base::Bind(&SpeechRecognizerImpl::OnAudioClosed,
this, audio_controller_));
audio_controller_ = NULL; // The controller is still refcounted by Bind.
audio_log_->OnClosed(0);
}
int SpeechRecognizerImpl::GetElapsedTimeMs() const {
return (num_samples_recorded_ * 1000) / kAudioSampleRate;
}
void SpeechRecognizerImpl::UpdateSignalAndNoiseLevels(const float& rms,
bool clip_detected) {
// Calculate the input volume to display in the UI, smoothing towards the
// new level.
// TODO(primiano): Do we really need all this floating point arith here?
// Perhaps it might be quite expensive on mobile.
float level = (rms - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
level = std::min(std::max(0.0f, level), kAudioMeterRangeMaxUnclipped);
const float smoothing_factor = (level > audio_level_) ? kUpSmoothingFactor :
kDownSmoothingFactor;
audio_level_ += (level - audio_level_) * smoothing_factor;
float noise_level = (endpointer_.NoiseLevelDb() - kAudioMeterMinDb) /
(kAudioMeterDbRange / kAudioMeterRangeMaxUnclipped);
noise_level = std::min(std::max(0.0f, noise_level),
kAudioMeterRangeMaxUnclipped);
listener()->OnAudioLevelsChange(
session_id(), clip_detected ? 1.0f : audio_level_, noise_level);
}
void SpeechRecognizerImpl::SetAudioManagerForTesting(
AudioManager* audio_manager) {
audio_manager_for_tests_ = audio_manager;
}
SpeechRecognizerImpl::FSMEventArgs::FSMEventArgs(FSMEvent event_value)
: event(event_value),
audio_data(NULL),
engine_error(SPEECH_RECOGNITION_ERROR_NONE) {
}
SpeechRecognizerImpl::FSMEventArgs::~FSMEventArgs() {
}
} // namespace content
| [
"jhonnyjosearana@gmail.com"
] | jhonnyjosearana@gmail.com |
d0248446d1e951c884883b8a936b1154e345ccf5 | 13e8bd98dd7befd6586b0b0f744a4bc481632441 | /src/lib/ipc/include/seraphim/ipc/shm_transport.h | 1b42a83ab16ac40600295f52eb144bfda43e8359 | [
"MIT"
] | permissive | raymanfx/seraphim | 245e1cbbf506e0aa35c3611378c33160ef1a4af4 | 4d388d21831d349fe1085bc3cb7c73f5d2b103a7 | refs/heads/master | 2020-06-24T17:41:29.107464 | 2019-12-08T18:08:25 | 2019-12-08T18:08:25 | 199,032,113 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,749 | h | /*
* (C) Copyright 2019
* The Seraphim Project Developers.
*
* SPDX-License-Identifier: MIT
*/
#ifndef SPH_IPC_SHM_TRANSPORT_H
#define SPH_IPC_SHM_TRANSPORT_H
#include <fcntl.h>
#include <queue>
#include <string>
#include <sys/mman.h>
#include "transport.h"
#include <seraphim/ipc/semaphore.h>
namespace sph {
namespace ipc {
/**
* @brief Shared memory message transport.
*
* This class uses POSIX shared memory to exchange messages between two or more readers and
* writers. At the moment, it behaves like a very simple bidirectional pipe.
*/
class SharedMemoryTransport : public Transport {
public:
/**
* @brief Shared memory message transport.
*/
SharedMemoryTransport() = default;
/**
* @brief Shared memory message transport destructor.
* Unmaps the shared memory region if it was mapped.
* Removed the shared memory region if it was created.
*/
~SharedMemoryTransport() override;
/**
* @brief Open a shared memory region by name.
* @param name The unique name of the file.
* @return true on success, false otherwise.
*/
bool open(const std::string &name);
/**
* @brief Close a shared memory region and release associated resources.
* @return true on success, false otherwise.
*/
bool close();
/**
* @brief Create a shared memory region.
* @param name The unique name of the file to be created.
* @param size The size of the memory region.
* @return true on success, false otherwise.
*/
bool create(const std::string &name, long size);
/**
* @brief Remove the shared memory region created by this instance.
* @return true on success, false otherwise.
*/
bool remove();
void set_rx_timeout(int ms) override { m_rx_timeout = ms; }
void set_tx_timeout(int ms) override { m_tx_timeout = ms; }
void receive(Seraphim::Message &msg) override;
void send(const Seraphim::Message &msg) override;
/**
* @brief Actors perform read/write operations within the shared memory segment (MessageStore).
*/
struct MessageStoreActors {
/// The current number of active actors.
/// An actor must increase this number when opening the message store and decrease it
/// once he wishes to no longer use it (aka close it).
unsigned int num_actors = 1;
/// Resource locking for the @ref num_actors field. Must be acquired before any operation
/// is performed on the field.
sem_t sem;
};
/**
* @brief Message type.
*/
enum MessageStoreType {
MESSAGE_TYPE_UNKNOWN = 0,
/// Corresponds to a Seraphim::Message request instance.
MESSAGE_TYPE_REQUEST,
/// Corresponds to a Seraphim::Message response instance.
MESSAGE_TYPE_RESPONSE
};
/**
* @brief Messages are objects used for reading/writing information within the MessageStore.
*/
struct MessageStoreMessage {
/// Source actor ID.
unsigned int source;
/// Destination actor ID.
unsigned int destination;
/// Type of the message, allows for multiple concurrent clients talking to a server.
int type;
/// Current message size
int size = 0;
/// Resource locking for the message. Must be acquired before performing any read/write
/// operation on the message segment.
sem_t sem;
};
/**
* @brief Shared memory area layout.
*
* Facilitates RX/TX with more than two peers writing and reading simultaneously by keeping
* track of read and write stats and holding an unnamed semaphore that must be acquired before
* writing to the shared memory area.
*/
struct MessageStore {
MessageStoreActors actors;
MessageStoreMessage msg;
};
private:
/**
* @brief Map a shared memory region.
* @param size The size of the memory region.
* @return true on success, false otherwise.
*/
bool map(size_t size);
/**
* @brief Unmap a shared memory region.
* @return true on success, false otherwise.
*/
bool unmap();
std::string m_name;
int m_fd = -1;
size_t m_size = 0;
int m_rx_timeout = 0;
int m_tx_timeout = 0;
bool m_created = false;
/// Unique identifier of this instance.
unsigned int m_actor_id;
/// The mapped MessageStore object.
MessageStore *m_msgstore = nullptr;
/// semaphores for inter-process resource locking
Semaphore m_actor_sem;
Semaphore m_msg_sem;
/// Type of the message that was sent by this instance
int m_last_msg_type = -1;
};
} // namespace ipc
} // namespace sph
#endif // SPH_IPC_SHM_TRANSPORT_H
| [
"raymanfx@gmail.com"
] | raymanfx@gmail.com |
91d726279bb59ad40dff91e43f38cae6a16bc9d1 | 050ebbbc7d5f89d340fd9f2aa534eac42d9babb7 | /grupa1/slewandowski1993/p2/czy.cpp | 6adfa9f7ff53c18e8b62a6583f0198fd20345ee2 | [] | no_license | anagorko/zpk2015 | 83461a25831fa4358366ec15ab915a0d9b6acdf5 | 0553ec55d2617f7bea588d650b94828b5f434915 | refs/heads/master | 2020-04-05T23:47:55.299547 | 2016-09-14T11:01:46 | 2016-09-14T11:01:46 | 52,429,626 | 0 | 13 | null | 2016-03-22T09:35:25 | 2016-02-24T09:19:07 | C++ | UTF-8 | C++ | false | false | 293 | cpp | #include <iostream>
using namespace std;
int main() {
int i;
cin >> i;
while (i>0){
if (i % 2 == 0) {i = i / 2;}
else if (i == 1) {cout << "TAK" << endl; i=0;}
else if (i == 3) {cout << "NIE" << endl; i=0;}
else {i = 3 * i + 3;}
}
}
| [
"sebastian1993lewandowski@gmail.com"
] | sebastian1993lewandowski@gmail.com |
575b61e7e10b21804a4fc90c56fd88f7e2a6634c | 3079356ad80009d009782a2386a6bdc2ef59f2fd | /Yuliya/lab6/lab6/Source.cpp | 7803e1f917272921da0c15298792006ad6c34740 | [] | no_license | mrkriv/Laboratory | 3cadd98b805e316a2e3f8dc262ec4c85f0c55d4f | f453bdf7381c4b06dcb423778a2292b80e7a685c | refs/heads/master | 2020-05-21T12:27:47.820844 | 2017-10-01T15:07:44 | 2017-10-01T15:07:44 | 54,062,460 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 2,918 | cpp | #include "iostream"
using namespace std;
template<typename type, unsigned int size>
class Matrix
{
typedef Matrix<type, size> thisType;
type data[size][size];
bool chekSize(unsigned int row, unsigned int col)
{
return row < size && col < size;
}
public:
Matrix()
{
setAll(0);
}
void setAll(type value)
{
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
data[r][c] = value;
}
}
void set(unsigned int row, unsigned int col, type value)
{
if (chekSize(row, col))
data[row][col] = value;
}
type get(unsigned int row, unsigned int col)
{
return chekSize(row, col) ? data[row][col] : 0;
}
void print()
{
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
cout << data[r][c] << ' ';
cout << endl;
}
cout << endl;
}
thisType& operator*(type b)
{
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
data[r][c] *= b;
}
return *this;
}
thisType& operator*(thisType b)
{
thisType m;
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
{
type temp = 0;
for (int k = 0; k < size; k++)
temp += data[r][k] * b.data[k][c];
m.data[r][c] = temp;
}
}
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
data[r][c] = m.data[r][c];
}
return *this;
}
thisType& operator+(thisType b)
{
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
data[r][c] += b.data[r][c];
}
return *this;
}
thisType& operator-(thisType b)
{
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
data[r][c] -= b.data[r][c];
}
return *this;
}
type determenant()
{
if (size == 1)
return data[0][0];
else if (size == 2)
return data[0][0] * data[1][1] - data[0][1] * data[1][0];
type result = 1;
thisType m;
for (int r = 0; r < size; r++)
{
for (int c = 0; c < size; c++)
m.data[r][c] = data[r][c];
}
for (int r = 0; r < size; r++)
{
for (int c = r + 1; c < size; c++)
{
type b = 0;
if (m.data[r][r] == 0 && m.data[r][c] != 0)
return 0;
else
b = m.data[c][r] / m.data[r][r];
for (int k = r; k < size; k++)
m.data[c][k] = m.data[c][k] - m.data[r][k] * b;
}
result *= m.data[r][r];
}
return result;
}
};
int main()
{
Matrix<double, 3> A, B;
cout << "A:" << endl;
A.set(0, 0, 5);
A.set(1, 1, 7);
A.set(2, 2, 9);
A.set(0, 1, 6);
A.set(0, 2, 7);
A.set(1, 0, 1);
A.print();
cout << "B:" << endl;
B.set(0, 0, 9);
B.set(1, 1, 1);
B.set(2, 2, 2);
B.set(0, 1, 1);
B.set(0, 2, 3);
B.set(1, 0, 4);
B.print();
cout << "det(A) = " << A.determenant() << endl;
cout << "det(B) = " << B.determenant() << endl << endl;
cout << "A+B" << endl;
(A + B).print();
cout << "A-B" << endl;
(A - B).print();
cout << "A*B" << endl;
(A * B).print();
cout << "A*-5" << endl;
(A * -5).print();
return 0;
} | [
"virus_450@mail.ru"
] | virus_450@mail.ru |
68bc58b83464d94e889af49fd51afbcecbccc199 | 95ca62ff230d38fb74dafbcfe6c29be1ac4b0582 | /cl_dll/ev_hldm.cpp | bc743a8b26e480c66b4adcfa0b83347b69cf5887 | [] | no_license | HLSources/Zombie-X | ecfdb8438a9e51d565edf57d6d87ceecbed0ecc3 | 961758dda207bc5e33d86cab92f60d6367972986 | refs/heads/master | 2023-01-24T02:35:56.497229 | 2020-12-07T15:42:50 | 2020-12-07T15:42:50 | 319,365,760 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71,391 | cpp | /***
*
* Copyright (c) 1996-2002, Valve LLC. All rights reserved.
*
* This product contains software technology licensed from Id
* Software, Inc. ("Id Technology"). Id Technology (c) 1996 Id Software, Inc.
* All Rights Reserved.
*
* Use, distribution, and modification of this source code and/or resulting
* object code is restricted to non-commercial enhancements to products from
* Valve LLC. All other use, distribution, or modification is prohibited
* without written permission from Valve LLC.
*
****/
#include "hud.h"
#include "cl_util.h"
#include "const.h"
#include "entity_state.h"
#include "cl_entity.h"
#include "entity_types.h"
#include "usercmd.h"
#include "pm_defs.h"
#include "pm_materials.h"
#include "eventscripts.h"
#include "ev_hldm.h"
#include "r_efx.h"
#include "event_api.h"
#include "event_args.h"
#include "in_defs.h"
#include <string.h>
#include "r_studioint.h"
#include "com_model.h"
extern engine_studio_api_t IEngineStudio;
static int tracerCount[ 32 ];
extern "C" char PM_FindTextureType( char *name );
void V_PunchAxis( int axis, float punch );
void VectorAngles( const float *forward, float *angles );
extern cvar_t *cl_lw;
extern "C"
{
// HLDM
void EV_FireGlock1( struct event_args_s *args );
void EV_FireGlock2( struct event_args_s *args );
void EV_FireEagel1( struct event_args_s *args );
void EV_FireEagel2( struct event_args_s *args );
void EV_FireShotGunSingle( struct event_args_s *args );
void EV_FireShotGunDouble( struct event_args_s *args );
void EV_FireShotGunASingle( struct event_args_s *args );
void EV_FireShotGunADouble( struct event_args_s *args );
void EV_FireMP5( struct event_args_s *args );
void EV_FireAK47( struct event_args_s *args );
void EV_FireUZI( struct event_args_s *args );
void EV_FireMP52( struct event_args_s *args );
void EV_FireMinigun( struct event_args_s *args );
void EV_FireMP41a( struct event_args_s *args );
void EV_FireMP41a2( struct event_args_s *args );
void EV_FirePython( struct event_args_s *args );
void EV_FireGauss( struct event_args_s *args );
void EV_SpinGauss( struct event_args_s *args );
void EV_Crowbar( struct event_args_s *args );
void EV_Swort( struct event_args_s *args );
void EV_FireCrossbow( struct event_args_s *args );
void EV_FireCrossbow2( struct event_args_s *args );
void EV_FireRpg( struct event_args_s *args );
void EV_EgonFire( struct event_args_s *args );
void EV_EgonStop( struct event_args_s *args );
void EV_HornetGunFire( struct event_args_s *args );
void EV_TripmineFire( struct event_args_s *args );
void EV_SnarkFire( struct event_args_s *args );
void EV_ShockFire( struct event_args_s *args );
void EV_TrainPitchAdjust( struct event_args_s *args );
}
#define VECTOR_CONE_1DEGREES Vector( 0.00873, 0.00873, 0.00873 )
#define VECTOR_CONE_2DEGREES Vector( 0.01745, 0.01745, 0.01745 )
#define VECTOR_CONE_3DEGREES Vector( 0.02618, 0.02618, 0.02618 )
#define VECTOR_CONE_4DEGREES Vector( 0.03490, 0.03490, 0.03490 )
#define VECTOR_CONE_5DEGREES Vector( 0.04362, 0.04362, 0.04362 )
#define VECTOR_CONE_6DEGREES Vector( 0.05234, 0.05234, 0.05234 )
#define VECTOR_CONE_7DEGREES Vector( 0.06105, 0.06105, 0.06105 )
#define VECTOR_CONE_8DEGREES Vector( 0.06976, 0.06976, 0.06976 )
#define VECTOR_CONE_9DEGREES Vector( 0.07846, 0.07846, 0.07846 )
#define VECTOR_CONE_10DEGREES Vector( 0.08716, 0.08716, 0.08716 )
#define VECTOR_CONE_15DEGREES Vector( 0.13053, 0.13053, 0.13053 )
#define VECTOR_CONE_20DEGREES Vector( 0.17365, 0.17365, 0.17365 )
// play a strike sound based on the texture that was hit by the attack traceline. VecSrc/VecEnd are the
// original traceline endpoints used by the attacker, iBulletType is the type of bullet that hit the texture.
// returns volume of strike instrument (crowbar) to play
float EV_HLDM_PlayTextureSound( int idx, pmtrace_t *ptr, float *vecSrc, float *vecEnd, int iBulletType )
{
// hit the world, try to play sound based on texture material type
char chTextureType = CHAR_TEX_CONCRETE;
float fvol;
float fvolbar;
char *rgsz[4];
int cnt;
float fattn = ATTN_NORM;
int entity;
char *pTextureName;
char texname[ 64 ];
char szbuffer[ 64 ];
entity = gEngfuncs.pEventAPI->EV_IndexFromTrace( ptr );
// FIXME check if playtexture sounds movevar is set
//
chTextureType = 0;
// Player
if ( entity >= 1 && entity <= gEngfuncs.GetMaxClients() )
{
// hit body
chTextureType = CHAR_TEX_FLESH;
}
else if ( entity == 0 )
{
// get texture from entity or world (world is ent(0))
pTextureName = (char *)gEngfuncs.pEventAPI->EV_TraceTexture( ptr->ent, vecSrc, vecEnd );
if ( pTextureName )
{
strcpy( texname, pTextureName );
pTextureName = texname;
// strip leading '-0' or '+0~' or '{' or '!'
if (*pTextureName == '-' || *pTextureName == '+')
{
pTextureName += 2;
}
if (*pTextureName == '{' || *pTextureName == '!' || *pTextureName == '~' || *pTextureName == ' ')
{
pTextureName++;
}
// '}}'
strcpy( szbuffer, pTextureName );
szbuffer[ CBTEXTURENAMEMAX - 1 ] = 0;
// get texture type
chTextureType = PM_FindTextureType( szbuffer );
}
}
switch (chTextureType)
{
default:
case CHAR_TEX_CONCRETE: fvol = 0.9; fvolbar = 0.6;
rgsz[0] = "player/pl_step1.wav";
rgsz[1] = "player/pl_step2.wav";
cnt = 2;
break;
case CHAR_TEX_METAL: fvol = 0.9; fvolbar = 0.3;
rgsz[0] = "player/pl_metal1.wav";
rgsz[1] = "player/pl_metal2.wav";
cnt = 2;
break;
case CHAR_TEX_DIRT: fvol = 0.9; fvolbar = 0.1;
rgsz[0] = "player/pl_dirt1.wav";
rgsz[1] = "player/pl_dirt2.wav";
rgsz[2] = "player/pl_dirt3.wav";
cnt = 3;
break;
case CHAR_TEX_VENT: fvol = 0.5; fvolbar = 0.3;
rgsz[0] = "player/pl_duct1.wav";
rgsz[1] = "player/pl_duct1.wav";
cnt = 2;
break;
case CHAR_TEX_GRATE: fvol = 0.9; fvolbar = 0.5;
rgsz[0] = "player/pl_grate1.wav";
rgsz[1] = "player/pl_grate4.wav";
cnt = 2;
break;
case CHAR_TEX_TILE: fvol = 0.8; fvolbar = 0.2;
rgsz[0] = "player/pl_tile1.wav";
rgsz[1] = "player/pl_tile3.wav";
rgsz[2] = "player/pl_tile2.wav";
rgsz[3] = "player/pl_tile4.wav";
cnt = 4;
break;
case CHAR_TEX_SLOSH: fvol = 0.9; fvolbar = 0.0;
rgsz[0] = "player/pl_slosh1.wav";
rgsz[1] = "player/pl_slosh3.wav";
rgsz[2] = "player/pl_slosh2.wav";
rgsz[3] = "player/pl_slosh4.wav";
cnt = 4;
break;
case CHAR_TEX_WOOD: fvol = 0.9; fvolbar = 0.2;
rgsz[0] = "debris/wood1.wav";
rgsz[1] = "debris/wood2.wav";
rgsz[2] = "debris/wood3.wav";
cnt = 3;
break;
case CHAR_TEX_GLASS:
case CHAR_TEX_COMPUTER:
fvol = 0.8; fvolbar = 0.2;
rgsz[0] = "debris/glass1.wav";
rgsz[1] = "debris/glass2.wav";
rgsz[2] = "debris/glass3.wav";
cnt = 3;
break;
case CHAR_TEX_FLESH:
if (iBulletType == BULLET_PLAYER_CROWBAR)
return 0.0; // crowbar already makes this sound
fvol = 1.0; fvolbar = 0.2;
rgsz[0] = "weapons/bullet_hit1.wav";
rgsz[1] = "weapons/bullet_hit2.wav";
fattn = 1.0;
cnt = 2;
break;
}
// play material hit sound
gEngfuncs.pEventAPI->EV_PlaySound( 0, ptr->endpos, CHAN_STATIC, rgsz[gEngfuncs.pfnRandomLong(0,cnt-1)], fvol, fattn, 0, 96 + gEngfuncs.pfnRandomLong(0,0xf) );
return fvolbar;
}
char *EV_HLDM_DamageDecal( physent_t *pe )
{
static char decalname[ 32 ];
int idx;
if ( pe->classnumber == 1 )
{
idx = gEngfuncs.pfnRandomLong( 0, 2 );
sprintf( decalname, "{break%i", idx + 1 );
}
else if ( pe->rendermode != kRenderNormal )
{
sprintf( decalname, "{bproof1" );
}
else
{
idx = gEngfuncs.pfnRandomLong( 0, 4 );
sprintf( decalname, "{shot%i", idx + 1 );
}
return decalname;
}
void EV_HLDM_GunshotDecalTrace( pmtrace_t *pTrace, char *decalName )
{
int iRand;
physent_t *pe;
gEngfuncs.pEfxAPI->R_BulletImpactParticles( pTrace->endpos );
iRand = gEngfuncs.pfnRandomLong(0,0x7FFF);
if ( iRand < (0x7fff/2) )// not every bullet makes a sound.
{
switch( iRand % 5)
{
case 0: gEngfuncs.pEventAPI->EV_PlaySound( -1, pTrace->endpos, 0, "weapons/ric1.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); break;
case 1: gEngfuncs.pEventAPI->EV_PlaySound( -1, pTrace->endpos, 0, "weapons/ric2.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); break;
case 2: gEngfuncs.pEventAPI->EV_PlaySound( -1, pTrace->endpos, 0, "weapons/ric3.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); break;
case 3: gEngfuncs.pEventAPI->EV_PlaySound( -1, pTrace->endpos, 0, "weapons/ric4.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); break;
case 4: gEngfuncs.pEventAPI->EV_PlaySound( -1, pTrace->endpos, 0, "weapons/ric5.wav", 1.0, ATTN_NORM, 0, PITCH_NORM ); break;
}
}
pe = gEngfuncs.pEventAPI->EV_GetPhysent( pTrace->ent );
// Only decal brush models such as the world etc.
if ( decalName && decalName[0] && pe && ( pe->solid == SOLID_BSP || pe->movetype == MOVETYPE_PUSHSTEP ) )
{
if ( CVAR_GET_FLOAT( "r_decals" ) )
{
gEngfuncs.pEfxAPI->R_DecalShoot(
gEngfuncs.pEfxAPI->Draw_DecalIndex( gEngfuncs.pEfxAPI->Draw_DecalIndexFromName( decalName ) ),
gEngfuncs.pEventAPI->EV_IndexFromTrace( pTrace ), 0, pTrace->endpos, 0 );
}
}
}
void EV_HLDM_DecalGunshot( pmtrace_t *pTrace, int iBulletType )
{
physent_t *pe;
pe = gEngfuncs.pEventAPI->EV_GetPhysent( pTrace->ent );
if ( pe && pe->solid == SOLID_BSP )
{
switch( iBulletType )
{
case BULLET_PLAYER_9MM:
case BULLET_PLAYER_50CAL:
case BULLET_MONSTER_9MM:
case BULLET_PLAYER_MP5:
case BULLET_MONSTER_MP5:
case BULLET_PLAYER_BUCKSHOT:
case BULLET_PLAYER_357:
default:
// smoke and decal
EV_HLDM_GunshotDecalTrace( pTrace, EV_HLDM_DamageDecal( pe ) );
break;
}
}
}
int EV_HLDM_CheckTracer( int idx, float *vecSrc, float *end, float *forward, float *right, int iBulletType, int iTracerFreq, int *tracerCount )
{
int tracer = 0;
int i;
qboolean player = idx >= 1 && idx <= gEngfuncs.GetMaxClients() ? true : false;
if ( iTracerFreq != 0 && ( (*tracerCount)++ % iTracerFreq) == 0 )
{
vec3_t vecTracerSrc;
if ( player )
{
vec3_t offset( 0, 0, -4 );
// adjust tracer position for player
for ( i = 0; i < 3; i++ )
{
vecTracerSrc[ i ] = vecSrc[ i ] + offset[ i ] + right[ i ] * 2 + forward[ i ] * 16;
}
}
else
{
VectorCopy( vecSrc, vecTracerSrc );
}
if ( iTracerFreq != 1 ) // guns that always trace also always decal
tracer = 1;
switch( iBulletType )
{
case BULLET_PLAYER_MP5:
case BULLET_MONSTER_MP5:
case BULLET_MONSTER_9MM:
case BULLET_MONSTER_12MM:
default:
EV_CreateTracer( vecTracerSrc, end );
break;
}
}
return tracer;
}
/*
TTT: Event which spawns a smokepuff and/or sparks at a given origin
Note that you have to precache the sprites in the game dll
*/
void EV_HLDM_SmokePuff( pmtrace_t *pTrace, float *vecSrc, float *vecEnd )
{
physent_t *pe;
// get entity at endpoint
pe = gEngfuncs.pEventAPI->EV_GetPhysent( pTrace->ent );
if ( pe && pe->solid == SOLID_BSP )
{ // if it's a solid wall / entity
char chTextureType = CHAR_TEX_CONCRETE;
char *pTextureName;
char texname[ 64 ];
char szbuffer[ 64 ];
// get texture name
pTextureName = (char *)gEngfuncs.pEventAPI->EV_TraceTexture( pTrace->ent, vecSrc, vecEnd );
if ( pTextureName )
{
strcpy( texname, pTextureName );
pTextureName = texname;
// strip leading '-0' or '+0~' or '{' or '!'
if (*pTextureName == '-' || *pTextureName == '+')
{
pTextureName += 2;
}
if (*pTextureName == '{' || *pTextureName == '!' || *pTextureName == '~' || *pTextureName == ' ')
{
pTextureName++;
}
// '}}'
strcpy( szbuffer, pTextureName );
szbuffer[ CBTEXTURENAMEMAX - 1 ] = 0;
// get texture type
chTextureType = PM_FindTextureType( szbuffer );
}
bool fDoPuffs = false;
bool fDoSparks = false;
int a,r,g,b;
switch (chTextureType)
{
// do smoke puff and eventually add sparks
case CHAR_TEX_TILE:
case CHAR_TEX_CONCRETE:
fDoSparks = (gEngfuncs.pfnRandomLong(1, 4) == 1);
fDoPuffs = true;
a = 128;
r = 200;
g = 200;
b = 200;
break;
// don't draw puff, but add sparks often
case CHAR_TEX_VENT:
case CHAR_TEX_GRATE:
case CHAR_TEX_METAL:
fDoSparks = (gEngfuncs.pfnRandomLong(1, 2) == 1);
break;
// draw brown puff, but don't do sparks
case CHAR_TEX_DIRT:
case CHAR_TEX_WOOD:
fDoPuffs = true;
a = 250;
r = 97;
g = 86;
b = 53;
break;
// don't do anything if those textures (perhaps add something later...)
default:
case CHAR_TEX_GLASS:
case CHAR_TEX_COMPUTER:
case CHAR_TEX_SLOSH:
break;
}
if( fDoPuffs )
{
vec3_t angles, forward, right, up;
VectorAngles( pTrace->plane.normal, angles );
AngleVectors( angles, forward, up, right );
forward.z = -forward.z;
// get sprite index
int iWallsmoke = gEngfuncs.pEventAPI->EV_FindModelIndex ("sprites/wallsmoke.spr");
// create sprite
TEMPENTITY *pTemp = gEngfuncs.pEfxAPI->R_TempSprite(
pTrace->endpos,
forward * gEngfuncs.pfnRandomFloat(10, 30) + right * gEngfuncs.pfnRandomFloat(-6, 6) + up * gEngfuncs.pfnRandomFloat(0, 6),
0.4,
iWallsmoke,
kRenderTransAlpha,
kRenderFxNone,
1.0,
0.3,
FTENT_SPRANIMATE | FTENT_FADEOUT
);
if(pTemp)
{ // sprite created successfully, adjust some things
pTemp->fadeSpeed = 2.0;
pTemp->entity.curstate.framerate = 20.0;
pTemp->entity.curstate.renderamt = a;
pTemp->entity.curstate.rendercolor.r = r;
pTemp->entity.curstate.rendercolor.g = g;
pTemp->entity.curstate.rendercolor.b = b;
}
}
if( fDoSparks )
{
// spawn some sparks
gEngfuncs.pEfxAPI->R_SparkShower( pTrace->endpos );
}
}
}
// <paul>
//
// Plays bullet flyby sounds
//
void EV_HLDM_BulletFlyBySound ( int idx, vec3_t start, vec3_t end )
{
// make the incidental sounds - all of these should already be precached on the server
vec3_t soundPoint;
char *zngs[17];
int cnt;
int iRand; // sound randomizer
// so where are we standing now?
cl_entity_t *pthisplayer = gEngfuncs.GetLocalPlayer();
iRand = gEngfuncs.pfnRandomLong(1,10);
// Dunno should we use viewangles or not?
if ( !EV_IsLocal(idx) )
{
#ifdef CORE_DEBUG
gEngfuncs.Con_Printf( "EV_HLDM->EV_HLDM_BulletFlyBySound, we arent the one firing,
lets check if the bullet passed us?\n" );
#endif
// did the bullet just pass our radius based on our origin?
if( EV_PointLineIntersect(start, end, pthisplayer->origin, 150, soundPoint ) )
{
#ifdef CORE_DEBUG
gEngfuncs.Con_Printf( "EV_HLDM->EV_HLDM_BulletFlyBySound, the bullet actually
did (PLI=true)...randomize sound?\n" );
#endif
// if so play flyby sound
if (iRand < 5)
{
zngs[0] = "fx/whizz_bullet1.wav";
zngs[1] = "fx/whizz_bullet2.wav";
zngs[2] = "fx/whizz_bullet3.wav";
zngs[3] = "fx/whizz_bullet4.wav";
zngs[4] = "fx/whizz_bullet6.wav";
zngs[5] = "fx/whizz_bullet7.wav";
zngs[6] = "fx/whizz_bullet8.wav";
zngs[7] = "fx/whizz_bullet9.wav";
zngs[8] = "fx/whizz_bullet10.wav";
zngs[9] = "fx/whizz_bullet11.wav";
zngs[10] = "fx/whizz_bullet12.wav";
zngs[11] = "fx/whizz_bullet13.wav";
zngs[12] = "fx/whizz_bullet14.wav";
zngs[13] = "fx/whizz_bullet15.wav";
zngs[14] = "fx/whizz_bullet16.wav";
zngs[15] = "fx/whizz_bullet17.wav";
zngs[16] = "fx/whizz_bullet18.wav";
cnt = 17;
// PAUL:TODO, figure out whats the best way to use the sound point because
// we are actually moving!
gEngfuncs.pEventAPI->EV_PlaySound( pthisplayer->index, soundPoint,
CHAN_STATIC, zngs[gEngfuncs.pfnRandomLong(0,cnt-1)],
gEngfuncs.pfnRandomFloat(0.92, 1.0),
ATTN_NORM, 0, 98 + gEngfuncs.pfnRandomLong( 0, 3 ) );
#ifdef CORE_DEBUG
gEngfuncs.Con_Printf( "EV_HLDM->EV_HLDM_BulletFlyBySound, we just played sounds\n" );
#endif
}
}
}
}
// </paul>
/*
================
FireBullets
Go to the trouble of combining multiple pellets into a single damage call.
================
*/
void EV_HLDM_FireBullets( int idx, float *forward, float *right, float *up, int cShots, float *vecSrc, float *vecDirShooting, float flDistance, int iBulletType, int iTracerFreq, int *tracerCount, float flSpreadX, float flSpreadY )
{
int i;
pmtrace_t tr;
int iShot;
int tracer;
if ( EV_IsLocal( idx ) )
for ( iShot = 1; iShot <= cShots; iShot++ )
{
vec3_t vecDir, vecEnd;
float x, y, z;
//We randomize for the Shotgun.
if ( iBulletType == BULLET_PLAYER_BUCKSHOT )
{
do {
x = gEngfuncs.pfnRandomFloat(-0.5,0.5) + gEngfuncs.pfnRandomFloat(-0.5,0.5);
y = gEngfuncs.pfnRandomFloat(-0.5,0.5) + gEngfuncs.pfnRandomFloat(-0.5,0.5);
z = x*x+y*y;
} while (z > 1);
for ( i = 0 ; i < 3; i++ )
{
vecDir[i] = vecDirShooting[i] + x * flSpreadX * right[ i ] + y * flSpreadY * up [ i ];
vecEnd[i] = vecSrc[ i ] + flDistance * vecDir[ i ];
}
}//But other guns already have their spread randomized in the synched spread.
else
{
for ( i = 0 ; i < 3; i++ )
{
vecDir[i] = vecDirShooting[i] + flSpreadX * right[ i ] + flSpreadY * up [ i ];
vecEnd[i] = vecSrc[ i ] + flDistance * vecDir[ i ];
}
}
gEngfuncs.pEventAPI->EV_SetUpPlayerPrediction( false, true );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc, vecEnd, PM_STUDIO_BOX, -1, &tr );
tracer = EV_HLDM_CheckTracer( idx, vecSrc, tr.endpos, forward, right, iBulletType, iTracerFreq, tracerCount );
// do damage, paint decals
if ( tr.fraction != 1.0 )
{
switch(iBulletType)
{
default:
case BULLET_PLAYER_9MM:
EV_HLDM_PlayTextureSound( idx, &tr, vecSrc, vecEnd, iBulletType );
EV_HLDM_DecalGunshot( &tr, iBulletType );
EV_HLDM_SmokePuff( &tr, vecSrc, vecEnd );
break;
case BULLET_PLAYER_50CAL:
EV_HLDM_PlayTextureSound( idx, &tr, vecSrc, vecEnd, iBulletType );
EV_HLDM_DecalGunshot( &tr, iBulletType );
EV_HLDM_SmokePuff( &tr, vecSrc, vecEnd );
break;
case BULLET_PLAYER_MP5:
if ( !tracer )
{
EV_HLDM_PlayTextureSound( idx, &tr, vecSrc, vecEnd, iBulletType );
EV_HLDM_DecalGunshot( &tr, iBulletType );
EV_HLDM_SmokePuff( &tr, vecSrc, vecEnd );
}
break;
case BULLET_PLAYER_BUCKSHOT:
EV_HLDM_DecalGunshot( &tr, iBulletType );
EV_HLDM_SmokePuff( &tr, vecSrc, vecEnd );
break;
case BULLET_PLAYER_357:
EV_HLDM_PlayTextureSound( idx, &tr, vecSrc, vecEnd, iBulletType );
EV_HLDM_DecalGunshot( &tr, iBulletType );
EV_HLDM_SmokePuff( &tr, vecSrc, vecEnd );
break;
}
}
gEngfuncs.pEventAPI->EV_PopPMStates();
}
}
//======================
// GLOCK START
//======================
void EV_FireGlock1( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
int empty;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
empty = args->bparam1;
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/9mm_shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( empty ? GLOCK_SHOOT_EMPTY : GLOCK_SHOOT, 2 );
V_PunchAxis( 0, -2.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/pl_gun3.wav", gEngfuncs.pfnRandomFloat(0.92, 1.0), ATTN_NORM, 0, 98 + gEngfuncs.pfnRandomLong( 0, 3 ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_9MM, 0, 0, args->fparam1, args->fparam2 );
}
void EV_FireGlock2( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/9mm_shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( GLOCK_SHOOT, 2 );
V_PunchAxis( 0, -2.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/pl_gun3.wav", gEngfuncs.pfnRandomFloat(0.92, 1.0), ATTN_NORM, 0, 98 + gEngfuncs.pfnRandomLong( 0, 3 ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_9MM, 0, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
//======================
// GLOCK END
//======================
//======================
// EAGEL START
//======================
void EV_FireEagel1( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
int empty;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
empty = args->bparam1;
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( empty ? EAGEL_FIRE1 : EAGEL_FIRE1, 2 );
V_PunchAxis( 0, -2.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/eagel_fire2.wav", gEngfuncs.pfnRandomFloat(0.92, 1.0), ATTN_NORM, 0, 98 + gEngfuncs.pfnRandomLong( 0, 3 ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_9MM, 0, 0, args->fparam1, args->fparam2 );
}
void EV_FireEagel2( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
gEngfuncs.pEventAPI->EV_WeaponAnimation( EAGEL_FIRE1, 2 );
V_PunchAxis( 0, -2.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/eagel_fire1.wav", gEngfuncs.pfnRandomFloat(0.92, 1.0), ATTN_NORM, 0, 98 + gEngfuncs.pfnRandomLong( 0, 3 ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_9MM, 0, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
//======================
// EAGEL END
//======================
//======================
// SHOTGUN START
//======================
void EV_FireShotGunDouble( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
int j;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shotgunshell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( SHOTGUN_FIRE2, 2 );
V_PunchAxis( 0, -10.0 );
}
for ( j = 0; j < 2; j++ )
{
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 32, -12, 6 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHOTSHELL );
}
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/dbarrel1.wav", gEngfuncs.pfnRandomFloat(0.98, 1.0), ATTN_NORM, 0, 85 + gEngfuncs.pfnRandomLong( 0, 0x1f ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 8, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.17365, 0.04362 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 12, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.08716 );
}
}
void EV_FireShotGunSingle( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shotgunshell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( SHOTGUN_FIRE, 2 );
V_PunchAxis( 0, -5.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 32, -12, 6 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHOTSHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/sbarrel1.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong( 0, 0x1f ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 4, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.04362 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 6, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.08716 );
}
}
//======================
// SHOTGUN END
//======================
//======================
// AUTO SHOTGUN START
//======================
void EV_FireShotGunADouble( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
int j;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/auto_shotgunshell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( SHOTGUNA_SHOOT, 2 );
V_PunchAxis( 0, -10.0 );
}
for ( j = 0; j < 2; j++ )
{
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 32, -12, 6 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHOTSHELL );
}
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/dbarrel1.wav", gEngfuncs.pfnRandomFloat(0.98, 1.0), ATTN_NORM, 0, 85 + gEngfuncs.pfnRandomLong( 0, 0x1f ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 8, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.17365, 0.04362 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 12, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.08716 );
}
}
void EV_FireShotGunASingle( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t vecSpread;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/auto_shotgunshell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( SHOTGUNA_SHOOT, 2 );
V_PunchAxis( 0, -5.0 );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 32, -12, 6 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHOTSHELL );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/sbarrel1.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong( 0, 0x1f ) );
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 4, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.04362 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 6, vecSrc, vecAiming, 2048, BULLET_PLAYER_BUCKSHOT, 0, &tracerCount[idx-1], 0.08716, 0.08716 );
}
}
//======================
// AUTO SHOTGUN END
//======================
//======================
// SHOCK START
//======================
enum shockrifle_e
{
SHOCK_IDLE1 = 0,
SHOCK_FIRE,
SHOCK_DRAW,
SHOCK_HOLSTER,
SHOCK_IDLE3
};
void EV_ShockFire( event_args_t *args )
{
int idx;
vec3_t origin;
gEngfuncs.pEventAPI->EV_WeaponAnimation(SHOCK_FIRE, 2);
cl_entity_t *view = gEngfuncs.GetViewModel();
if (view != NULL)
{
float life = 0.1;
gEngfuncs.pEfxAPI->R_BeamEnts(view->index | 0x2000, view->index | 0x1000, args->iparam2, life, 0.8, 0.5, 0.5, 0.6, 0, 10, 0, 4, 10);
gEngfuncs.pEfxAPI->R_BeamEnts(view->index | 0x3000, view->index | 0x1000, args->iparam2, life, 0.8, 0.5, 0.5, 0.6, 0, 10, 0, 4, 10);
gEngfuncs.pEfxAPI->R_BeamEnts(view->index | 0x4000, view->index | 0x1000, args->iparam2, life, 0.8, 0.5, 0.5, 0.6, 0, 10, 0, 4, 10);
}
idx = args->entindex;
VectorCopy( args->origin, origin );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/shock_fire.wav", 1, ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_ITEM, "weapons/shock_reload.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
//Only play the weapon anims if I shot it.
if ( EV_IsLocal( idx ) )
{
if ( args->iparam1 )
gEngfuncs.pEventAPI->EV_WeaponAnimation( SHOCK_FIRE, 1 );
V_PunchAxis( 0, -2.0 );
}
}
//======================
// SHOCK END
//======================
//======================
// UZI START
//======================
void EV_FireUZI( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/9mm_shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
gEngfuncs.GetViewAngles( (float *)viewangles );
gEngfuncs.SetViewAngles( (float *)viewangles );
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( UZI_FIRE1 + gEngfuncs.pfnRandomLong(0,2), 2 );
V_PunchAxis( 0, gEngfuncs.pfnRandomFloat( -2, 2 ) );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/uzi1.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/uzi2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
}
//======================
// UZI END
//======================
//======================
// MP5 START
//======================
void EV_FireMP5( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
int staerkedesrecoils = 1.00;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
gEngfuncs.GetViewAngles( (float *)viewangles );
viewangles[PITCH] -= staerkedesrecoils;
gEngfuncs.SetViewAngles( (float *)viewangles );
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( MP5_FIRE1 + gEngfuncs.pfnRandomLong(0,2), 2 );
V_PunchAxis( 0, gEngfuncs.pfnRandomFloat( -2, 2 ) );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/hks1.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/hks2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
}
// We only predict the animation and sound
// The grenade is still launched from the server.
void EV_FireMP52( event_args_t *args )
{
int idx;
vec3_t origin;
idx = args->entindex;
VectorCopy( args->origin, origin );
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( MP5_LAUNCH, 2 );
V_PunchAxis( 0, -10 );
}
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/glauncher.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/glauncher2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
}
//======================
// MP5 END
//======================
//======================
// AK47 START
//======================
void EV_FireAK47( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
int staerkedesrecoils = 1.00;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
gEngfuncs.GetViewAngles( (float *)viewangles );
viewangles[PITCH] -= staerkedesrecoils;
gEngfuncs.SetViewAngles( (float *)viewangles );
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( AK47_SHOOT_1 + gEngfuncs.pfnRandomLong(0,2), 2 );
V_PunchAxis( 0, gEngfuncs.pfnRandomFloat( -2, 2 ) );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/ak471.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/ak472.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
}
//======================
// AK47 END
//======================
//======================
// MINIGUN START
//======================
void EV_FireMinigun( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/12mm_shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( MINIGUN_FIRE1 + gEngfuncs.pfnRandomLong(0,2), 2 );
V_PunchAxis( 0, gEngfuncs.pfnRandomFloat( -2, 2 ) );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/minigun1.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/minigun2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_50CAL, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_50CAL, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
}
//======================
// MINIGUN END
//======================
//======================
// MP41a START
//======================
void EV_FireMP41a( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
int staerkedesrecoils = 1.00;
vec3_t ShellVelocity;
vec3_t ShellOrigin;
int shell;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
shell = gEngfuncs.pEventAPI->EV_FindModelIndex ("models/shell.mdl");// brass shell
if ( EV_IsLocal( idx ) )
{
gEngfuncs.GetViewAngles( (float *)viewangles );
viewangles[PITCH] -= staerkedesrecoils;
gEngfuncs.SetViewAngles( (float *)viewangles );
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( MP41a_FIRE1 + gEngfuncs.pfnRandomLong(0,2), 2 );
V_PunchAxis( 0, gEngfuncs.pfnRandomFloat( -2, 2 ) );
}
EV_GetDefaultShellInfo( args, origin, velocity, ShellVelocity, ShellOrigin, forward, right, up, 20, -12, 4 );
EV_EjectBrass ( ShellOrigin, ShellVelocity, angles[ YAW ], shell, TE_BOUNCE_SHELL );
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/m41ahks1.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/m41ahks2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
if ( gEngfuncs.GetMaxClients() > 1 )
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
else
{
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_MP5, 2, &tracerCount[idx-1], args->fparam1, args->fparam2 );
}
}
// We only predict the animation and sound
// The grenade is still launched from the server.
void EV_FireMP41a2( event_args_t *args )
{
int idx;
vec3_t origin;
idx = args->entindex;
VectorCopy( args->origin, origin );
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( MP41a_LAUNCH, 2 );
V_PunchAxis( 0, -10 );
}
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/m41aglauncher.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/m41aglauncher2.wav", 1, ATTN_NORM, 0, 94 + gEngfuncs.pfnRandomLong( 0, 0xf ) );
break;
}
}
//======================
// MP41a END
//======================
//======================
// PHYTON START
// ( .357 )
//======================
void EV_FirePython( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t vecSrc, vecAiming;
vec3_t up, right, forward;
float flSpread = 0.01;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
if ( EV_IsLocal( idx ) )
{
// Python uses different body in multiplayer versus single player
int multiplayer = gEngfuncs.GetMaxClients() == 1 ? 0 : 1;
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
gEngfuncs.pEventAPI->EV_WeaponAnimation( PYTHON_FIRE1, multiplayer ? 1 : 0 );
V_PunchAxis( 0, -10.0 );
}
switch( gEngfuncs.pfnRandomLong( 0, 1 ) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/357_shot1.wav", gEngfuncs.pfnRandomFloat(0.8, 0.9), ATTN_NORM, 0, PITCH_NORM );
break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/357_shot2.wav", gEngfuncs.pfnRandomFloat(0.8, 0.9), ATTN_NORM, 0, PITCH_NORM );
break;
}
EV_GetGunPosition( args, vecSrc, origin );
VectorCopy( forward, vecAiming );
EV_HLDM_FireBullets( idx, forward, right, up, 1, vecSrc, vecAiming, 8192, BULLET_PLAYER_357, 0, 0, args->fparam1, args->fparam2 );
}
//======================
// PHYTON END
// ( .357 )
//======================
//======================
// GAUSS START
//======================
#define SND_CHANGE_PITCH (1<<7) // duplicated in protocol.h change sound pitch
void EV_SpinGauss( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
int iSoundState = 0;
int pitch;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
pitch = args->iparam1;
iSoundState = args->bparam1 ? SND_CHANGE_PITCH : 0;
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "ambience/pulsemachine.wav", 1.0, ATTN_NORM, iSoundState, pitch );
}
/*
==============================
EV_StopPreviousGauss
==============================
*/
void EV_StopPreviousGauss( int idx )
{
// Make sure we don't have a gauss spin event in the queue for this guy
gEngfuncs.pEventAPI->EV_KillEvents( idx, "events/gaussspin.sc" );
gEngfuncs.pEventAPI->EV_StopSound( idx, CHAN_WEAPON, "ambience/pulsemachine.wav" );
}
extern float g_flApplyVel;
void EV_FireGauss( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
vec3_t viewangles;
int staerkedesrecoils = 3.00;
float flDamage = args->fparam1;
int primaryfire = args->bparam1;
int m_fPrimaryFire = args->bparam1;
int m_iWeaponVolume = GAUSS_PRIMARY_FIRE_VOLUME;
vec3_t vecSrc;
vec3_t vecDest;
edict_t *pentIgnore;
pmtrace_t tr, beam_tr;
float flMaxFrac = 1.0;
int nTotal = 0;
int fHasPunched = 0;
int fFirstBeam = 1;
int nMaxHits = 10;
physent_t *pEntity;
int m_iBeam, m_iGlow, m_iBalls;
vec3_t up, right, forward;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
if ( args->bparam2 )
{
EV_StopPreviousGauss( idx );
return;
}
// Con_Printf( "Firing gauss with %f\n", flDamage );
EV_GetGunPosition( args, vecSrc, origin );
m_iBeam = gEngfuncs.pEventAPI->EV_FindModelIndex( "sprites/smoke.spr" );
m_iBalls = m_iGlow = gEngfuncs.pEventAPI->EV_FindModelIndex( "sprites/hotglow.spr" );
AngleVectors( angles, forward, right, up );
VectorMA( vecSrc, 8192, forward, vecDest );
if ( EV_IsLocal( idx ) )
{
gEngfuncs.GetViewAngles( (float *)viewangles );
viewangles[PITCH] -= staerkedesrecoils;
gEngfuncs.SetViewAngles( (float *)viewangles );
V_PunchAxis( 0, -2.0 );
gEngfuncs.pEventAPI->EV_WeaponAnimation( GAUSS_FIRE2, 2 );
if ( m_fPrimaryFire == false )
g_flApplyVel = flDamage;
}
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/gauss2.wav", 0.5 + flDamage * (1.0 / 400.0), ATTN_NORM, 0, 85 + gEngfuncs.pfnRandomLong( 0, 0x1f ) );
while (flDamage > 10 && nMaxHits > 0)
{
nMaxHits--;
gEngfuncs.pEventAPI->EV_SetUpPlayerPrediction( false, true );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc, vecDest, PM_STUDIO_BOX, -1, &tr );
gEngfuncs.pEventAPI->EV_PopPMStates();
if ( tr.allsolid )
break;
if (fFirstBeam)
{
if ( EV_IsLocal( idx ) )
{
// Add muzzle flash to current weapon model
EV_MuzzleFlash();
}
fFirstBeam = 0;
gEngfuncs.pEfxAPI->R_BeamEntPoint(
idx | 0x1000,
tr.endpos,
m_iBeam,
0.1,
m_fPrimaryFire ? 1.0 : 2.5,
0.0,
m_fPrimaryFire ? 128.0 : flDamage,
0,
0,
0,
m_fPrimaryFire ? 255 : 255,
m_fPrimaryFire ? 128 : 255,
m_fPrimaryFire ? 0 : 255
);
}
else
{
gEngfuncs.pEfxAPI->R_BeamPoints( vecSrc,
tr.endpos,
m_iBeam,
0.1,
m_fPrimaryFire ? 1.0 : 2.5,
0.0,
m_fPrimaryFire ? 128.0 : flDamage,
0,
0,
0,
m_fPrimaryFire ? 255 : 255,
m_fPrimaryFire ? 128 : 255,
m_fPrimaryFire ? 0 : 255
);
}
pEntity = gEngfuncs.pEventAPI->EV_GetPhysent( tr.ent );
if ( pEntity == NULL )
break;
if ( pEntity->solid == SOLID_BSP )
{
float n;
pentIgnore = NULL;
n = -DotProduct( tr.plane.normal, forward );
if (n < 0.5) // 60 degrees
{
// ALERT( at_console, "reflect %f\n", n );
// reflect
vec3_t r;
VectorMA( forward, 2.0 * n, tr.plane.normal, r );
flMaxFrac = flMaxFrac - tr.fraction;
VectorCopy( r, forward );
VectorMA( tr.endpos, 8.0, forward, vecSrc );
VectorMA( vecSrc, 8192.0, forward, vecDest );
gEngfuncs.pEfxAPI->R_TempSprite( tr.endpos, vec3_origin, 0.2, m_iGlow, kRenderGlow, kRenderFxNoDissipation, flDamage * n / 255.0, flDamage * n * 0.5 * 0.1, FTENT_FADEOUT );
vec3_t fwd;
VectorAdd( tr.endpos, tr.plane.normal, fwd );
gEngfuncs.pEfxAPI->R_Sprite_Trail( TE_SPRITETRAIL, tr.endpos, fwd, m_iBalls, 3, 0.1, gEngfuncs.pfnRandomFloat( 10, 20 ) / 100.0, 100,
255, 100 );
// lose energy
if ( n == 0 )
{
n = 0.1;
}
flDamage = flDamage * (1 - n);
}
else
{
// tunnel
EV_HLDM_DecalGunshot( &tr, BULLET_MONSTER_12MM );
gEngfuncs.pEfxAPI->R_TempSprite( tr.endpos, vec3_origin, 1.0, m_iGlow, kRenderGlow, kRenderFxNoDissipation, flDamage / 255.0, 6.0, FTENT_FADEOUT );
// limit it to one hole punch
if (fHasPunched)
{
break;
}
fHasPunched = 1;
// try punching through wall if secondary attack (primary is incapable of breaking through)
if ( !m_fPrimaryFire )
{
vec3_t start;
VectorMA( tr.endpos, 8.0, forward, start );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( start, vecDest, PM_STUDIO_BOX, -1, &beam_tr );
if ( !beam_tr.allsolid )
{
vec3_t delta;
float n;
// trace backwards to find exit point
gEngfuncs.pEventAPI->EV_PlayerTrace( beam_tr.endpos, tr.endpos, PM_STUDIO_BOX, -1, &beam_tr );
VectorSubtract( beam_tr.endpos, tr.endpos, delta );
n = Length( delta );
if (n < flDamage)
{
if (n == 0)
n = 1;
flDamage -= n;
// absorption balls
{
vec3_t fwd;
VectorSubtract( tr.endpos, forward, fwd );
gEngfuncs.pEfxAPI->R_Sprite_Trail( TE_SPRITETRAIL, tr.endpos, fwd, m_iBalls, 3, 0.1, gEngfuncs.pfnRandomFloat( 10, 20 ) / 100.0, 100,
255, 100 );
}
//////////////////////////////////// WHAT TO DO HERE
// CSoundEnt::InsertSound ( bits_SOUND_COMBAT, pev->origin, NORMAL_EXPLOSION_VOLUME, 3.0 );
EV_HLDM_DecalGunshot( &beam_tr, BULLET_MONSTER_12MM );
gEngfuncs.pEfxAPI->R_TempSprite( beam_tr.endpos, vec3_origin, 0.1, m_iGlow, kRenderGlow, kRenderFxNoDissipation, flDamage / 255.0, 6.0, FTENT_FADEOUT );
// balls
{
vec3_t fwd;
VectorSubtract( beam_tr.endpos, forward, fwd );
gEngfuncs.pEfxAPI->R_Sprite_Trail( TE_SPRITETRAIL, beam_tr.endpos, fwd, m_iBalls, (int)(flDamage * 0.3), 0.1, gEngfuncs.pfnRandomFloat( 10, 20 ) / 100.0, 200,
255, 40 );
}
VectorAdd( beam_tr.endpos, forward, vecSrc );
}
}
else
{
flDamage = 0;
}
gEngfuncs.pEventAPI->EV_PopPMStates();
}
else
{
if ( m_fPrimaryFire )
{
// slug doesn't punch through ever with primary
// fire, so leave a little glowy bit and make some balls
gEngfuncs.pEfxAPI->R_TempSprite( tr.endpos, vec3_origin, 0.2, m_iGlow, kRenderGlow, kRenderFxNoDissipation, 200.0 / 255.0, 0.3, FTENT_FADEOUT );
{
vec3_t fwd;
VectorAdd( tr.endpos, tr.plane.normal, fwd );
gEngfuncs.pEfxAPI->R_Sprite_Trail( TE_SPRITETRAIL, tr.endpos, fwd, m_iBalls, 8, 0.6, gEngfuncs.pfnRandomFloat( 10, 20 ) / 100.0, 100,
255, 200 );
}
}
flDamage = 0;
}
}
}
else
{
VectorAdd( tr.endpos, forward, vecSrc );
}
}
}
//======================
// GAUSS END
//======================
//======================
// CROWBAR START
//======================
enum crowbar_e
{
CROWBAR_IDLE = 0,
CROWBAR_DRAW,
CROWBAR_HOLSTER,
CROWBAR_ATTACK1HIT,
CROWBAR_ATTACK1MISS,
CROWBAR_ATTACK2MISS,
CROWBAR_ATTACK2HIT,
CROWBAR_ATTACK3MISS,
CROWBAR_ATTACK3HIT
};
int g_iSwing;
//Only predict the miss sounds, hit sounds are still played
//server side, so players don't get the wrong idea.
void EV_Crowbar( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
idx = args->entindex;
VectorCopy( args->origin, origin );
//Play Swing sound
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/cbar_miss1.wav", 1, ATTN_NORM, 0, PITCH_NORM);
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( CROWBAR_ATTACK1MISS, 1 );
switch( (g_iSwing++) % 3 )
{
case 0:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( CROWBAR_ATTACK1MISS, 1 ); break;
case 1:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( CROWBAR_ATTACK2MISS, 1 ); break;
case 2:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( CROWBAR_ATTACK3MISS, 1 ); break;
}
}
}
//======================
// CROWBAR END
//======================
//======================
// SWORT START
//======================
enum swort_e
{
SWORT_IDLE = 0,
SWORT_DRAW,
SWORT_HOLSTER,
SWORT_ATTACK1HIT,
SWORT_ATTACK1MISS,
SWORT_ATTACK2MISS,
SWORT_ATTACK2HIT,
SWORT_ATTACK3MISS,
SWORT_ATTACK3HIT
};
int g_iSwort;
//Only predict the miss sounds, hit sounds are still played
//server side, so players don't get the wrong idea.
void EV_Swort( event_args_t *args )
{
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
idx = args->entindex;
VectorCopy( args->origin, origin );
//Play Swing sound
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/swort_miss1.wav", 1, ATTN_NORM, 0, PITCH_NORM);
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( SWORT_ATTACK1MISS, 1 );
switch( (g_iSwort++) % 3 )
{
case 0:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( SWORT_ATTACK1MISS, 1 ); break;
case 1:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( SWORT_ATTACK2MISS, 1 ); break;
case 2:
gEngfuncs.pEventAPI->EV_WeaponAnimation ( SWORT_ATTACK3MISS, 1 ); break;
}
}
}
//======================
// SWORT END
//======================
//======================
// CROSSBOW START
//======================
enum crossbow_e
{
CROSSBOW_IDLE,
CROSSBOW_FIDGET,
CROSSBOW_FIRE,
CROSSBOW_FIRE2,
CROSSBOW_FIRE3,
CROSSBOW_RELOAD,
CROSSBOW_DRAW,
CROSSBOW_HOLSTER,
};
//=====================
// EV_BoltCallback
// This function is used to correct the origin and angles
// of the bolt, so it looks like it's stuck on the wall.
//=====================
void EV_BoltCallback ( struct tempent_s *ent, float frametime, float currenttime )
{
ent->entity.origin = ent->entity.baseline.vuser1;
ent->entity.angles = ent->entity.baseline.vuser2;
}
void EV_FireCrossbow2( event_args_t *args )
{
vec3_t vecSrc, vecEnd;
vec3_t up, right, forward;
pmtrace_t tr;
int idx;
vec3_t origin;
vec3_t angles;
vec3_t velocity;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
VectorCopy( args->velocity, velocity );
AngleVectors( angles, forward, right, up );
EV_GetGunPosition( args, vecSrc, origin );
VectorMA( vecSrc, 8192, forward, vecEnd );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/arrow6_fire.wav", 1, ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_ITEM, "weapons/arrow6_reload.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
if ( EV_IsLocal( idx ) )
{
if ( args->iparam1 )
gEngfuncs.pEventAPI->EV_WeaponAnimation( CROSSBOW_FIRE, 1 );
else if ( args->iparam2 )
gEngfuncs.pEventAPI->EV_WeaponAnimation( CROSSBOW_FIRE3, 1 );
}
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc, vecEnd, PM_STUDIO_BOX, -1, &tr );
//We hit something
if ( tr.fraction < 1.0 )
{
physent_t *pe = gEngfuncs.pEventAPI->EV_GetPhysent( tr.ent );
//Not the world, let's assume we hit something organic ( dog, cat, uncle joe, etc ).
if ( pe->solid != SOLID_BSP )
{
switch( gEngfuncs.pfnRandomLong(0,1) )
{
case 0:
gEngfuncs.pEventAPI->EV_PlaySound( idx, tr.endpos, CHAN_BODY, "weapons/xbow_hitbod1.wav", 1, ATTN_NORM, 0, PITCH_NORM ); break;
case 1:
gEngfuncs.pEventAPI->EV_PlaySound( idx, tr.endpos, CHAN_BODY, "weapons/xbow_hitbod2.wav", 1, ATTN_NORM, 0, PITCH_NORM ); break;
}
}
//Stick to world but don't stick to glass, it might break and leave the bolt floating. It can still stick to other non-transparent breakables though.
else if ( pe->rendermode == kRenderNormal )
{
gEngfuncs.pEventAPI->EV_PlaySound( 0, tr.endpos, CHAN_BODY, "weapons/xbow_hit1.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, PITCH_NORM );
//Not underwater, do some sparks...
if ( gEngfuncs.PM_PointContents( tr.endpos, NULL ) != CONTENTS_WATER)
gEngfuncs.pEfxAPI->R_SparkShower( tr.endpos );
vec3_t vBoltAngles;
int iModelIndex = gEngfuncs.pEventAPI->EV_FindModelIndex( "models/crossbow_bolt.mdl" );
VectorAngles( forward, vBoltAngles );
TEMPENTITY *bolt = gEngfuncs.pEfxAPI->R_TempModel( tr.endpos - forward * 10, Vector( 0, 0, 0), vBoltAngles , 5, iModelIndex, TE_BOUNCE_NULL );
if ( bolt )
{
bolt->flags |= ( FTENT_CLIENTCUSTOM ); //So it calls the callback function.
bolt->entity.baseline.vuser1 = tr.endpos - forward * 10; // Pull out a little bit
bolt->entity.baseline.vuser2 = vBoltAngles; //Look forward!
bolt->callback = EV_BoltCallback; //So we can set the angles and origin back. (Stick the bolt to the wall)
}
}
}
gEngfuncs.pEventAPI->EV_PopPMStates();
}
//TODO: Fully predict the fliying bolt.
void EV_FireCrossbow( event_args_t *args )
{
int idx;
vec3_t origin;
idx = args->entindex;
VectorCopy( args->origin, origin );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/arrow6_fire.wav", 1, ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_ITEM, "weapons/arrow6_reload.wav", gEngfuncs.pfnRandomFloat(0.95, 1.0), ATTN_NORM, 0, 93 + gEngfuncs.pfnRandomLong(0,0xF) );
//Only play the weapon anims if I shot it.
if ( EV_IsLocal( idx ) )
{
if ( args->iparam1 )
gEngfuncs.pEventAPI->EV_WeaponAnimation( CROSSBOW_FIRE, 1 );
else if ( args->iparam2 )
gEngfuncs.pEventAPI->EV_WeaponAnimation( CROSSBOW_FIRE3, 1 );
V_PunchAxis( 0, -2.0 );
}
}
//======================
// CROSSBOW END
//======================
//======================
// RPG START
//======================
enum rpg_e
{
RPG_IDLE = 0,
RPG_FIDGET,
RPG_RELOAD, // to reload
RPG_FIRE2, // to empty
RPG_HOLSTER1, // loaded
RPG_DRAW1, // loaded
RPG_HOLSTER2, // unloaded
RPG_DRAW_UL, // unloaded
RPG_IDLE_UL, // unloaded idle
RPG_FIDGET_UL, // unloaded fidget
};
void EV_FireRpg( event_args_t *args )
{
int idx;
vec3_t origin;
idx = args->entindex;
VectorCopy( args->origin, origin );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "weapons/rocketfire1.wav", 0.9, ATTN_NORM, 0, PITCH_NORM );
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_ITEM, "weapons/glauncher.wav", 0.7, ATTN_NORM, 0, PITCH_NORM );
//Only play the weapon anims if I shot it.
if ( EV_IsLocal( idx ) )
{
gEngfuncs.pEventAPI->EV_WeaponAnimation( RPG_FIRE2, 1 );
V_PunchAxis( 0, -5.0 );
}
}
//======================
// RPG END
//======================
//======================
// EGON END
//======================
enum egon_e {
EGON_IDLE1 = 0,
EGON_FIDGET1,
EGON_ALTFIREON,
EGON_ALTFIRECYCLE,
EGON_ALTFIREOFF,
EGON_FIRE1,
EGON_FIRE2,
EGON_FIRE3,
EGON_FIRE4,
EGON_DRAW,
EGON_HOLSTER
};
int g_fireAnims1[] = { EGON_FIRE1, EGON_FIRE2, EGON_FIRE3, EGON_FIRE4 };
int g_fireAnims2[] = { EGON_ALTFIRECYCLE };
enum EGON_FIRESTATE { FIRE_OFF, FIRE_CHARGE };
enum EGON_FIREMODE { FIRE_NARROW, FIRE_WIDE};
#define EGON_PRIMARY_VOLUME 450
#define EGON_BEAM_SPRITE "sprites/xbeam1.spr"
#define EGON_FLARE_SPRITE "sprites/XSpark1.spr"
#define EGON_SOUND_OFF "weapons/egon_off1.wav"
#define EGON_SOUND_RUN "weapons/egon_run3.wav"
#define EGON_SOUND_STARTUP "weapons/egon_windup2.wav"
#define ARRAYSIZE(p) (sizeof(p)/sizeof(p[0]))
BEAM *pBeam;
BEAM *pBeam2;
void EV_EgonFire( event_args_t *args )
{
int idx, iFireState, iFireMode;
vec3_t origin;
idx = args->entindex;
VectorCopy( args->origin, origin );
iFireState = args->iparam1;
iFireMode = args->iparam2;
int iStartup = args->bparam1;
if ( iStartup )
{
if ( iFireMode == FIRE_WIDE )
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, EGON_SOUND_STARTUP, 0.98, ATTN_NORM, 0, 125 );
else
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, EGON_SOUND_STARTUP, 0.9, ATTN_NORM, 0, 100 );
}
else
{
if ( iFireMode == FIRE_WIDE )
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_STATIC, EGON_SOUND_RUN, 0.98, ATTN_NORM, 0, 125 );
else
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_STATIC, EGON_SOUND_RUN, 0.9, ATTN_NORM, 0, 100 );
}
//Only play the weapon anims if I shot it.
if ( EV_IsLocal( idx ) )
gEngfuncs.pEventAPI->EV_WeaponAnimation ( g_fireAnims1[ gEngfuncs.pfnRandomLong( 0, 3 ) ], 1 );
if ( iStartup == 1 && EV_IsLocal( idx ) && !pBeam && !pBeam2 && cl_lw->value ) //Adrian: Added the cl_lw check for those lital people that hate weapon prediction.
{
vec3_t vecSrc, vecEnd, origin, angles, forward, right, up;
pmtrace_t tr;
cl_entity_t *pl = gEngfuncs.GetEntityByIndex( idx );
if ( pl )
{
VectorCopy( gHUD.m_vecAngles, angles );
AngleVectors( angles, forward, right, up );
EV_GetGunPosition( args, vecSrc, pl->origin );
VectorMA( vecSrc, 2048, forward, vecEnd );
gEngfuncs.pEventAPI->EV_SetUpPlayerPrediction( false, true );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc, vecEnd, PM_STUDIO_BOX, -1, &tr );
gEngfuncs.pEventAPI->EV_PopPMStates();
int iBeamModelIndex = gEngfuncs.pEventAPI->EV_FindModelIndex( EGON_BEAM_SPRITE );
float r = 50.0f;
float g = 50.0f;
float b = 125.0f;
if ( IEngineStudio.IsHardware() )
{
r /= 100.0f;
g /= 100.0f;
}
pBeam = gEngfuncs.pEfxAPI->R_BeamEntPoint ( idx | 0x1000, tr.endpos, iBeamModelIndex, 99999, 3.5, 0.2, 0.7, 55, 0, 0, r, g, b );
if ( pBeam )
pBeam->flags |= ( FBEAM_SINENOISE );
pBeam2 = gEngfuncs.pEfxAPI->R_BeamEntPoint ( idx | 0x1000, tr.endpos, iBeamModelIndex, 99999, 5.0, 0.08, 0.7, 25, 0, 0, r, g, b );
}
}
}
void EV_EgonStop( event_args_t *args )
{
int idx;
vec3_t origin;
idx = args->entindex;
VectorCopy ( args->origin, origin );
gEngfuncs.pEventAPI->EV_StopSound( idx, CHAN_STATIC, EGON_SOUND_RUN );
if ( args->iparam1 )
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, EGON_SOUND_OFF, 0.98, ATTN_NORM, 0, 100 );
if ( EV_IsLocal( idx ) )
{
if ( pBeam )
{
pBeam->die = 0.0;
pBeam = NULL;
}
if ( pBeam2 )
{
pBeam2->die = 0.0;
pBeam2 = NULL;
}
}
}
//======================
// EGON END
//======================
//======================
// HORNET START
//======================
enum hgun_e {
HGUN_IDLE1 = 0,
HGUN_FIDGETSWAY,
HGUN_FIDGETSHAKE,
HGUN_DOWN,
HGUN_UP,
HGUN_SHOOT
};
void EV_HornetGunFire( event_args_t *args )
{
int idx, iFireMode;
vec3_t origin, angles, vecSrc, forward, right, up;
idx = args->entindex;
VectorCopy( args->origin, origin );
VectorCopy( args->angles, angles );
iFireMode = args->iparam1;
//Only play the weapon anims if I shot it.
if ( EV_IsLocal( idx ) )
{
V_PunchAxis( 0, gEngfuncs.pfnRandomLong ( 0, 2 ) );
gEngfuncs.pEventAPI->EV_WeaponAnimation ( HGUN_SHOOT, 1 );
}
switch ( gEngfuncs.pfnRandomLong ( 0 , 2 ) )
{
case 0: gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "agrunt/ag_fire1.wav", 1, ATTN_NORM, 0, 100 ); break;
case 1: gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "agrunt/ag_fire2.wav", 1, ATTN_NORM, 0, 100 ); break;
case 2: gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_WEAPON, "agrunt/ag_fire3.wav", 1, ATTN_NORM, 0, 100 ); break;
}
}
//======================
// HORNET END
//======================
//======================
// TRIPMINE START
//======================
enum tripmine_e
{
TRIPMINE_IDLE1 = 0,
TRIPMINE_IDLE2,
TRIPMINE_ARM1,
TRIPMINE_PLACE,
TRIPMINE_FIDGET,
TRIPMINE_HOLSTER,
TRIPMINE_DRAW,
TRIPMINE_WORLD,
TRIPMINE_GROUND,
};
//We only check if it's possible to put a trip mine
//and if it is, then we play the animation. Server still places it.
void EV_TripmineFire( event_args_t *args )
{
int idx;
vec3_t vecSrc, angles, view_ofs, forward;
pmtrace_t tr;
idx = args->entindex;
VectorCopy( args->origin, vecSrc );
VectorCopy( args->angles, angles );
AngleVectors ( angles, forward, NULL, NULL );
if ( !EV_IsLocal ( idx ) )
return;
// Grab predicted result for local player
gEngfuncs.pEventAPI->EV_LocalPlayerViewheight( view_ofs );
vecSrc = vecSrc + view_ofs;
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc, vecSrc + forward * 128, PM_NORMAL, -1, &tr );
//Hit something solid
if ( tr.fraction < 1.0 )
gEngfuncs.pEventAPI->EV_WeaponAnimation ( TRIPMINE_DRAW, 0 );
gEngfuncs.pEventAPI->EV_PopPMStates();
}
//======================
// TRIPMINE END
//======================
//======================
// SQUEAK START
//======================
enum squeak_e {
SQUEAK_IDLE1 = 0,
SQUEAK_FIDGETFIT,
SQUEAK_FIDGETNIP,
SQUEAK_DOWN,
SQUEAK_UP,
SQUEAK_THROW
};
#define VEC_HULL_MIN Vector(-16, -16, -36)
#define VEC_DUCK_HULL_MIN Vector(-16, -16, -18 )
void EV_SnarkFire( event_args_t *args )
{
int idx;
vec3_t vecSrc, angles, view_ofs, forward;
pmtrace_t tr;
idx = args->entindex;
VectorCopy( args->origin, vecSrc );
VectorCopy( args->angles, angles );
AngleVectors ( angles, forward, NULL, NULL );
if ( !EV_IsLocal ( idx ) )
return;
if ( args->ducking )
vecSrc = vecSrc - ( VEC_HULL_MIN - VEC_DUCK_HULL_MIN );
// Store off the old count
gEngfuncs.pEventAPI->EV_PushPMStates();
// Now add in all of the players.
gEngfuncs.pEventAPI->EV_SetSolidPlayers ( idx - 1 );
gEngfuncs.pEventAPI->EV_SetTraceHull( 2 );
gEngfuncs.pEventAPI->EV_PlayerTrace( vecSrc + forward * 20, vecSrc + forward * 64, PM_NORMAL, -1, &tr );
//Find space to drop the thing.
if ( tr.allsolid == 0 && tr.startsolid == 0 && tr.fraction > 0.25 )
gEngfuncs.pEventAPI->EV_WeaponAnimation ( SQUEAK_THROW, 0 );
gEngfuncs.pEventAPI->EV_PopPMStates();
}
//======================
// SQUEAK END
//======================
void EV_TrainPitchAdjust( event_args_t *args )
{
int idx;
vec3_t origin;
unsigned short us_params;
int noise;
float m_flVolume;
int pitch;
int stop;
char sz[ 256 ];
idx = args->entindex;
VectorCopy( args->origin, origin );
us_params = (unsigned short)args->iparam1;
stop = args->bparam1;
m_flVolume = (float)(us_params & 0x003f)/40.0;
noise = (int)(((us_params) >> 12 ) & 0x0007);
pitch = (int)( 10.0 * (float)( ( us_params >> 6 ) & 0x003f ) );
switch ( noise )
{
case 1: strcpy( sz, "plats/ttrain1.wav"); break;
case 2: strcpy( sz, "plats/ttrain2.wav"); break;
case 3: strcpy( sz, "plats/ttrain3.wav"); break;
case 4: strcpy( sz, "plats/ttrain4.wav"); break;
case 5: strcpy( sz, "plats/ttrain6.wav"); break;
case 6: strcpy( sz, "plats/ttrain7.wav"); break;
default:
// no sound
strcpy( sz, "" );
return;
}
if ( stop )
{
gEngfuncs.pEventAPI->EV_StopSound( idx, CHAN_STATIC, sz );
}
else
{
gEngfuncs.pEventAPI->EV_PlaySound( idx, origin, CHAN_STATIC, sz, m_flVolume, ATTN_NORM, SND_CHANGE_PITCH, pitch );
}
}
int EV_TFC_IsAllyTeam( int iTeam1, int iTeam2 )
{
return 0;
}
| [
"30539708+Maxxiii@users.noreply.github.com"
] | 30539708+Maxxiii@users.noreply.github.com |
d2a415e59b41b254fe63fcb217abe4a6afc17cf9 | 3de0d74ea5532e12c8aa1aea56d2a9c604e369e0 | /single.cpp | f311ad234f8d2b52a8e4cf095eba96f6eba1e806 | [] | no_license | SvetlanaHryhorenko/Image | be3c2424b8850938aa0c28f7f1a49bf129fbad82 | 058c7e08596c3a71b169c11b3ae8eec89bd28883 | refs/heads/master | 2021-04-06T19:55:03.356577 | 2018-03-15T19:08:03 | 2018-03-15T19:08:03 | 125,414,081 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,056 | cpp | #include "single.h"
#include "ui_single.h"
#include "singleton.h"
#include <QFileDialog>
#include <QFile>
#include <QPicture>
#include <QPainter>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QGraphicsPixmapItem>
#include <QMessageBox>
#include <QList>
Single::Single(QWidget *parent) :
QDialog(parent),
ui(new Ui::Single)
{
ui->setupUi(this);
}
Single::~Single()
{
delete ui;
}
void Single::on_Add_clicked()
{
QString filename=QFileDialog::getOpenFileName(this,tr("Open file "),"C://","All files (*.*)");
// ui->imageLabel= new QLabel;
if( Singleton:: getInstance()->myList0.size()<1)
{ //ui->imageLabel->setBackgroundRole(QPalette::Base);
//ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->imageLabel->setScaledContents(true);
QPixmap pix(filename);
ui->imageLabel->setPixmap(pix);}
Singleton:: getInstance()->myList0.push_back(filename);
// Singleton:: myList0.toStdList();
// QMessageBox::information(this,tr("File name"),Singleton::getInstance()->myList0.at(0));
}
void Single::on_Next_clicked()
{
if(Singleton:: getInstance()->iter0<Singleton::getInstance()->myList0.size()-1)
{
Singleton:: getInstance()->iter0++;
//ui->imageLabel->setBackgroundRole(QPalette::Base);
//ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->imageLabel->setScaledContents(true);
QPixmap pix(Singleton::getInstance()->myList0.at(Singleton::getInstance()->iter0));
ui->imageLabel->setPixmap(pix);}
}
void Single::on_Previous_clicked()
{
if(Singleton:: getInstance()->iter0>0)
{
Singleton:: getInstance()->iter0--;
ui->imageLabel->setBackgroundRole(QPalette::Base);
ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->imageLabel->setScaledContents(true);
QPixmap pix(Singleton::getInstance()->myList0.at(Singleton::getInstance()->iter0));
ui->imageLabel->setPixmap(pix);}
}
void Single::on_Delete_clicked()
{
Singleton::getInstance()->myList0.removeAt(Singleton::getInstance()->iter0);
if(Singleton::getInstance()->iter0>=Singleton::getInstance()->myList0.size())
{Singleton::getInstance()->iter0--;}
ui->imageLabel->setBackgroundRole(QPalette::Base);
ui->imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
ui->imageLabel->setScaledContents(true);
QPixmap pix(Singleton::getInstance()->myList0.at(Singleton::getInstance()->iter0));
ui->imageLabel->setPixmap(pix);
}
void Single::on_SaveChanges_clicked()
{
QString outfile="C://users/sveta/documents/image/single.txt";
QFile file(outfile);
if (!file.open(QIODevice::WriteOnly)) {
QMessageBox::information(this, tr("Unable to open file"),
file.errorString());}
QDataStream out(&file);
out.setVersion(QDataStream::Qt_4_8);
for(int i=0;i<Singleton::getInstance()->myList0.size();i++)
{
out <<Singleton::getInstance()->myList0.at(i)/*<<"\n"*/ ;
}
file.close();
}
| [
"sa_grigorenko@ukr.net"
] | sa_grigorenko@ukr.net |
0d8055f553255f38a8e1440b32eb02d066d20adb | e2dbf39128a75c1caa7ddf4aec12b973c8980a35 | /examples/nytl/convert.hpp | fd1a3f31ca6e620714e69f10fdc50646846a4828 | [
"MIT"
] | permissive | vazgriz/vpp | a7fa856632d78bcb098de3e621496c89efa56a9c | 11b294a6dc00c0f1cfd69baba119fa1cec166bfc | refs/heads/master | 2021-06-01T07:48:24.160448 | 2016-08-04T15:34:24 | 2016-08-04T15:34:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,702 | hpp | /*
* The MIT License (MIT)
*
* Copyright (c) 2016 nyorain
*
* 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.
*/
///\file
///\brief Defines a utility to implement easy conversions without conversion operator.
#pragma once
#include <type_traits>
namespace nytl
{
///Specialize this template with a static call function to enable explicit conversions
///from type O to type T using the nytl::convert function.
///By default it will just perform a static cast.
///\sa nytl::convert
template<typename T, typename O, typename = void>
struct Converter;
template<typename T, typename O>
struct Converter<T, O, decltype(static_cast<T>(std::declval<O>()))>
{
static O call(const T& other) { return static_cast<O>(other); }
};
///The convert function can be used to call specialization of the Converted struct.
///This can be used to implement free conversion operations in a consistent way.
template<typename T, typename O>
auto convert(const O& other) -> decltype(Converter<T, O>::call(other))
{
return Converter<T, O>::call(other);
}
///Utility wrapper around type O that will convert into any type to which the stored object
///can be converted to.
template<typename O>
class AutoCastable
{
public:
template<typename T>
operator T() const { return convert<T>(*data_); }
public:
const O* data_;
};
///Convert overload that only takes one template parameter which will be deduced.
///Returns a wrapper object that will implicitly cast into any object into which the given
///object of type O can be converted.
template<typename O> AutoCastable<O> convert(const O& other) { return {&other}; }
}
| [
"nyorain@gmail.com"
] | nyorain@gmail.com |
a5698a833ff8a04bd07399fe5ee87e1146902886 | 8ff311c3226cdfc783f1cd5bd48f68021fd7a669 | /2017/2017070501_assets.cpp | 07895e19a7abf526aed4f0cca696c50e143c32f1 | [
"MIT"
] | permissive | maku693/daily-snippets | 9e958460532aff0ac40c49772646fe2bef5f5831 | 53e3a516eeb293b3c11055db1b87d54284e6ac52 | refs/heads/master | 2021-01-19T04:25:23.245479 | 2020-01-15T22:29:10 | 2020-01-15T22:29:10 | 87,369,916 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 956 | cpp | #include <array>
#include <cstddef>
#include <cstdint>
inline std::array<std::uint8_t, 4> toLE(std::uint32_t val)
{
return std::array<std::uint8_t, 4> {
static_cast<std::uint8_t>(val >> 0),
static_cast<std::uint8_t>(val >> 8),
static_cast<std::uint8_t>(val >> 16),
static_cast<std::uint8_t>(val >> 24)
};
}
inline std::uint32_t fromLE(std::array<std::uint8_t, 4> data)
{
return static_cast<std::uint32_t>(data.at(0) << 0) |
static_cast<std::uint32_t>(data.at(1) << 8) |
static_cast<std::uint32_t>(data.at(2) << 16) |
static_cast<std::uint32_t>(data.at(3) << 24);
}
template <std::size_t HeaderSize, std::size_t ContentsSize>
struct Library {
std::array<std::uint32_t, HeaderSize> offsets;
std::array<char, ContentSize> contents;
template <class T>
T getContentAtIndex(std::uint32_t i)
{
return contents.at(i);
}
};
struct Loader {
};
int main()
{
}
| [
"maku3ts@gmail.com"
] | maku3ts@gmail.com |
515455f665fb61faf33bbc4166db7e68d892aaf5 | 1144037869d6b9e304c7b4eb483d190b6505e643 | /playerT/StringConvertions.h | fd5bc18afb227e39eac1170662c3e51f7701c22c | [] | no_license | TravHSV/player | 0cafdf9c6f9c20dd62aa0bddf44af7157a97a3df | f982361acca8dd1d9a15e4293e10702222213c66 | refs/heads/master | 2022-02-26T09:32:58.705532 | 2014-11-04T09:58:37 | 2014-11-04T09:58:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,249 | h | #include "stdafx.h"
#include <string>
#pragma once
LPSTR Unicode2Ansi(LPCWSTR s);
LPSTR Unicode2UTF8(LPWSTR s);
LPWSTR Ansi2Unicode(LPSTR s);
LPWSTR UTF82Unicode(LPSTR s);
//-----------------------------------------
//read file with encode UTF8 or UTF16 or ANSI
//-----------------------------------------
enum ENCODETYPE
{
UNKNOW,
ANSI,
UTF8,
UTF16_big_endian,
UTF16_little_endian
};
ENCODETYPE TellEncodeType(BYTE* pBuf,int bufLen);
void CleanAfterFileCovert(BYTE* pBufOld,BYTE *pBufNew);
void CovertFileBuf2UTF16littleEndian(BYTE* pBuf,int bufLen,ENCODETYPE filetype,OUT TCHAR **pBufU,OUT int &filesizeAfterCovert);
int MyGetLine(TCHAR *pBuf,int bufLen,std::wstring &str);
int StringCmpNoCase(std::tstring a,std::tstring b);
int StrCmpIgnoreCaseAndSpace(std::tstring a,std::tstring b);
int hex2dec(char c);
void trimLeftAndRightSpace(std::tstring &str);
void TrimRightByNull(std::wstring &_str);
long Conv(int i) ;
void CreateQianQianCode(char *id,char *ar,char*ti,std::string &code);
std::string str2UnicodeCode(const WCHAR *c,int len);
LONG GetStrSizeX(HDC dc,TCHAR *str);
//void MakeShortString(HDC dc,TCHAR *str,long width);
//void DrawTriangleInRect(HDC dc,RECT &rc);
| [
"Administrator@c573b714-58c8-aa40-881b-c130d9d1abad"
] | Administrator@c573b714-58c8-aa40-881b-c130d9d1abad |
7ed79edc899322c16192e327df83cc970e64f209 | ac91d39e35a6667a26d52e8227a7969f81bcf5c6 | /singlethreadimpl.hpp | 6337c27c91c55766ebb81e0b09ba22f7188d8b18 | [
"MIT"
] | permissive | skdmno4/wavevizdumps | 0e03b1f827a0b7b8e60182d684f678d6f10f97ef | 7bfb17a2474d879a3216b928db93e7384fc45806 | refs/heads/master | 2021-08-30T05:02:00.928446 | 2017-12-03T07:12:46 | 2017-12-03T07:12:46 | 112,877,502 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,049 | hpp | #pragma once
#include "localtypes.h"
#include <cmath>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
const double PI = 3.14159265358979;
double eval(int x, int y, float xDel, float yDel, int t)
{
double phaseangle = xDel * x + yDel * y;
return sin(t + phaseangle);
}
void CalculateAndDump(Frame2d<double> *pFrame)
{
const int ht = pFrame->size();
const int wd = (*pFrame)[0].size();
const double xDel = 4*PI/wd;
const double yDel = 4*PI/ht;
cout << "Constants: " << xDel << ',' << yDel << '\n';
static int t = 0;
t++;
char flname[40];
sprintf(flname, "dump_%d.json",t);
fstream fs;
fs.open(flname, ios::out);
fs <<"{";
for (int y = 0; y < ht; y ++)
{
fs <<"{";
for (int x = 0; x < wd; x ++)
{
(*pFrame)[y][x] = eval(x, y, xDel, yDel, t);
fs << ' ' << (*pFrame)[y][x] << ',';
}
fs <<"}\n";
}
fs <<"}\n";
fs.close();
}
void ConvertFormats()
{
cout << "To be implemented\n";
}
| [
"noreply@github.com"
] | noreply@github.com |
d19fa02c4551087b4741017e633b77dc6795e84f | 0ba7b4d7c836ff7fefcc74240841fb8306164ce2 | /cc/google/fhir/r4/extensions.h | fcb8ac53db7c52c3bb4ccf1617d55dda36d86e8e | [
"Apache-2.0"
] | permissive | FHIR-CN/FhirProto | 8e862f3dc1fe23a2350bdae938c435b8af84b797 | f042f19de529ff42cc15a06f2cfcade502144037 | refs/heads/master | 2022-12-12T11:22:30.990554 | 2020-09-10T23:19:39 | 2020-09-11T17:31:48 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,060 | h | /*
* Copyright 2020 Google LLC
*
* 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 GOOGLE_FHIR_R4_EXTENSIONS_H_
#define GOOGLE_FHIR_R4_EXTENSIONS_H_
#include "google/protobuf/message.h"
#include "google/fhir/extensions.h"
#include "google/fhir/status/statusor.h"
#include "proto/r4/core/datatypes.pb.h"
namespace google {
namespace fhir {
namespace r4 {
// This adds all functions on extensions_lib, which work on any version, so that
// users don't need to care which functions are defined on the core extensions.h
// and can just import the r4 version
using namespace extensions_lib; // NOLINT
absl::Status ExtensionToMessage(const core::Extension& extension,
::google::protobuf::Message* message);
absl::Status ConvertToExtension(const ::google::protobuf::Message& message,
core::Extension* extension);
// Given a datatype message (E.g., String, Code, Boolean, etc.),
// finds the appropriate field on the target extension and sets it.
// Returns InvalidArgument if there's no matching oneof type on the extension
// for the message.
absl::Status SetDatatypeOnExtension(const ::google::protobuf::Message& message,
core::Extension* extension);
absl::Status ValueToMessage(
const ::google::fhir::r4::core::Extension& extension,
::google::protobuf::Message* message, const ::google::protobuf::FieldDescriptor* field);
} // namespace r4
} // namespace fhir
} // namespace google
#endif // GOOGLE_FHIR_R4_EXTENSIONS_H_
| [
"nickgeorge@google.com"
] | nickgeorge@google.com |
032c6b374f3184480eb3a6c5cafdf1d580061c5b | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/MuonSpectrometer/MuonValidation/MuonDQA/MuonRawDataMonitoring/TgcRawDataMonitoring/src/TgcLv1RawDataValAlg_TriggerTiming.cxx | 41c362c4078a812db43e4cd98fcb7747969ff302 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 50,423 | cxx | /*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Package: TgcLv1RawDataValAlg
// Authors: A.Ishikawa(Kobe) akimasa.ishikawa@cern.ch, M.King(Kobe) kingmgl@stu.kobe-u.ac.jp
// Original: Apr. 2008
// Modified: June 2011
//
// DESCRIPTION:
// Subject: TGCLV1-->Offline Muon Data Quality/
/////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include "GaudiKernel/MsgStream.h"
#include "GaudiKernel/AlgFactory.h"
#include "StoreGate/DataHandle.h"
// GeoModel
#include "MuonReadoutGeometry/MuonDetectorManager.h"
#include "MuonReadoutGeometry/TgcReadoutParams.h"
#include "MuonDQAUtils/MuonChamberNameConverter.h"
#include "MuonDQAUtils/MuonChambersRange.h"
#include "MuonDQAUtils/MuonCosmicSetup.h"
#include "MuonDQAUtils/MuonDQAHistMap.h"
#include "Identifier/Identifier.h"
#include "TgcRawDataMonitoring/TgcLv1RawDataValAlg.h"
#include "AthenaMonitoring/AthenaMonManager.h"
//for express menu
#include "TrigSteeringEvent/TrigOperationalInfo.h"
#include "TrigSteeringEvent/TrigOperationalInfoCollection.h"
#include <TH1F.h>
#include <TH2F.h>
#include <TH1.h>
#include <TH2.h>
#include <TMath.h>
#include <TF1.h>
#include <inttypes.h>
#include <sstream>
using namespace std;
///////////////////////////////////////////////////////////////////////////
// bookTimingHisto
///////////////////////////////////////////////////////////////////////////
StatusCode
TgcLv1RawDataValAlg::bookHistogramsTiming(){
StatusCode sc = StatusCode::SUCCESS;
///////////////////////////////////////////////////////////////////////////
// Make MonGroups for histogram booking paths
std::string m_generic_path_tgclv1 = "Muon/MuonRawDataMonitoring/TGCLV1";
MonGroup tgclv1_shift( this, m_generic_path_tgclv1+"/Global", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_shift_a( this, m_generic_path_tgclv1+"/TGCEA", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_shift_c( this, m_generic_path_tgclv1+"/TGCEC", run, ATTRIB_UNMANAGED );
MonGroup* tgclv1_shift_ac[2] = { &tgclv1_shift_a, &tgclv1_shift_c};
MonGroup tgclv1_expert( this, m_generic_path_tgclv1+"/Global", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_expert_a( this, m_generic_path_tgclv1+"/TGCEA", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_expert_c( this, m_generic_path_tgclv1+"/TGCEC", run, ATTRIB_UNMANAGED );
MonGroup* tgclv1_expert_ac[2] = { &tgclv1_expert_a, &tgclv1_expert_c};
MonGroup tgclv1_timing( this, m_generic_path_tgclv1+"/Global/Timing", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_timing_a( this, m_generic_path_tgclv1+"/TGCEA/Timing", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_timing_c( this, m_generic_path_tgclv1+"/TGCEC/Timing", run, ATTRIB_UNMANAGED );
MonGroup* tgclv1_timing_ac[2] = { &tgclv1_timing_a, &tgclv1_timing_c};
MonGroup tgclv1_timing_a_ES( this, m_generic_path_tgclv1+"/TGCEA/ES/Timing", run, ATTRIB_UNMANAGED );
MonGroup tgclv1_timing_c_ES( this, m_generic_path_tgclv1+"/TGCEC/ES/Timing", run, ATTRIB_UNMANAGED );
MonGroup* tgclv1_timing_ac_ES[2] = { &tgclv1_timing_a_ES, &tgclv1_timing_c_ES};
MonGroup tgclv1_timing_a_ES_GM( this, m_generic_path_tgclv1+"/TGCEA/ES/GM", run, ATTRIB_UNMANAGED, "", "weightedEff" );
MonGroup tgclv1_timing_c_ES_GM( this, m_generic_path_tgclv1+"/TGCEC/ES/GM", run, ATTRIB_UNMANAGED, "", "weightedEff");
MonGroup* tgclv1_timing_ac_ES_GM[2] = { &tgclv1_timing_a_ES_GM, &tgclv1_timing_c_ES_GM};
int k=0;
std::stringstream ss;
std::string side[2] ={"A","C"};
std::string triggertype[4] ={"_TGC_Triggered", "_RPC_Low_Triggered", "_RPC_High_Triggered", "_L1Calo_Triggered"};
std::string smuid[1] ={"_Muid"};
std::string schamberT3[6] ={"E1", "E2", "E3", "E4", "E5", "F"};
std::string sbc[3] ={"_{Prev}", "_{Curr}", "_{Next}"};
std::string lpt = "Low_Pt_";
std::string lpttiming = "Low_Pt_Timing";
std::string sl = "SL_";
std::string sltiming = "SL_Timing";
std::string slvslpttiming = "SL_Vs_Low_Pt_Timing";
std::string Sector = "_Sector";
std::string Layer = "_Layer";
std::string PT = "_PT";
std::string morethanpt1 = "_More_Than_PT1";
std::string lessthanpt2 = "_Less_Than_PT2";
///////////////////////////////////////////////////////////////////////////
// SL Timing histograms
for(int ac=0;ac<2;ac++){// side
/////////////////////////////////////
// SL Timing hists per side
// SL Timing hist
ss.str(""); ss << sltiming << "_" << side[ac];
tgclv1sltiming[ac] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltiming[ac]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1sltiming[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing hist for pT threshold > pT1
ss.str(""); ss << sltiming << morethanpt1 << "_" << side[ac];
tgclv1sltimingptcut[ac] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltimingptcut[ac]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1sltimingptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing hist for each pT threshold
for(int ipt=0;ipt<6;ipt++){
ss.str(""); ss << sltiming << PT << ipt+1 << "_" << side[ac];
tgclv1sltimingpt[ac][ipt] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltimingpt[ac][ipt]);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingpt[ac][ipt]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
}
/////////////////////////////////////
// SL Timing maps per side
// Timing maps show prev,curr,next stationEta (pcn3xeta6) vs stationPhi (phi48)
// SL Timing map
ss.str(""); ss << sltiming << "_Map_" << side[ac];
tgclv1sltimingmap[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1sltimingmap[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1sltimingmap[ac]->SetMinimum(0.0);
// SL Timing Current Fraction map
ss.str(""); ss << sl << "Timing_Fraction_Map_" << side[ac];
tgclv1slcurrentfractionmap[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1slcurrentfractionmap[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing map for pT threshold > pT1
ss.str(""); ss << sltiming << "_Map" << morethanpt1 << "_" << side[ac];
tgclv1sltimingmapptcut[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1sltimingmapptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1sltimingmapptcut[ac]->SetMinimum(0.0);
// SL Timing Current Fraction map for pT threshold > pT1
ss.str(""); ss << sl << "Timing_Fraction_Map" << morethanpt1 << side[ac];
tgclv1slcurrentfractionmapptcut[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1slcurrentfractionmapptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// Set Bin Labels for SL Timing maps
for(int pcn=0;pcn<3;pcn++){
for(int eta=0;eta<6;eta++){
tgclv1sltimingmap[ac] ->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1slcurrentfractionmap[ac]->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1sltimingmapptcut[ac] ->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1slcurrentfractionmapptcut[ac]->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
}// eta
}// pcn
k=1;
for(int sec=1;sec<=12;sec++){
for(int phi=0;phi<4;phi+=4){
ss.str(""); ss << side[ac];
if(sec<10)ss << "0";
ss << sec << "Ephi" << phi;
tgclv1sltimingmap[ac] ->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1slcurrentfractionmap[ac]->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1sltimingmapptcut[ac] ->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1slcurrentfractionmapptcut[ac]->GetYaxis()->SetBinLabel(k, ss.str().c_str());
}// phi
}// sector
/////////////////////////////////////
// SL Timing per sector
for(int isect=0;isect<12;isect++){// sector
// SL Timing hist
ss.str(""); ss << sltiming << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1sltimingsector[ac][isect] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingsector[ac][isect]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1sltimingsector[ac][isect]);
// SL Timing hist for pT threshold > pT1
ss.str(""); ss << sltiming << morethanpt1 << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1sltimingptcutsector[ac][isect] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingptcutsector[ac][isect]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1sltimingptcutsector[ac][isect]);
}// sector
/////////////////////////////////////
// SL Timing per trigger type
for(int itrig=0;itrig<4;itrig++){// trigger type
// SL Timing hist
ss.str(""); ss << sltiming << triggertype[itrig] << "_" << side[ac];
tgclv1sltimingtrg[ac][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltimingtrg[ac][itrig]);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1sltimingtrg[ac][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing hist for pT threshold > pT1
ss.str(""); ss << sltiming << morethanpt1 << triggertype[itrig] << "_" << side[ac];
tgclv1sltimingptcuttrg[ac][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltimingptcuttrg[ac][itrig]);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1sltimingptcuttrg[ac][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing hist for each pT threshold
for(int ipt=0;ipt<6;ipt++){// pT
ss.str(""); ss << sltiming << PT << ipt+1 << triggertype[itrig] << "_" << side[ac];
tgclv1sltimingpttrg[ac][ipt][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1sltimingpttrg[ac][ipt][itrig]);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingpttrg[ac][ipt][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
}// pT
}// trigger type
/////////////////////////////////////
// SL Timing per sector-trigger
for(int isect=0;isect<12;isect++){// sector
for(int itrig=0;itrig<4;itrig++){// trigger type
// SL Timing hist
ss.str(""); ss << sltiming << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1sltimingsectortrg[ac][isect][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1sltimingsectortrg[ac][isect][itrig]);
// SL Timing hist for pT threshold > pT1
ss.str(""); ss << sltiming << morethanpt1 << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
m_log << MSG::DEBUG << "histos for SL sector timing for pt>2" << endreq;
tgclv1sltimingptcutsectortrg[ac][isect][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1sltimingptcutsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1sltimingptcutsectortrg[ac][isect][itrig]);
}// trigger type
}// sector
/////////////////////////////////////
// SL Timing of associated offline muons
for(int imuid=0;imuid<m_nMuonAlgorithms;imuid++){// muonalg
// SL Timing hist
ss.str(""); ss << sltiming << smuid[imuid] << "_" << side[ac];
tgclv1sltimingtrack[ac][imuid] = new TH1F(ss.str().c_str(), ss.str().c_str(), 3, 0, 3 );
setTH1TitleLabelBCID(tgclv1sltimingtrack[ac][imuid]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1sltimingtrack[ac][imuid] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Timing hist for pT threshold > pT1
ss.str(""); ss << sltiming << morethanpt1 << smuid[imuid] << "_" << side[ac];
tgclv1sltimingptcuttrack[ac][imuid] = new TH1F(ss.str().c_str(), ss.str().c_str(), 3, 0, 3 );
setTH1TitleLabelBCID(tgclv1sltimingptcuttrack[ac][imuid]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1sltimingptcuttrack[ac][imuid] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
}// muonalg
}// side
///////////////////////////////////////////////////////////////////////////
// LpT Timing histograms
for(int ac=0;ac<2;ac++){// side
/////////////////////////////////////
// LpT Timing hists per side
// LpT Timing hist
ss.str(""); ss << lpttiming << "_" << side[ac];
tgclv1lpttiming[ac] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1lpttiming[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttiming[ac]);
// LpT Timing hist for pT threshold > pT1
ss.str(""); ss << lpttiming << morethanpt1 << "_" << side[ac];
tgclv1lpttimingptcut[ac] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lpttimingptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttimingptcut[ac]);
// LpT Timing hist for each pT threshold
for(int ipt=0;ipt<6;ipt++){
ss.str(""); ss << lpttiming << PT << ipt+1 << "_" << side[ac];
tgclv1lpttimingpt[ac][ipt] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingpt[ac][ipt]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingpt[ac][ipt]->SetMinimum(0.0);
setTH1TitleLabelBCID(tgclv1lpttimingpt[ac][ipt]);
}
/////////////////////////////////////
// LpT Timing maps per side
// Timing maps show prev,curr,next stationEta (pcn3xeta6) vs stationPhi (phi48)
// LpT Timing map
ss.str(""); ss << lpttiming << "_Map_" << side[ac];
tgclv1lpttimingmap[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lpttimingmap[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingmap[ac]->SetMinimum(0.0);
// LpT Timing Current Fraction map
ss.str(""); ss << lpt << "Timing_Fraction_Map_" << side[ac];
tgclv1lptcurrentfractionmap[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lptcurrentfractionmap[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Timing map for pT threshold > pT1
ss.str(""); ss << lpttiming << "_Map" << morethanpt1 << side[ac];
tgclv1lpttimingmapptcut[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lpttimingmapptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingmapptcut[ac]->SetMinimum(0.0);
// LpT Timing Current Fraction map for pT threshold > pT1
ss.str(""); ss << lpt << "Timing_Fraction_Map" << morethanpt1 << side[ac];
tgclv1lptcurrentfractionmapptcut[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 18, 0, 18, 48, 1 , 49);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lptcurrentfractionmapptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// Set Bin Labels for LpT Timing maps
for(int pcn=0;pcn<3;pcn++){//
for(int eta=0;eta<6;eta++){
tgclv1lpttimingmap[ac] ->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1lptcurrentfractionmap[ac]->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1lpttimingmapptcut[ac] ->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
tgclv1lptcurrentfractionmapptcut[ac]->GetXaxis()->SetBinLabel(pcn*6 + eta+1, (schamberT3[eta] + sbc[pcn]).c_str());
}// chambertype
}// pcn
k=1;
for(int sec=1;sec<=12;sec++){
for(int phi=0;phi<4;phi+=4){
ss.str(""); ss << side[ac];
if(sec<10)ss << "0";
ss << sec << "Ephi" << phi;
tgclv1lpttimingmap[ac] ->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1lptcurrentfractionmap[ac]->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1lpttimingmapptcut[ac] ->GetYaxis()->SetBinLabel(k, ss.str().c_str());
tgclv1lptcurrentfractionmapptcut[ac]->GetYaxis()->SetBinLabel(k, ss.str().c_str());
k+=4;
}// phi
}// sector
/////////////////////////////////////
// LpT Timing per sector
for(int k=0;k<12;k++){// sector
// LpT Timing hist
ss.str(""); ss << lpttiming << "_" << side[ac];
if(k+1<10)ss << "0";
ss << k+1;
tgclv1lpttimingsector[ac][k] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingsector[ac][k]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttimingsector[ac][k]);
// LpT Timing hist for pT threshold > pT1
m_log << MSG::DEBUG << "histos for LPT sector timing for pt>2" << endreq;
ss.str(""); ss << lpttiming << morethanpt1 << "_" << side[ac];
if(k+1<10)ss << "0";
ss << k+1;
tgclv1lpttimingptcutsector[ac][k] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingptcutsector[ac][k]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttimingptcutsector[ac][k]);
}// sector
/////////////////////////////////////
// LpT Timing per trigger type
for(int itrig=0;itrig<4;itrig++){// trigger type
// LpT Timing hist
ss.str(""); ss << lpttiming << triggertype[itrig] << "_" << side[ac];
tgclv1lpttimingtrg[ac][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1lpttimingtrg[ac][itrig]);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lpttimingtrg[ac][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingtrg[ac][itrig]->SetMinimum(0.0);
// LpT Timing hist for pT threshold > pT1
ss.str(""); ss << lpttiming << morethanpt1 << triggertype[itrig] << "_" << side[ac];
tgclv1lpttimingptcuttrg[ac][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1lpttimingptcuttrg[ac][itrig]);
if( ( tgclv1_expert_ac[ac]->regHist(tgclv1lpttimingptcuttrg[ac][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingptcuttrg[ac][itrig]->SetMinimum(0.0);
// LpT Timing hist for each pT threshold
for(int ipt=0;ipt<6;ipt++){
ss.str(""); ss << lpttiming << PT << ipt+1 << triggertype[itrig] << "_" << side[ac];
tgclv1lpttimingpttrg[ac][ipt][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
setTH1TitleLabelBCID(tgclv1lpttimingpttrg[ac][ipt][itrig]);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingpttrg[ac][ipt][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
tgclv1lpttimingpttrg[ac][ipt][itrig]->SetMinimum(0.0);
}// pT
}// trigger type
/////////////////////////////////////
// LpT Timing per sector-trigger
for(int isect=0;isect<12;isect++){// sector
for(int itrig=0;itrig<4;itrig++){// trigger type
// LpT Timing hist
ss.str(""); ss << lpttiming << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1lpttimingsectortrg[ac][isect][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttimingsectortrg[ac][isect][itrig]);
// LpT Timing hist for pT threshold > pT1
ss.str(""); ss << lpttiming << morethanpt1 << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1lpttimingptcutsectortrg[ac][isect][itrig] = new TH1F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1lpttimingptcutsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1lpttimingptcutsectortrg[ac][isect][itrig]);
}// trigger type
}// sector
/////////////////////////////////////
// LpT Timing of associated offline muons
for(int imuid=0;imuid<m_nMuonAlgorithms;imuid++){// muonalg
// LpT Timing hist
ss.str(""); ss << lpttiming << smuid[imuid] << "_" << side[ac];
tgclv1lpttimingtrack[ac][imuid] = new TH1F(ss.str().c_str(), ss.str().c_str(), 3, 0, 3 );
setTH1TitleLabelBCID(tgclv1lpttimingtrack[ac][imuid]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1lpttimingtrack[ac][imuid] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Timing hist for pT threshold > pT1
ss.str(""); ss << lpttiming << morethanpt1 << smuid[imuid] << "_" << side[ac];
tgclv1lpttimingptcuttrack[ac][imuid] = new TH1F(ss.str().c_str(), ss.str().c_str(), 3, 0, 3 );
setTH1TitleLabelBCID(tgclv1lpttimingptcuttrack[ac][imuid]);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1lpttimingptcuttrack[ac][imuid] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
}// muonalg
}// side
///////////////////////////////////////////////////////////////////////////
// SL vs LpT Timings
for(int ac=0;ac<2;ac++){// side
/////////////////////////////////////
// SL Timing hists per side
// SL vs LpT Timing hist
ss.str(""); ss << slvslpttiming << "_" << side[ac];
tgclv1slvslpttiming[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1slvslpttiming[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH2TitleLabelBCID(tgclv1slvslpttiming[ac]);
// SL vs LpT Timing hists for pT threshold > pT1
ss.str(""); ss << slvslpttiming << morethanpt1 << "_" << side[ac];
tgclv1slvslpttimingptcut[ac] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_shift_ac[ac]->regHist(tgclv1slvslpttimingptcut[ac]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH2TitleLabelBCID(tgclv1slvslpttimingptcut[ac]);
/////////////////////////////////////
// SL Timing per sector
for(int isect=0;isect<12;isect++){// sector
// SL vs LpT Timing matrix
ss.str(""); ss << slvslpttiming << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1slvslpttimingsector[ac][isect] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1slvslpttimingsector[ac][isect]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1slvslpttimingsector[ac][isect]);
// SL vs LpT Timing matrix for pT threshold > pT1
ss.str(""); ss << slvslpttiming << morethanpt1 << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1slvslpttimingptcutsector[ac][isect] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1slvslpttimingptcutsector[ac][isect]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1slvslpttimingptcutsector[ac][isect]);
}// sector
/////////////////////////////////////
// SL Timing per sector-trigger
for(int isect=0;isect<12;isect++){// sector
for( int itrig = 0 ; itrig < 4; itrig ++){// trigger type
// SL vs Lpt Timing matrix
ss.str(""); ss << slvslpttiming << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1slvslpttimingsectortrg[ac][isect][itrig] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1slvslpttimingsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1slvslpttimingsectortrg[ac][isect][itrig]);
//SL vs Lpt Timing matrix for pT threshold > pT1
ss.str(""); ss << slvslpttiming << morethanpt1 << triggertype[itrig] << "_" << side[ac];
if(isect+1<10)ss << "0";
ss << isect+1;
tgclv1slvslpttimingptcutsectortrg[ac][isect][itrig] = new TH2F(ss.str().c_str(),ss.str().c_str(), 3, 0, 3, 3, 0, 3);
if( ( tgclv1_timing_ac[ac]->regHist(tgclv1slvslpttimingptcutsectortrg[ac][isect][itrig]) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
setTH1TitleLabelBCID(tgclv1slvslpttimingptcutsectortrg[ac][isect][itrig]);
}//trigger type
}//sector
}// ac
///////////////////////////////////////////////////////////////////////////
// Express Stream histograms
// Timing, Associated with Track
for(int ac=0;ac<2;ac++){// side
// SL Sector profile of Current Timing fraction
ss.str(""); ss << "ES_" << sltiming << "_" << side[ac];
tgclv1_SL_trigger_timing_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Current Fraction").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_SL_trigger_timing_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Sector profile of Current Timing fraction GM
ss.str(""); ss << "ES_GM_" << sltiming << "_" << side[ac];
tgclv1_SL_trigger_timing_ES_GM[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Current Fraction").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES_GM[ac]->regHist( tgclv1_SL_trigger_timing_ES_GM[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Sector profile of Current Timing fraction Numerator
ss.str(""); ss << "ES_" << sltiming << "_" << side[ac] << "_Numerator";
tgclv1_SL_trigger_timing_num_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Entry").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_SL_trigger_timing_num_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// SL Sector profile of Current Timing fraction Denominator
ss.str(""); ss << "ES_" << sltiming << "_" << side[ac] << "_Denominator";
tgclv1_SL_trigger_timing_denom_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Entry").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_SL_trigger_timing_denom_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Sector profile of Current Timing fraction
ss.str(""); ss << "ES_" << lpttiming << "_" << side[ac];
tgclv1_LPT_trigger_timing_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Current Fraction").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_LPT_trigger_timing_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Sector profile of Current Timing fraction GM
ss.str(""); ss << "ES_GM_" << lpttiming << "_" << side[ac];
tgclv1_LPT_trigger_timing_ES_GM[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Current Fraction").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES_GM[ac]->regHist( tgclv1_LPT_trigger_timing_ES_GM[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Sector profile of Current Timing fraction Numerator
ss.str(""); ss << "ES_" << lpttiming << "_" << side[ac] << "_Numerator";
tgclv1_LPT_trigger_timing_num_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Entry").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_LPT_trigger_timing_num_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// LpT Sector profile of Current Timing fraction Denominator
ss.str(""); ss << "ES_" << lpttiming << "_" << side[ac] << "_Denominator";
tgclv1_LPT_trigger_timing_denom_ES[ac] = new TH1F(ss.str().c_str(), ( ss.str() + ";;Entry").c_str(), 12, 0, 12);
if( ( tgclv1_timing_ac_ES[ac]->regHist( tgclv1_LPT_trigger_timing_denom_ES[ac] ) ).isFailure() ){
m_log << MSG::FATAL << ss.str() << " Failed to register histogram " << endreq;
return StatusCode::FAILURE;
}
// Set Bin Labels for Sector profiles
for( int isect=0 ; isect<12 ; isect++ ){// sector
ss.str(""); ss << side[ac] ;
if( isect<9 ) ss<< "0";
ss << isect + 1 ;
tgclv1_SL_trigger_timing_ES[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_SL_trigger_timing_num_ES[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_SL_trigger_timing_denom_ES[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_SL_trigger_timing_ES_GM[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_LPT_trigger_timing_ES[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_LPT_trigger_timing_num_ES[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_LPT_trigger_timing_denom_ES[ac]->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
tgclv1_LPT_trigger_timing_ES_GM[ac] ->GetXaxis()->SetBinLabel(isect+1, ss.str().c_str());
}// sector
}// side
// Express Stream end
return sc;
}
///////////////////////////////////////////////////////////////////////////
// fillTriggerTiming
///////////////////////////////////////////////////////////////////////////
void
TgcLv1RawDataValAlg::fillTriggerTiming(int ptcut){
//fillTriggerTiming0(ptcut);//multiple triggers from TGC is accepted
fillTriggerTiming1(ptcut);//only single trigger from TGC is accepted
}
///////////////////////////////////////////////////////////////////////////
// fillTriggerTiming0
///////////////////////////////////////////////////////////////////////////
// Accepts multiple TGC triggers
void
TgcLv1RawDataValAlg::fillTriggerTiming0(int ptcut){
for(int ac=0;ac<2;ac++){// side
for(int eta=0;eta<6;eta++){// stationEta
// Get Forward/Endcap Index
int ef=0;
if(eta!=0)ef=1;
for(int phi48=0;phi48<48;phi48++){// stationPhi
// Get sector index and phi map index
int sect=phi2sector(phi48, ef);//[0:11]
int phi = phi48+2;// [2:49] shifted to align with sector acis
if(phi>47) phi-=48;// [0:47]
///////////////////////////////////////////////////////////////////////////
// Fill SL trigger histograms
// Initialize SL Bunch Crossing ID variables
int SLBC = -1;
int SLBCpt = -1;
// Select earliest SL trigger in this chamber
if (m_maxSLtrigger[ac][eta][phi48][PREV]>0) SLBC = PREV;
else if (m_maxSLtrigger[ac][eta][phi48][CURR]>0) SLBC = CURR;
else if (m_maxSLtrigger[ac][eta][phi48][NEXT]>0) SLBC = NEXT;
// Check that SL trigger exists
if(SLBC>-1){
// Select earliest SL trigger over the ptcut in this chamber
if (m_maxSLtrigger[ac][eta][phi48][PREV]>ptcut) SLBCpt = PREV;
else if (m_maxSLtrigger[ac][eta][phi48][CURR]>ptcut) SLBCpt = CURR;
else if (m_maxSLtrigger[ac][eta][phi48][NEXT]>ptcut) SLBCpt = NEXT;
// Fill no-ptcut timing histograms
tgclv1sltiming[ac] ->Fill(SLBC);
tgclv1sltimingsector[ac][sect]->Fill(SLBC);
// Fill ptcut timing histograms
if(SLBCpt>ptcut){
tgclv1sltimingptcut[ac] ->Fill(SLBCpt);
tgclv1sltimingptcutsector[ac][sect]->Fill(SLBCpt);
// not monitor these profiles at GM
if( m_environment != AthenaMonManager::online )
tgclv1sltimingptcutlowstat[ac]->Fill(SLBCpt);
}
}
///////////////////////////////////////////////////////////////////////////
// Fill LpT trigger histograms
// Initialize LpT Bunch Crossing ID variables
int LptBC = -1;
// Select earliest LpT trigger for which both a wire and a strip trigger exist
if (m_hasLpTtrigger[0][ac][eta][phi48][PREV]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][PREV]==true) LptBC = PREV;
else if(m_hasLpTtrigger[0][ac][eta][phi48][CURR]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][CURR]==true) LptBC = CURR;
else if(m_hasLpTtrigger[0][ac][eta][phi48][NEXT]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][NEXT]==true) LptBC = NEXT;
// Get eta&BCID index for filling maps
int etaBCLpt = eta + LptBC*6;
// Check that LpT trigger exists
if(LptBC>-1){
// Fill timing histograms
tgclv1lpttiming[ac] ->Fill(LptBC);
tgclv1lpttimingsector[ac][sect]->Fill(LptBC);
// Fill timing maps
tgclv1lpttimingmap[ac]->Fill(etaBCLpt, phi+1);
// Fill ptcut timing histograms
if(SLBCpt>ptcut){
tgclv1lpttimingptcut[ac] ->Fill(LptBC);
tgclv1lpttimingptcutsector[ac][sect]->Fill(LptBC);
tgclv1lpttimingmapptcut[ac] ->Fill(LptBC, phi+1);
}
}
///////////////////////////////////////////////////////////////////////////
// Fill SL trigger vs LpT trigger histograms
if((LptBC>-1)&&(SLBC>-1)){
tgclv1slvslpttiming[ac] ->Fill(SLBC, LptBC);
tgclv1slvslpttimingsector[ac][sect]->Fill(SLBC, LptBC);
if(SLBCpt>ptcut){
tgclv1slvslpttimingptcut[ac] ->Fill(SLBCpt, LptBC);
tgclv1slvslpttimingptcutsector[ac][sect]->Fill(SLBCpt, LptBC);
}
}
}// stationPhi
}// stationEta
}// ac
}// EOF
///////////////////////////////////////////////////////////////////////////
// fillTriggerTiming1
///////////////////////////////////////////////////////////////////////////
// Accepts earliest SL triggers only
void
TgcLv1RawDataValAlg::fillTriggerTiming1(int ptcut){//only the earlest triggers in TGC are accepted
// Check that a trigger was detected
if(m_earliestTrigger<0)return;
// Initialize SL Bunch Crossing ID and pT variables
int SLBC = -1;
int SLpt = -1;
for(int ac=0;ac<2;ac++){// side
for(int eta=0;eta<6;eta++){// stationEta
// Get Forward/Endcap Index
int ef=0;
if(eta!=0)ef=1;
for(int phi48=0;phi48<48;phi48++){// stationPhi
// Only run if SL trigger exists at earliest detected timing
if(m_maxSLtrigger[ac][eta][phi48][m_earliestTrigger]>0){
// Get sector index and phi map index
int sect=phi2sector(phi48, ef);//[0:11]
int phi = phi48+2;// [2:49] shifted to align with sector acis
if(phi>47) phi-=48;// [0:47]
///////////////////////////////////////////////////////////////////////////
// Fill SL trigger histograms
// Get SL Bunch Crossing ID and variables
SLpt = m_maxSLtrigger[ac][eta][phi48][m_earliestTrigger];
SLBC = m_earliestTrigger;
// Get eta&BCID and phi bin indexes for filling maps
int etaBCSL = (5 - eta) + SLBC*6;
// Fill timing histograms
tgclv1sltiming[ac] ->Fill(SLBC);
tgclv1sltimingpt[ac][SLpt-1] ->Fill(SLBC);
tgclv1sltimingsector[ac][sect]->Fill(SLBC);
// Fill timing maps
tgclv1sltimingmap[ac]->Fill(etaBCSL, phi+1);
// Fill timing histograms for different trigger types
for(int trg=0;trg<4;trg++){
if(m_L1TriggerType[trg]>0 && SLpt>0){
tgclv1sltimingtrg[ac][trg] ->Fill(SLBC);
tgclv1sltimingpttrg[ac][SLpt-1][trg] ->Fill(SLBC);
tgclv1sltimingsectortrg[ac][sect][trg]->Fill(SLBC);
}
}
// Fill ptcut timing histograms
if(SLpt>ptcut){
tgclv1sltimingptcut[ac] ->Fill(SLBC);
tgclv1sltimingptcutsector[ac][sect]->Fill(SLBC);
tgclv1sltimingmapptcut[ac] ->Fill(etaBCSL, phi+1);
for(int trg=0;trg<4;trg++){
if(m_L1TriggerType[trg]>0){
tgclv1sltimingptcuttrg[ac][trg] ->Fill(SLBC);
tgclv1sltimingptcutsectortrg[ac][sect][trg]->Fill(SLBC);
}
}
// not monitor these profiles at GM
if( m_environment != AthenaMonManager::online )
tgclv1sltimingptcutlowstat[ac] ->Fill(SLBC);
}
///////////////////////////////////////////////////////////////////////////
// Fill LpT trigger histograms
// Initialize LpT Bunch Crossing ID variables
int LptBC = -1;
// Select latest LpT trigger for which both a wire and a strip trigger exist
if (m_hasLpTtrigger[0][ac][eta][phi48][NEXT]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][NEXT]==true) LptBC = NEXT;
else if(m_hasLpTtrigger[0][ac][eta][phi48][CURR]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][CURR]==true) LptBC = CURR;
else if(m_hasLpTtrigger[0][ac][eta][phi48][PREV]==true &&
m_hasLpTtrigger[1][ac][eta][phi48][PREV]==true) LptBC = PREV;
// Check that LpT trigger exists
if(LptBC>-1){
// Get eta&BCIDbin index for filling maps
int etaBCLpt = eta + LptBC * 6;
// Fill timing histograms
tgclv1lpttiming[ac] ->Fill(LptBC);
tgclv1lpttimingpt[ac][SLpt-1] ->Fill(LptBC);
tgclv1lpttimingsector[ac][sect]->Fill(LptBC);
// Fill timing maps
tgclv1lpttimingmap[ac]->Fill(etaBCLpt, phi+1);
// Fill timing histograms for different trigger types
for(int trg=0;trg<4;trg++){
if(m_L1TriggerType[trg]>0){
tgclv1lpttimingtrg[ac][trg] ->Fill(LptBC);
tgclv1lpttimingpttrg[ac][SLpt-1][trg] ->Fill(LptBC);
tgclv1lpttimingsectortrg[ac][sect][trg]->Fill(LptBC);
}
}
// Fill ptcut timing histograms
if(SLpt>ptcut){
tgclv1lpttimingptcut[ac] ->Fill(LptBC);
tgclv1lpttimingptcutsector[ac][sect]->Fill(LptBC);
tgclv1lpttimingmapptcut[ac] ->Fill(etaBCLpt, phi+1);
for(int trg=0;trg<4;trg++){
if(m_L1TriggerType[trg]>0){
tgclv1lpttimingptcuttrg[ac][trg] ->Fill(LptBC);
tgclv1lpttimingptcutsectortrg[ac][sect][trg]->Fill(LptBC);
}
}
}
}
///////////////////////////////////////////////////////////////////////////
// Fill SL trigger vs LpT trigger histograms
if(LptBC>-1){
tgclv1slvslpttiming[ac] ->Fill(SLBC, LptBC);
tgclv1slvslpttimingsector[ac][sect]->Fill(SLBC, LptBC);
if(SLpt>ptcut){
tgclv1slvslpttimingptcut[ac] ->Fill(SLBC, LptBC);
tgclv1slvslpttimingptcutsector[ac][sect]->Fill(SLBC, LptBC);
}
}
}// SL trigger for earliest timing
}// stationPhi
}// stationEta
}// ac
}// EOF
///////////////////////////////////////////////////////////////////////////
// fillTriggerTimingAssociatedWithTrack
///////////////////////////////////////////////////////////////////////////
void
TgcLv1RawDataValAlg::fillTriggerTimingAssociatedWithTrack( int ms,// 0:Muid 1:Staco
vector<float>* mu_pt, vector<float>* mu_eta,
vector<float>* mu_phi,vector<float>* mu_q ){
// Get/Set vector size and cut variables
int osize = mu_pt->size();
// Skip Event if any Offline Muons were found close to each other
for(int o1 = 0 ; o1 < osize ; o1++){
for(int o2 = o1+1 ; o2 < osize ; o2++){
float eta1 = mu_eta->at(o1);
float phi1 = mu_phi->at(o1);
float eta2 = mu_eta->at(o2);
float phi2 = mu_phi->at(o2);
float trackdr = deltaR(eta1, phi1, eta2, phi2);
if(trackdr < 0.8 ) return;
}
}
// Loop over Offline Muon vectors
for(int o = 0 ; o < osize ; o++ ){
// Get variables
float opt = mu_pt->at(o)/CLHEP::GeV;
float oeta = mu_eta->at(o);
float ophi = mu_phi->at(o);
float oq = mu_q->at(o);
if( fabs(opt) > 50. ) opt = 50.1 * oq;
// Get side index
int ac = (oeta<0);
// Initialise SL variables
int slpt=-1;
int sltidw=-1;
int sltids=-1;
bool slisAside=false;
bool slisForward=false;
int slphi48=-1;
for(int pcn=0;pcn<3;pcn++){
float deltarmin=1.;
int tptmin=-1;
int tsize = m_sl_pt[pcn].size();
for(int t=0;t<tsize;t++){
int tpt = m_sl_pt[pcn].at(t);
float teta = m_sl_eta[pcn].at(t);
float tphi = m_sl_phi[pcn].at(t);
int tidw = m_sl_tidw[pcn].at(t);
int tids = m_sl_tids[pcn].at(t);
bool isAside = m_sl_isAside[pcn].at(t);
bool isForward = m_sl_isForward[pcn].at(t);
int phi48 = m_sl_phi48[pcn].at(t);
if(oeta*teta<0.) continue;
float deltar = deltaR( oeta, ophi, teta, tphi );
if(deltar>1.) continue;
//select lowest dr trigger
if(deltar<deltarmin){
deltarmin=deltar;
tptmin=tpt;
if(slpt<tpt){
slpt=tpt;
sltidw=tidw;
sltids=tids;
slisAside=isAside;
slisForward=isForward;
slphi48=phi48;
}
}
}//trigger
//fill SL timing
if(tptmin!=-1){
if(m_debuglevel ) m_log << "fill triggertiming " <<ac <<" " << ms << " " << pcn << endreq;
tgclv1sltimingtrack[ac][ms]->Fill(pcn);
if( tptmin > 1 )
tgclv1sltimingptcuttrack[ac][ms]->Fill(pcn);
if( m_found_express_stream && m_found_nonmuon_express_chain ){
int sect12=phi2sector(slphi48, !slisForward);//[0:11]
tgclv1_SL_trigger_timing_denom_ES[ac]->Fill( sect12 );
if( pcn == 1 )
tgclv1_SL_trigger_timing_num_ES[ac]->Fill( sect12 );
}
}
}//pcn
//LPT timing
// This block fills tgclv1pttimingtrack(cuttrack) histogram(s)
bool lptflag=false;
if(slpt>=0) {
for(int pcn=2;pcn>-1;pcn--){
// Loop Wire LpT Trigger Vectors
for(int lptw=0;lptw<(int) m_lpt_delta[0][pcn].size();lptw++){
// Get Wire Low pT Variables
int tidlptw = m_lpt_tid[0][pcn].at(lptw);
int isAsidelptw = m_lpt_isAside[0][pcn].at(lptw);
int isForwardlptw = m_lpt_isForward[0][pcn].at(lptw);
int phi48lptw = m_lpt_phi48[0][pcn].at(lptw);
// Check LpTwire is the same tracklet as the SL
if( tidlptw != sltidw ||
isAsidelptw != slisAside ||
isForwardlptw != slisForward ||
phi48lptw != slphi48 ) continue ;
// Loop Strip LpT Trigger Vectors
for(int lpts=0;lpts<(int) m_lpt_delta[1][pcn].size();lpts++ ){
// Get Strip Low pT Variables
int tidlpts = m_lpt_tid[1][pcn].at(lpts);
int isAsidelpts = m_lpt_isAside[1][pcn].at(lpts);
int isForwardlpts = m_lpt_isForward[1][pcn].at(lpts);
int phi48lpts = m_lpt_phi48[1][pcn].at(lpts);
// Check LpTstrip is the same tracklet as the SL
if( tidlpts != sltids ||
isAsidelpts != slisAside ||
isForwardlpts != slisForward ||
phi48lpts != slphi48 ) continue ;
// Fill LpT Track Timing Histograms
if(m_debuglevel ) m_log << "fill triggertiming " <<ac <<" " << ms << " " << pcn << endreq;
tgclv1lpttimingtrack[ac][ms]->Fill(pcn);
if( slpt > 1 )
tgclv1lpttimingptcuttrack[ac][ms]->Fill(pcn);
// Fill Express Stream, "Current Fraction" histograms
if(m_found_express_stream&&m_found_nonmuon_express_chain){
int sect12=phi2sector(slphi48, !slisForward);//[0:11]
tgclv1_LPT_trigger_timing_denom_ES[ac]->Fill( sect12 );
if( pcn == 1 )
tgclv1_LPT_trigger_timing_num_ES[ac]->Fill( sect12 );
}
lptflag=true;
break;
}// Strip LpT strip
if(lptflag==true)break;
}// Wire LpT
if(lptflag==true)break;
}// pcn
}// SLpT
}// Offline
}// EOF fillTriggerTimingAssociatedWithTrack
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
c74155a947bce20c39b6f0596d35cd05a37c50b3 | 7b980be3e3108ab637b20d955884ee383c7f6c82 | /FGPrototype/BoneAnimation.h | 83d48e567b006d5069377dce1a479b4aab7c6238 | [
"MIT"
] | permissive | a-roy/FGPrototype | eb25b0dc249fecf1a14a3dfc6015a9d959e7f440 | f7d0b29b80200eb1f3fc997d6e7fd33898aa4a0a | refs/heads/master | 2021-01-19T00:46:11.119265 | 2017-04-05T11:58:32 | 2017-04-05T11:58:32 | 87,206,417 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,177 | h | //! \file
//! BoneAnimation, KeyFrame class declarations
#pragma once
#define GLM_FORCE_RADIANS
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <glm/gtx/transform.hpp>
#include <vector>
namespace gfx
{
template<typename T>
struct KeyFrame
{
int Time;
T Value;
};
//! Describes a full animation for a single bone.
class BoneAnimation
{
public:
//! Keyframes indicating bone scaling
//!
//! \warning Key containers should always be sorted in ascending order with no duplicate times.
std::vector<KeyFrame<glm::vec3> > ScaleKeys;
//! Keyframes indicating bone rotation
//!
//! \copydetails ::ScaleKeys
std::vector<KeyFrame<glm::quat> > RotateKeys;
//! Keyframes indicating bone translation
//!
//! \copydetails ::ScaleKeys
std::vector<KeyFrame<glm::vec3> > TranslateKeys;
//!
void Interpolate(
int time,
glm::vec3 *scale, glm::quat *rotate, glm::vec3 *trans) const;
//! Interpolates key frames to a transformation matrix for a given frame.
//!
//! Requires all key frames to be sorted.
glm::mat4 Interpolate(int time) const;
//! Interpolates a key frame between two animations.
//!
//! If the new animation has already reached a nonzero key in any sub-channel, it will simply
//! interpolate with itself.
static glm::mat4 Interpolate(const BoneAnimation* prevAnim, int prevTime, const BoneAnimation* newAnim, int newTime);
private:
//! Returns the index of the lower or upper bound of the searched time.
//!
//! \param keys The vector to search, which must be sorted.
//! \param time The frame to search for.
template<typename T>
static int BinarySearch(const std::vector<KeyFrame<T> >& keys, int time);
//! Finds the first nonzero time of a key frame in an animation sub-channel.
//!
//! \param keys
//! \returns The index of a key frame, or -1 if not found.
template<typename T>
static int FirstNonzeroKey(const std::vector<KeyFrame<T> >& keys);
static glm::vec3 Lerp(const std::vector<KeyFrame<glm::vec3> >& keys, int time);
static glm::quat Slerp(const std::vector<KeyFrame<glm::quat> >& keys, int time);
};
typedef std::vector<BoneAnimation> Animation;
} | [
"roy.aneesh@gmail.com"
] | roy.aneesh@gmail.com |
39a04f26aa7688c4dbc1fd3964b343bd5b4c1e4e | df56c3d9f44132d636c0cef1b70e40034ff09022 | /networksecurity/tlsprovider/Test/tlstest2/decryptstep.cpp | 53af01487f078e23eccf4f7863aa33747e9ece67 | [] | no_license | SymbianSource/oss.FCL.sf.os.networkingsrv | e6317d7ee0ebae163572127269c6cf40b98e3e1c | b283ce17f27f4a95f37cdb38c6ce79d38ae6ebf9 | refs/heads/master | 2021-01-12T11:29:50.765762 | 2010-10-14T06:50:50 | 2010-10-14T06:50:50 | 72,938,071 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 8,569 | cpp | // Copyright (c) 2006-2009 Nokia Corporation and/or its subsidiary(-ies).
// All rights reserved.
// This component and the accompanying materials are made available
// under the terms of "Eclipse Public License v1.0"
// which accompanies this distribution, and is available
// at the URL "http://www.eclipse.org/legal/epl-v10.html".
//
// Initial Contributors:
// Nokia Corporation - initial contribution.
//
// Contributors:
//
// Description:
//
/**
@file decryptstep.cpp
@internalTechnology
*/
#include "decryptstep.h"
#include <tlsprovinterface.h>
#include <x509cert.h>
#include <asymmetric.h>
#include <asymmetrickeys.h>
#include <asnpkcs.h>
CDecryptStep::CDecryptStep()
{
SetTestStepName(KDecryptStep);
}
TVerdict CDecryptStep::doTestStepPreambleL()
{
ConstructL();
CTlsCryptoAttributes* atts = Provider()->Attributes();
// Reads PSK values if included in INI file.
ReadPskToBeUsedL();
// Reads if NULL ciphers suites are to be allowed from INI file.
ReadUseNullCipher();
// read the "server" random
HBufC8* random = ServerRandomL();
atts->iMasterSecretInput.iServerRandom.Copy(*random);
delete random;
// and the client random
random = ClientRandomL();
atts->iMasterSecretInput.iClientRandom.Copy(*random);
delete random;
// we only support null compression...
atts->iCompressionMethod = ENullCompression;
// read the cipher suite for the test
atts->iCurrentCipherSuite = CipherSuiteL();
// read the protocol version
TTLSProtocolVersion version = ProtocolVersionL();
atts->iNegotiatedProtocol = version;
atts->iProposedProtocol = version;
// set the session ID and "server" name (localhost)
atts->iSessionNameAndID.iSessionId = SessionId();
atts->iSessionNameAndID.iServerName.iAddress = KLocalHost;
atts->iSessionNameAndID.iServerName.iPort = 443;
atts->idomainName.Copy(DomainNameL());
// If cipher suite under test is uses PSK (Pre Shared Key)
if(UsePsk())
{
// Populates values for PSK
atts->iPskConfigured = true;
atts->iPublicKeyParams->iKeyType = EPsk;
atts->iPublicKeyParams->iValue4 = PskIdentity();
atts->iPublicKeyParams->iValue5 = PskKey();
}
else
{
// If cipher suite under test is NOT PSK
TRAPD(err, ReadDHParamsL());
if (err == KErrNone)
{
atts->iPublicKeyParams->iKeyType = EDHE;
// The params are:
// 1 - Prime
// 2 - Generator
// 3 - generator ^ random mod prime
atts->iPublicKeyParams->iValue1 = Prime().BufferLC();
CleanupStack::Pop(atts->iPublicKeyParams->iValue1);
atts->iPublicKeyParams->iValue2 = Generator().BufferLC();
CleanupStack::Pop(atts->iPublicKeyParams->iValue2);
atts->iPublicKeyParams->iValue3 = KeyPair()->PublicKey().X().BufferLC();
CleanupStack::Pop(atts->iPublicKeyParams->iValue3);
}
}
// No client authentication or dialogs for this test, please
atts->iClientAuthenticate = EFalse;
atts->iDialogNonAttendedMode = ETrue;
if(UseNullCipher())
{
// Enables null cipher by setting appropiate parameter
atts->iAllowNullCipherSuites = ETrue;
}
return EPass;
}
TVerdict CDecryptStep::doTestStepL()
{
INFO_PRINTF1(_L("Calling TLS Provider to fetch cipher suites."));
// first we have to retrieve the available cipher suites
TInt err = GetCipherSuitesL();
if (err != KErrNone)
{
INFO_PRINTF2(_L("Failed! Cannot retrieve supported cipher suites! (Error %d)"),
err);
SetTestStepResult(EFail);
return TestStepResult();
}
// verifies certificate if is not a PSK cipher suite
if( !UsePsk() )
{
// we have to verify the server certificate, to supply the certificate
// and its parameters to the TLS provider.
INFO_PRINTF1(_L("Calling TLS Provider to verify server certificate."));
CX509Certificate* cert = NULL;
err = VerifyServerCertificateL(cert);
delete cert;
// make sure it completed sucessfully.
if (err != KErrNone)
{
INFO_PRINTF2(_L("Failed! Server Certificate did not verify correctly! (Error %d)"),
err);
SetTestStepResult(EFail);
return TestStepResult();
}
}
INFO_PRINTF1(_L("Creating TLS Session."));
// now, create a session with the parameters set in the preamble
err = CreateSessionL();
// ensure we succeeded
if (err != KErrNone)
{
INFO_PRINTF2(_L("Failed! Create Session failed! (Error %d)"), err);
SetTestStepResult(EFail);
return TestStepResult();
}
INFO_PRINTF1(_L("Calling TLS session key exchange."));
HBufC8* keyExMessage = NULL;
err = ClientKeyExchange(keyExMessage);
if (err != KErrNone)
{
INFO_PRINTF2(_L("Failed! Key exchange failed! (Error %d)"), err);
delete keyExMessage;
SetTestStepResult(EFail);
return TestStepResult();
}
INFO_PRINTF1(_L("Deriving premaster secret."));
// derive the premaster secret from the key exchange method
CleanupStack::PushL(keyExMessage);
HBufC8* premaster = DerivePreMasterSecretL(*keyExMessage);
CleanupStack::PopAndDestroy(keyExMessage);
INFO_PRINTF1(_L("Deriving master secret."));
// compute the master secret from the premaster.
CleanupStack::PushL(premaster);
HBufC8* master = ComputeMasterSecretL(*premaster);
CleanupStack::PopAndDestroy(premaster);
delete master;
// Do the main meat of the test
VerifyDecryptionL();
return TestStepResult();
}
void CDecryptStep::VerifyDecryptionL()
{
TInt expectedError(KErrNone);
// Read in the parameters we'll use to configure this step...
// Record Size - The size of the record to encrypt
TInt recordSize(0);
if (!GetIntFromConfig(ConfigSection(), KDRecordSize, recordSize))
{
INFO_PRINTF1(_L("Failed! Could not read test record size from config!"));
SetTestStepResult(EFail);
return;
}
// Record type - The type to record in the MAC
TInt recordTypeInt(0);
if (!GetIntFromConfig(ConfigSection(), KDRecordType, recordTypeInt))
{
INFO_PRINTF1(_L("Failed! Could not read test type size from config!"));
SetTestStepResult(EFail);
return;
}
TRecordProtocol recordType = (TRecordProtocol)recordTypeInt; // cast it to the enum.
// Sequence number - The (fake) sequence number this packet is supposed to have arrived in
TInt sequenceNumber(0);
if (!GetIntFromConfig(ConfigSection(), KDSequenceNumber, sequenceNumber))
{
INFO_PRINTF1(_L("Failed! Could not read test record sequence number from config!"));
SetTestStepResult(EFail);
return;
}
// Security checking, we may tamper with some parameters
TInt serverRecordTypeInt(0);
if (!GetIntFromConfig(ConfigSection(), KTamperedRecordType, serverRecordTypeInt))
{
// if this parameter isn't present, use the same value (no tampering)
serverRecordTypeInt = recordTypeInt;
}
else
{
INFO_PRINTF3(_L("Using tampered record type of %d (original %d)."), serverRecordTypeInt, recordTypeInt);
expectedError = KErrSSLAlertBadRecordMac;
}
TRecordProtocol serverRecordType = (TRecordProtocol)serverRecordTypeInt;
TInt serverSequenceNumber(0);
if (!GetIntFromConfig(ConfigSection(), KTamperedSequenceNumber, serverSequenceNumber))
{
serverSequenceNumber = sequenceNumber;
}
else
{
INFO_PRINTF3(_L("Using tampered sequence number of %d (original %d)."), serverSequenceNumber, sequenceNumber);
expectedError = KErrSSLAlertBadRecordMac;
}
// Generate a block of random data of the size specified in the test ini
HBufC8* record = HBufC8::NewLC(recordSize);
TPtr8 ptr = record->Des();
ptr.SetLength(recordSize);
TRandom::RandomL(ptr);
INFO_PRINTF1(_L("Creating server encrypted record."));
TInt64 serverSeq = serverSequenceNumber;
// encrypt the block with the server parameters
HBufC8* ourRecord = EncryptRecordL(*record, serverSeq, serverRecordType, ETrue);
CleanupStack::PushL(ourRecord);
INFO_PRINTF1(_L("Calling TLS Session to decrypt record."));
TInt64 seq = sequenceNumber;
// now, call TLS Provider's DecryptAndVerifyL on the record
HBufC8* decryptedRecord = NULL;
TInt err = Session()->DecryptAndVerifyL(*ourRecord, decryptedRecord, seq, recordType);
CleanupStack::PopAndDestroy(ourRecord);
// check the error is the expected error...
if (err != expectedError)
{
INFO_PRINTF3(_L("Failed! Error returned (%d) did not match expected error (%d)!"),
err, expectedError);
SetTestStepResult(EFail);
}
// if it is, check the decrypted block was the same
else if (*decryptedRecord != *record)
{
INFO_PRINTF1(_L("Failed! Decrypted block is corrupt!"));
SetTestStepResult(EFail);
return;
}
else
{
INFO_PRINTF1(_L("Test passed."));
SetTestStepResult(EPass);
}
delete decryptedRecord;
CleanupStack::PopAndDestroy(record);
}
| [
"kirill.dremov@nokia.com"
] | kirill.dremov@nokia.com |
215eebc7943ce55ac75247eaa0016f18a8487c3a | 0dac0929c7153b2ca3581d8814a5830e76f21902 | /caffe/src/caffe/layers/split_layer.cpp | aa49b3892b8719ce61fb0aca74538cb110790467 | [
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause",
"LicenseRef-scancode-public-domain"
] | permissive | juliebernauer/tx1-lab2 | d8816dfa71d4682a758dd9ca49ff6c518f9b7558 | 6d87dfa9d54a631b50ff7afe2ba7a1fff606e0fd | refs/heads/master | 2021-01-10T09:27:09.955170 | 2016-04-07T19:20:18 | 2016-04-07T19:20:18 | 55,698,752 | 10 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 2,076 | cpp | #include <vector>
#include "caffe/layer.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/vision_layers.hpp"
namespace caffe {
template <typename Dtype, typename Mtype>
void SplitLayer<Dtype,Mtype>::Reshape(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
count_ = bottom[0]->count();
for (int i = 0; i < top.size(); ++i) {
// Do not allow in-place computation in the SplitLayer. Instead, share data
// by reference in the forward pass, and keep separate diff allocations in
// the backward pass. (Technically, it should be possible to share the diff
// blob of the first split output with the input, but this seems to cause
// some strange effects in practice...)
CHECK_NE(top[i], bottom[0]) << this->type() << " Layer does not "
"allow in-place computation.";
top[i]->ReshapeLike(*bottom[0]);
CHECK_EQ(count_, top[i]->count());
}
}
template <typename Dtype, typename Mtype>
void SplitLayer<Dtype,Mtype>::Forward_cpu(const vector<Blob<Dtype,Mtype>*>& bottom,
const vector<Blob<Dtype,Mtype>*>& top) {
for (int i = 0; i < top.size(); ++i) {
top[i]->ShareData(*bottom[0]);
}
}
template <typename Dtype, typename Mtype>
void SplitLayer<Dtype,Mtype>::Backward_cpu(const vector<Blob<Dtype,Mtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype,Mtype>*>& bottom) {
if (!propagate_down[0]) { return; }
if (top.size() == 1) {
caffe_copy<Dtype,Mtype>(count_, top[0]->cpu_diff(), bottom[0]->mutable_cpu_diff());
return;
}
caffe_add<Dtype,Mtype>(count_, top[0]->cpu_diff(), top[1]->cpu_diff(),
bottom[0]->mutable_cpu_diff());
// Add remaining top blob diffs.
for (int i = 2; i < top.size(); ++i) {
const Dtype* top_diff = top[i]->cpu_diff();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
caffe_axpy<Dtype,Mtype>(count_, Mtype(1.), top_diff, bottom_diff);
}
}
#ifdef CPU_ONLY
STUB_GPU(SplitLayer);
#endif
INSTANTIATE_CLASS(SplitLayer);
REGISTER_LAYER_CLASS(Split);
} // namespace caffe
| [
"jbernauer@nvidia.com"
] | jbernauer@nvidia.com |
6a66a63c949d90ac912793b02b07f4ec4497907e | 5dc149c4f4000f5f25e44effe0ed72badf31ddb3 | /examples/check_xyz_to_sensors/check_xyz_to_sensors.ino | 22c2255c7baa44d920f2a29bce78bd000b8d246f | [] | no_license | joelgreenwood/StompyLegControl | 6ece0878a7450366a35f38c3de02b30ee968b482 | 9ec018c1f0012806ca2c7968514fb75fbd4221c4 | refs/heads/master | 2021-10-19T23:15:03.100242 | 2019-02-24T17:26:39 | 2019-02-24T17:26:39 | 83,385,826 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,193 | ino | #include <legControl.h>
legControl leg1;
float startingAngles[3] = {0, 80, 100};
float goalAngles[3] = {30, 60, 20};
float startingXYZ[3];
float goalXYZ[3];
float sensorGoals[3];
float sensors[3] = {1724.00, 255.00, 1273.00};
float xyz[3] = {50, 0, -3};
void setup() {
Serial.begin(9600);
while(!Serial);
leg1.anglesToXYZ(startingAngles, startingXYZ);
leg1.anglesToXYZ(goalAngles, goalXYZ);
//int startingSensors[3];
//int goalSensors[3];
float sensorVelocities[3];
float move_time = 10; //in seconds
//leg1.goal_XYZ_toSensorVelocities(startingXYZ, goalXYZ, sensorVelocities, move_time);
// Serial.println("staring");
// for (int i = 0; i < 3; i++) {
// Serial.print("angle:joint ");
// Serial.print(startingAngles[i]);
// Serial.print(" : ");
// Serial.print(i);
// Serial.print('\t');
// Serial.print("sensor: ");
// Serial.println(leg1.angleToSensor(i, startingAngles[i]));
// }
// Serial.println("ending");
// for (int i = 0; i < 3; i++) {
// Serial.print("angle:joint ");
// Serial.print(goalAngles[i]);
// Serial.print(" : ");
// Serial.print(i);
// Serial.print('\t');
// Serial.print("sensor: ");
// Serial.println(leg1.angleToSensor(i, goalAngles[i]));
// }
Serial.println("xyz in:");
for (int i = 0; i < 3; i ++) {
Serial.print(xyz[i]);
Serial.print(" ");
}
Serial.println();
leg1.xyzToSensors(xyz, sensors);
Serial.println("sensors out:");
for (int i = 0; i < 3; i ++) {
Serial.print(sensors[i]);
Serial.print(" ");
}
Serial.println();
// Serial.println("staring sensors");
// for (int i = 0; i < 3; i ++) {
// Serial.print(sensors[i]);
// Serial.print(" ");
// }
// Serial.println();
leg1.sensors_to_xyz(sensors, xyz);
Serial.println("sensors back in to xyz");
for (int i = 0; i < 3; i ++) {
Serial.print(xyz[i]);
Serial.print(" ");
}
Serial.println();
Serial.println("xyz back again to sensors:");
leg1.xyzToSensors(xyz, sensors);
for (int i = 0; i < 3; i ++) {
Serial.print(sensors[i]);
Serial.print(" ");
}
Serial.println();
Serial.println("finally, sensors back to xyz:");
leg1.sensors_to_xyz(sensors, xyz);
for (int i = 0; i < 3; i ++) {
Serial.print(xyz[i]);
Serial.print(" ");
}
Serial.println();
}
void loop() {
// leg1.anglesToXYZ(startingAngles, startingXYZ);
// leg1.anglesToXYZ(goalAngles, goalXYZ);
// //int startingSensors[3];
// //int goalSensors[3];
// float sensorVelocities[3];
// float move_time = 10; //in seconds
// //leg1.goal_XYZ_toSensorVelocities(startingXYZ, goalXYZ, sensorVelocities, move_time);
// for (int i = 0; i < 3; i++) {
// Serial.print("angle:joint ");
// Serial.print(startingAngles[i]);
// Serial.print(":");
// Serial.print(i);
// Serial.print('\t');
// Serial.print("sensor: ");
// Serial.println(leg1.angleToSensor(i, startingAngles[i]));
// }
// // Serial.print("sensor velocities: ");
// // for (int i = 0; i < 3; i ++) {
// // Serial.print(sensorVelocities[i]);
// // Serial.print("\t");
// // }
// // Serial.println();
delay(2000);
} | [
"greenwood.joel@gmail.com"
] | greenwood.joel@gmail.com |
911e426d8b68ddd0623cdefcd903fd3d8b803b51 | 269ea378278a93cbaf49662bd569b178561daf14 | /tensorrt-sys/trt-sys/TRTTensor/TRTTensor.cpp | 0aa6f5f48a1b5823f4c551fec3098ef474597046 | [] | no_license | i1i1/tensorrt-rs | a7553265c435e51983825a5631622c8c8a937d8f | 3d31801a042ccbeac8e663f1b45213a7661cb096 | refs/heads/master | 2023-01-24T00:50:27.576547 | 2020-12-08T09:30:53 | 2020-12-08T15:07:34 | 298,585,800 | 0 | 0 | null | 2020-09-25T13:48:46 | 2020-09-25T13:48:45 | null | UTF-8 | C++ | false | false | 464 | cpp | //
// Created by mason on 10/10/20.
//
#include "TRTTensorInternal.hpp"
#include "../TRTDims/TRTDimsInternal.hpp"
const char* tensor_get_name(Tensor_t *tensor) {
return tensor->internal_tensor->getName();
}
void tensor_set_dimensions(Tensor_t *tensor, Dims_t *dimensions) {
if (tensor == nullptr) {
return;
}
tensor->internal_tensor->setDimensions(dims_get(dimensions));
}
void tensor_destroy(Tensor_t *tensor) {
delete tensor;
}
| [
"masonstallmo@gmail.com"
] | masonstallmo@gmail.com |
3b99308f0cce7b85759e254e95cec91dc893f005 | 8f8acf52400314e969a57d0b9d7439b3d2fb247e | /src/Font.h | efeb965cf91964a0107f0655ab54565da2f19357 | [] | no_license | GFHund/S5HOverlay | e1cb2c42454cb0f0dc3dd1ba5cd994d6bd9ac403 | d2172e664994f28fff01055d07431411bb659221 | refs/heads/master | 2022-12-25T18:38:27.313409 | 2020-10-06T17:13:46 | 2020-10-06T17:13:46 | 291,284,462 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 957 | h | #ifndef __FONT__
#define __FONT__
#include "pixelFormat/RGBA.h"
class Font{
protected:
int mFontSize;
std::string mFontFamily;
RGBA mFontColor;
RGBA mBgColor;
float mLineHeight;
public:
void setFontSize(int size){
this->mFontSize = size;
}
void setFontFamily(std::string family){
this->mFontFamily = family;
}
void setFontColor(RGBA color){
this->mFontColor = color;
}
void setBackgroundColor(RGBA color){
this->mBgColor = color;
}
void setLineHeight(float lineHeight){
this->mLineHeight = lineHeight;
}
int getFontSize(){
return this->mFontSize;
}
std::string getFontFamily(){
return this->mFontFamily;
}
RGBA getFontColor(){
return this->mFontColor;
}
RGBA getBackgroundColor(){
return this->mBgColor;
}
float getLineHeight(){
return this->mLineHeight;
}
};
#endif | [
"Philipp1990@web.de"
] | Philipp1990@web.de |
0fdf43dc44883f01bedcb1e40e277d13e4013b15 | 8a2508c0916ba33a8f7b8103c7a3e784ad4a48aa | /informatics/informatics arrays/2d arrays/h.cpp | 7d5cf31a34cb626345fb5a7a486b4e35fa4d3375 | [] | no_license | SemaMolchanov/cpp-basics | 85a628c0afca793f84ef4f35e316e2305510e0ca | 1e44e0e7b462d123ce8e31e3f37f587629ea9af3 | refs/heads/main | 2023-05-27T15:25:40.672669 | 2021-03-16T12:51:52 | 2021-03-16T12:51:52 | 348,340,816 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 310 | cpp | #include <iostream>
using namespace std;
int main(){
int row, col;
cin >> row >> col;
int m[row][col];
for (int r = 0; r < row; r++){
for (int c = 0; c < col; c++){
m[r][c] = r * c;
cout << m[r][c] << " ";
}
cout << endl;
}
return 0;
} | [
"sema.molchanov@gmail.com"
] | sema.molchanov@gmail.com |
b349a09971775de573ea672ae8ebbd1c6b22d70c | 31b33fd6d6500964b2f4aa29186451c3db30ea1b | /Userland/Libraries/LibWeb/DOM/HTMLCollection.h | 47fa3ce94f938b446f31e590dd52399166a63211 | [
"BSD-2-Clause"
] | permissive | jcs/serenity | 4ca6f6eebdf952154d50d74516cf5c17dbccd418 | 0f1f92553213c6c2c7268078c9d39b813c24bb49 | refs/heads/master | 2022-11-27T13:12:11.214253 | 2022-11-21T17:01:22 | 2022-11-22T20:13:35 | 229,094,839 | 10 | 2 | BSD-2-Clause | 2019-12-19T16:25:40 | 2019-12-19T16:25:39 | null | UTF-8 | C++ | false | false | 1,983 | h | /*
* Copyright (c) 2021-2022, Andreas Kling <kling@serenityos.org>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#pragma once
#include <AK/FlyString.h>
#include <AK/Function.h>
#include <LibJS/Heap/GCPtr.h>
#include <LibWeb/Bindings/LegacyPlatformObject.h>
#include <LibWeb/Forward.h>
namespace Web::DOM {
// NOTE: HTMLCollection is in the DOM namespace because it's part of the DOM specification.
// This class implements a live, filtered view of a DOM subtree.
// When constructing an HTMLCollection, you provide a root node + a filter.
// The filter is a simple Function object that answers the question
// "is this Element part of the collection?"
// FIXME: HTMLCollection currently does no caching. It will re-filter on every access!
// We should teach it how to cache results. The main challenge is invalidating
// these caches, since this needs to happen on various kinds of DOM mutation.
class HTMLCollection : public Bindings::LegacyPlatformObject {
WEB_PLATFORM_OBJECT(HTMLCollection, Bindings::LegacyPlatformObject);
public:
static JS::NonnullGCPtr<HTMLCollection> create(ParentNode& root, Function<bool(Element const&)> filter);
virtual ~HTMLCollection() override;
size_t length();
Element* item(size_t index) const;
Element* named_item(FlyString const& name) const;
JS::MarkedVector<Element*> collect_matching_elements() const;
virtual JS::Value item_value(size_t index) const override;
virtual JS::Value named_item_value(FlyString const& name) const override;
virtual Vector<String> supported_property_names() const override;
virtual bool is_supported_property_index(u32) const override;
protected:
HTMLCollection(ParentNode& root, Function<bool(Element const&)> filter);
JS::NonnullGCPtr<ParentNode> root() { return *m_root; }
private:
virtual void visit_edges(Cell::Visitor&) override;
JS::NonnullGCPtr<ParentNode> m_root;
Function<bool(Element const&)> m_filter;
};
}
| [
"kling@serenityos.org"
] | kling@serenityos.org |
25bdaeb35089cfdd2dba62d6db4b50406e159b7d | e86b4e925649c625ae41c8b617b1dd66d12483e7 | /src/talker_pedals.cpp | ab002b9b6c4292cbf915a406d17f8a3c3fd75892 | [] | no_license | huensf/ros_rasp2 | 23680d8684b2ba6445fe619417229d8412b0682a | b2063a0523cd2f7cb0a1a409fede65c2ec4d91c1 | refs/heads/master | 2023-05-29T12:31:13.113866 | 2021-04-08T19:00:13 | 2021-04-08T19:00:13 | 375,953,943 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,113 | cpp | #include "ros/ros.h"
#include "std_msgs/String.h"
#include "ros_rasp2/Pedals_msg.h"
#include <sstream>
#include <fstream>
int main(int argc, char **argv)
{
// Initialization
std::cout << "Initialization of the node 'talker_pedals'" << std::endl;
ros::init(argc, argv, "talker_pedals");
ros::NodeHandle n;
ros::Publisher chatter_pub = n.advertise<ros_rasp2::Pedals_msg>("chatter_pedals",1000);
ros::Rate loop_rate(1000);
std::cout << "Running ..." << std::endl;
while(ros::ok())
{
std::ifstream f1("/sys/bus/iio/devices/iio:device0/in_voltage1_raw");
std::ifstream f2("/sys/bus/iio/devices/iio:device0/in_voltage2_raw");
if(f1 && f2)
{
std::string value1, value2;
getline(f1,value1);
getline(f2,value2);
ros_rasp2::Pedals_msg msg;
msg.pedal1_value = ::atof(value1.c_str());
msg.pedal2_value = ::atof(value2.c_str());
chatter_pub.publish(msg);
ros::spinOnce();
loop_rate.sleep();
}
else
{
std::cout << "ERREUR: Impossible d'ouvrir le fichier en lecture" << std::endl;
}
}
std::cout << "Finished" << std::endl;
return 0;
}
| [
"francois.huens@student.uclouvain.be"
] | francois.huens@student.uclouvain.be |
5b5ec57f08c25a19a5248631d8a1136e91ec2bd6 | 706f50d780a5549c2de1f28e6579ef1a406d4531 | /src/ds/surface.cpp | 11afc540ae12f7acf1a7c29a9bf184496503e1b2 | [
"WTFPL"
] | permissive | dearshuto/gal | b519a27b83d2cb80617484aa7fda858d9fdd017f | ebb8ddbabab971e517b527d72736c676515526d0 | refs/heads/master | 2021-09-03T07:52:29.653196 | 2018-01-07T09:50:51 | 2018-01-07T09:50:51 | 115,930,132 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,904 | cpp | //
// surface.cpp
// gal
//
// Created by Shuto Shikama on 2018/01/06.
//
#include <list>
#include <gal/ds//surface.hpp>
void gal::ds::Surface::makeHalfedge(const std::vector<float> &vertexData, std::vector<std::uint32_t> &indices)
{
m_vertexData = vertexData;
m_faces.resize(indices.size()/3);
m_halfedges.resize(indices.size());
m_vertices.resize(vertexData.size()/3);
// 頂点情報のセット
for (std::uint32_t i = 0; i < m_vertexData.size()/3; ++i)
{
// xi へのポインタをもたせます。
// 3つ飛びにすると xi へのポインタになる。
// ↓0 ↓1
// x1, y1, z1, x2, y2, z2, x3, y3, z3, ...
m_vertices[i].pLocation = &m_vertexData[i*3];
}
// 3角ポリゴンを前提にしているので、3つとびにアクセスしています。
for (std::uint32_t i = 0; i < indices.size()/3; ++i)
{
// ハーフエッジの始点の設定。
m_halfedges[i*3 + 0].pBegin = &m_vertices[indices[i*3 + 0]];
m_vertices[indices[i*3 + 0]].pHalfedge = &m_halfedges[i*3 + 0];
m_halfedges[i*3 + 1].pBegin = &m_vertices[indices[i*3 + 1]];
m_vertices[indices[i*3 + 1]].pHalfedge = &m_halfedges[i*3 + 1];
m_halfedges[i*3 + 2].pBegin = &m_vertices[indices[i*3 + 2]];
m_vertices[indices[i*3 + 2]].pHalfedge = &m_halfedges[i*3 + 2];
// ハーフエッジ同士の接続
m_halfedges[i*3 + 0].pNext = &m_halfedges[i*3 + 1];
m_halfedges[i*3 + 1].pNext = &m_halfedges[i*3 + 2];
m_halfedges[i*3 + 2].pNext = &m_halfedges[i*3 + 0];
// ハーフエッジ同士の接続
m_halfedges[i*3 + 0].pPrevious = &m_halfedges[i*3 + 2];
m_halfedges[i*3 + 1].pPrevious = &m_halfedges[i*3 + 0];
m_halfedges[i*3 + 2].pPrevious = &m_halfedges[i*3 + 1];
// ハーフエッジが所属する面の設定
m_faces[i].pHalfedge = &m_halfedges[i*3+0];
}
// ペアを探す
// 総当たりでもいいですが、
// ここではいちどリストにコピーして、みつかるたびにリストから外して、
// 重複がないようにしています。
// いちどリストにコピーするコストと、全頂点で毎回総当たりするコスト
// どっちが大きいのかはわからないです。
std::list<gal::ds::Halfedge*> target;
std::list<gal::ds::Halfedge*> pair;
target.resize(m_halfedges.size());
pair.resize(m_halfedges.size());
// リストにコピー。アドレスに変換します。
std::transform(std::begin(m_halfedges), std::end(m_halfedges)
, std::begin(target)
, [](gal::ds::Halfedge& halfedge){ return &halfedge; });
// 初期状態では、ターゲットとペア候補はすべてのエッジが入っています
std::copy(std::begin(target), std::end(target), std::begin(pair));
for (const auto& pTarget : target)
{
auto result = std::find_if(std::begin(pair), std::end(pair)
, [&](gal::ds::Halfedge* pPair)
{
const float kMatchBegenEnd = (pTarget->pBegin == pPair->pNext->pBegin);
const float kMatchEndBegin = (pTarget->pNext->pBegin == pPair->pBegin);
return kMatchBegenEnd && kMatchEndBegin;
});
if (result == std::end(pair))
{
// ペアが見つからないときはなにもしない
continue;
}
else
{
// ペアがみつかったらそれぞれ設定して、pair リストから除外
gal::ds::Halfedge* pResult = *result;
pTarget->pPair = pResult;
pResult->pPair = pTarget;
pair.erase(result);
}
}
}
| [
"shuto@ShutonoMac-mini.local"
] | shuto@ShutonoMac-mini.local |
fc7318916ff552b098cfce1edcaa352926a743a1 | 5f0169b2242d254ca5dca7dce15bff6af6993ea4 | /netfilter.cpp | bae06129a19aaac5c050d95fc5f566adacf2f3cf | [] | no_license | ch4rli3kop/netfilter_test_gilgil | d076eecb97d8eab4a85e2c6b77e1435bcc3764cb | dda83555b27f355c1170fe6edf528b7786cd3ca4 | refs/heads/master | 2020-07-10T02:12:59.371000 | 2019-08-25T04:13:57 | 2019-08-25T04:13:57 | 204,140,337 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,344 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <netinet/in.h>
#include <linux/types.h>
#include <linux/netfilter.h> /* for NF_ACCEPT */
#include <errno.h>
#include <string.h>
#include <libnetfilter_queue/libnetfilter_queue.h>
struct ethernet_header{
uint8_t dst_mac[6];
uint8_t src_mac[6];
uint8_t type[2];
};
struct ip_header{
uint8_t version_and_length;
uint8_t type;
uint16_t length;
uint16_t identification;
uint16_t flag_and_offset;
uint8_t ttl;
uint8_t protocol;
uint16_t checksum;
uint8_t src_ip[4];
uint8_t dst_ip[4];
};
struct tcp_header{
uint8_t src_port[2];
uint8_t dst_port[2];
uint32_t seq;
uint32_t ack;
uint8_t data_offset;
uint8_t flag;
uint16_t window;
uint16_t checksum;
uint16_t urgent_p;
};
struct packet{
struct ip_header ip;
struct tcp_header tcp;
};
char* domain = NULL;
bool filter(unsigned char* data, int size){
struct packet p;
struct ip_header ip;
struct tcp_header tcp;
unsigned char buf[0x100];
unsigned char payload[0x100];
int ip_header_length = 0;
int tcp_header_length = 0;
int tcp_data_length = 0;
int i;
if (data == NULL)
return false;
memcpy(&p, data, 40);
if ( ((p.ip.version_and_length & (0xf0)) >> 4) == 0x4 ){
if (p.ip.protocol == 0x6){
ip_header_length = (p.ip.version_and_length & 0xf)*4;
tcp_header_length = ((p.tcp.data_offset & 0xf0) >> 4)*4;
tcp_data_length = size - ip_header_length - tcp_header_length;
if (!memcmp(&data[40], "GET", 3)){
if (tcp_data_length < 0x100)
memcpy(payload, &data[40], tcp_data_length);
else
memcpy(payload, &data[40], 0x100);
if (strstr((char*)payload, (char*)domain)){
return true;
}
}
}
}
return false;
}
bool process_pkt (struct nfq_data *tb, uint64_t &id)
{
struct nfqnl_msg_packet_hdr *ph;
struct nfqnl_msg_packet_hw *hwph;
u_int32_t mark,ifi;
int ret;
unsigned char *data;
ph = nfq_get_msg_packet_hdr(tb);
if (ph) {
id = ntohl(ph->packet_id);
printf("hw_protocol=0x%04x hook=%u id=%u ",
ntohs(ph->hw_protocol), ph->hook, id);
}
hwph = nfq_get_packet_hw(tb);
if (hwph) {
int i, hlen = ntohs(hwph->hw_addrlen);
printf("hw_src_addr=");
for (i = 0; i < hlen-1; i++)
printf("%02x:", hwph->hw_addr[i]);
printf("%02x ", hwph->hw_addr[hlen-1]);
}
mark = nfq_get_nfmark(tb);
if (mark)
printf("mark=%u ", mark);
ifi = nfq_get_indev(tb);
if (ifi)
printf("indev=%u ", ifi);
ifi = nfq_get_outdev(tb);
if (ifi)
printf("outdev=%u ", ifi);
ifi = nfq_get_physindev(tb);
if (ifi)
printf("physindev=%u ", ifi);
ifi = nfq_get_physoutdev(tb);
if (ifi)
printf("physoutdev=%u ", ifi);
ret = nfq_get_payload(tb, &data);
if (ret >= 0)
printf("payload_len=%d ", ret);
fputc('\n', stdout);
if(filter(data, ret)){
return true;
} else {
return false;
}
}
static int cb(struct nfq_q_handle *qh, struct nfgenmsg *nfmsg,
struct nfq_data *nfa, void *data)
{
uint64_t id = 0;
bool result = process_pkt(nfa, id);
printf("entering callback\n");
if(result){
return nfq_set_verdict(qh, id, NF_DROP, 0, NULL);
} else {
return nfq_set_verdict(qh, id, NF_ACCEPT, 0, NULL);
}
}
int main(int argc, char **argv)
{
struct nfq_handle *h;
struct nfq_q_handle *qh;
struct nfnl_handle *nh;
int fd;
int rv;
char buf[4096] __attribute__ ((aligned));
if(argc != 2){
printf("usage : netfilter_test <host>\n");
return 1;
}
domain = argv[1];
printf("opening library handle\n");
h = nfq_open();
if (!h) {
fprintf(stderr, "error during nfq_open()\n");
exit(1);
}
printf("unbinding existing nf_queue handler for AF_INET (if any)\n");
if (nfq_unbind_pf(h, AF_INET) < 0) {
fprintf(stderr, "error during nfq_unbind_pf()\n");
exit(1);
}
printf("binding nfnetlink_queue as nf_queue handler for AF_INET\n");
if (nfq_bind_pf(h, AF_INET) < 0) {
fprintf(stderr, "error during nfq_bind_pf()\n");
exit(1);
}
printf("binding this socket to queue '0'\n");
qh = nfq_create_queue(h, 0, &cb, NULL);
if (!qh) {
fprintf(stderr, "error during nfq_create_queue()\n");
exit(1);
}
printf("setting copy_packet mode\n");
if (nfq_set_mode(qh, NFQNL_COPY_PACKET, 0xffff) < 0) {
fprintf(stderr, "can't set packet_copy mode\n");
exit(1);
}
fd = nfq_fd(h);
for (;;) {
if ((rv = recv(fd, buf, sizeof(buf), 0)) >= 0) {
printf("pkt received\n");
nfq_handle_packet(h, buf, rv);
continue;
}
/* if your application is too slow to digest the packets that
* are sent from kernel-space, the socket buffer that we use
* to enqueue packets may fill up returning ENOBUFS. Depending
* on your application, this error may be ignored. nfq_nlmsg_verdict_putPlease, see
* the doxygen documentation of this library on how to improve
* this situation.
*/
if (rv < 0 && errno == ENOBUFS) {
printf("losing packets!\n");
continue;
}
perror("recv failed");
break;
}
printf("unbinding from queue 0\n");
nfq_destroy_queue(qh);
#ifdef INSANE
/* normally, applications SHOULD NOT issue this command, since
* it detaches other programs/sockets from AF_INET, too ! */
printf("unbinding from AF_INET\n");
nfq_unbind_pf(h, AF_INET);
#endif
printf("closing library handle\n");
nfq_close(h);
exit(0);
}
| [
"pch2180@gmail.com"
] | pch2180@gmail.com |
5010653b96ef8318acdf057cd9727284bf6e27b8 | 8cc9b565fa027504b33893987ffa29ec45183126 | /nheqminer/primitives/block.h | eea64fbcaee89a128cdbc86829ca64af7004b8fa | [
"MIT"
] | permissive | ksaynice/Equihash-96_5-VDS | dedaac976ae66c1c3834d4b6dd9446dbdfe89cd3 | 4bfc88dd052cc9e4b9d9fab3dd210952872a4f98 | refs/heads/master | 2020-05-24T20:21:57.213442 | 2019-05-18T14:44:33 | 2019-05-18T14:44:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,094 | h | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_BLOCK_H
#define BITCOIN_PRIMITIVES_BLOCK_H
#include "primitives/transaction.h"
#include "serialize.h"
#include "uint256.h"
/** Nodes collect new transactions into a block, hash them into a hash tree,
* and scan through nonce values to make the block's hash satisfy proof-of-work
* requirements. When they solve the proof-of-work, they broadcast the block
* to everyone and the block is added to the block chain. The first transaction
* in the block is a special one that creates a new coin owned by the creator
* of the block.
*/
class CBlockHeader
{
public:
// header
static const size_t HEADER_SIZE = 4 + 32 + 32 + 32 + 8 + 4 + 4 + 32 + 32 + 32; // excluding Equihash solution
static const int32_t CURRENT_VERSION=4;
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint256 hashReserved;
int64_t nVibPool;
uint32_t nTime;
uint32_t nBits;
uint256 hashStateRoot; // qtum
uint256 hashUTXORoot; // qtum
uint256 nNonce;
std::vector<unsigned char> nSolution;
CBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(hashReserved);
READWRITE(nVibPool);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(hashStateRoot); // qtum
READWRITE(hashUTXORoot); // qtum
READWRITE(nNonce);
READWRITE(nSolution);
}
void SetNull()
{
nVersion = CBlockHeader::CURRENT_VERSION;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
hashReserved.SetNull();
nVibPool = 0;
nTime = 0;
nBits = 0;
hashStateRoot.SetNull(); // qtum
hashUTXORoot.SetNull(); // qtum
nNonce = uint256();
nSolution.clear();
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
uint256 GetPoWHash() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
};
class CBlock : public CBlockHeader
{
public:
// network and disk
std::vector<CTransaction> vtx;
// memory only
mutable CTxOut txoutMasternode; // masternode payment
mutable std::vector<CTxOut> voutSuperblock; // superblock payment
mutable bool fChecked;
mutable std::vector<uint256> vMerkleTree;
CBlock()
{
SetNull();
}
CBlock(const CBlockHeader &header)
{
SetNull();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(*(CBlockHeader*)this);
READWRITE(vtx);
}
void SetNull()
{
CBlockHeader::SetNull();
vtx.clear();
vMerkleTree.clear();
txoutMasternode = CTxOut();
voutSuperblock.clear();
fChecked = false;
}
CBlockHeader GetBlockHeader() const
{
CBlockHeader block;
block.nVersion = nVersion;
block.hashPrevBlock = hashPrevBlock;
block.hashMerkleRoot = hashMerkleRoot;
block.hashReserved = hashReserved;
block.nVibPool = nVibPool;
block.nTime = nTime;
block.nBits = nBits;
block.hashStateRoot = hashStateRoot; // qtum
block.hashUTXORoot = hashUTXORoot; // qtum
block.nNonce = nNonce;
block.nSolution = nSolution;
return block;
}
// Build the in-memory merkle tree for this block and return the merkle root.
// If non-NULL, *mutated is set to whether mutation was detected in the merkle
// tree (a duplication of transactions in the block leading to an identical
// merkle root).
uint256 BuildMerkleTree(bool* mutated = NULL) const;
std::vector<uint256> GetMerkleBranch(int nIndex) const;
static uint256 CheckMerkleBranch(uint256 hash, const std::vector<uint256>& vMerkleBranch, int nIndex);
std::string ToString() const;
};
/**
* Custom serializer for CBlockHeader that omits the nonce and solution, for use
* as input to Equihash.
*/
class CEquihashInput : private CBlockHeader
{
public:
CEquihashInput(const CBlockHeader &header)
{
CBlockHeader::SetNull();
*((CBlockHeader*)this) = header;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
READWRITE(this->nVersion);
nVersion = this->nVersion;
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(hashReserved);
READWRITE(nVibPool);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(hashStateRoot); // qtum
READWRITE(hashUTXORoot); // qtum
}
};
/** Describes a place in the block chain to another node such that if the
* other node doesn't have the same branch, it can find a recent common trunk.
* The further back it is, the further before the fork it may be.
*/
struct CBlockLocator
{
std::vector<uint256> vHave;
CBlockLocator() {}
CBlockLocator(const std::vector<uint256>& vHaveIn)
{
vHave = vHaveIn;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion) {
if (!(nType & SER_GETHASH))
READWRITE(nVersion);
READWRITE(vHave);
}
void SetNull()
{
vHave.clear();
}
bool IsNull() const
{
return vHave.empty();
}
};
#endif // BITCOIN_PRIMITIVES_BLOCK_H
| [
"jakeandtom@test.com"
] | jakeandtom@test.com |
535bac758d4c0d33f9c7c1bb25f11a08068841cd | c6e805f910c9203f5f137fdb1680c7385406b966 | /practice.cc | cfb82692ae3d2556a4114faa183aac320dbd81c4 | [] | no_license | briansrls/common | ff4ec282a66d3f216c50283fc0160c55cf0f9117 | 919c8c8e6507e2b59912ec3750444e73ebe5c6ee | refs/heads/master | 2016-08-11T19:38:30.650769 | 2016-03-31T02:44:46 | 2016-03-31T02:44:46 | 51,096,286 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,144 | cc | #include <stdlib.h>
#include <stdio.h>
#include <iostream>
#include <string.h>
int uniqueChars(char* sentence, int size){
std::cout<<size;
for(int i = 0; i < (size); i++){
for(int j=i+1; j < (size); j++){
if(sentence[i]==sentence[j]) return 0;
}
}
return 1;
}
void reverse(char* str){
int size = strlen(str);
char a[size];
for(int i = 0; i<size ;i++)
{
a[i]=str[size-1-i];
std::cout<<a[i];
}
str = a;
}
void shiftBy2(char* str, int start){
}
void insert20(char* str){
int size = strlen(str);
char a[size];
int x = 0;
for(int i = 0; i<size; i++){
if(x == size) break;
else if(str[i]==' '){
a[x]='%';
a[x+1]='2';
a[x+2]='3';
x = x+2;
}
else{ a[x] = str[i]; x++; }
}
str = a;
}
int main(){
char greeting[8] = {'H', 'e', ' ', 'l', 'l', 'o', ' ', ' ',};
//int z = uniqueChars(greeting, sizeof(greeting));
//printf("%d", z);
//reverse(greeting);
shiftBy2();
for(int i = 0; i<strlen(greeting); i++)
std::cout<<greeting[i];
} | [
"bsearls@DoCS-0685.CE-Directory.rutgers.edu"
] | bsearls@DoCS-0685.CE-Directory.rutgers.edu |
f597c2180cdcc760403f26fa3238085936a40a22 | b034c29d0ffc4fe296deb2a23214e1235d7f3cc6 | /src/ClientLib/LocalLayer.cpp | e21868a1784d140cf75d101dd1b2dc8b861f6a7d | [
"MIT"
] | permissive | blockspacer/BurgWar | 702da94a8b812267dc2e348e499e9366aa59c79a | 6eeb38180938160111aa0626ead6ed1b56ee59b5 | refs/heads/master | 2022-04-17T00:03:28.913497 | 2020-04-06T12:05:18 | 2020-04-06T12:05:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,501 | cpp | // Copyright (C) 2020 Jérôme Leclercq
// This file is part of the "Burgwar" project
// For conditions of distribution and use, see copyright notice in LICENSE
#include <ClientLib/LocalLayer.hpp>
#include <ClientLib/ClientSession.hpp>
#include <ClientLib/LocalMatch.hpp>
#include <ClientLib/Components/LayerEntityComponent.hpp>
#include <ClientLib/Systems/FrameCallbackSystem.hpp>
#include <ClientLib/Systems/PostFrameCallbackSystem.hpp>
#include <ClientLib/Systems/VisualInterpolationSystem.hpp>
#include <ClientLib/Scripting/ClientEntityStore.hpp>
#include <ClientLib/Scripting/ClientWeaponStore.hpp>
#include <NDK/Components/NodeComponent.hpp>
#include <NDK/Systems/LifetimeSystem.hpp>
namespace bw
{
LocalLayer::LocalLayer(LocalMatch& match, LayerIndex layerIndex, const Nz::Color& backgroundColor) :
SharedLayer(match, layerIndex),
m_backgroundColor(backgroundColor),
m_isEnabled(false),
m_isPredictionEnabled(false)
{
Ndk::World& world = GetWorld();
world.AddSystem<FrameCallbackSystem>(match);
world.AddSystem<PostFrameCallbackSystem>(match);
world.AddSystem<VisualInterpolationSystem>();
}
LocalLayer::~LocalLayer()
{
// Kill all entities while still alive
GetWorld().Clear();
}
LocalLayer::LocalLayer(LocalLayer&& layer) noexcept :
SharedLayer(std::move(layer)),
m_clientEntities(std::move(layer.m_clientEntities)),
m_serverEntities(std::move(layer.m_serverEntities)),
m_backgroundColor(layer.m_backgroundColor),
m_isEnabled(layer.m_isEnabled),
m_isPredictionEnabled(layer.m_isPredictionEnabled)
{
for (auto it = m_clientEntities.begin(); it != m_clientEntities.end(); ++it)
{
EntityData& clientEntity = it.value();
clientEntity.onDestruction.Connect(clientEntity.layerEntity.GetEntity()->OnEntityDestruction, this, &LocalLayer::HandleClientEntityDestruction);
}
for (auto it = m_serverEntities.begin(); it != m_serverEntities.end(); ++it)
{
EntityData& serverEntity = it.value();
serverEntity.onDestruction.Connect(serverEntity.layerEntity.GetEntity()->OnEntityDestruction, [this, serverId = serverEntity.layerEntity.GetServerId()](Ndk::Entity*)
{
HandleServerEntityDestruction(serverId);
});
}
}
void LocalLayer::Enable(bool enable)
{
if (m_isEnabled == enable)
return;
m_isEnabled = enable;
if (enable)
{
OnEnabled(this);
}
else
{
OnDisabled(this);
m_clientEntities.clear();
m_serverEntities.clear();
// Since we are disabled, refresh won't be called until we are enabled, refresh the world now to kill entities
GetWorld().Refresh();
}
}
LocalMatch& LocalLayer::GetLocalMatch()
{
return static_cast<LocalMatch&>(SharedLayer::GetMatch());
}
void LocalLayer::FrameUpdate(float elapsedTime)
{
Ndk::World& world = GetWorld();
world.ForEachSystem([](Ndk::BaseSystem& system)
{
system.Enable(false);
});
world.GetSystem<Ndk::LifetimeSystem>().Enable(true);
world.GetSystem<FrameCallbackSystem>().Enable(true);
world.Update(elapsedTime);
}
void LocalLayer::PreFrameUpdate(float elapsedTime)
{
Ndk::World& world = GetWorld();
world.ForEachSystem([](Ndk::BaseSystem& system)
{
system.Enable(false);
});
world.GetSystem<VisualInterpolationSystem>().Enable(true);
world.Update(elapsedTime);
}
void LocalLayer::PostFrameUpdate(float elapsedTime)
{
Ndk::World& world = GetWorld();
world.ForEachSystem([](Ndk::BaseSystem& system)
{
system.Enable(false);
});
world.GetSystem<PostFrameCallbackSystem>().Enable(true);
world.Update(elapsedTime);
// Sound
for (auto& soundOpt : m_sounds)
{
if (soundOpt)
{
if (!soundOpt->sound.Update(elapsedTime))
{
OnSoundDelete(this, soundOpt->soundIndex, soundOpt->sound);
m_freeSoundIds.Set(soundOpt->soundIndex);
soundOpt.reset();
}
}
}
}
LocalLayerEntity& LocalLayer::RegisterEntity(LocalLayerEntity layerEntity)
{
const Ndk::EntityHandle& entity = layerEntity.GetEntity();
assert(entity);
assert(entity->GetWorld() == &GetWorld());
if (layerEntity.GetServerId() == LocalLayerEntity::ClientsideId)
{
assert(m_clientEntities.find(entity->GetId()) == m_clientEntities.end());
auto it = m_clientEntities.emplace(entity->GetId(), std::move(layerEntity)).first;
// Warning: entity reference is invalidated from here
EntityData& clientEntity = it.value();
clientEntity.onDestruction.Connect(clientEntity.layerEntity.GetEntity()->OnEntityDestruction, this, &LocalLayer::HandleClientEntityDestruction);
OnEntityCreated(this, clientEntity.layerEntity);
return clientEntity.layerEntity;
}
else
{
Nz::UInt32 serverId = layerEntity.GetServerId();
assert(m_serverEntities.find(serverId) == m_serverEntities.end());
auto it = m_serverEntities.emplace(serverId, std::move(layerEntity)).first;
// Warning: entity reference is invalidated from here
EntityData& serverEntity = it.value();
serverEntity.onDestruction.Connect(serverEntity.layerEntity.GetEntity()->OnEntityDestruction, [this, serverId = serverEntity.layerEntity.GetServerId()](Ndk::Entity*)
{
HandleServerEntityDestruction(serverId);
});
OnEntityCreated(this, serverEntity.layerEntity);
return serverEntity.layerEntity;
}
}
LocalLayerSound& LocalLayer::RegisterSound(LocalLayerSound layerEntity)
{
std::size_t soundIndex = m_freeSoundIds.FindFirst();
if (soundIndex == m_freeSoundIds.npos)
{
soundIndex = m_freeSoundIds.GetSize();
m_freeSoundIds.Resize(soundIndex + 1, false);
}
else
m_freeSoundIds.Reset(soundIndex);
auto& soundOpt = m_sounds.emplace_back();
soundOpt.emplace(std::move(layerEntity));
soundOpt->soundIndex = soundIndex;
OnSoundCreated(this, soundOpt->soundIndex, soundOpt->sound);
return soundOpt->sound;
}
void LocalLayer::SyncVisuals()
{
ForEachLayerEntity([&](LocalLayerEntity& layerEntity)
{
layerEntity.SyncVisuals();
});
}
void LocalLayer::TickUpdate(float elapsedTime)
{
Ndk::World& world = GetWorld();
world.ForEachSystem([](Ndk::BaseSystem& system)
{
system.Enable(true);
});
world.GetSystem<Ndk::LifetimeSystem>().Enable(false);
world.GetSystem<FrameCallbackSystem>().Enable(false);
world.GetSystem<VisualInterpolationSystem>().Enable(false);
SharedLayer::TickUpdate(elapsedTime);
}
void LocalLayer::CreateEntity(Nz::UInt32 entityId, const Packets::Helper::EntityData& entityData)
{
static std::string entityPrefix = "entity_";
static std::string weaponPrefix = "weapon_";
assert(m_isEnabled);
LocalMatch& localMatch = GetLocalMatch();
ClientEntityStore& entityStore = localMatch.GetEntityStore();
ClientWeaponStore& weaponStore = localMatch.GetWeaponStore();
const NetworkStringStore& networkStringStore = localMatch.GetNetworkStringStore();
const std::string& entityClass = networkStringStore.GetString(entityData.entityClass);
EntityProperties properties;
for (const auto& property : entityData.properties)
{
const std::string& propertyName = networkStringStore.GetString(property.name);
std::visit([&](auto&& value)
{
using T = std::decay_t<decltype(value)>;
using StoredType = typename T::value_type;
if (property.isArray)
{
EntityPropertyArray<StoredType> elements(value.size());
for (std::size_t i = 0; i < value.size(); ++i)
elements[i] = value[i];
properties.emplace(propertyName, std::move(elements));
}
else
properties.emplace(propertyName, value.front());
}, property.value);
}
const LocalLayerEntity* parent = nullptr;
if (entityData.parentId)
{
auto it = m_serverEntities.find(entityData.parentId.value());
assert(it != m_serverEntities.end());
parent = &it.value().layerEntity;
}
Nz::Int64 uniqueId = static_cast<Nz::Int64>(entityData.uniqueId);
std::optional<LocalLayerEntity> layerEntity;
//FIXME: Entity creation failure should instantiate some placeholder entity
try
{
if (entityClass.compare(0, entityPrefix.size(), entityPrefix) == 0)
{
// Entity
if (std::size_t elementIndex = entityStore.GetElementIndex(entityClass); elementIndex != ClientEntityStore::InvalidIndex)
{
auto entity = entityStore.InstantiateEntity(*this, elementIndex, entityId, uniqueId, entityData.position, entityData.rotation, properties, (parent) ? parent->GetEntity() : Ndk::EntityHandle::InvalidHandle);
if (!entity)
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate entity {0} of type {1}", uniqueId, entityClass);
return;
}
layerEntity.emplace(std::move(entity.value()));
}
else
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate entity {0}: {0}", uniqueId, entityClass);
return;
}
}
else if (entityClass.compare(0, weaponPrefix.size(), weaponPrefix) == 0)
{
// Weapon
if (std::size_t weaponIndex = weaponStore.GetElementIndex(entityClass); weaponIndex != ClientEntityStore::InvalidIndex)
{
if (!parent)
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Weapon entities should always have parents", entityClass);
return;
}
auto weapon = weaponStore.InstantiateWeapon(*this, weaponIndex, entityId, uniqueId, properties, parent->GetEntity());
if (!weapon)
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate weapon {0} of type {1}", uniqueId, entityClass);
return;
}
weapon->Disable(); //< Disable weapon entities by default
layerEntity.emplace(std::move(weapon.value()));
}
else
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate weapon {0}: unknown entity type: {0}", uniqueId, entityClass);
return;
}
}
else
{
// Unknown
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to decode element {0} entity type: {1}", uniqueId, entityClass);
return;
}
}
catch (const std::exception & e)
{
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Failed to instantiate element {0} of type {1}: {2}", entityId, entityClass, e.what());
return;
}
if (entityData.health)
layerEntity->InitializeHealth(entityData.health->maxHealth, entityData.health->currentHealth);
if (entityData.name)
layerEntity->InitializeName(entityData.name.value());
RegisterEntity(std::move(layerEntity.value()));
}
void LocalLayer::HandleClientEntityDestruction(Ndk::Entity* entity)
{
auto it = m_clientEntities.find(entity->GetId());
assert(it != m_clientEntities.end());
OnEntityDelete(this, it.value().layerEntity);
m_clientEntities.erase(it);
}
void LocalLayer::HandleServerEntityDestruction(Nz::UInt32 serverId)
{
auto it = m_serverEntities.find(serverId);
assert(it != m_serverEntities.end());
OnEntityDelete(this, it.value().layerEntity);
m_serverEntities.erase(it);
}
void LocalLayer::HandlePacket(const Packets::CreateEntities::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
auto& entityData = entities[i].data;
CreateEntity(entityId, entityData);
}
}
void LocalLayer::HandlePacket(const Packets::DeleteEntities::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
auto it = m_serverEntities.find(entityId);
if (it == m_serverEntities.end())
continue;
OnEntityDelete(this, it.value().layerEntity);
m_serverEntities.erase(it);
}
}
void LocalLayer::HandlePacket(const Packets::EnableLayer::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
auto& entityData = entities[i].data;
CreateEntity(entityId, entityData);
}
}
void LocalLayer::HandlePacket(const Packets::EntitiesAnimation::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].entityId;
Nz::UInt8 animationId = entities[i].animId;
auto it = m_serverEntities.find(entityId);
if (it == m_serverEntities.end())
continue;
LocalLayerEntity& localEntity = it.value().layerEntity;
localEntity.UpdateAnimation(animationId);
}
}
void LocalLayer::HandlePacket(const Packets::EntitiesDeath::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
auto it = m_serverEntities.find(entityId);
if (it == m_serverEntities.end())
continue;
LocalLayerEntity& localEntity = it.value().layerEntity;
if (localEntity.HasHealth())
localEntity.UpdateHealth(0);
else
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Received death event for entity {} which has no life", localEntity.GetUniqueId());
OnEntityDelete(this, it.value().layerEntity);
m_serverEntities.erase(it);
}
}
void LocalLayer::HandlePacket(const Packets::EntitiesInputs::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
const auto& inputs = entities[i].inputs;
auto it = m_serverEntities.find(entityId);
if (it == m_serverEntities.end())
continue;
LocalLayerEntity& localEntity = it.value().layerEntity;
localEntity.UpdateInputs(inputs);
}
}
void LocalLayer::HandlePacket(const Packets::HealthUpdate::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
Nz::UInt32 entityId = entities[i].id;
Nz::UInt16 currentHealth = entities[i].currentHealth;
auto it = m_serverEntities.find(entityId);
if (it == m_serverEntities.end())
continue;
LocalLayerEntity& localEntity = it.value().layerEntity;
if (localEntity.HasHealth())
localEntity.UpdateHealth(currentHealth);
else
bwLog(GetMatch().GetLogger(), LogLevel::Error, "Received health data for entity {} which has none", localEntity.GetUniqueId());
}
}
void LocalLayer::HandlePacket(const Packets::MatchState::Entity* entities, std::size_t entityCount)
{
assert(m_isEnabled);
for (std::size_t i = 0; i < entityCount; ++i)
{
auto& entityData = entities[i];
auto it = m_serverEntities.find(entityData.id);
if (it == m_serverEntities.end())
continue;
LocalLayerEntity& localEntity = it.value().layerEntity;
if (localEntity.IsPhysical())
{
if (entityData.physicsProperties.has_value())
{
auto& physData = entityData.physicsProperties.value();
localEntity.UpdateState(entityData.position, entityData.rotation, physData.linearVelocity, physData.angularVelocity);
}
else
{
bwLog(GetMatch().GetLogger(), LogLevel::Warning, "Entity {} has client-side physics but server sends no data", localEntity.GetUniqueId());
localEntity.UpdateState(entityData.position, entityData.rotation);
}
}
else
{
if (entityData.physicsProperties.has_value())
bwLog(GetMatch().GetLogger(), LogLevel::Warning, "Received physics properties for entity {} which is not physical client-side", localEntity.GetUniqueId());
localEntity.UpdateState(entityData.position, entityData.rotation);
}
if (entityData.playerMovement)
localEntity.UpdatePlayerMovement(entityData.playerMovement->isFacingRight);
}
}
}
| [
"lynix680@gmail.com"
] | lynix680@gmail.com |
05835cc1ce558197ae4fbd1e514f4bf46a3e1539 | dfe0ff3dd471b65ac345c87c82afe102a4dfdc73 | /src/stats.h | e825292a80133c49d377140109ed637c32ba0fa7 | [] | no_license | GedasTheEvil/game-dungeon-crawl | 6254b9d191f25f11cda190c1b0b62dd00290602e | 90c83ebf74a2f0effabfdef245cece58b83d170a | refs/heads/master | 2021-01-21T11:08:52.046055 | 2015-07-12T17:02:57 | 2015-07-12T17:02:57 | 38,969,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 798 | h | #ifndef StatsH
#define StatsH
#include "monster.h"
#include "item.h"
#include "inventory.h"
#include "fstream"
class stats
{
private:
int level;
double XP;
bool AdvanceLevel();
int Armor;
int MaxHP;
int HP;
int Might;
Font Impact;
float realPscale; // player scale
float realIscale; // item scale
timer *stats_ani;
public:
int Damage();
bool show;
void GetStronger(int ns = 1);
void Draw();
void GetXP(int xp);
void Heal(int hp_part);
stats();
~stats();
void GetArmored(int na = 1);
void GetHit(int dmg);
void MouseFunction(int button, int state , int x, int y);
void GetTougher(int hp_part);
void Dump(std::ofstream &f);
void LoadDump(std::ifstream &f);
};
#endif
| [
"gediminas.skucas@gmail.com"
] | gediminas.skucas@gmail.com |
4846318cb40a61f6824692838993836444a0d659 | ffecc2faee340865d375270c4b3af358ceb2c8df | /src/plug/host/internal_filter.cpp | 3f046f0c96c879183868e22ddb8c7b55b664d40d | [
"MIT"
] | permissive | ompu/ompu | c81a184162ff7b166b85e8748b2aefd6b6869010 | c45d292a0af1b50039db9aa79e444fb7019615e9 | refs/heads/master | 2018-12-18T13:56:36.786538 | 2018-09-14T15:37:33 | 2018-09-14T15:37:33 | 103,842,388 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,328 | cpp | #include "ompu/plug/host/internal_filter.hpp"
#include "ompu/plug/host/filter_graph.hpp"
namespace ompu { namespace plug { namespace host {
InternalPluginFormat::InternalPluginFormat()
{
{
juce::AudioProcessorGraph::AudioGraphIOProcessor p (juce::AudioProcessorGraph::AudioGraphIOProcessor::audioOutputNode);
p.fillInPluginDescription (audioOutDesc);
}
{
juce::AudioProcessorGraph::AudioGraphIOProcessor p (juce::AudioProcessorGraph::AudioGraphIOProcessor::audioInputNode);
p.fillInPluginDescription (audioInDesc);
}
{
juce::AudioProcessorGraph::AudioGraphIOProcessor p (juce::AudioProcessorGraph::AudioGraphIOProcessor::midiInputNode);
p.fillInPluginDescription (midiInDesc);
}
}
void InternalPluginFormat::createPluginInstance (const juce::PluginDescription& desc,
double /*initialSampleRate*/,
int /*initialBufferSize*/,
void* userData,
void (*callback) (void*, juce::AudioPluginInstance*, const juce::String&))
{
juce::AudioPluginInstance* p = nullptr;
if (desc.name == audioOutDesc.name) p = new juce::AudioProcessorGraph::AudioGraphIOProcessor (juce::AudioProcessorGraph::AudioGraphIOProcessor::audioOutputNode);
if (desc.name == audioInDesc.name) p = new juce::AudioProcessorGraph::AudioGraphIOProcessor (juce::AudioProcessorGraph::AudioGraphIOProcessor::audioInputNode);
if (desc.name == midiInDesc.name) p = new juce::AudioProcessorGraph::AudioGraphIOProcessor (juce::AudioProcessorGraph::AudioGraphIOProcessor::midiInputNode);
callback (userData, p, p == nullptr ? NEEDS_TRANS ("Invalid internal filter name") : juce::String());
}
bool InternalPluginFormat::requiresUnblockedMessageThreadDuringCreation (const juce::PluginDescription&) const noexcept
{
return false;
}
void InternalPluginFormat::getAllTypes (juce::OwnedArray<juce::PluginDescription>& results)
{
results.add (new juce::PluginDescription (audioInDesc));
results.add (new juce::PluginDescription (audioOutDesc));
results.add (new juce::PluginDescription (midiInDesc));
}
}}} // ompu
| [
"saki7@setna.io"
] | saki7@setna.io |
c1e253de14e99a6e3505acbb420b1b2fc31fe641 | 6ced41da926682548df646099662e79d7a6022c5 | /aws-cpp-sdk-fsx/source/model/UpdateOntapVolumeConfiguration.cpp | b410ea7c520a8fe5c850304081068369634b6535 | [
"Apache-2.0",
"MIT",
"JSON"
] | permissive | irods/aws-sdk-cpp | 139104843de529f615defa4f6b8e20bc95a6be05 | 2c7fb1a048c96713a28b730e1f48096bd231e932 | refs/heads/main | 2023-07-25T12:12:04.363757 | 2022-08-26T15:33:31 | 2022-08-26T15:33:31 | 141,315,346 | 0 | 1 | Apache-2.0 | 2022-08-26T17:45:09 | 2018-07-17T16:24:06 | C++ | UTF-8 | C++ | false | false | 2,891 | cpp | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/fsx/model/UpdateOntapVolumeConfiguration.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace FSx
{
namespace Model
{
UpdateOntapVolumeConfiguration::UpdateOntapVolumeConfiguration() :
m_junctionPathHasBeenSet(false),
m_securityStyle(SecurityStyle::NOT_SET),
m_securityStyleHasBeenSet(false),
m_sizeInMegabytes(0),
m_sizeInMegabytesHasBeenSet(false),
m_storageEfficiencyEnabled(false),
m_storageEfficiencyEnabledHasBeenSet(false),
m_tieringPolicyHasBeenSet(false)
{
}
UpdateOntapVolumeConfiguration::UpdateOntapVolumeConfiguration(JsonView jsonValue) :
m_junctionPathHasBeenSet(false),
m_securityStyle(SecurityStyle::NOT_SET),
m_securityStyleHasBeenSet(false),
m_sizeInMegabytes(0),
m_sizeInMegabytesHasBeenSet(false),
m_storageEfficiencyEnabled(false),
m_storageEfficiencyEnabledHasBeenSet(false),
m_tieringPolicyHasBeenSet(false)
{
*this = jsonValue;
}
UpdateOntapVolumeConfiguration& UpdateOntapVolumeConfiguration::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("JunctionPath"))
{
m_junctionPath = jsonValue.GetString("JunctionPath");
m_junctionPathHasBeenSet = true;
}
if(jsonValue.ValueExists("SecurityStyle"))
{
m_securityStyle = SecurityStyleMapper::GetSecurityStyleForName(jsonValue.GetString("SecurityStyle"));
m_securityStyleHasBeenSet = true;
}
if(jsonValue.ValueExists("SizeInMegabytes"))
{
m_sizeInMegabytes = jsonValue.GetInteger("SizeInMegabytes");
m_sizeInMegabytesHasBeenSet = true;
}
if(jsonValue.ValueExists("StorageEfficiencyEnabled"))
{
m_storageEfficiencyEnabled = jsonValue.GetBool("StorageEfficiencyEnabled");
m_storageEfficiencyEnabledHasBeenSet = true;
}
if(jsonValue.ValueExists("TieringPolicy"))
{
m_tieringPolicy = jsonValue.GetObject("TieringPolicy");
m_tieringPolicyHasBeenSet = true;
}
return *this;
}
JsonValue UpdateOntapVolumeConfiguration::Jsonize() const
{
JsonValue payload;
if(m_junctionPathHasBeenSet)
{
payload.WithString("JunctionPath", m_junctionPath);
}
if(m_securityStyleHasBeenSet)
{
payload.WithString("SecurityStyle", SecurityStyleMapper::GetNameForSecurityStyle(m_securityStyle));
}
if(m_sizeInMegabytesHasBeenSet)
{
payload.WithInteger("SizeInMegabytes", m_sizeInMegabytes);
}
if(m_storageEfficiencyEnabledHasBeenSet)
{
payload.WithBool("StorageEfficiencyEnabled", m_storageEfficiencyEnabled);
}
if(m_tieringPolicyHasBeenSet)
{
payload.WithObject("TieringPolicy", m_tieringPolicy.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace FSx
} // namespace Aws
| [
"aws-sdk-cpp-automation@github.com"
] | aws-sdk-cpp-automation@github.com |
ccebd8246f61c14809de85fb215b0174337a0ab8 | 95ce3386827693d213e6f3688242aabe0ce3abe8 | /preparedata/dealdata.cpp | 01c40c84a99738c3fd8595b9bfe0ca0b582ef9a3 | [] | no_license | alwayschasing/schoolWork | 99773cf459e2833a3301ffa2d78df19e724b5bf0 | 75b038e3230a3b03298dd5db754a9dee007c1a3b | refs/heads/master | 2021-06-18T15:29:46.353040 | 2017-06-14T07:40:59 | 2017-06-14T07:40:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,555 | cpp | /*************************************************************************
> File Name: dealdata.cpp
> Author: ruihong
> Mail:
> Created Time: 2016年12月20日 星期二 21时05分32秒
************************************************************************/
#include<iostream>
#include<fstream>
#include<regex>
#include"dealdata.h"
UBasedData::UBasedData(int hs):uhashtable(vector<vector<uunit>*>(hs,NULL)),hashsize(hs){
//usernumber = unum;
//hashsize = hs;
//uhashtable = vector<vector<uunit>*>(hs,NULL);
}
void UBasedData::setUserNum(int unum){
usernumber = unum;
}
int UBasedData::getUserNum(){
return usernumber;
}
PrepareData::PrepareData(string rawdatapath,int userhashsize,int itemhashsize)
:datapath(rawdatapath),user_hash_size(userhashsize),item_hash_size(itemhashsize){
//datapath = rawdatapath;
//user_hash_size = userhashsize;
//item_hash_size = itemhashsize;
}
UBasedData::~UBasedData(){
int size = uhashtable.size();
for(int i = 0; i < size; ++i){
if(uhashtable[i] != NULL){
delete uhashtable[i];
}
}
}
IBasedData::IBasedData(int hs):ihashtable(vector<vector<iunit>*>(hs,NULL)),hashsize(hs){}
IBasedData::~IBasedData(){
int size = ihashtable.size();
for(int i = 0; i < size; ++i){
if(ihashtable[i] != NULL){
delete ihashtable[i];
}
}
}
//the uunit and iunit initial function
uunit::uunit(int movid,int rating,int time):movid(movid),rating(rating),time(time){}
iunit::iunit(int userid,int rating,int time):userid(userid),rating(rating),time(time){}
UBasedData* PrepareData::getUserBasedData(){
regex reg(".*\\.dat$");
//detect the delimiter character befor user and item
if(regex_match(datapath,reg)) delim = ':';
ifstream input(datapath);
char *title = new char[35];
char *dm = new char[3];
int userid;
int itemid;
int rating;
int timestamp;
//define the UBasedData
UBasedData* u2item = new UBasedData(user_hash_size);
//process the .dat file
if(delim == ':'){
while(!input.eof()){
input>>userid;
input.get(dm,3);
input>>itemid;
input.get(dm,3);
input>>rating;
input.get(dm,3);
input>>timestamp;
input.get();
//cout<<userid<<','<<itemid<<','<<rating<<','<<timestamp<<endl;
if(u2item->uhashtable[userid] == NULL){
u2item->uhashtable[userid] = new vector<uunit>();
(*u2item->uhashtable[userid]).push_back(uunit(itemid,rating,timestamp));
}else{
(*u2item->uhashtable[userid]).push_back(uunit(itemid,rating,timestamp));
}
}
}
//precess the .csv file
else if(delim == ','){
input.getline(title,35);
while(!input.eof()){
input>>userid;
input.get();
input>>itemid;
input.get();
input>>rating;
input.get();
input>>timestamp;
input.get();
//cout<<userid<<','<<itemid<<','<<rating<<','<<timestamp<<endl;
if(u2item->uhashtable[userid] == NULL){
u2item->uhashtable[userid] = new vector<uunit>();
(*u2item->uhashtable[userid]).push_back(uunit(itemid,rating,timestamp));
}else{
(*u2item->uhashtable[userid]).push_back(uunit(itemid,rating,timestamp));
}
}
}
else cout<<"input get errors"<<endl;
input.close();
delete [] title;
delete [] dm;
return u2item;
}
IBasedData* PrepareData::getItemBasedData(){
regex reg(".*\\.dat$");
//detect the delimiter character befor user and item
if(regex_match(datapath,reg)) delim = ':';
ifstream input(datapath);
char *title = new char[35];
char *dm = new char[3];
int userid;
int itemid;
int rating;
int timestamp;
IBasedData* i2user = new IBasedData(item_hash_size);
if(delim == ':'){
while(!input.eof()){
input>>userid;
input.get(dm,3);
input>>itemid;
input.get(dm,3);
input>>rating;
input.get(dm,3);
input>>timestamp;
input.get();
//cout<<userid<<','<<itemid<<','<<rating<<','<<timestamp<<endl;
if(i2user->ihashtable[itemid] == NULL){
i2user->ihashtable[itemid] = new vector<iunit>();
(*i2user->ihashtable[itemid]).push_back(iunit(userid,rating,timestamp));
}else{
(*i2user->ihashtable[itemid]).push_back(iunit(userid,rating,timestamp));
}
}
}
else if(delim == ','){
input.getline(title,35);
while(!input.eof()){
input>>userid;
input.get();
input>>itemid;
input.get();
input>>rating;
input.get();
input>>timestamp;
input.get();
//cout<<userid<<','<<itemid<<','<<rating<<','<<timestamp<<endl;
if(i2user->ihashtable[userid] == NULL){
i2user->ihashtable[userid] = new vector<iunit>();
(*i2user->ihashtable[itemid]).push_back(iunit(userid,rating,timestamp));
}else{
(*i2user->ihashtable[itemid]).push_back(iunit(userid,rating,timestamp));
}
}
}
else cout<<"input get error"<<endl;
input.close();
delete [] title;
delete [] dm;
return i2user;
}
| [
"13021131633@163.com"
] | 13021131633@163.com |
c6aa15870a4b121cdf52aca78737d7806f302903 | f22443112f789b2265ca111b8972408b13d43a29 | /Source/Vec2.cpp | 3f24cbedb05329e8c3ed27d79b9f73cca959b0b3 | [] | no_license | vvasilescu-uni/KekeIsYou | f22a4aef4fd2cc82dcde38e19c97d6e6c8b7661e | 0a850fc9fc4d243b246334be4dae8c26dd32481b | refs/heads/master | 2022-01-27T18:15:22.849505 | 2019-05-30T17:33:04 | 2019-05-30T17:33:04 | 182,148,709 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,126 | cpp | //-----------------------------------------------------------------------------
// File: Vec2.h
//
// Desc: Defines vector based co-ords used throughout game.
// Overrides operators to allow two entry vector based calculations
//
//-----------------------------------------------------------------------------
//-----------------------------------------------------------------------------
// Vec2 Specific Includes
//-----------------------------------------------------------------------------
#include "../Includes/Vec2.h"
#include "../Includes/Main.h"
Vec2& Vec2::operator-()
{
x = -x;
y = -y;
return *this;
}
bool Vec2::operator==(Vec2 v)
{
return (x == v.x && y == v.y);
}
bool Vec2::operator!=(Vec2 v)
{
return (x != v.x || y != v.y);
}
Vec2 Vec2::operator+(Vec2 v)
{
return Vec2(x + v.x, y + v.y);
}
Vec2 Vec2::operator-(Vec2 v)
{
return Vec2(x - v.x, y - v.y);
}
Vec2& Vec2::operator+=(Vec2 v)
{
*this = *this + v;
return *this;
}
Vec2& Vec2::operator-=(Vec2 v)
{
*this = *this - v;
return *this;
}
double Vec2::Magnitude() const
{
return sqrt(x*x + y*y);
}
double Vec2::Argument() const
{
if (x < 0.0)
{
return PI + atan(y / x);
}
else if (fabs(x) < EPS)
{
return (y > 0 ? PI : -PI);
}
else
{
return atan(y / x);
}
}
double Vec2::Distance(Vec2 v) const // Euclidean distance
{
double dx = x - v.x;
double dy = y - v.y;
return sqrt(dx*dx + dy*dy);
}
Vec2 Polar(double r, double radians)
{
Vec2 result;
if (r < 0)
{
r = -r;
}
radians = PrincipleAngle(radians);
result.x = r * cos(radians);
result.y = r * sin(radians);
return result;
}
double Vec2::operator*(Vec2 v) // dot product
{
return x*v.x + y*v.y;
}
void Vec2::Rotate(double radians)
{
double xx = cos(radians)*x - sin(radians)*y;
double yy = sin(radians)*x + cos(radians)*y;
x = xx;
y = yy;
}
Vec2 Vec2::operator*(double s) // scale
{
return Vec2(s*x, s*y);
}
Vec2 Vec2::operator/(double s) // scale
{
return Vec2(x/s, y/s);
}
double PrincipleAngle(double radians)
{
double result = fmod(radians, 2 * PI);
if (radians > 0)
{
return result;
}
else
{
return 2 * PI + result;
}
}
| [
"vladvas98@yahoo.com"
] | vladvas98@yahoo.com |
0d4e12a165bef52313c0cf7c4530e9e2c4350cc4 | 52d4552da2077b275755211b15937249636fd70c | /Examples/Code Constructs/Conditionals/Conditionals.cpp | eca5ada5f1438ebf95eed99fdda28c8bb8b74bd3 | [] | no_license | nnandiha/SREClass | 49376086b939e07a3895897b613a9cc2453212a1 | a8fee61cb0134c8de3af6a848457704ab4899a09 | refs/heads/master | 2020-06-24T11:31:57.254421 | 2016-05-11T13:27:56 | 2016-05-11T13:27:56 | 96,933,611 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | // Conditionals.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
int _tmain(int argc, _TCHAR* argv[])
{
int x = 0;
scanf("Enter a number: %d", &x);
if (x < 3){
printf("%d is too small!\n", x);
}
else{
printf("%d is big enough!\n", x);
}
return 0;
}
| [
"nayan.nandihalli@intel.com"
] | nayan.nandihalli@intel.com |
ae1556dc9e56a5ebf19ee30ab38b0e1833d7b55f | 4724afa8472b0d961d40cc3be71f5abd1373143f | /spoj/avchess.cpp | a946edd316ef2340c84794f7e4280898f10f3405 | [] | no_license | banarun/my_competitive_codes | 2f88334c563ad050c21c68ae449134a28fb2ba95 | c5a5af3cf74341d02a328974e8e316d300a221b2 | refs/heads/master | 2021-01-18T22:46:47.419449 | 2016-06-25T14:14:15 | 2016-06-25T14:14:15 | 33,266,178 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,503 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <cstring>
#include <ctime>
#include <vector>
#include <deque>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <bitset>
#include <string>
#include <algorithm>
#include <complex>
#include <climits>
#include <utility>
using namespace std;
#ifdef DEBUG
#define dbg(args...) { cerr<<#args<<": "; dbgr,args; cerr<<endl;}
#else
#define dbg(args...)
#endif
struct debugger{template<typename T> debugger& operator , (const T& v){cerr<<v<<" "; return *this; }}dbgr;
typedef pair <int, int> ii;
const int Inf = 1000000000;
const int Maxn = 8;
const int Maxd = 8;
const int Maxdo = 4;
const int kdy[Maxd] = {-2, -2, -1, -1, 1, 1, 2, 2};
const int kdx[Maxd] = {-1, 1, -2, 2, -2, 2, -1, 1};
const int rdy[Maxdo] = {-1, 0, 0, 1};
const int rdx[Maxdo] = {0, -1, 1, 0};
const int bdy[Maxdo] = {-1, -1, 1, 1};
const int bdx[Maxdo] = {-1, 1, -1, 1};
struct pos {
ii c1, c2, c3;
int tim;
pos(ii c1 = ii(0, 0), ii c2 = ii(0, 0), ii c3 = ii(0, 0), int tim = 0): c1(c1), c2(c2), c3(c3), tim(tim) {}
bool operator ==(const pos &p) const {
return c1 == p.c1 && c2 == p.c2 && c3 == p.c3;
}
};
int t;
pos s, e;
int dist[Maxn][Maxn][Maxn][Maxn][Maxn][Maxn][3];
queue <pos> Q;
int res;
void Update(const pos &u, int d)
{
if (d < dist[u.c1.first][u.c1.second][u.c2.first][u.c2.second][u.c3.first][u.c3.second][u.tim]) {
dist[u.c1.first][u.c1.second][u.c2.first][u.c2.second][u.c3.first][u.c3.second][u.tim] = d;
Q.push(u);
}
}
void goKnight(const pos &p, int dy, int dx, int d)
{
pos u(ii(p.c1.first + dy, p.c1.second + dx), p.c2, p.c3, 1);
if (0 <= u.c1.first && u.c1.first < Maxn && 0 <= u.c1.second && u.c1.second < Maxn && u.c1 != u.c2 && u.c1 != u.c3)
Update(u, d);
}
void goRook(const pos &p, int cy, int cx, int dy, int dx, int d)
{
pos u(p.c1, ii(p.c2.first + cy, p.c2.second + cx), p.c3, 2);
if (0 <= u.c2.first && u.c2.first < Maxn && 0 <= u.c2.second && u.c2.second < Maxn && u.c1 != u.c2 && u.c2 != u.c3) {
Update(u, d); goRook(p, cy + dy, cx + dx, dy, dx, d);
}
}
void goBishop(const pos &p, int cy, int cx, int dy, int dx, int d)
{
pos u(p.c1, p.c2, ii(p.c3.first + cy, p.c3.second + cx), 0);
if (0 <= u.c3.first && u.c3.first < Maxn && 0 <= u.c3.second && u.c3.second < Maxn && u.c3 != u.c1 && u.c3 != u.c2) {
Update(u, d); goBishop(p, cy + dy, cx + dx, dy, dx, d);
}
}
int main()
{
scanf("%d", &t);
while (t--) {
scanf("%d %d %d %d %d %d", &s.c1.first, &s.c1.second, &s.c2.first, &s.c2.second, &s.c3.first, &s.c3.second); s.tim = 0;
e = pos(s.c3, s.c1, s.c2);
fill((int*)dist, (int*)dist + Maxn * Maxn * Maxn * Maxn * Maxn * Maxn * 3, Inf);
while (!Q.empty()) Q.pop();
res = -1;
dist[s.c1.first][s.c1.second][s.c2.first][s.c2.second][s.c3.first][s.c3.second][s.tim] = 0;
Q.push(s);
while (!Q.empty()) {
s = Q.front(); int d = dist[s.c1.first][s.c1.second][s.c2.first][s.c2.second][s.c3.first][s.c3.second][s.tim]; Q.pop();
if (s == e) { res = d; break; }
if (s.tim == 0)
for (int i = 0; i < Maxd; i++)
goKnight(s, kdy[i], kdx[i], d + 1);
else if (s.tim == 1)
for (int i = 0; i < Maxdo; i++)
goRook(s, rdy[i], rdx[i], rdy[i], rdx[i], d + 1);
else for (int i = 0; i < Maxdo; i++)
goBishop(s, bdy[i], bdx[i], bdy[i], bdx[i], d + 1);
}
printf("%d\n", res);
}
return 0;
}
| [
"banarunk@gmail.com"
] | banarunk@gmail.com |
465cc4ff54ff2069991842c316fdfe2a84f7a5cf | e8c79a50bb3ae6de451fbbae6e6865677626a07c | /overload/overload-function.cpp | 7acc3e7e23d9950a040b5d257168b2395ffb9c53 | [] | no_license | doc-cloud/cpp | 24ddf931a501d4660c6755587500d4989b9b1639 | c9dfe9d527b04d3d0890f2a3effed3b9e7f2a373 | refs/heads/master | 2021-01-23T23:04:17.952391 | 2017-09-09T13:03:47 | 2017-09-09T13:03:47 | 102,954,864 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 374 | cpp | #include <iostream>
using namespace std;
class printData {
public:
void print(int i)
{
cout << "Printing int : " << i << endl;
}
void print(double i)
{
cout << "Printing float : " << i << endl;
}
void print(string i)
{
cout << "Printing string : " << i << endl;
}
};
int main()
{
printData pd;
pd.print(5);
pd.print(55.234);
pd.print("fadfadqwqwer");
}
| [
"Linkerist@163.com"
] | Linkerist@163.com |
93f6924b6abb9aa086d92d538ff22e6bfc0e3552 | ff80072eacc2cc9dc849380b793cab0233d33439 | /oarphkit_test/ok/fli/Core/CoreTest.cpp | 4d0b76cd44dd56d3b34bf0dacba6213be3e40a5a | [
"Apache-2.0"
] | permissive | pwais/oarphkit | 3477d71420c274cb56e22bf7ff08450a050ae7b4 | e799e7904d5b374cb6b58cd06a42d05506e83d94 | refs/heads/master | 2021-01-01T05:59:31.179043 | 2015-09-09T08:17:18 | 2015-09-09T08:17:18 | 39,921,203 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,992 | cpp | /*
* Copyright 2015 Maintainers of OarphKit
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "gtest/gtest.h"
#include "ok/fli/Core/Core.hpp"
#include "ok_test/fli/OKFliUtils.hpp"
using namespace ok::fli;
TEST(OKFLiTypeCheckTest, TestFatal) {
EXPECT_NO_THROW(
OK_FLI_TYPECHECK(typeid(int), typeid(int), "test"));
#if OK_FLI_EXCEPTIONS_ENABLED
EXPECT_THROW(
OK_FLI_TYPECHECK(typeid(int), typeid(float), "test"),
OK_FLI_TYPECHECK_ERROR_EXCEPTION_TYPE);
#else
EXPECT_NO_THROW(OK_FLI_TYPECHECK(typeid(int), typeid(float), "test"));
#endif
}
TEST(OKFLiRTDatumTest, TestEmpty) {
rt_datumptr d;
EXPECT_EQ(nullptr, d.value);
#if OK_FLI_RUNTIME_TYPECHECK_ENABLED
EXPECT_EQ(std::type_index(typeid(nullptr)), d.type);
#else
EXPECT_EQ(sizeof(d), sizeof(d.value));
#endif
}
TEST(OKFLiRTDatumTest, TestIntegral) {
auto xup = std::unique_ptr<int>(new int);
*xup = 5;
rt_datumptr d = rt_datumptr::Wrap(std::move(xup));
EXPECT_TRUE(!xup); // datum now owns x
EXPECT_TRUE(d.value);
EXPECT_EQ(5, *d.Get<int>());
EXPECT_EQ(5, d.GetRef<int>());
EXPECT_RT_EQ(std::type_index(typeid(int)), d.type);
EXPECT_RT_THROW(d.Get<float>());
}
TEST(OKFLiRTDatumTest, TestStruct) {
struct oarph { int x; };
auto oup = std::unique_ptr<oarph>(new oarph());
oup->x = 5;
rt_datumptr d = rt_datumptr::Wrap(std::move(oup));
EXPECT_TRUE(!oup); // datum now owns o
EXPECT_TRUE(d.value);
EXPECT_EQ(5, d.Get<oarph>()->x);
EXPECT_EQ(5, d.GetRef<oarph>().x);
EXPECT_RT_EQ(std::type_index(typeid(oarph)), d.type);
EXPECT_RT_THROW(d.Get<float>());
}
TEST(OKFLiCTDatumTest, TestEmpty) {
ct_datumptr d;
EXPECT_EQ(nullptr, d.value);
#if OK_FLI_COMPILETIME_TYPECHECK_ENABLED
EXPECT_EQ(std::type_index(typeid(nullptr)), d.type);
#else
EXPECT_EQ(sizeof(d), sizeof(d.value));
#endif
}
TEST(OKFLiCTDatumTest, TestIntegral) {
auto xup = std::unique_ptr<int>(new int);
*xup = 5;
ct_datumptr d = ct_datumptr::Wrap(std::move(xup));
EXPECT_TRUE(!xup); // datum now owns x
EXPECT_TRUE(d.value);
EXPECT_EQ(5, *d.Get<int>());
EXPECT_EQ(5, d.GetRef<int>());
EXPECT_CT_EQ(std::type_index(typeid(int)), d.type);
EXPECT_CT_THROW(d.Get<float>());
}
TEST(OKFLiCTDatumTest, TestStruct) {
struct oarph { int x; };
auto oup = std::unique_ptr<oarph>(new oarph());
oup->x = 5;
ct_datumptr d = ct_datumptr::Wrap(std::move(oup));
EXPECT_TRUE(!oup); // datum now owns o
EXPECT_TRUE(d.value);
EXPECT_EQ(5, d.Get<oarph>()->x);
EXPECT_EQ(5, d.GetRef<oarph>().x);
EXPECT_CT_EQ(std::type_index(typeid(oarph)), d.type);
EXPECT_CT_THROW(d.Get<float>());
}
class TestAddOneFunctor : public FunctorBase {
public:
TestAddOneFunctor() { }
virtual ~TestAddOneFunctor() { }
int AddOne(int x) {
auto in = std::unique_ptr<int>(new int);
*in = x;
auto result_datum = this->Call(rt_datumptr::Wrap(std::move(in)));
return result_datum.GetRef<int>();
}
protected:
virtual rt_datumptr Call(rt_datumptr in) override {
int x = in.GetRef<int>();
auto out = std::unique_ptr<int>(new int);
*out = x + 1;
return rt_datumptr::Wrap(std::move(out));
}
};
TEST(OKFLiFunctorBase, TestBasic) {
TestAddOneFunctor f;
EXPECT_EQ(6, f.AddOne(5));
}
TEST(OKFLiFunctorBase, TestPB) {
auto kMsg = "";
auto f = MakeOwned(new FunctorBase());
auto f_decoded =
ok_test::CheckFunctorEncoding(*f, kMsg, true /* is pure */);
#if OK_ENABLE_PROTOBUF
EXPECT_TRUE(f_decoded);
#endif
}
| [
"paulwais@gmail.com"
] | paulwais@gmail.com |
00bdbc9289c4f3a9aee9e19dd56fd0aaaff00096 | d560580abd8cde94c0bfa5674124c30d87355a47 | /AED/7/7q4.cpp | 525a5b7b79ca4473fabfa72925a34701818f8df4 | [
"MIT"
] | permissive | Iigorsf/AED | 22efa9b2d9521f17209a2f651e9673d4d88c2174 | 2151ef562be8088cd76efe7afb9e73b165027fa1 | refs/heads/main | 2023-01-02T19:58:04.807746 | 2020-10-30T18:02:34 | 2020-10-30T18:02:34 | 308,702,936 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 664 | cpp | #include <iostream>
using namespace std;
struct atleta
{
string nome;
string esport;
int idade;
float altura;
};
int main(int argc, char **argv)
{
int velho , maior1=0, velho1=0;
float maior;
atleta atl[5];
for( int i=0; i<5; i++){
cin>>atl[i].nome;
cin>>atl[i].esport;
cin>>atl[i].idade;
cin>>atl[i].altura;
}
maior=atl[0].altura;
velho=atl[0].idade;
for( int i=0; i<5; i++){
if(atl[i].altura>maior){
maior=atl[i].altura;
maior1=i;
}
if(atl[i].idade>velho){
velho=atl[i].idade;
velho1=i;
}
}
cout<<atl[maior1].nome<<" "<<atl[maior1].esport<<endl;
cout<<atl[velho1].nome<<" "<<atl[velho1].esport<<endl;
return 0;
}
| [
"igordo.sf@gmail.com"
] | igordo.sf@gmail.com |
e78d1a5cac50407cd1375a5aa4e0e0d7dee3627f | 30a7f84922ee4bccbc446d35184e749d78479b07 | /src/CWBEMObject.h | b7fc4b1ff2d700967d9621b633f35c8ddbbb3d38 | [] | no_license | JonAxtell/WMIApp-AsyncQuery | 03668ca41128cd993e5b183f2db4b8e9102cf89c | e654071bb0e7ab3da4fe05e460eb958e668750dd | refs/heads/master | 2020-04-28T06:08:26.967032 | 2019-11-22T09:32:52 | 2019-11-22T09:32:52 | 175,045,384 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,598 | h | #pragma once
#include "pch.h"
#include "CVariant.h"
#include "CWBEMProperty.h"
#define _WIN32_DCOM
#include <iostream>
using namespace std;
#include <comdef.h>
#include <Wbemidl.h>
#ifndef __MINGW_GCC_VERSION
#pragma comment(lib, "wbemuuid.lib")
#endif
#include <vector>
#include <memory>
//#################################################################################################################################
//
// Class that encapsulates the process of retrieving a data set from the WBEM sub system in Windows and storing it
// in a vector of variants.
//
// A WBEM object is something like the Operating System or a Printer or a Process. Each object can have many properties from
// common ones like a description to properties tied to the object such as stepping model for a processor. A system can
// have either single objects (a single OS) or multiple ones (multiple printers).
//
class CWBEMObject
{
public:
typedef std::pair<int, const CWBEMProperty*> index_property_t;
// Default constructor
CWBEMObject() {}
// Copy constructor (does a deep copy of the whole vector)
CWBEMObject(const CWBEMObject& other)
{
for (auto p : other._properties)
{
_properties.push_back(p);
}
}
// Move constructor (just transfers the vector)
CWBEMObject(CWBEMObject&& other)
{
this->swap(other);
}
// Destructor, deletes all objects in the vector
virtual ~CWBEMObject()
{
for (std::vector<CWBEMProperty*>::iterator p = _properties.begin(); p != _properties.end(); ++p)
{
delete (*p);
(*p) = nullptr;
}
_properties.clear();
}
// Copy assignment (does a deep copy of the whole vector)
CWBEMObject& operator=(const CWBEMObject& other)
{
for (auto p : other._properties)
{
_properties.push_back(p);
}
return *this;
}
// Move assignment (just transfers the vector)
CWBEMObject& operator=(CWBEMObject&& other)
{
this->swap(other);
return *this;
}
// Public swap function for use in move operations
friend void swap(CWBEMObject& first, CWBEMObject& second)
{
first.swap(second);
}
void swap(CWBEMObject &other)
{
using std::swap;
swap(_properties, other._properties);
swap(_propertyCount, other._propertyCount);
}
// Method that gets the properties from the service and places them in the _properties array
virtual void Populate(const char** propertyNames, IWbemClassObject __RPC_FAR * pwbemObj);
// Methods to access the properties
const std::vector<CWBEMProperty* >& Properties() const { return _properties; }
std::vector<index_property_t> Properties(enum VARENUM type) const;
const CWBEMProperty Property(int prop) const { return (*Properties().at(prop)); }
// Methdos to access details about the properties
virtual const char* PropertyName(int prop) = 0;
unsigned int PropertyCount()
{
if (_propertyCount == 0)
{
// If count is zero, assume that the list of property names in the derived class hasn't been scanned yet.
// This is done here rather because you can't call a method in a derived class from a virtual base class's constructor.
while (PropertyName(_propertyCount++))
{
}
--_propertyCount;
}
return _propertyCount;
}
private:
unsigned int _propertyCount{ 0 };
std::vector<CWBEMProperty* > _properties;
};
| [
"jaxtell@innovative-technology.com"
] | jaxtell@innovative-technology.com |
b7db4ddfc33adf50cf69cdf6689ecb5ad6dbb7ce | 01af2e0a1ab3e0fb3e48fe6186e5968630d01610 | /Palindrome/Pal.h | a821b1c83973914672c60ca775140fc92322ce68 | [] | no_license | iznor/CPP-Projects | 552d56e935254e22ca7ac98af6c7c4751d40b00f | dfe2cc33248e981a710a1a43619f0ce407298c4e | refs/heads/main | 2023-02-18T17:27:38.378245 | 2021-01-16T16:41:41 | 2021-01-16T16:41:41 | 330,054,085 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,478 | h | #ifndef PLDRM
#define PLDRM
#include <iostream>
#include <cstring>
using namespace std;
#define MAX 50
class Pallindrome{
public:
Pallindrome(): original(nullptr), pallindrome(nullptr) ,size(0){}
Pallindrome(const char* string, int Size);
Pallindrome(const char* pallindrome_string);
Pallindrome(const Pallindrome& other);
~Pallindrome();
public:
// Binar Operators
Pallindrome& operator=(const Pallindrome& other);// Deep copy
Pallindrome operator+(const Pallindrome& other)const;
Pallindrome& operator+=(const Pallindrome& other);
Pallindrome& operator+=(const char to_append);
Pallindrome& operator-=(const Pallindrome& other);
bool operator==(const Pallindrome& other)const;
bool operator<(const Pallindrome& other)const;
// Unar Operators
Pallindrome& operator!();
Pallindrome operator++(int);
const char* operator()()const;
const char& operator[](int index)const;
public:
void Print()const;
char* get_original()const;
char* get_pallindrome()const;
int get_size()const;
bool odd_original()const;
bool short_pallindrome()const;
bool empty()const;
bool sub_pallindrome(const Pallindrome& other)const;
bool valid_index(int index)const;
private:
char *pallindrome;
char *original;
int size;
void set_size(int new_size);
void set_original(char* new_org);
void set_pallindrome(char* new_pall);
int leftShift(char* string);// deletes the first char of a given string
char *strremove(char *str, const char *sub);
void reverse_string(char* string,int pallindrome_size); // Especially reverse a string according to a specific size given (can only work for 2*strlen or (2*strlen)-1)
void clear_obj();
friend ostream &operator<<(ostream &out, const Pallindrome& p);
};
char* get_original_from_pallindrome(const char* string);// get a copy of the original string from a given pallindrome (doesn't change the given string)
bool isPallindrome(const char *str);
bool isPallindrome(char *str);
bool ValidChars(const char *string);// Valid chars check (doesn't change the given string)
istream &operator>>(istream &in, Pallindrome &pallindrome);// Input a string to Pallindrome object: if the string is a valid pallindrome - object will represent it. else, default c'tor.
ostream &operator<<(ostream &out, const Pallindrome &pallindrome);
#endif | [
"noreply@github.com"
] | noreply@github.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.