text
stringlengths 8
6.88M
|
|---|
/*
* ulcd_label.h
*
*
*
*/
#ifndef ULCD_LABEL_H
#define ULCD_LABEL_H
#include "ulcd_component.h"
//#include <iostream>
#include <string>
#include "uLCD_4DLibrary.h"
/*
* public types
*
*/
typedef enum
{
ulcd_font_size_1 = 1,
ulcd_font_size_2 = 2,
ulcd_font_size_3 = 3,
ulcd_font_size_4 = 4,
ulcd_font_size_5 = 5,
ulcd_font_size_6 = 6,
ulcd_font_size_7 = 7,
ulcd_font_size_8 = 8,
ulcd_font_size_9 = 9,
ulcd_font_size_10 = 10,
ulcd_font_size_11 = 11,
ulcd_font_size_12 = 12,
ulcd_font_size_13 = 13,
ulcd_font_size_14 = 14,
ulcd_font_size_15 = 15,
ulcd_font_size_16 = 16
} ulcd_font_size;
typedef enum
{
h_center ,
h_right ,
h_left
} ulcd_h_alignment;
typedef enum
{
v_center ,
v_top ,
v_bottom
} ulcd_v_alignment;
typedef struct
{
ulcd_v_alignment v_alignment;
ulcd_h_alignment h_alignment;
} ulcd_alignment_t;
/*
* public class
*
*/
class ulcd_label : public ulcd_component
{
private :
uLCD_4DLibrary* m_lcd;
void write_text();
public :
ulcd_alignment_t m_alignment;
string m_text;
uint16_t m_foreground_color, m_background_color;
ulcd_font_size m_font;
void update_attributes();
void show_label();
void show_delimitation();
void change_color(uint16_t foreground_color, uint16_t background_color);
void change_size(uint16_t width, uint16_t height);
void change_origin(uint16_t x_origin, uint16_t y_origin);
void change_alignment(ulcd_h_alignment h_alignment, ulcd_v_alignment v_alignment);
void change_font_size(ulcd_font_size font);
void change_text(string text);
void change_text2(string text);
void new_label(string text, uint16_t foreground_color, uint16_t x_origin, uint16_t y_origin, uint16_t width, uint16_t height, ulcd_font_size font, ulcd_h_alignment h_alignment, ulcd_v_alignment v_alignment);
// constructor
ulcd_label(uLCD_4DLibrary* p_lcd, string text, uint16_t foreground_color = Color::WHITE, uint16_t x_origin = 0, uint16_t y_origin = 0, uint16_t width = 20, uint16_t height = 20, ulcd_font_size font = ulcd_font_size_1, ulcd_h_alignment h_alignment = h_left, ulcd_v_alignment v_alignmen = v_top);
ulcd_label(uLCD_4DLibrary* p_lcd);
~ulcd_label();
};
#endif
|
#include <iostream>
#include <string>
class X {
private:
int m;
public:
X(int i=0)
: m{i}
{}
int mf(int i)
{
int old = m;
m = i;
return old;
}
};
X var{7};
int user(X var, X *ptr)
{
int x = var.mf(7);
int y = ptr->mf(9);
// int z = var.m;
//
return 0;
}
class Date {
private:
int d, m, y;
mutable std::string cache;
mutable bool cache_valid;
public:
Date()
: d{-1}, m{-1}, y{-1}
{}
explicit Date(int x)
: d{x}, m{x}, y{x}
{}
Date(int d, int m, int y)
: d{d}, m{m}, y{y}
{}
void compute_cache_value() const
{
// do nothin
}
std::string string_rep() const
{
if (!cache_valid) {
compute_cache_value();
cache_valid = true;
}
return cache;
}
Date& add_year(int n) { return *this; }
Date& add_month(int m) { return *this; }
Date& add_day(int d) { return *this; }
friend std::ostream& operator<<(std::ostream&, Date const&);
};
std::ostream& operator<<(std::ostream& os, Date const& date)
{
return os << date.d << "/" << date.m << "/" << date.y;
}
struct S {
int m;
int f() { return 1; }
static int sm;
};
int main()
{
Date today = Date{23, 6, 1983};
Date other = {23, 6, 1983};
Date also{23, 6, 1983};
// note: this initialization will be ambiguous
// as there is a default ctor and also a ctor with all arguments
// having default values => if no arguments provided u get ambiguity
Date some;
// implicit call to Date(int) - type conversion
Date check = Date{1};
std::cout << today << std::endl;
std::cout << other << std::endl;
std::cout << some << std::endl;
std::cout << check << std::endl;
int (S::*) pmf() { &S::f };
}
|
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* MateriaSource.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: Kwillum <daniilxod@gmail.com> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/01/12 18:58:58 by kwillum #+# #+# */
/* Updated: 2021/01/13 00:25:41 by Kwillum ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MATERIASOURCE_HPP
# define MATERIASOURCE_HPP
# include <iostream>
# include "AMateria.hpp"
# include "IMateriaSource.hpp"
class MateriaSource : public IMateriaSource
{
private:
static const int _memoryVolume = 4;
int _alreadyLearned;
AMateria *_materiaSrcs[_memoryVolume];
public:
MateriaSource();
MateriaSource(const MateriaSource &toCopy);
void learnMateria(AMateria *m);
AMateria* createMateria(std::string const & type);
MateriaSource &operator=(const MateriaSource &toCopy);
virtual ~MateriaSource();
};
#endif
|
/home/mikcy/Documents/Coding/SimpleAlgorithmJudge/Client/acm_gui/jsoncpp.cpp
|
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <memory.h>
#include <math.h>
#include <string>
#include <string.h>
#include <queue>
#include <vector>
#include <set>
#include <deque>
#include <map>
#include <functional>
#include <numeric>
#include <sstream>
typedef long double LD;
typedef long long LL;
typedef unsigned long long ULL;
typedef unsigned int uint;
#define PI 3.1415926535897932384626433832795
#define sqr(x) ((x)*(x))
using namespace std;
#define N 222
int k, n, x, t[N];
vector<int> keys[N];
int was[5555555], endMask;
int brute(int mask, int* K) {
int& v = was[mask];
if (v != -1) return v;
if (mask == endMask) return v = 1;
v = 0;
for (int i = 0; i < n; ++i)
if ((mask & (1 << i)) == 0)
if (K[t[i]]) {
if (was[mask | (1 << i)] != -1) {
v |= was[mask | (1 << i)];
} else
{
--K[t[i]];
for (size_t j = 0; j < keys[i].size(); ++j) ++K[keys[i][j]];
v |= brute(mask | (1 << i), K);
for (size_t j = 0; j < keys[i].size(); ++j) --K[keys[i][j]];
++K[t[i]];
}
}
return v;
}
int main() {
freopen("in", "r", stdin);
freopen("out", "w", stdout);
int T;
cin >> T;
for (int __it = 1; __it <= T; ++__it) {
scanf("%d%d", &k, &n);
endMask = (1 << n) - 1;
int K[222] = {0};
for (int i = 0; i < k; ++i) {
scanf("%d", &x);
++K[x];
}
for (int i = 0; i < n; ++i) {
int kk;
scanf("%d%d", &t[i], &kk);
keys[i].resize(kk);
for (size_t j = 0; j < keys[i].size(); ++j) {
scanf("%d", &keys[i][j]);
}
}
if (__it != 14) continue;
memset(was, -1, sizeof(was));
brute(0, K);
printf("Case #%d: ", __it);
if (was[endMask] == -1) {
puts("IMPOSSIBLE");
} else {
int mask = 0;
vector<int> ans;
for (int i = 0; i < n; ++i)
for (int j = 0; j < n; ++j)
if ((mask & (1 << j)) == 0 && was[mask | (1 << j)] == 1) {
ans.push_back(j);
mask |= (1 << j);
printf("%d ", j + 1);
break;
}
puts("");
vector<int> cnt(222, 0);
for (int i = 0; i < 222; ++i) cnt[i] += K[i];
for (int i = 0; i < n; ++i) {
int x = ans[i];
if (K[t[x]] == 0) {
cout << __it << " " << i << " " << x << " ERROR" << endl;
}
--K[t[x]];
for (int j = 0; j < keys[x].size(); ++j) ++K[keys[x][j]];
}
}
}
return 0;
}
|
#ifndef APPLICATION_REGISTRATE_H
#define APPLICATION_REGISTRATE_H
#include <QObject>
#include <QMessageBox>
#include <CallbacksHolder/Callback/BaseCallback.h>
#include <Controller/Controller.h>
#include "ui/RegistrateWidget/registratewidget.h"
#include "ui/UserData/UserData.h"
// Callback for Registrate
class RegistrationCallback : public BaseCallback {
public:
RegistrationCallback(RegistrateWidget* widget) : widget(widget) {};
public:
void operator()(std::shared_ptr<BaseObject> data,
const std::optional<std::string>& error) override {
if (error)
widget->setErrorStatus(QString::fromStdString("Sing up error: " + (*error)));
else {
auto authInfo = std::static_pointer_cast<UserInfo>(data);
widget->setSuccessStatus(QString::fromStdString(authInfo->firstName +
" " + authInfo->lastName + " was registered"));
}
}
private:
RegistrateWidget* widget;
};
#endif //APPLICATION_REGISTRATE_H
|
// Created on: 1999-03-11
// Created by: data exchange team
// Copyright (c) 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 _StepShape_RevolvedFaceSolid_HeaderFile
#define _StepShape_RevolvedFaceSolid_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <StepShape_SweptFaceSolid.hxx>
class StepGeom_Axis1Placement;
class TCollection_HAsciiString;
class StepShape_FaceSurface;
class StepShape_RevolvedFaceSolid;
DEFINE_STANDARD_HANDLE(StepShape_RevolvedFaceSolid, StepShape_SweptFaceSolid)
class StepShape_RevolvedFaceSolid : public StepShape_SweptFaceSolid
{
public:
//! Returns a RevolvedFaceSolid
Standard_EXPORT StepShape_RevolvedFaceSolid();
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepShape_FaceSurface)& aSweptArea);
Standard_EXPORT void Init (const Handle(TCollection_HAsciiString)& aName, const Handle(StepShape_FaceSurface)& aSweptArea, const Handle(StepGeom_Axis1Placement)& aAxis, const Standard_Real aAngle);
Standard_EXPORT void SetAxis (const Handle(StepGeom_Axis1Placement)& aAxis);
Standard_EXPORT Handle(StepGeom_Axis1Placement) Axis() const;
Standard_EXPORT void SetAngle (const Standard_Real aAngle);
Standard_EXPORT Standard_Real Angle() const;
DEFINE_STANDARD_RTTIEXT(StepShape_RevolvedFaceSolid,StepShape_SweptFaceSolid)
protected:
private:
Handle(StepGeom_Axis1Placement) axis;
Standard_Real angle;
};
#endif // _StepShape_RevolvedFaceSolid_HeaderFile
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*-
**
** Copyright (C) 2000-2011 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve Pettersen
**
*/
#include "core/pch.h"
#if defined(_NATIVE_SSL_SUPPORT_)
#ifdef _SSL_USE_OPENSSL_
#include "modules/libssl/sslbase.h"
#include "modules/libssl/ssl_api.h"
#include "modules/libssl/external/openssl/eayhead.h"
#include "modules/libssl/external/openssl/genciph.h"
#include "modules/libssl/sslrand.h"
#include "modules/libssl/methods/sslcipher.h"
#include "modules/libssl/methods/sslnull.h"
#include "modules/util/cleanse.h"
#include "modules/url/tools/arrays.h"
#include "modules/libssl/debug/tstdump2.h"
#ifdef _DEBUG
#ifdef YNP_WORK
#define TST_DUMP
#endif
#endif
#define SSLEAY_MAX_KEY_LENGTH 24
#define SSLEAY_MAX_IV_LENGTH 8
const EVP_MD *GetMD_From_Algorithm(SSL_HashAlgorithmType digest);
typedef const EVP_CIPHER* (*EVP_CIPHER_CB)();
struct SSL_Cipher_and_NID
{
SSL_BulkCipherType cipher_alg;
int nid;
EVP_CIPHER_CB func;
};
#define CIPHER_ENTRY(typ, ciphername) CONST_TRIPLE_ENTRY(cipher_alg, typ, nid, NID_##ciphername , func, EVP_##ciphername )
#define CIPHER_ENTRY_NID(typ, ciphername, cfb_nid) CONST_TRIPLE_ENTRY(cipher_alg, typ, nid, cfb_nid , func, EVP_##ciphername )
// param2 "name" will be expanded to NID_name and EVP_name
PREFIX_CONST_ARRAY(static, SSL_Cipher_and_NID, SSL_Cipher_map, libssl)
CIPHER_ENTRY(SSL_RC4, rc4)
#ifndef OPENSSL_NO_AES
CIPHER_ENTRY(SSL_AES_128_CBC, aes_128_cbc)
CIPHER_ENTRY(SSL_AES_256_CBC, aes_256_cbc)
#endif
CIPHER_ENTRY(SSL_3DES, des_ede3_cbc)
#ifdef OPENSSL_USE_CFB_CIPHERS
CIPHER_ENTRY_NID(SSL_3DES_CFB, des_ede3_cfb, NID_des_ede3_cfb64)
#ifndef OPENSSL_NO_AES
CIPHER_ENTRY_NID(SSL_AES_128_CFB, aes_128_cfb, NID_aes_128_cfb128)
CIPHER_ENTRY_NID(SSL_AES_192_CFB, aes_192_cfb, NID_aes_192_cfb128)
CIPHER_ENTRY_NID(SSL_AES_256_CFB, aes_256_cfb, NID_aes_256_cfb128)
#endif
#ifndef OPENSSL_NO_CAST
CIPHER_ENTRY_NID(SSL_CAST5_CFB, cast5_cfb, NID_cast5_cfb64)
#endif
#endif
#ifdef SSL_BLOWFISH_SUPPORT
CIPHER_ENTRY(SSL_BLOWFISH_CBC, bf_cbc)
#endif
#ifdef LIBSSL_USE_RC4_256
CIPHER_ENTRY_NID(SSL_RC4_256, rc4_256, NID_rc4)
#endif
CONST_END(SSL_Cipher_map)
SSL_GeneralCipher *SSL_API::CreateSymmetricCipher(SSL_BulkCipherType cipher_alg, OP_STATUS &op_err)
{
op_err = OpStatus::OK;
if(cipher_alg== SSL_NoCipher)
{
SSL_GeneralCipher *ret = OP_NEW(SSL_Null_Cipher, ());
if(ret == NULL)
op_err = OpStatus::ERR_NO_MEMORY;
return ret;
}
const EVP_CIPHER *cipher = NULL;
size_t i;
for(i = 0; i<CONST_ARRAY_SIZE(libssl, SSL_Cipher_map); i++)
{
if(g_SSL_Cipher_map[i].cipher_alg == cipher_alg)
{
cipher = g_SSL_Cipher_map[i].func();
break;
}
}
if(cipher == NULL)
{
op_err = OpStatus::ERR_OUT_OF_RANGE;
return NULL;
}
OpAutoPtr<SSL_GeneralCipher> key(OP_NEW(SSLEAY_GeneralCipher, (cipher_alg, cipher)));
if(key.get() == NULL)
{
op_err = OpStatus::ERR_NO_MEMORY;
return NULL;
}
if(key->Error())
{
op_err = key->GetOPStatus();
return NULL;
}
return key.release();
}
SSLEAY_GeneralCipher::SSLEAY_GeneralCipher(SSL_BulkCipherType cipher_id, const EVP_CIPHER *cipherspec)
{
encrypt_status = NULL;
cipher = cipherspec;
if(cipher == NULL)
{
RaiseAlert(SSL_Internal, SSL_InternalError);
}
else
{
cipher_alg = cipher_id;
cipher_type =((cipher->flags & EVP_CIPH_MODE)!= EVP_CIPH_CFB_MODE && cipher->block_size >1 ?
SSL_BlockCipher : SSL_StreamCipher);
out_block_size = in_block_size = ((cipher->flags & EVP_CIPH_MODE)!= EVP_CIPH_CFB_MODE ? cipher->block_size : 1);
key_size = cipher->key_len;
iv_size = cipher->iv_len;
}
InitCipher(NULL);
}
void SSLEAY_GeneralCipher::InitCipher(const EVP_CIPHER_CTX *old)
{
encrypt_status = OP_NEW(EVP_CIPHER_CTX, ());
if(encrypt_status == NULL)
{
RaiseAlert(SSL_Internal, SSL_InternalError);
return;
}
#ifdef USE_SSL_PGP_CFB_MODE
PGP_CFB_mode = SSL_Cipher::PGP_CFB_Mode_Disabled;
PGP_CFB_started = FALSE;
PGP_CFB_IVread = 0;
#endif
if(old != NULL)
*encrypt_status = *old;
else
{
encrypt_status->encrypt = 1;
if (!EVP_CipherInit(encrypt_status,cipher,NULL,NULL,encrypt_status->encrypt))
RaiseAlert(SSL_Internal, SSL_InternalError);
}
}
// Unref YNP
#if 0
SSLEAY_GeneralCipher::SSLEAY_GeneralCipher(const SSLEAY_GeneralCipher *old)
{
if(old == NULL || old->cipher == NULL)
{
RaiseAlert(SSL_Internal, SSL_InternalError);
return;
}
cipher = (EVP_CIPHER *)++ old->cipher;
encrypt_status = NULL;
cipher_alg = old->CipherID();
cipher_type =((cipher->flags & EVP_CIPH_MODE)!= EVP_CIPH_CFB_MODE && cipher->block_size >1 ?
SSL_BlockCipher : SSL_StreamCipher);
out_block_size = in_block_size = ((cipher->flags & EVP_CIPH_MODE)!= EVP_CIPH_CFB_MODE ? cipher->block_size : 1)
key_size = cipher->key_len;
iv_size = cipher->iv_len;
if(old->encrypt_status != NULL)
{
InitCipher(old->encrypt_status);
}
}
#endif
SSLEAY_GeneralCipher::~SSLEAY_GeneralCipher()
{
cipher = NULL;
if(encrypt_status != NULL)
{
EVP_CIPHER_CTX_cleanup(encrypt_status);
OPERA_cleanse_heap(encrypt_status,sizeof(EVP_CIPHER_CTX));
OP_DELETE(encrypt_status);
encrypt_status = NULL;
}
#ifdef USE_SSL_PGP_CFB_MODE
op_memset(PGP_CFB_IVbuffer,0, sizeof(PGP_CFB_IVbuffer));
#endif
}
void SSLEAY_GeneralCipher::SetCipherDirection(SSL_CipherDirection dir)
{
encrypt_status->encrypt = (dir == SSL_Encrypt ? 1 : 0);
}
#ifdef USE_SSL_PGP_CFB_MODE
void SSLEAY_GeneralCipher::SetPGP_CFB_Mode(SSL_Cipher::PGP_CFB_Mode_Type mode)
{
PGP_CFB_mode = mode;
}
#endif
void SSLEAY_GeneralCipher::StartCipher()
{
EVP_CIPHER_CTX_set_padding(encrypt_status, appendpad != SSL_NO_PADDING);
#ifdef USE_SSL_PGP_CFB_MODE
PGP_CFB_started = FALSE;
PGP_CFB_IVread = 0;
op_memset(PGP_CFB_Resync, 0, sizeof(PGP_CFB_Resync));
#endif
}
byte *SSLEAY_GeneralCipher::CipherUpdate(const byte *source,uint32 len,byte *target, uint32 &len1,uint32 bufferlen)
{
int len2 = 0;
len1 = 0;
ERR_clear_error();
#ifdef USE_SSL_PGP_CFB_MODE
if(PGP_CFB_mode != SSL_Cipher::PGP_CFB_Mode_Disabled && !PGP_CFB_started)
{
byte *trg = target;
const byte *src =source;
uint32 len_in=0;
if(encrypt_status->encrypt)
{
OP_ASSERT(len + (cipher->iv_len+2) <= bufferlen);
SSL_RND(PGP_CFB_IVbuffer, cipher->iv_len);
PGP_CFB_IVbuffer[cipher->iv_len] = PGP_CFB_IVbuffer[cipher->iv_len-2];
PGP_CFB_IVbuffer[cipher->iv_len+1] = PGP_CFB_IVbuffer[cipher->iv_len-1];
src = (byte *) PGP_CFB_IVbuffer;
len_in = cipher->iv_len+2;
}
else
{
if(source == NULL || len == 0)
return target;
trg = PGP_CFB_IVbuffer + PGP_CFB_IVread;
len_in = (cipher->iv_len+2) - PGP_CFB_IVread;
if(len_in > len)
len_in = len;
}
// ALways in CFB mode
EVP_CipherUpdate(encrypt_status,trg,&len2, src,len_in);
if(encrypt_status->encrypt)
{
op_memcpy(PGP_CFB_Resync, target+2, cipher->iv_len);
target += len2;
len1 += len2;
}
else
{
op_memcpy(PGP_CFB_Resync + PGP_CFB_IVread, src, len_in);
PGP_CFB_IVread += len_in;
if(PGP_CFB_IVread < cipher->iv_len+2)
return target;
if(PGP_CFB_IVbuffer[cipher->iv_len-2] != PGP_CFB_IVbuffer[cipher->iv_len] ||
PGP_CFB_IVbuffer[cipher->iv_len-1] != PGP_CFB_IVbuffer[cipher->iv_len+1])
{
RaiseAlert(SSL_Fatal, SSL_Decrypt_Error);
return target;
}
op_memmove(PGP_CFB_Resync, PGP_CFB_Resync+2, cipher->iv_len);
source += len_in;
len -= len_in;
}
PGP_CFB_IVread = 0;
PGP_CFB_started = TRUE;
if(PGP_CFB_mode != SSL_Cipher::PGP_CFB_Mode_Enabled_No_Resync)
CFB_Resync();
}
#endif
if(source == NULL || len == 0 || target == NULL || bufferlen == 0)
return target;
EVP_CipherUpdate(encrypt_status,target,&len2, source,(int) len);
#ifdef USE_SSL_PGP_CFB_MODE
if(EVP_CIPHER_CTX_mode(encrypt_status) == EVP_CIPH_CFB_MODE)
{
const byte *resync_src = target;
int resync_len = len2;
if(encrypt_status->encrypt)
{
resync_src = target;
resync_len = len2;
}
else
{
resync_src = source;
resync_len = len;
}
if(resync_len >= cipher->iv_len)
{
op_memcpy(PGP_CFB_Resync, resync_src +(resync_len -cipher->iv_len), cipher->iv_len);
PGP_CFB_IVread = 0;
}
else
{
for(int i=0; i< resync_len; i++)
{
PGP_CFB_Resync[PGP_CFB_IVread++] = resync_src[i];
if(PGP_CFB_IVread >= cipher->iv_len)
PGP_CFB_IVread = 0;
}
}
}
#endif
len1 += (uint32) len2;
CheckError();
return target + len1;
}
byte *SSLEAY_GeneralCipher::FinishCipher(byte *target, uint32 &len1,uint32 bufferlen)
{
int len2=0;
ERR_clear_error();
#ifdef TST_DUMP
DumpTofile(debug_key, debug_key.GetLength(),"SSLEAY_GeneralCipher Finsish En/Decrypt key ","sslcrypt.txt");
#endif
#ifdef USE_SSL_PGP_CFB_MODE
if(!encrypt_status->encrypt && PGP_CFB_mode != SSL_Cipher::PGP_CFB_Mode_Disabled && !PGP_CFB_started)
{
RaiseAlert(SSL_Fatal, SSL_Decrypt_Error);
return target;
}
#endif
EVP_CipherFinal_ex(encrypt_status,target,&len2);
len1 = (uint32) len2;
CheckError();
return target + len1;
}
void SSLEAY_GeneralCipher::InitEncrypt()
{
StartCipher();
}
byte *SSLEAY_GeneralCipher::Encrypt(const byte *source,uint32 len,byte *target, uint32 &len1,uint32 bufferlen)
{
return CipherUpdate(source, len, target, len1, bufferlen);
}
byte *SSLEAY_GeneralCipher::FinishEncrypt(byte *target, uint32 &len1,uint32 bufferlen)
{
return FinishCipher(target,len1, bufferlen);
}
void SSLEAY_GeneralCipher::InitDecrypt()
{
StartCipher();
}
byte *SSLEAY_GeneralCipher::Decrypt(const byte *source,uint32 len,byte *target, uint32 &len1,uint32 bufferlen)
{
return CipherUpdate(source, len, target, len1, bufferlen);
}
byte *SSLEAY_GeneralCipher::FinishDecrypt(byte *target, uint32 &len1,uint32 bufferlen)
{
return FinishCipher(target,len1, bufferlen);
}
#ifdef USE_SSL_PGP_CFB_MODE
void SSLEAY_GeneralCipher::CFB_Resync()
{
if(encrypt_status && EVP_CIPHER_CTX_mode(encrypt_status) == EVP_CIPH_CFB_MODE && encrypt_status->num != 0)
{
size_t i,j, max;
i = PGP_CFB_IVread;
max = cipher->iv_len;
j = max - i;
op_memcpy(encrypt_status->iv, PGP_CFB_Resync+ i, j);
op_memcpy(encrypt_status->iv + j, PGP_CFB_Resync, i);
encrypt_status->num = 0;
}
}
void SSLEAY_GeneralCipher::UnloadPGP_Prefix(SSL_varvector32 &buf)
{
buf.Set(PGP_CFB_IVbuffer, cipher->iv_len+2);
}
#endif
const byte *SSLEAY_GeneralCipher::LoadKey(const byte *source)
{
#ifdef TST_DUMP
DumpTofile(source, cipher->key_len,"SSLEAY_GeneralCipher LoadKey ","sslcrypt.txt");
debug_key.Set(source, cipher->key_len);
#endif
ERR_clear_error();
EVP_CipherInit(encrypt_status,NULL,(byte *) source,NULL, encrypt_status->encrypt);
CheckError();
return source + cipher->key_len;
}
const byte *SSLEAY_GeneralCipher::LoadIV(const byte *source)
{
#ifdef TST_DUMP
DumpTofile(source, cipher->iv_len,"SSLEAY_GeneralCipher LoadIV ","sslcrypt.txt");
#endif
ERR_clear_error();
EVP_CipherInit(encrypt_status,NULL,NULL,(byte *) source, encrypt_status->encrypt);
CheckError();
return source + cipher->iv_len;
}
void SSLEAY_GeneralCipher::BytesToKey(SSL_HashAlgorithmType mdtype,
const SSL_varvector32 &string, const SSL_varvector32 &salt, int count)
{
byte *key= (byte *) g_memory_manager->GetTempBuf2k();
byte *iv = key+ SSLEAY_MAX_KEY_LENGTH;
const EVP_MD *md = GetMD_From_Algorithm(mdtype);
EVP_BytesToKey(cipher, md, (byte *) salt.GetDirect(), (byte *) string.GetDirect(),
(int) string.GetLength(), count, key, iv);
EVP_CipherInit(encrypt_status,NULL,key,iv,encrypt_status->encrypt);
OPERA_cleanse_heap(key,SSLEAY_MAX_KEY_LENGTH+SSLEAY_MAX_IV_LENGTH);
}
/*
SSL_GeneralCipher *SSLEAY_GeneralCipher::Fork() const
{
return new SSLEAY_GeneralCipher(this);
}*/
void SSLEAY_CheckError(SSL_Error_Status *target);
void SSLEAY_GeneralCipher::CheckError()
{
SSLEAY_CheckError(this);
}
#endif
#endif
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 2004-2006 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
**
** Yngve N. Pettersen
*/
#ifndef __LONGBATCH_TLS_H__
#define __LONGBATCH_TLS_H__
#include "modules/url/url_man.h"
#include "modules/util/adt/opvector.h"
#include "modules/network_selftest/urldoctestman.h"
#include "modules/network_selftest/justload.h"
#include "modules/network_selftest/remote_framework.h"
#include "modules/locale/oplanguagemanager.h"
#include "modules/olddebug/tstdump.h"
class NeverFail_Manager : public URL_DocSelfTest_Manager
{
private:
unsigned int completed;
unsigned int completed_successfully;
unsigned int completed_unsuccessfully;
public:
NeverFail_Manager():completed(0),completed_successfully(0),completed_unsuccessfully(0){}
void RegisterCompleted(BOOL success, URL &url, const OpStringC &reason=OpStringC())
{
completed += 1;
if(success)
completed_successfully += 1;
else
{
completed_unsuccessfully += 1;
OpString8 url_str;
url.GetAttribute(URL::KName,url_str);
OpStringC error=url.GetAttribute(URL::KInternalErrorString);
OpString8 error8;
OpStringC empty(UNI_L(""));
error8.SetUTF8FromUTF16(error.HasContent() ? error : empty);
if(error8.IsEmpty())
error8.SetUTF8FromUTF16(reason.HasContent() ? reason : empty);
output("Failed URL:%s\n%s\n------------\n",url_str.CStr(),error8.CStr());
PrintfTofile("manyload_fails.txt", "Failed URL:%s\n%s\n------------\n",url_str.CStr(),error8.CStr());
}
if( completed %100 == 0)
{
output("Loaded %d URL (Total %d/%d)\n",GetCompleted(), items_completed, items_added);
output("Completed successfully %d\n",GetCompletedSuccess());
output("Completed unsuccessfully %d\n",GetCompletedNoSuccess());
output("\nCompleted successfully %7.2f%%\n",((double)GetCompletedSuccess()/(double) GetCompleted())*100.0);
output("==================\n");
}
}
unsigned int GetCompleted(){return completed;}
unsigned int GetCompletedSuccess(){return completed_successfully;}
unsigned int GetCompletedNoSuccess(){return completed_unsuccessfully;}
};
class NeverFail_Batch : public URL_DocSelfTest_Batch
{
private:
OpVector<OpString8> str_batch_list;
public:
virtual BOOL Verify_function(URL_DocSelfTest_Event event, URL_DocSelfTest_Item *source)
{
if(source)
{
source->url_use->Unload();
source->url_use.UnsetURL();
}
return URL_DocSelfTest_Batch::Verify_function(URLDocST_Event_Item_Finished, source);
}
virtual BOOL SetUpBatchEntry(const OpStringC8 &url_str);
virtual BOOL StartLoading()
{
urlManager->RemoveSensitiveData();
UINT32 n = str_batch_list.GetCount();
if(n)
{
UINT32 i;
for(i = 0; i < n; i++)
{
if (!SetUpBatchEntry(*str_batch_list.Get(i)))
return FALSE;
}
str_batch_list.Empty();
}
return URL_DocSelfTest_Batch::StartLoading();
}
virtual OP_STATUS AddWorkURL(const OpStringC8 &url_str)
{
OpString8 *new_url_str = OP_NEW(OpString8, ());
RETURN_OOM_IF_NULL(new_url_str);
RETURN_IF_ERROR(new_url_str->Set(url_str));
return str_batch_list.Add(new_url_str);
}
virtual BOOL Empty(){return str_batch_list.GetCount() == 0 && URL_DocSelfTest_Batch::Empty();}
virtual int Cardinal(){return (str_batch_list.GetCount()== 0 ? URL_DocSelfTest_Batch::Cardinal() : static_cast<int>(str_batch_list.GetCount()));}
};
class NeverFailLoad_Tester : public JustLoad_Tester
{
private:
BOOL reported;
BOOL singular;
public:
NeverFailLoad_Tester():reported(FALSE),singular(FALSE){};
NeverFailLoad_Tester(URL &a_url, URL &ref, BOOL unique=TRUE) : JustLoad_Tester(a_url, ref, unique), reported(FALSE),singular(FALSE){};
virtual ~NeverFailLoad_Tester(){}
void SetSingular(){singular=TRUE;}
virtual void RegisterCompleted(BOOL success, URL &url, const OpStringC &reason=OpStringC())
{
if(success || singular)
{
((NeverFail_Manager*)(GetBatch()->GetManager()))->RegisterCompleted(success, url,reason);
return;
}
OpAutoPtr<NeverFail_Batch> batch(OP_NEW(NeverFail_Batch, ()));
if(batch.get() == NULL)
{
((NeverFail_Manager*)(GetBatch()->GetManager()))->RegisterCompleted(success, url,reason);
return;
}
batch->Construct(GetBatch()->GetMessageHandler());
batch->SetTimeOutIdle(30);
batch->SetTimeOut(150);
batch->SetTimeOutStartConnection(TRUE);
URL ref_url;
OpString8 urlstr;
url.GetAttribute(URL::KName_Username_Password_Escaped_NOT_FOR_UI, urlstr);
OpAutoPtr<NeverFailLoad_Tester> test(OP_NEW(NeverFailLoad_Tester, ()));
if(test.get() != NULL)
test->SetSingular();
if(urlstr.IsEmpty() || test.get() == NULL || OpStatus::IsError(test->Construct(urlstr, ref_url, TRUE)) || !batch->AddTestCase(test.release()))
{
((NeverFail_Manager*)(GetBatch()->GetManager()))->RegisterCompleted(success, url,reason);
return;
}
url.GetServerName()->RemoveSensitiveData();
batch->SetManager(GetBatch()->GetManager());
batch->Follow(GetBatch());
batch.release();
}
virtual BOOL Verify_function(URL_DocSelfTest_Event event, Str::LocaleString status_code=Str::NOT_A_STRING)
{
// Always continue
switch(event)
{
case URLDocST_Event_Header_Loaded:
header_loaded = TRUE;
break;
case URLDocST_Event_Redirect:
return TRUE;
break;
case URLDocST_Event_Data_Received:
return TRUE;
break;
default:
{
// increment failure count
if(!reported)
{
reported = TRUE;
OpString str;
OpString str2;
if(status_code!=Str::NOT_A_STRING)
g_languageManager->GetString(status_code, str2);
str2.Append(UNI_L("\nVerify_function"));
str.AppendFormat(UNI_L("Event %d reported (response %d): %s"), (int) event, url.GetAttribute(URL::KHTTP_Response_Code), (str2.CStr() ? str2.CStr() : UNI_L("")));
if(url.GetAttribute(g_KSSLHandshakeSent))
RegisterCompleted((url.GetAttribute(URL::KHTTP_Response_Code)>0 || url.GetAttribute(g_KSSLHandshakeCompleted)), url,str);
}
return FALSE;
}
}
return TRUE;
}
BOOL OnURLRedirected(URL &url, URL &redirected_to)
{
if(!reported)
{
reported = TRUE;
RegisterCompleted(TRUE, url);
}
GetBatch()->Verify_function(URLDocST_Event_Item_Finished, this);
return FALSE;
}
BOOL OnURLDataLoaded(URL &url, BOOL finished, OpAutoPtr<URL_DataDescriptor> &stored_desc)
{
URLStatus status = (URLStatus) url.GetAttribute(URL::KLoadStatus, TRUE);
if(status == URL_LOADED)
{
if(!reported)
{
reported = TRUE;
RegisterCompleted(TRUE, url);
if(GetBatch())
GetBatch()->Verify_function(URLDocST_Event_Item_Finished, this);
}
return FALSE;
}
else if(status != URL_LOADING)
{
// increment failure count
if(!reported)
{
reported = TRUE;
if(url.GetAttribute(g_KSSLHandshakeSent))
{
int response = url.GetAttribute(URL::KHTTP_Response_Code);
RegisterCompleted(((response>0 && response<400) || response == 404 || response == 401 || response == 407), url, UNI_L("Loading failed for some reason"));
}
if(GetBatch())
GetBatch()->Verify_function(URLDocST_Event_Item_Finished, this);
return FALSE;
}
}
return (finished ? FALSE : TRUE);
}
void OnURLLoadingFailed(URL &url, Str::LocaleString status_code, OpAutoPtr<URL_DataDescriptor> &stored_desc)
{
if(!reported)
{
reported = TRUE;
if(url.GetAttribute(g_KSSLHandshakeSent))
{
if(!url.GetAttribute(g_KSSLHandshakeCompleted))
{
OpString str2;
if(status_code!=Str::NOT_A_STRING)
g_languageManager->GetString(status_code, str2);
str2.AppendFormat(UNI_L("\nOnURLLoadingFailed%d"),(unsigned int)status_code);
RegisterCompleted(url.GetAttribute(URL::KHTTP_Response_Code)>0, url, str2);
}
else
RegisterCompleted(TRUE, url);
}
if(GetBatch())
GetBatch()->Verify_function(URLDocST_Event_Item_Finished, this);
}
}
};
class NeverFail_RemoteFrameworkManager : public RemoteFrameworkManager
{
public:
class TextFile : public RemoteFrameworkManager::RemoteTextMaster
{
private:
OpAutoPtr<NeverFail_Batch> batch;
public:
TextFile(RemoteFrameworkManager *mgr):RemoteTextMaster(mgr) {}
protected:
virtual OP_STATUS ProcessFile()
{
RETURN_IF_ERROR(RemoteFrameworkManager::RemoteTextMaster::ProcessFile());
if(batch.get() && batch->Cardinal())
GetManager()->AddTestBatch(batch.release());
return OpStatus::OK;
}
virtual OP_STATUS HandleTextLine(const OpStringC8 &line)
{
if(line.IsEmpty())
return OpStatus::OK;
if (batch.get() == NULL)
{
batch.reset(OP_NEW(NeverFail_Batch, ()));
RETURN_OOM_IF_NULL(batch.get());
batch->Construct(GetManager()->GetMessageHandler());
batch->SetTimeOutIdle(30);
batch->SetTimeOut(150);
batch->SetTimeOutStartConnection(TRUE);
}
RETURN_IF_ERROR(batch->AddWorkURL(line));
if(batch->Cardinal()>=40)
GetManager()->AddTestBatch(batch.release());
return OpStatus::OK;
}
};
virtual AutoFetch_Element *ProduceTestSuiteMaster(URL &url, OP_STATUS &op_err)
{
op_err = OpStatus::OK;
OpAutoPtr<TextFile> loader(OP_NEW(TextFile, (this)));
if(!loader.get())
{
op_err = OpStatus::ERR_NO_MEMORY;
return NULL;
}
op_err = loader->Construct(url);
if(OpStatus::IsError(op_err))
loader.reset();
return loader.release();
}
virtual URL_DocSelfTest_Manager *ProduceTestManager(){return OP_NEW(NeverFail_Manager,());}
NeverFail_Manager *GetTestManager(){return (NeverFail_Manager *) RemoteFrameworkManager::GetTestManager();}
};
inline BOOL NeverFail_Batch::SetUpBatchEntry(const OpStringC8 &url_str)
{
URL ref_url;
OpAutoPtr<NeverFailLoad_Tester> test(OP_NEW(NeverFailLoad_Tester, ()));
if(test.get() == NULL)
return FALSE;
RETURN_VALUE_IF_ERROR(test->Construct(url_str, ref_url, TRUE), FALSE);
test->url.SetAttribute(URL::KHTTP_Method, HTTP_METHOD_HEAD);
if(!AddTestCase(test.release()))
return FALSE;
return TRUE;
}
#endif
|
#ifndef COMMUNITYFUNDDISPLAYDETAILED_H
#define COMMUNITYFUNDDISPLAYDETAILED_H
#include <QWidget>
#include <consensus/dao.h>
#include <wallet/wallet.h>
#include <QDialog>
#include <QAbstractButton>
namespace Ui {
class CommunityFundDisplayDetailed;
}
class CommunityFundDisplayDetailed : public QDialog
{
Q_OBJECT
public:
explicit CommunityFundDisplayDetailed(QWidget *parent = 0, CProposal proposal = CProposal());
~CommunityFundDisplayDetailed();
private:
Ui::CommunityFundDisplayDetailed *ui;
CProposal proposal;
CWallet *wallet;
void setProposalLabels();
public Q_SLOTS:
void click_buttonBoxYesNoVote(QAbstractButton *button);
void onDetails();
};
#endif // COMMUNITYFUNDDISPLAYDETAILED_H
|
// Created by: Peter KURNEV
// 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 BOPTools_ConnexityBlock_HeaderFile
#define BOPTools_ConnexityBlock_HeaderFile
#include <NCollection_BaseAllocator.hxx>
#include <TopTools_ListOfShape.hxx>
//=======================================================================
//class : ConnexityBlock
//purpose :
//=======================================================================
class BOPTools_ConnexityBlock {
public:
BOPTools_ConnexityBlock() :
myAllocator(NCollection_BaseAllocator::CommonBaseAllocator()),
myRegular(Standard_True),
myShapes(myAllocator),
myLoops(myAllocator) {
};
//
BOPTools_ConnexityBlock(const Handle(NCollection_BaseAllocator)& theAllocator):
myAllocator(theAllocator),
myRegular(Standard_True),
myShapes(myAllocator),
myLoops(myAllocator) {
};
//
const TopTools_ListOfShape& Shapes()const {
return myShapes;
};
//
TopTools_ListOfShape& ChangeShapes() {
return myShapes;
};
//
void SetRegular(const Standard_Boolean theFlag) {
myRegular=theFlag;
}
//
Standard_Boolean IsRegular()const {
return myRegular;
}
//
const TopTools_ListOfShape& Loops()const {
return myLoops;
};
//
TopTools_ListOfShape& ChangeLoops() {
return myLoops;
};
//
protected:
Handle(NCollection_BaseAllocator) myAllocator;
Standard_Boolean myRegular;
TopTools_ListOfShape myShapes;
TopTools_ListOfShape myLoops;
};
#endif
|
#pragma once
#include <string>
#include <fstream>
#include <vector>
constexpr int FPGA_RB_IGNORE_BYTES_CONTROL = 48;
constexpr int FPGA_RB_IGNORE_BYTES_DATA = 44;
enum {
FPGA_WR_FLAG_FULL_BS = 0,
FPGA_WR_FLAG_PARTIAL_BS = 1
};
enum {
FPGA_RB_FLAG_TYPE_CONTROL = 0,
FPGA_RB_FLAG_TYPE_DATA = 1
};
class FPGAManager {
std::string sysfsFirm, sysfsFlags, sysfsRBImage, sysfsRBFlags;
void setFPGAFlags(int flags) {
std::ofstream flagfile(sysfsFlags);
flagfile << flags;
flagfile.close();
if (!flagfile)
throw std::runtime_error("Could not write fpga flags");
}
void setFPGAFirmware(const std::string &firmware) {
std::ofstream firmfile(sysfsFirm);
firmfile << firmware;
firmfile.close();
if (!firmfile)
throw std::runtime_error("Could not write fpga firmware");
}
void setFPGAReadbackFlags(int flags) {
std::ofstream flagfile(sysfsRBFlags);
flagfile << flags;
flagfile.close();
if (!flagfile)
throw std::runtime_error("Could not write readback flags");
}
std::vector<char> performFPGAReadback(int seekoffset) {
std::ifstream readbackfile(sysfsRBImage, std::ios::binary);
readbackfile.ignore(seekoffset);
std::vector<char> filedata((std::istreambuf_iterator<char>(readbackfile)),
std::istreambuf_iterator<char>());
readbackfile.close();
if (!readbackfile)
throw std::runtime_error("Could not open readback file");
return filedata;
}
public:
FPGAManager(int fpga_id) {
std::string sysfsRoot = "/sys/class/fpga_manager/fpga" + std::to_string(fpga_id);
sysfsFirm = sysfsRoot + "/firmware";
sysfsFlags = sysfsRoot + "/flags";
sysfsRBImage = "/sys/kernel/debug/fpga/fpga" + std::to_string(fpga_id) + "/image";
sysfsRBFlags = "/sys/module/zynqmp_fpga/parameters/readback_type";
}
std::vector<char> readbackImage() {
setFPGAReadbackFlags(FPGA_RB_FLAG_TYPE_DATA);
return performFPGAReadback(FPGA_RB_IGNORE_BYTES_DATA);
}
std::vector<char> readbackConfig() {
setFPGAReadbackFlags(FPGA_RB_FLAG_TYPE_CONTROL);
return performFPGAReadback(FPGA_RB_IGNORE_BYTES_CONTROL);
}
void loadFull(const std::string &firmware) {
setFPGAFlags(FPGA_WR_FLAG_FULL_BS);
setFPGAFirmware(firmware);
}
void loadPartial(const std::string &firmware) {
setFPGAFlags(FPGA_WR_FLAG_PARTIAL_BS);
setFPGAFirmware(firmware);
}
};
|
#pragma once
class Monster;
enum Motion
{
en_front,
en_rotate,
en_left,
en_right,
};
enum Form
{
enAdhesion,
enFixed,
};
class MonsterEffect :public GameObject
{
public:
~MonsterEffect();
void init(const wchar_t* path,Motion motion,Monster* me,CVector3 offset,CVector3 scale);
void Update() override final;
void FAdhesion();
void FFixed();
void MFront();
void MRotate();
void MLeft();
void MRight();
bool IsPlay();
private:
CEffect* m_effect = nullptr;
Monster* m_me = nullptr;
CVector3 m_offset = CVector3::Zero();
CVector3 m_scale = CVector3::Zero();
Motion m_motion = en_front;
float m_time = 0.0f;
};
|
#ifndef TREEFACE_NODE_PRIVATE_H
#define TREEFACE_NODE_PRIVATE_H
#include "treeface/scene/SceneNode.h"
#include "treeface/scene/SceneObject.h"
#include "treeface/scene/guts/Utils.h"
#include "treeface/math/Mat4.h"
#include <treecore/AlignedMalloc.h>
#include <treecore/HashSet.h>
#include <treecore/RefCountHolder.h>
#include <treecore/SortedSet.h>
namespace treeface {
TREECORE_ALN_BEGIN( 16 )
struct SceneNode::Guts
{
TREECORE_ALIGNED_ALLOCATOR( SceneNode::Guts )
Mat4f trans;
Mat4f trans_inv;
Mat4f trans_global;
Mat4f trans_global_inv;
bool trans_dirty = true;
bool global_dirty = true;
bool uniform_cache_dirty = true;
treecore::SortedSet<treecore::RefCountHolder<SceneNode> > child_nodes;
SceneNode* parent = nullptr;
treecore::SortedSet<treecore::RefCountHolder<SceneObject> > objects;
void update_trans_descendent();
void update_global_descendent();
} TREECORE_ALN_END( 16 );
} // namespace treeface
#endif // TREEFACE_NODE_PRIVATE_H
|
#include "am_pm_clock.h"
am_pm_clock::am_pm_clock():
hours(12),
minutes(0),
seconds(0),
am(1)
{};
am_pm_clock::am_pm_clock(unsigned int hrs, unsigned int mins,
unsigned int secs, bool am_val):
hours(hrs),
minutes(mins),
seconds(secs),
am(am_val)
{};
am_pm_clock::am_pm_clock(const am_pm_clock &clock)
{
hours=clock.hours;
minutes=clock.minutes;
seconds=clock.seconds;
am=clock.am;
}
am_pm_clock& am_pm_clock::operator=(const am_pm_clock& clock){
hours=clock.hours;
minutes=clock.minutes;
seconds=clock.seconds;
am=clock.am;
}
void am_pm_clock::toggle_am_pm(){
if(hours == 11 && minutes == 59 && seconds == 59 && am == 1)
{seconds++;
am=0;}
else if(hours == 11 && minutes == 59 && seconds == 59 && am == 0)
{seconds++;
am=1;}
}
void am_pm_clock::reset(){
hours=12;
minutes=0;
seconds=0;
am=1;
}
void am_pm_clock::advance_one_sec(){
seconds++;
}
void am_pm_clock::advance_n_secs(unsigned int n){
seconds+=n;
}
unsigned int am_pm_clock::get_hours() const{
return hours;
}
void am_pm_clock::set_hours(unsigned int hrs){
if(hrs>12)
throw std::invalid_argument("Is not a legal hours value");
hours=hrs;
}
unsigned int am_pm_clock::get_minutes() const{
return minutes;
}
void am_pm_clock::set_minutes(unsigned int mins){
if(mins>59)
throw std::invalid_argument("Is not a legal minutes value");
minutes=mins;
}
unsigned int am_pm_clock::get_seconds() const{
return seconds;
}
void am_pm_clock::set_seconds(unsigned int secs){
if(secs>59)
throw std::invalid_argument("Is not a legal seconds value");
seconds=secs;
}
bool am_pm_clock::is_am() const{
if(am)
return true;
else
return false;
}
void am_pm_clock::set_am(bool am_val){
am=am_val;
}
void am_pm_clock::print(std::ostream& out) const {
char buff[11];
std::sprintf(buff, "%02d:%02d:%02d%cm", hours, minutes, seconds,
( am ? 'a' : 'p' ));
out << buff;
}
am_pm_clock::~am_pm_clock()
{
};
|
#include "StdAfx.h"
#include "Gt2DMesh.h"
GnImplementRTTI(Gt2DMesh, GtObject);
Gt2DMesh::Gt2DMesh(void)
{
}
Gt2DMesh::~Gt2DMesh(void)
{
}
|
#include <iostream>
#include <vector>
using namespace std;
void rotate_matrix(vector<vector<int>>& matrix) {
for (int r = 0; r < (matrix.size() / 2); r++) {
for (int c = r; c < (matrix.size() - r - 1); c++) {
// Upper left to upper right
int up_right = matrix[c][matrix.size() - r - 1];
matrix[c][matrix.size() - r - 1] = matrix[r][c];
// Upper right to bottom right
int bot_right
= matrix[matrix.size() - r - 1][matrix.size() - c - 1];
matrix[matrix.size() - r - 1][matrix.size() - c - 1] = up_right;
// Bottom right to bottom left
int bot_left = matrix[matrix.size() - c - 1][r];
matrix[matrix.size() - c - 1][r] = bot_right;
// Bottom left to top left
matrix[r][c] = bot_left;
}
}
}
void print_matrix(const vector<vector<int>>& matrix) {
for (auto& row : matrix) {
for (auto col : row) {
cout << '\t' << col;
}
cout << "\n";
}
cout << endl;
}
void run_rotate_matrix(vector<vector<int>> matrix) {
print_matrix(matrix);
rotate_matrix(matrix);
print_matrix(matrix);
rotate_matrix(matrix);
print_matrix(matrix);
rotate_matrix(matrix);
print_matrix(matrix);
rotate_matrix(matrix);
print_matrix(matrix);
cout << "--- Done ---\n\n" << endl;
}
int main() {
run_rotate_matrix({
{1, 2, 3},
{4, 5, 6},
{7, 8, 9}});
run_rotate_matrix({
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 12},
{13, 14, 15, 16}});
run_rotate_matrix({
{1, 2, 3, 4, 5},
{6, 7, 8, 9, 10},
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25}});
}
|
#include "HungryCondition.h"
|
#include <string>
#include "../headers/MethodNode.hpp"
#include "../headers/ClassNode.hpp"
#include "../headers/AstNode.hpp"
using namespace std;
MethodNode::MethodNode() = default;
void MethodNode::setName(string name) {
this->name = name;
}
void MethodNode::setRetType(string returnType) {
this->returnType = returnType;
this->type = returnType;
}
void MethodNode::setRetValue(Node *returnValue) {
this->returnValue = returnValue;
}
void MethodNode::setNbArgs(int nbArgs) {
this->nbArgs = nbArgs;
}
Node *MethodNode::getExpr() {
return this->returnValue;
}
int MethodNode::getArgNumber() {
return this->nbArgs;
}
vector<FormalNode *> MethodNode::getFormals() {
return this->formals;
}
string MethodNode::getName() {
return name;
}
void MethodNode::addFormal(FormalNode *formal) {
formals.push_back(formal);
}
bool MethodNode::argsRightType(vector<Node *> arguments) {
if (this->formals.size() != arguments.size())
return false;
for (int i = 0; i < this->formals.size(); i++) {
if (formals.at(i)->getType() != arguments.at(i)->getType())
return false;
}
return true;
}
string MethodNode::argRedef() {
if (this->formals.empty())
return "";
vector<string> argsName;
for (auto &formal : this->formals) {
for (const auto &j : argsName) {
if (j == formal->getValue())
return j;
}
argsName.push_back(formal->getValue());
}
return "";
}
void MethodNode::printTree() {
printf("Method(%s, [", name.c_str());
for (int i = 0; i < formals.size(); i++) {
formals.at(i)->printTree();
if (i < formals.size() - 1)
printf(", ");
}
printf("], ");
printf("%s", returnType.c_str());
printf(", ");
if (returnValue != nullptr)
returnValue->printTree();
printf(")");
}
string MethodNode::printCheck(ClassNode *classNode) {
classNode->getVariableTable()->addVariable(name, returnType, false, true);
classNode->getVariableTable()->addFunction();
this->setNbArgs(formals.size());
string retString = "Method(" + name + ", [";
if (!classNode->getAstNode()->isParentExist(this->type) and this->type != "int32" and this->type != "bool" and
this->type != "string" and this->type != "Object" and this->type != "IO" and this->type != "unit")
return "ErrorSemanticOneTime:" + to_string(this->nbLine - 1) + ":" + to_string(this->nbColumn + 5) +
": semantic error : use of undefined type " + this->type + ".";
string errArg = argRedef();
if (!errArg.empty())
return "ErrorSemanticOneTime:" + to_string(this->getNbLine() - 1) + ":" + to_string(this->getNbColumn() + 1) +
": semantic error : redefinition of argument " + errArg + ".";
for (int i = 0; i < formals.size(); i++) {
if (formals.at(i)->printCheck(classNode).find("ErrorSemanticOneTime:") != string::npos)
return formals.at(i)->printCheck(classNode);
retString += formals.at(i)->printCheck(classNode);
if (i < formals.size() - 1)
retString += ", ";
}
retString += "], " + returnType + ", ";
classNode->getVariableTable()->addVariable(name, returnType, false, true);
if (returnValue != nullptr) {
if (returnValue->printCheck(classNode).find("ErrorSemanticOneTime:") != string::npos)
return returnValue->printCheck(classNode);
if (returnValue->getType() != this->returnType and
(!returnValue->getLastField() or !returnValue->getLastField()->getTypeClass() or
!returnValue->getLastField()->getTypeClass()->isAncestor(this->returnType)))
return "ErrorSemanticOneTime:" + to_string(this->getNbLine() - 1) + ":" +
to_string(this->getNbColumn() + 13) +
": semantic error : expression returns type " + this->returnType + ", but " +
returnValue->getType() +
" was given.";
retString += returnValue->printCheck(classNode);
}
classNode->getVariableTable()->removeFunction();
retString += ")";
return retString;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2009-2012 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef MEDIA_PLAYER_SUPPORT
#ifndef MEDIA_SIMPLE_CONTROLS
#include "modules/media/src/controls/mediacontrols.h"
#include "modules/media/src/controls/mediaslider.h"
#include "modules/display/vis_dev.h"
#include "modules/skin/OpSkinManager.h"
/* static */ OP_STATUS
MediaSlider::Create(MediaSlider*& slider, MediaSliderType slider_type)
{
if ((slider = OP_NEW(MediaSlider, (slider_type))))
return OpStatus::OK;
return OpStatus::ERR_NO_MEMORY;
}
MediaSlider::MediaSlider(MediaSliderType slider_type)
: m_slider_type(slider_type),
m_min(0),
m_max(0),
m_current(0),
m_is_dragging(FALSE)
{}
/* virtual */ BOOL
MediaSlider::OnInputAction(OpInputAction* action)
{
switch (action->GetAction())
{
#ifdef ACTION_MEDIA_SEEK_FORWARD_ENABLED
case OpInputAction::ACTION_MEDIA_SEEK_FORWARD:
{
SetValue(m_current + action->GetActionData());
HandleOnChange(FALSE);
return TRUE;
}
#endif // ACTION_MEDIA_SEEK_FORWARD_ENABLED
#ifdef ACTION_MEDIA_SEEK_BACKWARD_ENABLED
case OpInputAction::ACTION_MEDIA_SEEK_BACKWARD:
{
SetValue(m_current - action->GetActionData());
HandleOnChange(FALSE);
return TRUE;
}
#endif // ACTION_MEDIA_SEEK_BACKWARD_ENABLED
}
return FALSE;
}
/* virtual */ void
MediaSlider::OnPaint(OpWidgetPainter* widget_painter, const OpRect &paint_rect)
{
// Abuse the skin system to draw a background color for the
// unbuffered ranges, then the buffered ranges and finally the
// actual seek track and knob on top of that.
VisualDevice* visdev = GetVisualDevice();
UINT32 color = 0;
OpStatus::Ignore(g_skin_manager->GetBackgroundColor("Media Seek Background", &color));
visdev->SetColor(color);
visdev->FillRect(paint_rect);
PaintBufferedRanges(paint_rect);
g_skin_manager->DrawElement(visdev, GetTrackSkin(), paint_rect);
OpRect knob_rect;
if (CalcKnobRect(knob_rect))
{
g_skin_manager->DrawElement(visdev, GetKnobSkin(), knob_rect);
if (IsFocused())
{
GetVisualDevice()->SetColor(200, 200, 200);
GetVisualDevice()->RectangleOut(knob_rect.x, knob_rect.y, knob_rect.width, knob_rect.height, CSS_VALUE_dashed);
}
}
}
/* virtual */ void
MediaSlider::GetPreferedSize(INT32* w, INT32* h, INT32 cols, INT32 rows)
{
g_skin_manager->GetSize(GetTrackSkin(), w, h);
}
/* virtual */ void
MediaSlider::OnMouseMove(const OpPoint &point)
{
if (m_is_dragging)
{
SetValue(PointToOffset(point));
HandleOnChange(TRUE);
}
}
/* virtual */ void
MediaSlider::OnMouseDown(const OpPoint &point, MouseButton button, UINT8 nclicks)
{
if (button == MOUSE_BUTTON_1)
{
m_is_dragging = TRUE;
if (!IsPointInKnob(point))
{
SetValue(PointToOffset(point));
HandleOnChange(TRUE);
}
}
}
/* virtual */ void
MediaSlider::OnMouseUp(const OpPoint &point, MouseButton button, UINT8 nclicks)
{
if (m_is_dragging)
{
m_is_dragging = FALSE;
HandleOnChange(TRUE);
}
}
BOOL
MediaSlider::IsPointInKnob(const OpPoint &point) const
{
OpRect rect;
if (CalcKnobRect(rect))
return rect.Contains(point);
return FALSE;
}
bool
MediaSlider::CalcKnobRect(OpRect& res) const
{
if (!op_isfinite(m_max) || m_max <= 0)
return false;
OpSkinElement* element = g_skin_manager->GetSkinElement(GetKnobSkin());
if (!element)
return false;
INT32 width, height, pad_left, pad_right, pad_top, pad_bottom;
if (OpStatus::IsError(element->GetSize(&width, &height, 0)) ||
OpStatus::IsError(element->GetPadding(&pad_left, &pad_top, &pad_right, &pad_bottom, 0)))
return false;
res.width = width;
res.height = height;
const OpRect r = const_cast<MediaSlider*>(this)->GetBounds();
const double relative_offset = m_current / (m_max - m_min);
if (IsHorizontal())
{
res.x = pad_left + (INT32)(relative_offset * (r.width - pad_left - pad_right)) - res.width/2;
res.y = pad_top + r.height / 2 - res.height;
}
else
{
res.x = pad_left + r.width / 2 - res.width;
res.y = pad_top + (INT32)((1.0 - relative_offset) * (r.height - pad_top - pad_bottom)) - res.height/2;
}
return true;
}
OpRect
MediaSlider::CalcRangeRect(const OpRect& bounds, double start, double end) const
{
const double size = m_max - m_min;
// Prevent division by zero and negative values.
if (size <= 0)
return OpRect();
// Clamp values to [m_min, m_max].
start = MAX(start, m_min);
end = MIN(end, m_max);
const double start_offset = (start - m_min) / size;
const double end_offset = (end - m_min) / size;
// Round towards the center of the interval. (See documentation of
// function declaration).
const INT32 x0 = (INT32)op_ceil(start_offset * bounds.width);
const INT32 x1 = (INT32)op_floor(end_offset * bounds.width);
// Due to rounding, very small ranges can end up producing negative
// rectangle width. Don't allow that.
const INT32 width = MAX(0, x1 - x0);
return OpRect(bounds.x + x0, bounds.y, width, bounds.height);
}
double
MediaSlider::PointToOffset(const OpPoint& point)
{
INT32 pad_left, pad_right, pad_top, pad_bottom;
OpStatus::Ignore(g_skin_manager->GetPadding(GetTrackSkin(), &pad_left, &pad_top, &pad_right, &pad_bottom));
double offset = 0;
if (IsHorizontal())
{
offset = (double)(point.x - pad_left) / (double)(GetBounds().width - pad_left - pad_right);
}
else
{
offset = 1.0 - (double)(point.y - pad_bottom) / (double)(GetBounds().height - pad_top - pad_bottom);
}
// Clamp to [0,1]
if (offset < 0)
offset = 0;
else if (offset > 1)
offset = 1;
return (m_max - m_min) * offset;
}
void
MediaSlider::SetValue(double val, BOOL invalidate)
{
if (m_current != val)
{
m_current = val;
if (invalidate)
InvalidateAll();
}
}
void
MediaSlider::HandleOnChange(BOOL changed_by_mouse)
{
if (listener)
listener->OnChange(this, changed_by_mouse);
}
void
MediaSlider::PaintBufferedRanges(const OpRect& paint_rect)
{
VisualDevice* visdev = GetVisualDevice();
if (!IsHorizontal())
return;
UINT32 color = 0;
OpStatus::Ignore(g_skin_manager->GetBackgroundColor("Media Seek Buffered", &color));
visdev->SetColor(color);
UINT32 length = m_buffered_ranges.Length();
for (UINT32 i = 0; i < length; i++)
{
double start = m_buffered_ranges.Start(i);
double end = m_buffered_ranges.End(i);
OpRect progress = CalcRangeRect(paint_rect, start, end);
visdev->FillRect(progress);
}
}
OpRect
VolumeSliderContainer::CalculateRect()
{
VisualDevice* vd = m_controls->GetVisualDevice();
GetWidgetContainer()->GetVisualDevice()->SetScale(vd->GetScale(), FALSE);
INT32 w, h;
m_slider->GetPreferedSize(&w, &h, 0, 0);
AffinePos p = m_controls->GetPosInDocument();
OpPoint preferred_pos(m_controls->GetWidth() - w, 0);
p.Apply(preferred_pos);
OpRect preferred_rect(preferred_pos.x, preferred_pos.y - h, w, h);
// Translate from document to view coordinates
preferred_rect.OffsetBy(-vd->GetRenderingViewX(), -vd->GetRenderingViewY());
// Scale to screen
preferred_rect = vd->ScaleToScreen(preferred_rect);
// Get position of upper left corner of the view
OpPoint pos = m_controls->GetVisualDevice()->view->ConvertToScreen(OpPoint(0, 0));
preferred_rect.OffsetBy(pos);
if (preferred_rect.y < pos.y)
preferred_rect.y = pos.y;
return preferred_rect;
}
void
VolumeSliderContainer::UpdatePosition()
{
int m_scale = m_slider->GetVisualDevice()->GetScale();
GetWidgetContainer()->GetRoot()->GetVisualDevice()->SetScale(m_scale, FALSE);
OpRect rect = CalculateRect();
m_window->SetOuterPos(rect.x, rect.y);
m_window->SetInnerSize(rect.width, rect.height);
}
void
VolumeSliderContainer::OnResize(UINT32 width, UINT32 height)
{
WidgetWindow::OnResize(width, height);
int m_scale = m_controls->GetVisualDevice()->GetScale();
m_slider->SetRect(OpRect(0, 0,
width * 100 / m_scale,
height * 100 / m_scale));
}
OP_STATUS
VolumeSliderContainer::Init()
{
RETURN_IF_ERROR(WidgetWindow::Init(OpWindow::STYLE_POPUP,
m_controls->GetParentOpWindow(),
0, OpWindow::EFFECT_TRANSPARENT));
RETURN_IF_ERROR(MediaSlider::Create(m_slider, MediaSlider::Volume));
GetWidgetContainer()->GetRoot()->GetVisualDevice()->SetScale(100);
GetWidgetContainer()->GetRoot()->AddChild(m_slider);
m_slider->SetParentInputContext(m_controls);
m_slider->SetListener(static_cast<MediaButtonListener*>(m_controls));
m_slider->SetMaxValue(1.0);
return OpStatus::OK;
}
/* static */ OP_STATUS
VolumeSliderContainer::Create(VolumeSliderContainer*& container, MediaControls* controls)
{
OpAutoPtr<VolumeSliderContainer> container_safe(OP_NEW(VolumeSliderContainer, (controls)));
if (container_safe.get())
{
RETURN_IF_ERROR(container_safe->Init());
container = container_safe.release();
return OpStatus::OK;
}
return OpStatus::ERR_NO_MEMORY;
}
VolumeSliderContainer::~VolumeSliderContainer()
{
m_controls->DetachVolumeSlider();
}
#endif // !MEDIA_SIMPLE_CONTROLS
#endif // MEDIA_PLAYER_SUPPORT
|
#include <iostream>
#include <list>
#include <string>
#include <algorithm>
#include <iomanip>
using namespace std;
struct item {
int exp;
double coe;
item(int e, double c):exp(e), coe(c){}
};
bool operator< (const item& a, const item& b) {
return a.exp > b.exp;
}
item operator* (const item& a, const item& b) {
return item(a.exp + b.exp, a.coe*b.coe);
}
struct poly {
list<item> ls;
poly() {}
poly(list<item> l):ls(l) {}
void operator+=(const item& a) {
if (ls.empty()) {
ls.push_back(a);
}
else {
auto it = lower_bound(ls.begin(), ls.end(), a);
if (it != ls.end() && it->exp == a.exp) {
it->coe += a.coe;
if (it->coe == 0) {
ls.erase(it);
}
}
else {
ls.insert(it, a);
}
}
}
};
ostream& operator<<(ostream& out, poly p) {
out << p.ls.size();
for (auto it = p.ls.begin(); it != p.ls.end(); it++) {
out << ' ' << it->exp;
out << fixed << setprecision(1) << ' ' << it->coe;
}
out << endl;
return out;
}
int main() {
int n;
int exp;
double coe;
cin >> n;
poly a; poly b; poly res;
while (n--) {
cin >> exp >> coe;
a += item(exp, coe);
}
cin >> n;
while (n--) {
cin >> exp >> coe;
b += item(exp, coe);
}
for (auto i = a.ls.begin(); i != a.ls.end(); i++) {
for (auto j = b.ls.begin(); j != b.ls.end(); j++) {
res += (*i)*(*j);
}
}
cout << res;
return 0;
}
|
// https://codeforces.com/problemset/problem/687/A
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<vector<int>> edges(10001);
int n, m, u, v;
bool colors[100001];
int markColor(int src, int color)
{
queue<int> q;
colors[src] = color;
q.push(src);
while (!q.empty())
{
int u = q.front();
q.pop();
cout << "source color " << u << " " << colors[u] << endl;
for (int v : edges[u])
{
if (colors[v] == 0)
{
if (colors[u] == 1)
colors[v] = 2;
else
colors[v] = 1;
cout << "marked " << u << " " << v << " " << colors[v] << endl;
q.push(v);
}
else if (colors[v] == colors[u])
{
cout << u << " " << v << " " << colors[u] << endl;
return -1;
}
}
}
return 1;
}
int main()
{
cin >> n >> m;
for (int i = 0; i < m; i++)
{
cin >> u >> v;
edges[u].push_back(v);
edges[v].push_back(u);
}
for (int i = 1; i <= n; i++)
{
if (colors[i] == 0)
{
int res = markColor(i, 1);
if (res == -1)
{
cout << -1 << endl;
return 0;
}
}
}
}
|
// BEGIN CUT HERE
// PROBLEM STATEMENT
// Given a positive integer number, concatenate one or more
// copies of number to create an integer that is divisible by
// k. Do not add any leading zeroes. Return the least
// number of copies needed, or -1 if it is impossible.
//
// DEFINITION
// Class:ConcatenateNumber
// Method:getSmallest
// Parameters:int, int
// Returns:int
// Method signature:int getSmallest(int number, int k)
//
//
// CONSTRAINTS
// -number will be between 1 and 1,000,000,000, inclusive.
// -k will be between 1 and 100,000, inclusive.
//
//
// EXAMPLES
//
// 0)
// 2
// 9
//
// Returns: 9
//
// At least 9 copies are needed, since 222222222 is divisible
// by 9.
//
// 1)
// 121
// 11
//
// Returns: 1
//
// 121 is divisible by 11.
//
// 2)
// 1
// 2
//
// Returns: -1
//
// You can never get an even number by concatenating only 1's.
//
// 3)
// 35
// 98765
//
// Returns: 9876
//
// The resulting integer could be really big.
//
// 4)
// 1000000000
// 3
//
// Returns: 3
//
//
//
// END CUT HERE
#line 66 "ConcatenateNumber.cc"
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <algorithm>
#include <numeric>
#include <functional>
#include <map>
#include <set>
#include <cassert>
#include <list>
#include <deque>
#include <iomanip>
#include <cstring>
#include <cmath>
#include <cstdio>
#include <cctype>
using namespace std;
#define fi(n) for(int i=0;i<(n);i++)
#define fj(n) for(int j=0;j<(n);j++)
#define f(i,a,b) for(int (i)=(a);(i)<(b);(i)++)
typedef vector <int> VI;
typedef vector <string> VS;
typedef vector <VI> VVI;
typedef long long ll;
class ConcatenateNumber
{
public:
int getSmallest(int number, int k)
{
ll no = number;
while (no < 1LL<<32) {
if (no % k == 0) return no;
no = 10*no + number;
}
return -1;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 2; int Arg1 = 9; int Arg2 = 9; verify_case(0, Arg2, getSmallest(Arg0, Arg1)); }
void test_case_1() { int Arg0 = 121; int Arg1 = 11; int Arg2 = 1; verify_case(1, Arg2, getSmallest(Arg0, Arg1)); }
void test_case_2() { int Arg0 = 1; int Arg1 = 2; int Arg2 = -1; verify_case(2, Arg2, getSmallest(Arg0, Arg1)); }
void test_case_3() { int Arg0 = 35; int Arg1 = 98765; int Arg2 = 9876; verify_case(3, Arg2, getSmallest(Arg0, Arg1)); }
void test_case_4() { int Arg0 = 1000000000; int Arg1 = 3; int Arg2 = 3; verify_case(4, Arg2, getSmallest(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ConcatenateNumber ___test;
___test.run_test(-1);
}
// END CUT HERE
|
// Created on: 1993-01-09
// Created by: CKY / Contract Toubro-Larsen ( Arun MENON )
// Copyright (c) 1993-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 _IGESDimen_BasicDimension_HeaderFile
#define _IGESDimen_BasicDimension_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <Standard_Integer.hxx>
#include <gp_XY.hxx>
#include <IGESData_IGESEntity.hxx>
class gp_Pnt2d;
class IGESDimen_BasicDimension;
DEFINE_STANDARD_HANDLE(IGESDimen_BasicDimension, IGESData_IGESEntity)
//! Defines IGES Basic Dimension, Type 406, Form 31,
//! in package IGESDimen
//! The basic Dimension Property indicates that the referencing
//! dimension entity is to be displayed with a box around text.
class IGESDimen_BasicDimension : public IGESData_IGESEntity
{
public:
Standard_EXPORT IGESDimen_BasicDimension();
Standard_EXPORT void Init (const Standard_Integer nbPropVal, const gp_XY& lowerLeft, const gp_XY& lowerRight, const gp_XY& upperRight, const gp_XY& upperLeft);
//! returns the number of properties = 8
Standard_EXPORT Standard_Integer NbPropertyValues() const;
//! returns coordinates of lower left corner
Standard_EXPORT gp_Pnt2d LowerLeft() const;
//! returns coordinates of lower right corner
Standard_EXPORT gp_Pnt2d LowerRight() const;
//! returns coordinates of upper right corner
Standard_EXPORT gp_Pnt2d UpperRight() const;
//! returns coordinates of upper left corner
Standard_EXPORT gp_Pnt2d UpperLeft() const;
DEFINE_STANDARD_RTTIEXT(IGESDimen_BasicDimension,IGESData_IGESEntity)
protected:
private:
Standard_Integer theNbPropertyValues;
gp_XY theLowerLeft;
gp_XY theLowerRight;
gp_XY theUpperRight;
gp_XY theUpperLeft;
};
#endif // _IGESDimen_BasicDimension_HeaderFile
|
#include "CharacterObject.h"
#include <DxLib.h>
#include <cassert>
#include "Camera.h"
#include "Game.h"
//アニメーションの変更
void CharacterObject::ChangeAction(const char * name)
{
_nowName = name;
_nowCutIdx = 0;
_frame = 0;
}
//アニメーションのフレームを1進める
bool CharacterObject::ProceedAnimationFrame()
{
if ((signed)_frame < _actionData.actInfo[_nowName].cuts[_nowCutIdx].duration) {
_frame++;
}
else {
_frame = 0;
if (_nowCutIdx < (signed)_actionData.actInfo[_nowName].cuts.size() - 1) {
++_nowCutIdx;
}
else {
if (_actionData.actInfo[_nowName].isLoop) {
_nowCutIdx = 0;
}
else {
return true;
}
}
}
return false;
}
///ファイルの読み込み
void CharacterObject::readActfile(const char * actionPath)
{
int h = DxLib::FileRead_open(actionPath, false);
float version = 0.0f;
DxLib::FileRead_read(&version, sizeof(version), h);
assert(version == 1.01f);
int imgpathsize = 0;
DxLib::FileRead_read(&imgpathsize, sizeof(imgpathsize), h);
std::string imgPath = "";
imgPath.resize(imgpathsize);
DxLib::FileRead_read(&imgPath[0], imgpathsize, h);
std::string actPath = actionPath;
auto ipos = actPath.find_last_of("/") + 1;
_actionData.imgFilePath = actPath.substr(0, ipos) + imgPath;
///このアプリケーションからの相対パスにする
//アクションの数
int actionCount = 0;
DxLib::FileRead_read(&actionCount, sizeof(actionCount), h);
for (int idx = 0; idx < actionCount; ++idx) {
//アクションの名前
int actionNameSize = 0;
DxLib::FileRead_read(&actionNameSize, sizeof(actionNameSize), h);
std::string actionName;
actionName.resize(actionNameSize);
DxLib::FileRead_read(&actionName[0], actionName.size(), h);
ActionInfo actInfo;
//ループ読み込み
DxLib::FileRead_read(&actInfo.isLoop, sizeof(actInfo.isLoop), h);
//カットデータ数の取得
int cutCount = 0;
DxLib::FileRead_read(&cutCount, sizeof(cutCount), h);
//カットデータ取得
actInfo.cuts.resize(cutCount);
for (int i = 0; i < cutCount; i++) {
DxLib::FileRead_read(&actInfo.cuts[i], sizeof(actInfo.cuts[i]) - sizeof(actInfo.cuts[i].actrects), h);
//アクション矩形の読み込み
int actrcCount = 0;
DxLib::FileRead_read(&actrcCount, sizeof(actrcCount), h);
if (actrcCount == 0)continue;
actInfo.cuts[i].actrects.resize(actrcCount);
DxLib::FileRead_read(&actInfo.cuts[i].actrects[0], actrcCount * sizeof(ActionRect), h);
}
//アクションマップに登録
_actionData.actInfo[actionName] = actInfo;
}
DxLib::FileRead_close(h);
}
void CharacterObject::Draw(int & Img)
{
Game& game = Game::Instance();
auto& actInfo = _actionData.actInfo[_nowName];
auto& cut = actInfo.cuts[_nowCutIdx];
auto& rc = cut.rc;
auto centerX = _isTurn ? rc.Width() - cut.center.x : cut.center.x;
Position2f pos = _camera.CalculatePosition(_pos);
auto _tmp = _camera.GetViewport();
auto scroll = _tmp.Top();//上スクロール値算出
scroll %= (bgimg_y_size + bnimg_y_size + unimg_y_size) * 2;
DxLib::DrawRectRotaGraph2((int)pos.x, (int)pos.y-scroll, rc.Left(), rc.Top(), rc.Width(), rc.Height(), centerX, cut.center.y, (int)game.GetObjectScale(), 0.0, Img, true, _isTurn);
#ifdef _DEBUG
DebugDraw();
#endif
}
void CharacterObject::DebugDraw()
{
///矩形の表示
Game& game = Game::Instance();
auto& actInfo = _actionData.actInfo[_nowName];
auto& cut = actInfo.cuts[_nowCutIdx];
auto _tmp = _camera.GetViewport();
auto scroll = _tmp.Top();//上スクロール値算出
scroll %= (bgimg_y_size + bnimg_y_size + unimg_y_size) * 2;
for (ActionRect& act : cut.actrects) {
Rect rc = GetActuralRectForAction(act.rc);
SetDrawBlendMode(DX_BLENDMODE_ALPHA, 100);
DrawBox(rc.Left(), rc.Top()-scroll, rc.Right(), rc.Bottom()-scroll, 0xff0000, true);
SetDrawBlendMode(DX_BLENDMODE_NOBLEND, 0);
DrawBox(rc.Left(), rc.Top()-scroll, rc.Right(), rc.Bottom()-scroll, 0xff0000, false);
}
}
Rect CharacterObject::GetActuralRectForAction(const Rect & _rec) const
{
Game& game = Game::Instance();
Rect rc = _rec;
rc.size.width *= (int)game.GetObjectScale();
rc.size.height *= (int)game.GetObjectScale();
auto offset = _isTurn ? rc.size.width : rc.size.width / 2;
Position2f pos = _camera.CalculatePosition(_pos);
rc.center.x = rc.center.x * (int)game.GetObjectScale() + (int)pos.x - offset;
rc.center.y = rc.center.y * (int)game.GetObjectScale() + (int)pos.y - rc.size.height;
return rc;
}
//アクション矩形情報取得
const std::vector<ActionRect>& CharacterObject::GetActionRects() const
{
return _actionData.actInfo.at(_nowName).cuts[_nowCutIdx].actrects;
}
//キャラの座標を返す
const Position2f & CharacterObject::GetPos() const
{
return _pos;
}
//アクションデータコピー
void CharacterObject::Copy(const CharacterObject & c)
{
_actionData.imgFilePath = c._actionData.imgFilePath;
for (auto& info : c._actionData.actInfo){
_actionData.actInfo[info.first] = info.second;
}
_isTurn = c._isTurn;
_pos = c._pos;
_nowName = c._nowName;
_nowCutIdx = c._nowCutIdx;
_frame = c._frame;
}
CharacterObject::CharacterObject(const Camera & c) :_frame(0), _nowCutIdx(0), _camera(c)
{
}
CharacterObject::~CharacterObject()
{
}
|
#include<iostream>
using namespace std;
long long int mem[10000001] = {0};
long long int k;
long long int func(long long int n) {
if(n<12) {
return n;
}
else if(n == 12) {
return 13;
}
else if(n<1000000) {
if(mem[n]!=0){
return mem[n];
}
}
k = func((long long)n/2)+func((long long)n/3)+func((long long)n/4);
if(n<1000000) {
mem[n]=k;
}
return k;
}
int main() {
long long int n1;
while(cin>>n1){
cout<<func(n1)<<"\n";
}
}
|
#pragma once
class AIEditnode;
class AIEditNodeInequ;
class AIEditNodeOrder;
class AIEditLine;
class AIEditNodeButton;
class AIEditNodeProcess;
class AIEditNodeNum : public GameObject
{
public:
~AIEditNodeNum();
bool Start() override final;
void Update() override final;
void Order();
void FontsConfirmation();
void GetChoice3(bool a)
{
Choice3 = a;
}
enum Num {
en1 = 400,
en10,
en30,
en50,
en70,
en90,
en100,
ennull = 0
};
int GetNum()
{
return m_num;
}
bool Getnumfont()
{
return Numfont;
}
private:
Num m_num = ennull;
int button = 7; //ボタン。
bool Choice3 = false; //何かが選択されたらtrueになる。
bool Numfont = false;
float scale = 0.9;
bool contact1 = false;
bool contact2 = false;
CVector2 SetShadowPos = { 5.f,-5.f };
CVector3 m_position = CVector3::Zero();
CVector3 m_pointposition = CVector3::Zero();
std::vector<FontRender*> m_fonts;
std::vector<FontRender*> m_font;
std::vector<SpriteRender*> m_spriteRenders;
std::vector<AIEditNodeButton*> m_nodebuttons;
SpriteRender * m_spriteRender;
SpriteRender * sr;
AIEditNode * m_aieditnode;
GameCursor * m_gamecursor;
AIEditNodeOrder * m_aieditnodeorder;
AIEditLine * m_aieditline;
AIEditNodeButton* m_aieditnodebutton;
AIEditNodeProcess* m_aieditnodeprocess;
};
|
/*
Copyright (c) 2014 Mircea Daniel Ispas
This file is part of "Push Game Engine" released under zlib license
For conditions of distribution and use, see copyright notice in Push.hpp
*/
#pragma once
#include "Core/Hash.hpp"
#include "Core/CoreConfig.hpp"
namespace Push
{
namespace CoreConfig
{
inline constexpr size_t EnumSize()
{
return 64;
}
inline constexpr size_t PathSize()
{
return 256;
}
}
}
|
//---------------------------------------------------------------------------
#ifndef TFrmMainH
#define TFrmMainH
//---------------------------------------------------------------------------
#include <Classes.hpp>
#include <Controls.hpp>
#include <StdCtrls.hpp>
#include <Forms.hpp>
#include <Dialogs.hpp>
#include <ExtDlgs.hpp>
#include <XPMan.hpp>
#include <ExtCtrls.hpp>
#include <ActnList.hpp>
#include <Menus.hpp>
#include <ComCtrls.hpp>
#include <Grids.hpp>
#include <System.Actions.hpp>
#include <Data.Bind.Components.hpp>
#include <Data.Bind.EngExt.hpp>
#include <System.Bindings.Outputs.hpp>
#include <System.Rtti.hpp>
#include <System.ImageList.hpp>
#include <Vcl.Bind.DBEngExt.hpp>
#include <Vcl.Bind.Editors.hpp>
#include <Vcl.Buttons.hpp>
#include <Vcl.ImgList.hpp>
#include "cspin.h"
#include <memory>
#include <vector>
#include <esgui/include/esgui.h>
//---------------------------------------------------------------------------
class TFrmMain : public TForm
{
__published: // IDE-managed Components
TOpenPictureDialog *dlgOpen_;
TScrollBox *viewImage_;
TLabel *lblImageInfo_;
TMainMenu *mnuMain_;
TActionList *lstCmds_;
TAction *actFileOpen_;
TMenuItem *File1;
TMenuItem *Fileopen1;
TAction *actFileExit_;
TMenuItem *Exit1;
TMenuItem *N1;
TComboBox *cbxOutFmt_;
TLabel *lblOutFmt_;
TPaintBox *pbxOrigView_;
TPanel *pnlTop_;
TCSpinEdit *edLeft_;
TCSpinEdit *edTop_;
TCSpinEdit *edRight_;
TLabel *lblLeft_;
TLabel *lblTop_;
TLabel *lblRight_;
TCSpinEdit *edBottom_;
TLabel *lblBottom_;
TGroupBox *gbxSelection_;
TBevel *bvl1_;
TPanel *pnlContents_;
TGroupBox *gbxExport_;
TGroupBox *gbxInfo_;
TGroupBox *gbxPalette_;
TGroupBox *gbxEstimate_;
TCheckBox *chkExportPalette_;
TLabel *lblEstimate_;
TLabel *lblBaseName_;
TEdit *edBaseName_;
TDrawGrid *gridPal_;
TAction *actFileExport_;
TSaveDialog *dlgExport_;
TMenuItem *Export1;
TPageControl *pgImages_;
TTabSheet *tabOriginal_;
TTabSheet *tabResult_;
TScrollBox *viewResult_;
TPaintBox *pbxResult_;
TCheckBox *chkHaveTransparentColor_;
TGridPanel *laySettings_;
TLabel *lblTransparentColor_;
TAction *actHaveTranspColor_;
TAction *actExportPalette_;
TGridPanel *layPalette_;
TLabel *lblPalOutputFmt_;
TComboBox *cbxPaletteOutFmt_;
TSpeedButton *btnEyedropper_;
TAction *actEyeDropper_;
TImageList *imgs_;
TLabel *lblSelectedClr_;
TControlAction *actSelectedClr_;
void __fastcall pbxImage_MouseMove(TObject *Sender, TShiftState Shift, int X,
int Y);
void __fastcall actFileExit_Execute(TObject *Sender);
void __fastcall actFileOpen_Execute(TObject *Sender);
void __fastcall edLeft_Change(TObject *Sender);
void __fastcall edTop_Change(TObject *Sender);
void __fastcall edRight_Change(TObject *Sender);
void __fastcall edBottom_Change(TObject *Sender);
void __fastcall pbxOrigView_Paint(TObject *Sender);
void __fastcall cbxOutFmt_Change(TObject *Sender);
void __fastcall gridPal_DrawCell(TObject *Sender, int ACol, int ARow,
TRect &Rect, TGridDrawState State);
void __fastcall actFileExport_Execute(TObject *Sender);
void __fastcall actFileExport_Update(TObject *Sender);
void __fastcall pbxResult_Paint(TObject *Sender);
void __fastcall actHaveTranspColor_Update(TObject *Sender);
void __fastcall actHaveTranspColor_Execute(TObject *Sender);
void __fastcall actExportPalette_Update(TObject *Sender);
void __fastcall cbxPaletteOutFmt_Change(TObject *Sender);
void __fastcall actExportPalette_Execute(TObject *Sender);
void __fastcall actEyeDropper_Update(TObject *Sender);
void __fastcall actEyeDropper_Execute(TObject *Sender);
void __fastcall img_Click(TObject *Sender);
void __fastcall actSelectedClr_Update(TObject *Sender);
void __fastcall gridPal_MouseUp(TObject *Sender, TMouseButton Button, TShiftState Shift,
int X, int Y);
public: // User declarations
__fastcall TFrmMain(TComponent* Owner);
protected:
int outputClrFmtGetFromCtl() const;
int palOutputClrFmtGetFromCtl() const;
static UnicodeString esguiClrfmtStringGet(int clrfmt);
void updateImageInfo();
void updateMemoryEstimate();
void updatePaletteControls();
void updateSelectionControls();
void updatePaletteView();
void bitmapExport(const String& file);
void updatePalette();
void updateResult();
void updateTransparencyControls();
int palIdxGetFromMousePos(int x, int y);
void outputBaseNameUpdate();
protected:
UnicodeString m_srcFileName;
std::unique_ptr<Graphics::TBitmap> m_orig;
std::unique_ptr<Graphics::TBitmap> m_result;
RGBQUAD m_pal[256];
size_t m_palCnt;
TColor m_curClr;
esU32 m_selClr;
int m_bpp;
bool m_canUseTranspColor;
bool m_useTranspColor;
bool m_transpColorSelected;
bool m_canExportPalette;
bool m_exportPalette;
bool m_eyeDropperActive;
bool m_transpColorIsPalIdx;
};
//---------------------------------------------------------------------------
extern PACKAGE TFrmMain *FrmMain;
//---------------------------------------------------------------------------
#endif
|
#include <SoftwareSerial.h>
SoftwareSerial BTSerial(2, 3); // RX | TX
const int potPin = A0; // potentiometer
const int pwmOutPin = 10; // PWM output
int potentiometerValue; //range from 0 to 1023
int pwmValue; //range from 0 to 255
int speedPercentage; //range from 0 to 100
int motorValue; //range from 0 to 180
void setup()
{
Serial.begin(9600);
Serial.println("Enter AT commands:");
// HC-06 default baud rate is 9600
BTSerial.begin(9600);
pinMode(potPin, INPUT);
pinMode(pwmOutPin, OUTPUT);
myMotor.attach(pwmOutPin);
}
void loop()
{
// Keep reading from HC-06 and send to Arduino Serial Monitor
if (BTSerial.available()){
Serial.write(BTSerial.read());
}
// Keep reading from Arduino Serial Monitor and send to HC-06
if (Serial.available()){
BTSerial.write(Serial.read());
}
potentiometerValue = analogRead(potPin);
pwmValue = map(potentiometerValue, 0,1023, 0, 255);
speedPercentage = (int) (potentiometerValue/1023.0*100);
motorValue = map(pwmValue,0,255,0,180);
myMotor.write(motorValue);
Serial.print(potentiometerValue);
Serial.print("\t");
Serial.print(pwmValue);
Serial.print("\t");
Serial.print(speedPercentage);
Serial.print("\t");
Serial.print(motorValue);
Serial.println();
}
|
#include "_pch.h"
#include "CtrlExecAct.h"
using namespace wh;
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
//---------------------------------------------------------------------------
CtrlActExecWindow::CtrlActExecWindow(
const std::shared_ptr<ViewExecActWindow>& view
, const std::shared_ptr<ModelActExecWindow>& model)
: CtrlWindowBase(view, model)
{
mCtrlObjBrowser = std::make_shared<CtrlTableObjBrowser_RO>
(view->GetViewObjBrowser(), model->mModelObjBrowser );
mCtrlActBrowser = std::make_shared<CtrlActBrowser>
(view->GetViewActBrowser(), model->mModelActBrowser);
mCtrlPropPG = std::make_shared<CtrlPropPg>
(view->GetViewPropPG(), model->mModelPropPg);
namespace ph = std::placeholders;
connModel_SelectPage = mModel->sigSelectPage
.connect(std::bind(&T_View::SetSelectPage, mView.get(), ph::_1));
connViewCmd_Unlock = mView->sigUnlock
.connect(std::bind(&CtrlActExecWindow::Unlock, this));
connViewCmd_SelectAct = mView->sigSelectAct
.connect(std::bind(&CtrlActExecWindow::SelectAct, this));
connViewCmd_Execute = mView->sigExecute
.connect(std::bind(&CtrlActExecWindow::Execute, this));
};
//---------------------------------------------------------------------------
CtrlActExecWindow::~CtrlActExecWindow()
{
}
//---------------------------------------------------------------------------
void CtrlActExecWindow::SetObjects(const std::set<ObjectKey>& obj)
{
mModel->LockObjects(obj);
}
//---------------------------------------------------------------------------
void CtrlActExecWindow::SelectAct()
{
mModel->DoSelectAct();
}
//---------------------------------------------------------------------------
void CtrlActExecWindow::Execute()
{
mModel->DoExecute();
}
//---------------------------------------------------------------------------
void CtrlActExecWindow::Unlock()
{
mModel->UnlockObjects();
}
|
#include <iostream.h>
#include <conio.h>
void main (){
clrscr(); // Weight Convertor
int op;
float gm, kg, pd;
cout <<"\n\n\t\tSoftware for Conversion of Weight";
cout <<"\n\n\t1. Gram into Kilogram";
cout <<"\n\n\t2. Kilogram into Gram";
cout <<"\n\n\t3. Pounds into Kilogram";
cout <<"\n\n\t4. Kilogram into Pounds";
cout <<"\n\n\t5. Gram into Pounds";
cout <<"\n\n\t6. Pounds into Gram";
cout <<"\n\n\t7. Exit";
cout <<"\n\n\n\tEnter the case no. for desired conversion:";
cin >>op;
switch (op) {
case 1:
clrscr();
cout <<"\n\n\t\tConversion of Gram into Kilogram";
cout <<"\n\n\n\tEnter the value in Grams = ";
cin >>gm;
kg=(gm*0.001);
cout <<"\n\n\tThe given Grams are equal to ";
cout <<kg;
cout <<" Kilograms";
cout <<"\n\n\tPress Enter to Exit";
break;
case 2:
clrscr();
cout <<"\n\n\t\tConversion of Kilogram into Gram";
cout <<"\n\n\n\tEnter the value in Kilograms = ";
cin >>kg;
gm=(kg*1000);
cout <<"\n\n\tThe given Kilograms are equal to ";
cout <<gm;
cout <<" Grams";
cout <<"\n\n\tPress Enter to Exit";
break;
case 3:
clrscr();
cout <<"\n\n\t\tConversion of Pounds into Kilogram";
cout <<"\n\n\n\tEnter the value in Pounds = ";
cin >>pd;
kg=(pd*0.45359237);
cout <<"\n\n\tThe given Pounds are equal to ";
cout <<kg;
cout <<" Kilograms";
cout <<"\n\n\tPress Enter to Exit";
break;
case 4:
clrscr();
cout <<"\n\n\t\tConversion of Kilogram into Pounds";
cout <<"\n\n\n\tEnter the value in Kilograms = ";
cin >>kg;
pd=(kg*2.20462262);
cout <<"\n\n\tThe given Kilograms are equal to ";
cout <<pd;
cout <<" Pounds";
cout <<"\n\n\tPress Enter to Exit";
break;
case 5:
clrscr();
cout <<"\n\n\t\tConversion of Gram into Pounds";
cout <<"\n\n\n\tEnter the value in Grams = ";
cin >>gm;
pd=(gm*0.00220462262);
cout <<"\n\n\tThe given Grams are equal to ";
cout <<pd;
cout <<" Pounds";
cout <<"\n\n\tPress Enter to Exit";
break;
case 6:
clrscr();
cout <<"\n\n\t\tConversion of Pounds into Gram";
cout <<"\n\n\n\tEnter the value in Pounds = ";
cin >>pd;
gm=(pd*453.59237);
cout <<"\n\n\tThe given Pounds are equal to ";
cout <<gm;
cout <<" Grams";
cout <<"\n\n\tPress Enter to Exit";
break;
case 7:
cout <<"\n\n\n\tPress Enter to Exit";
break;
default:
cout <<"\n\n\t\tInvalid Case...";
cout <<"\n\n\n\tPress Enter to Exit";
}
getche();
}
|
int speakerpin = 12; //스피커가 연결된 디지털핀 설정
int note[] = {262,294,330,349,392,440,494,523}; //도레미파솔라시도
void setup() {
int elementCount = sizeof(note) / sizeof(int);
for (int i=0; i < elementCount; i++) //note를 play
{
tone(speakerpin,note[i],500);
delay(100);
}
}
void loop() {
}
|
// Created on: 1992-01-24
// Created by: Remi LEQUETTE
// Copyright (c) 1992-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 _TopAbs_State_HeaderFile
#define _TopAbs_State_HeaderFile
//! Identifies the position of a vertex or a set of
//! vertices relative to a region of a shape.
//! The figure shown above illustrates the states of
//! vertices found in various parts of the edge relative
//! to the face which it intersects.
enum TopAbs_State
{
TopAbs_IN,
TopAbs_OUT,
TopAbs_ON,
TopAbs_UNKNOWN
};
#endif // _TopAbs_State_HeaderFile
|
//
// sendmsgtests.hpp
// AutoCaller
//
// Created by Micheal Chen on 2017/7/18.
//
//
#ifndef sendmsgtests_hpp
#define sendmsgtests_hpp
#include "cocos2d.h"
#include "testbase/BaseTest.h"
DEFINE_TEST_SUITE(SendMsgTests);
class SendTextMsgTest : public TestCase
{
public:
virtual bool init() override ;
CREATE_FUNC(SendTextMsgTest);
virtual std::string subtitle() const override {
return "Send Text Message Test";
}
void sendTextMsg();
virtual void onEnter() override;
private:
};
class SendCuostomMsgTest : public TestCase
{
public:
virtual bool init() override;
CREATE_FUNC(SendCuostomMsgTest);
virtual std::string subtitle() const override {
return "Send Custom Message Test";
}
virtual void onEnter() override;
void sendCustomMsg();
};
class SendGiftMsgTest : public TestCase
{
public:
virtual bool init() override;
CREATE_FUNC(SendGiftMsgTest);
virtual std::string subtitle() const override {
return "Send Gift Message Test";
}
virtual void onEnter() override;
void sendGiftMsg();
};
class SendMessageTestsNoCrash : public TestCase
{
public:
CREATE_FUNC(SendMessageTestsNoCrash);
virtual bool init() override;
virtual std::string subtitle() const override {
return "Should not be crash";
}
virtual void onEnter() override;
private:
cocos2d::Label *_label;
};
#endif /* sendmsgtests_hpp */
|
/*
My IR Remote codes, see this video to find out the codes for your remote: https://youtu.be/ftdJ0R_5NZk
PLAY: FFA25D
EQ: FF22DD
CH+: FFE21D
CH-: FF629D
VOL+: FFC23D
VOL-: FF02FD
0: FFE01F
PREV: FFA857
NEXT: FF906F
1: FF6897
2: FF9867
3: FFB04F
4: FF30CF
5: FF18E7
6: FF7A85
7: FF10EF
8: FF38C7
9: FF5AA5
PICK SONG: FF42BD
CH SET: FF52AD
*/
#include <IRremote.h>
#include <Wire.h>
#include <LiquidCrystal.h>
LiquidCrystal lcd(12, 11, 10, 9, 8, 7);
int RECV_PIN = 14;
IRrecv irrecv(RECV_PIN);
decode_results results;
byte second, minute, hour, dayOfWeek, dayOfMonth, month, year; // Values to read from DS3231 RTC Module
byte alarmHour = 5;
byte alarmMinute = 0;
bool alarmOn = true;
bool alarmActive = false;
long lastTimeReading = 0;
const int backlightLCD = 2;
const int btnAlarmHour = 3;
const int btnAlarmMinute = 4;
const int btnAlarmToggle = 5;
const int ledMosfet = 6;
long alarmTurnedOnAt = 0;
long alarmDuration = 10800000; //3 hours.
long alarmStepTime = 0;
long pushedButtonAt = 0;
long backlightDuration = 10000;
bool backlightOnForButton = false;
int brightness = 0;
int brightnessStep = 51;
int smallBrightnessStep = 10;
bool lightOn = false;
// Variables for debouncing the buttons
int stateBtnAlarmHour = 0;
int stateBtnAlarmMinute = 0;
int stateBtnAlarmToggle = 0;
int lastStateBtnAlarmHour = 0;
int lastStateBtnAlarmMinute = 0;
int lastStateBtnAlarmToggle = 0;
int readingBtnAlarmHour = 0;
int readingBtnAlarmMinute = 0;
int readingBtnAlarmToggle = 0;
long lastDebounceTimeBtnAlarmHour = 0;
long lastDebounceTimeBtnAlarmMinute = 0;
long lastDebounceTimeBtnAlarmToggle = 0;
const long debounceDelay = 50;
#define DS3231_I2C_ADDRESS 0x68
// Convert normal decimal numbers to binary coded decimal
byte decToBcd(byte val)
{
return((val / 10 * 16) + (val % 10));
}
// Convert binary coded decimal to normal decimal numbers
byte bcdToDec(byte val)
{
return((val / 16 * 10) + (val % 16));
}
//Defining a special character to use as brightness icon
byte sunCharacter[8] = {
0b00000,
0b00100,
0b10101,
0b01110,
0b11011,
0b01110,
0b10101,
0b00100
};
void setup()
{
Wire.begin();
irrecv.enableIRIn();
Serial.begin(9600);
pinMode(backlightLCD, OUTPUT);
pinMode(ledMosfet, OUTPUT);
pinMode(btnAlarmHour, INPUT);
pinMode(btnAlarmMinute, INPUT);
pinMode(btnAlarmToggle, INPUT);
lcd.createChar(0, sunCharacter);
lcd.begin(16, 2);
/* set the initial time here:
DS3231 seconds, minutes, hours, day(1 for sunday, 2 for monday...), date, month, year
Set the time by uncommenting the following line after editing the values and load the sketch on your arduino. Right after that, comment out the line and load the sketch again. */
// setDS3231time(00,59,23,1,31,12,16);
}
void loop()
{
ListenForButtonPress();
if (millis() - lastTimeReading > 1000) //Once every second
{
ReadTime();
DisplayTimeAndDateOnSerialMonitor();
RefreshLCD();
if (alarmOn)
{
if (second == 0)
{
CheckAlarm();
}
}
lastTimeReading = millis();
}
if (alarmActive)
{
if (millis() - alarmTurnedOnAt < alarmDuration) //For the duration of alarm
{
digitalWrite(backlightLCD, HIGH);
if (millis() - alarmStepTime > 7000) //Once in seven seconds, will reach full brightness at 30 minutes
{
ChangeBrightness(1);
alarmStepTime = millis();
}
}
else //Once at the end of alarm duration
{
brightness = 0;
SetBrightness(brightness);
alarmActive = false;
digitalWrite(backlightLCD, LOW);
}
}
if (backlightOnForButton)
{
if (millis() - pushedButtonAt < backlightDuration) //For the backlight duration
{
digitalWrite(backlightLCD, HIGH);
}
else //Once at the end of backlight duration
{
digitalWrite(backlightLCD, LOW);
backlightOnForButton = false;
}
}
if (irrecv.decode(&results)) { //If a button is pressed on the IR remote
if (results.value == 0xFFA25D)
{
LightOn();
PushedAnyButton();
}
if (results.value == 0xFF22DD)
{
LightOff();
PushedAnyButton();
}
if (results.value == 0xFFE21D)
{
ChangeBrightness(brightnessStep);
PushedAnyButton();
}
if (results.value == 0xFF629D)
{
ChangeBrightness(-brightnessStep);
PushedAnyButton();
}
if (results.value == 0xFFC23D)
{
ChangeBrightness(smallBrightnessStep);
PushedAnyButton();
}
if (results.value == 0xFF02FD)
{
ChangeBrightness(-smallBrightnessStep);
PushedAnyButton();
}
if (results.value == 0xFF52AD)
{
ChangeBrightness(-1);
PushedAnyButton();
}
if (results.value == 0xFF5AA5)
{
ChangeBrightness(1);
PushedAnyButton();
}
if (results.value == 0xFF6897)
{
if (backlightOnForButton)
{
IncreaseAlarmHour();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
if (results.value == 0xFF9867)
{
if (backlightOnForButton)
{
IncreaseAlarmMinute();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
if (results.value == 0xFFB04F)
{
if (backlightOnForButton)
{
ToggleAlarm();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
irrecv.resume();
}
//delay(100);
}
void ListenForButtonPress() //https://www.arduino.cc/en/Tutorial/Debounce
{
readingBtnAlarmHour = digitalRead(btnAlarmHour);
readingBtnAlarmMinute = digitalRead(btnAlarmMinute);
readingBtnAlarmToggle = digitalRead(btnAlarmToggle);
if (readingBtnAlarmHour != lastStateBtnAlarmHour)
{
lastDebounceTimeBtnAlarmHour = millis();
}
if (readingBtnAlarmMinute != lastStateBtnAlarmMinute)
{
lastDebounceTimeBtnAlarmMinute = millis();
}
if (readingBtnAlarmToggle != lastStateBtnAlarmToggle)
{
lastDebounceTimeBtnAlarmToggle = millis();
}
if (millis() - lastDebounceTimeBtnAlarmHour > debounceDelay)
{
if (readingBtnAlarmHour != stateBtnAlarmHour)
{
stateBtnAlarmHour = readingBtnAlarmHour;
if (stateBtnAlarmHour == LOW)
{
if (backlightOnForButton)
{
IncreaseAlarmHour();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
}
}
if (millis() - lastDebounceTimeBtnAlarmMinute > debounceDelay)
{
if (readingBtnAlarmMinute != stateBtnAlarmMinute)
{
stateBtnAlarmMinute = readingBtnAlarmMinute;
if (stateBtnAlarmMinute == LOW)
{
if (backlightOnForButton)
{
IncreaseAlarmMinute();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
}
}
if (millis() - lastDebounceTimeBtnAlarmToggle > debounceDelay)
{
if (readingBtnAlarmToggle != stateBtnAlarmToggle)
{
stateBtnAlarmToggle = readingBtnAlarmToggle;
if (stateBtnAlarmToggle == LOW)
{
if (backlightOnForButton)
{
ToggleAlarm();
PushedAnyButton();
}
else
{
PushedAnyButton();
}
}
}
}
lastStateBtnAlarmHour = readingBtnAlarmHour;
lastStateBtnAlarmMinute = readingBtnAlarmMinute;
lastStateBtnAlarmToggle = readingBtnAlarmToggle;
}
void ReadTime()
{
// retrieve data from DS3231
readDS3231time(&second, &minute, &hour, &dayOfWeek, &dayOfMonth, &month, &year);
}
void DisplayTimeAndDateOnSerialMonitor()
{
Serial.print(hour, DEC);
Serial.print(":");
if (minute < 10)
{
Serial.print("0");
}
Serial.print(minute, DEC);
Serial.print(":");
if (second < 10)
{
Serial.print("0");
}
Serial.print(second, DEC);
Serial.print(" ");
Serial.print(dayOfMonth, DEC);
Serial.print("/");
Serial.print(month, DEC);
Serial.print("/");
Serial.print(year, DEC);
Serial.print(" Day of week: ");
switch (dayOfWeek) {
case 1:
Serial.println("Sunday");
break;
case 2:
Serial.println("Monday");
break;
case 3:
Serial.println("Tuesday");
break;
case 4:
Serial.println("Wednesday");
break;
case 5:
Serial.println("Thursday");
break;
case 6:
Serial.println("Friday");
break;
case 7:
Serial.println("Saturday");
break;
}
}
void RefreshLCD()
{
lcd.clear();
PrintOnLCD(hour);
lcd.print(":");
PrintOnLCD(minute);
lcd.print(":");
PrintOnLCD(second);
lcd.print(" ");
if (alarmActive)
{
lcd.print("!");
}
else
{
lcd.print(" ");
}
lcd.write(byte(0));
lcd.print(brightness);
lcd.setCursor(0, 1);
lcd.print("Alarm:");
PrintOnLCD(alarmHour);
lcd.print(":");
PrintOnLCD(alarmMinute);
if (alarmOn)
{
lcd.print(" (on)");
}
else
{
lcd.print("(off)");
}
}
void PrintOnLCD(byte value)
{
if (value < 10)
{
lcd.print(0);
}
lcd.print(value);
}
void CheckAlarm()
{
if (hour == alarmHour)
{
if (minute == alarmMinute)
{
Alarm();
}
}
}
void Alarm()
{
alarmActive = true;
alarmTurnedOnAt = millis();
alarmStepTime = millis();
}
void IncreaseAlarmHour()
{
if (alarmHour == 23)
{
alarmHour = 0;
}
else
{
alarmHour++;
}
RefreshLCD();
}
void IncreaseAlarmMinute()
{
if (alarmMinute == 59)
{
alarmMinute = 0;
}
else
{
alarmMinute++;
}
RefreshLCD();
}
void ToggleAlarm()
{
alarmOn = !alarmOn;
RefreshLCD();
}
void BacklightForButtonPress()
{
backlightOnForButton = true;
pushedButtonAt = millis();
}
void ChangeBrightness(int step) {
brightness += step;
if (brightness > 255)
{
brightness = 255;
}
if (brightness < 0)
{
brightness = 0;
}
SetBrightness(brightness);
}
void SetBrightness(int brightnessValue)
{
analogWrite(ledMosfet, brightnessValue);
if (brightnessValue == 0)
{
lightOn = false;
}
else
{
lightOn = true;
}
}
void LightOn() {
if (brightness != 255)
{
brightness = 255;
SetBrightness(brightness);
}
else
{
return;
}
}
void LightOff() {
if (brightness != 0)
{
brightness = 0;
SetBrightness(brightness);
}
else
{
return;
}
}
void PushedAnyButton()
{
BacklightForButtonPress();
if (alarmActive)
{
alarmActive = false;
brightness = 0;
SetBrightness(brightness);
}
}
void setDS3231time(byte second, byte minute, byte hour, byte dayOfWeek, byte
dayOfMonth, byte month, byte year)
{
// sets time and date data to DS3231
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set next input to start at the seconds register
Wire.write(decToBcd(second)); // set seconds
Wire.write(decToBcd(minute)); // set minutes
Wire.write(decToBcd(hour)); // set hours
Wire.write(decToBcd(dayOfWeek)); // set day of week (1=Sunday, 7=Saturday)
Wire.write(decToBcd(dayOfMonth)); // set date (1 to 31)
Wire.write(decToBcd(month)); // set month
Wire.write(decToBcd(year)); // set year (0 to 99)
Wire.endTransmission();
}
void readDS3231time(byte *second,
byte *minute,
byte *hour,
byte *dayOfWeek,
byte *dayOfMonth,
byte *month,
byte *year)
{
Wire.beginTransmission(DS3231_I2C_ADDRESS);
Wire.write(0); // set DS3231 register pointer to 00h
Wire.endTransmission();
Wire.requestFrom(DS3231_I2C_ADDRESS, 7);
// request seven bytes of data from DS3231 starting from register 00h
*second = bcdToDec(Wire.read() & 0x7f);
*minute = bcdToDec(Wire.read());
*hour = bcdToDec(Wire.read() & 0x3f);
*dayOfWeek = bcdToDec(Wire.read());
*dayOfMonth = bcdToDec(Wire.read());
*month = bcdToDec(Wire.read());
*year = bcdToDec(Wire.read());
}
|
// Created on: 1993-02-24
// Created by: Laurent PAINNOT
// Copyright (c) 1993-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 _AppParCurves_ConstraintCouple_HeaderFile
#define _AppParCurves_ConstraintCouple_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <AppParCurves_Constraint.hxx>
//! associates an index and a constraint for an object.
//! This couple is used by AppDef_TheVariational when performing approximations.
class AppParCurves_ConstraintCouple
{
public:
DEFINE_STANDARD_ALLOC
//! returns an indefinite ConstraintCouple.
Standard_EXPORT AppParCurves_ConstraintCouple();
//! Create a couple the object <Index> will have the
//! constraint <Cons>.
Standard_EXPORT AppParCurves_ConstraintCouple(const Standard_Integer TheIndex, const AppParCurves_Constraint Cons);
//! returns the index of the constraint object.
Standard_EXPORT Standard_Integer Index() const;
//! returns the constraint of the object.
Standard_EXPORT AppParCurves_Constraint Constraint() const;
//! Changes the index of the constraint object.
Standard_EXPORT void SetIndex (const Standard_Integer TheIndex);
//! Changes the constraint of the object.
Standard_EXPORT void SetConstraint (const AppParCurves_Constraint Cons);
protected:
private:
Standard_Integer myIndex;
AppParCurves_Constraint myConstraint;
};
#endif // _AppParCurves_ConstraintCouple_HeaderFile
|
/****************************************************************************
* *
* Author : lukasz.iwaszkiewicz@gmail.com *
* ~~~~~~~~ *
* License : see COPYING file for details. *
* ~~~~~~~~~ *
****************************************************************************/
#ifndef BAJKA_MODEDL_CIRCLE_STATIC_H_
#define BAJKA_MODEDL_CIRCLE_STATIC_H_
#include "../AbstractModel.h"
namespace Model {
class Circle : public AbstractModel {
public:
C__ (void)
b_ ("AbstractModel")
Circle () : radius (0), origin (Geometry::ZERO_POINT) {}
virtual ~Circle () {}
/*--------------------------------------------------------------------------*/
Geometry::Point computeCenter () const;
virtual Geometry::Point getOrigin () const { return origin; }
m_ (setOrigin) virtual void setOrigin (Geometry::Point const &p) { origin = p; }
virtual double getRadius () const { return radius; }
m_ (setRadius) virtual void setRadius (double r) { radius = r; }
/*--------------------------------------------------------------------------*/
virtual Geometry::Box getBoundingBoxImpl (Geometry::AffineMatrix const &transformation) const;
virtual bool contains (Geometry::Point const &p) const;
protected:
double radius;
Geometry::Point origin;
E_ (Circle)
};
} /* namespace Model */
# endif /* BOXB_H_ */
|
#include "GameSeaquence.h"
#include "GameSeaquenceController.h"
//派生クラスの挙動に任せる
Boot* GameSeaquence::Update(Boot* p){
GameSeaquenceController* controller = dynamic_cast<GameSeaquenceController*>(p);
return Update(controller);
}
GameSeaquence::~GameSeaquence()
{
}
|
#ifndef STACK
#define STACK
#include "Vector.hpp"
class Stack : private Vector {
public:
Stack();
Stack(const int, const int);
Stack(const Stack&);
Stack(Stack&&);
void push1(const int);
void pop1();
void printStack() const;
};
#endif
|
#ifndef MUSICCONFIG_H
#define MUSICCONFIG_H
#include <QDialog>
#include <QSlider>
#include <QPushButton>
namespace Ui {
class MusicConfig;
}
class MusicConfig : public QDialog
{
Q_OBJECT
public:
explicit MusicConfig(int bgMusicVolume,int jumpMusicVolume,int launchMusicVlume,
int successMusicVolume, int gameOverMusicVolume, QWidget *parent = nullptr);
~MusicConfig();
QSlider* getBGMusicSlider() const;
QSlider* getJumpMusicSlider() const;
QSlider* getLaunchMusicSlider() const;
QSlider* getSuccessMusicSlider() const;
QSlider* getGameOverMusicSlider() const;
QPushButton* getJumpMusicButton() const;
QPushButton* getLaunchMusicButton() const;
QPushButton* getSuccessMusicButton() const;
QPushButton* getGameOverMusicButton() const;
private:
Ui::MusicConfig *ui;
};
#endif // MUSICCONFIG_H
|
#include "stdafx.h"
#include "Callsign.h"
#include "StringUtils.h"
#include "Qso.h"
Callsign::Callsign(Qso *qso)
:
QsoItem(qso),
m_callsign(),
m_prefix(),
m_suffix(),
m_isCanada(false),
m_isUSA(false)
{
}
Callsign::Callsign(const Callsign& c)
:
QsoItem(c),
m_callsign(c.m_callsign),
m_prefix(c.m_prefix),
m_suffix(c.m_suffix),
m_isCanada(c.m_isCanada),
m_isUSA(c.m_isUSA)
{
}
Callsign::~Callsign()
{
}
void Callsign::Copy(const Callsign& source)
{
QsoItem::Copy(source);
m_callsign = source.m_callsign;
m_prefix = source.m_prefix;
m_suffix = source.m_suffix;
m_isCanada = source.m_isCanada;
m_isUSA = source.m_isUSA;
}
bool Callsign::ProcessToken(const string& token, Qso* qso)
{
bool status = QsoItem::ProcessToken(token, qso);
if (!status)
return false;
if (token.empty())
{
printf("Callsign::ProcessToken - empty token\n");
return false;
}
auto pos = token.find('.');
if (pos != string::npos)
{
printf("Callsign Error: Bad Character in Callsign %s\n", token.c_str());
}
pos = token.find('/');
if (pos == string::npos)
{
m_callsign = token;
DetermineCountry();
return true;
}
string t1 = token.substr(0, pos);
string t2 = token.substr(pos + 1, token.length() - pos);
if (t1.length() == t2.length())
{
int i = StringUtils::GetFirstDigit(t1);
int j = StringUtils::GetFirstDigit(t2);
if (i >= 0)
{
m_callsign = t1;
m_suffix = t2;
}
else
{
m_suffix = t1;
m_callsign = t2;
}
}
else if (t1.length() > t2.length())
{
m_callsign = t1;
m_suffix = t2;
}
else
{
m_prefix = t1;
m_callsign = t2;
}
DetermineCountry();
return true;
}
void Callsign::DetermineCountry()
{
if (m_callsign.empty())
return;
string lowerCallsign(m_callsign);
StringUtils::ToLower(lowerCallsign);
char c = lowerCallsign.at(0);
if (c == 'a' || c == 'k' || c == 'n' || c == 'w')
{
m_isUSA = true;
return;
}
string prefix2 = lowerCallsign.substr(0, 2);
if (prefix2 == "va" || prefix2 == "ve" || prefix2 == "cf")
{
m_isCanada = true;
}
// if we get here, the callsign is not Canada or USA so the Dx function will return true
}
|
/*
** EPITECH PROJECT, 2018
** main
** File description:
** main
*/
#include "Manager.hpp"
int test_hud();
int main(int ac, char **av)
{
try {
if (ac == 3) {
auto man = std::make_shared<Manager>();
if (man->init(av[1], atoi(av[2]))) {
man->spectateGame();
}
} else if (ac == 1) {
auto man = std::make_shared<Manager>();
man->init();
if (!man->needToExit()) {
man->spectateGame();
}
}
} catch (std::exception &e) {
std::cerr << e.what() << std::endl;
return (84);
}
return (0);
}
|
#include "CCDirector.h"
#include "GreeJniHelper.h"
#include <jni.h>
#include "jni/Java_org_cocos2dx_lib_Cocos2dxGreePlatform.h"
using namespace cocos2d;
using namespace cocos2d::gree_extension;
extern "C" {
void loadCodeJni(){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "loadCode", "(Lnet/gree/asdk/api/FriendCode$CodeListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeCodeListener", "<init>", "(I)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (int)fTypeLoadCode);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
bool requestCodeJni(const char *expireTime){
bool ret = false;
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "requestCode", "(Ljava/lang/String;Lnet/gree/asdk/api/FriendCode$CodeListener;)Z")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeCodeListener", "<init>", "(I)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (int)fTypeRequestCode);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return ret;
}
jstring jStr;
if(!expireTime){
jStr = t.env->NewStringUTF("");
}else{
jStr = t.env->NewStringUTF(expireTime);
}
ret = t.env->CallStaticBooleanMethod(t.classID, t.methodID, jStr, listener);
l.env->DeleteLocalRef(l.classID);
t.env->DeleteLocalRef(jStr);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
void deleteCodeJni(){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "deleteCode", "(Lnet/gree/asdk/api/FriendCode$SuccessListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeFriendCodeSuccessListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)0, (int)fTypeDeleteCode);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
void verifyCodeJni(const char* code){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "verifyCode", "(Ljava/lang/String;Lnet/gree/asdk/api/FriendCode$SuccessListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeFriendCodeSuccessListener", "<init>", "(JI)V")){
jobject listener = l.env->NewObject(l.classID, l.methodID, (unsigned long long)0, (int)fTypeVerifyCode);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
jstring jStr;
if(!code){
jStr = t.env->NewStringUTF("");
}else{
jStr = t.env->NewStringUTF(code);
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, jStr, listener);
l.env->DeleteLocalRef(l.classID);
t.env->DeleteLocalRef(jStr);
}
t.env->DeleteLocalRef(t.classID);
}
}
void loadFriendIdsJni(int startIndex, int count){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "loadFriends", "(IILnet/gree/asdk/api/FriendCode$EntryListGetListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeEntryListGetListener", "<init>", "()V")){
jobject listener = l.env->NewObject(l.classID, l.methodID);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, startIndex, count, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
void loadOwnerJni(){
JniMethodInfo t;
if(JniHelper::getStaticMethodInfo(t, "net/gree/asdk/api/FriendCode", "loadOwner", "(Lnet/gree/asdk/api/FriendCode$OwnerGetListener;)V")){
JniMethodInfo l;
if(JniHelper::getMethodInfo(l, "org/cocos2dx/lib/gree/NativeOwnerGetListener", "<init>", "()V")){
jobject listener = l.env->NewObject(l.classID, l.methodID);
if(listener == NULL){
CCLog("Cannot create new listener object in %s", __func__);
return;
}
t.env->CallStaticVoidMethod(t.classID, t.methodID, listener);
l.env->DeleteLocalRef(l.classID);
}
t.env->DeleteLocalRef(t.classID);
}
}
std::string getCodeJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getCode", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getExpireTimeJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getExpireTime", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
std::string getUserIdFromGreeDataJni(jobject obj){
JniMethodInfo t;
std::string ret;
if(GreeJniHelper::getInstanceMethodInfo(t, obj, "getUserId", "()Ljava/lang/String;")){
jstring jstr = (jstring)t.env->CallObjectMethod(obj, t.methodID);
const char* str = NULL;
if(jstr != NULL){
str = t.env->GetStringUTFChars(jstr, 0);
ret = str;
t.env->ReleaseStringUTFChars(jstr, str);
}
t.env->DeleteLocalRef(t.classID);
}
return ret;
}
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
*
* Copyright (C) 1995-2011 Opera Software AS. All rights reserved.
*
* This file is part of the Opera web browser. It may not be distributed
* under any circumstances.
*
* @author Arjan van Leeuwen (arjanl)
*/
#include "core/pch.h"
#include "adjunct/desktop_util/filelogger/desktopfilelogger.h"
#include "adjunct/quick/managers/ManagerHolder.h"
#include "adjunct/quick/managers/DesktopManager.h"
// include managers here
#include "adjunct/quick/hotlist/HotlistManager.h"
#include "adjunct/quick/managers/AnimationManager.h"
#include "adjunct/quick/managers/AutoUpdateManager.h"
#include "adjunct/quick/managers/DesktopClipboardManager.h"
#include "adjunct/quick/managers/DesktopCookieManager.h"
#include "adjunct/quick/managers/DesktopBookmarkManager.h"
#include "adjunct/quick/managers/DesktopExtensionsManager.h"
#include "adjunct/quick/managers/DesktopGadgetManager.h"
#include "adjunct/quick/managers/DesktopSecurityManager.h"
#include "adjunct/quick/managers/DesktopTransferManager.h"
#include "adjunct/quick/managers/FavIconManager.h"
#include "adjunct/quick/managers/FeatureManager.h"
#include "adjunct/quick/managers/MailManager.h"
#include "adjunct/quick/managers/MessageConsoleManager.h"
#include "adjunct/quick/managers/MouseGestureUI.h"
#include "adjunct/quick/managers/NotificationManager.h"
#include "adjunct/quick/managers/OperaAccountManager.h"
#include "adjunct/quick/managers/opsetupmanager.h"
#include "adjunct/quick/managers/SecurityUIManager.h"
#include "adjunct/quick/managers/SpeedDialManager.h"
#include "adjunct/quick/managers/SyncManager.h"
#include "adjunct/quick/managers/WebmailManager.h"
#include "adjunct/quick/managers/WebServerManager.h"
#include "adjunct/quick/managers/OperaTurboManager.h"
#include "adjunct/quick/models/DesktopHistoryModel.h"
#include "adjunct/desktop_util/sessions/SessionAutoSaveManager.h"
#include "adjunct/quick/managers/DownloadManagerManager.h"
#include "adjunct/quick/managers/ToolbarManager.h"
#include "adjunct/quick/managers/TipsManager.h"
#ifdef PLUGIN_AUTO_INSTALL
#include "adjunct/quick/managers/PluginInstallManager.h"
#endif // PLUGIN_AUTO_INSTALL
#include "adjunct/quick/managers/RedirectionManager.h"
// This is where the manager type constants are mapped to C++ types.
//
// List all the managers here in any order. The order and dependencies
// are defined in the ManagerType enum, and are handled later on in
// InitManagers(INT32).
ManagerHolder::ManagerDescr ManagerHolder::s_manager_descrs[] = {
#ifdef AUTO_UPDATE_SUPPORT
CreateManagerDescr<AutoUpdateManager>(TYPE_AUTO_UPDATE, "Autoupdate"),
#endif
CreateManagerDescr<DesktopCookieManager>(TYPE_COOKIE, "Cookie"),
CreateManagerDescr<DesktopBookmarkManager>(TYPE_BOOKMARK, "Bookmarks"),
#ifdef GADGET_SUPPORT
CreateManagerDescr<DesktopGadgetManager>(TYPE_GADGET, "Gadgets"),
#endif
CreateManagerDescr<DesktopHistoryModel>(TYPE_HISTORY, "History"),
CreateManagerDescr<DesktopSecurityManager>(TYPE_SECURITY, "Security"),
CreateManagerDescr<DesktopTransferManager>(TYPE_TRANSFER, "Transfers"),
CreateManagerDescr<FavIconManager>(TYPE_FAV_ICON, "Favicons"),
CreateManagerDescr<FeatureManager>(TYPE_FEATURE, "Feature"),
CreateManagerDescr<HotlistManager>(TYPE_HOTLIST, "Hotlist"),
#ifdef M2_SUPPORT
CreateManagerDescr<MailManager>(TYPE_MAIL, "Mail"),
#endif
#ifdef OPERA_CONSOLE
CreateManagerDescr<MessageConsoleManager>(TYPE_CONSOLE, "Console"),
#endif // OPERA_CONSOLE
CreateManagerDescr<NotificationManager>(TYPE_NOTIFICATION, "Notifications"),
CreateManagerDescr<OperaAccountManager>(TYPE_OPERA_ACCOUNT, "Account"),
#ifdef WEB_TURBO_MODE
CreateManagerDescr<OperaTurboManager>(TYPE_OPERA_TURBO, "Turbo"),
#endif
#ifdef VEGA_OPPAINTER_SUPPORT
CreateManagerDescr<QuickAnimationManager>(TYPE_QUICK_ANIMATION, "Animation"),
CreateManagerDescr<MouseGestureUI>(TYPE_MOUSE_GESTURE_UI, "Mouse Gesture UI"),
#endif
CreateManagerDescr<SecurityUIManager>(TYPE_SECURITY_UI, "Security UI"),
#ifdef SUPPORT_SPEED_DIAL
CreateManagerDescr<SpeedDialManager>(TYPE_SPEED_DIAL, "Speed Dial"),
#endif
#ifdef SUPPORT_DATA_SYNC
CreateManagerDescr<SyncManager>(TYPE_SYNC, "Sync"),
#endif
CreateManagerDescr<WebmailManager>(TYPE_WEBMAIL, "Webmail"),
#ifdef WEBSERVER_SUPPORT
CreateManagerDescr<WebServerManager>(TYPE_WEB_SERVER, "Webserver"),
#endif
CreateManagerDescr<SessionAutoSaveManager>(TYPE_SESSION_AUTO_SAVE, "Session"),
CreateManagerDescr<DownloadManagerManager>(TYPE_EXTERNAL_DOWNLOAD_MANAGER, "External download"),
CreateManagerDescr<ToolbarManager>(TYPE_TOOLBAR, "Toolbar manager"),
CreateManagerDescr<DesktopExtensionsManager>(TYPE_EXTENSIONS, "Extensions"),
CreateManagerDescr<TipsManager>(TYPE_TIPS, "Tips Manager"),
#ifdef PLUGIN_AUTO_INSTALL
CreateManagerDescr<PluginInstallManager>(TYPE_PLUGIN_INSTALL, "Plugin install"),
#endif
CreateManagerDescr<RedirectionManager>(TYPE_REDIRECTION, "Redirection"),
CreateManagerDescr<DesktopClipboardManager>(TYPE_CLIPBOARD, "Clipboard")
};
int ManagerHolder::ManagerDescrLessThan(const void* lhs, const void* rhs)
{
return reinterpret_cast<const ManagerDescr*>(lhs)->type
- reinterpret_cast<const ManagerDescr*>(rhs)->type;
}
ManagerHolder::~ManagerHolder()
{
if (m_destroy_managers)
{
OP_PROFILE_METHOD("Destructed managers");
// Destroy in reverse order of when they were created
for (int i = ARRAY_SIZE(s_manager_descrs) - 1; i >= 0; --i)
(*s_manager_descrs[i].destroyer)();
}
{
// Commit all pref changed made by the managers on destruction
OP_PROFILE_METHOD("Committed prefs");
TRAPD(err, g_prefsManager->CommitL());
}
}
OP_STATUS ManagerHolder::InitManagers(INT32 type_mask)
{
op_qsort(s_manager_descrs, ARRAY_SIZE(s_manager_descrs),
sizeof(ManagerDescr), ManagerDescrLessThan);
for (size_t i = 0; i < ARRAY_SIZE(s_manager_descrs); ++i)
{
const ManagerDescr& descr = s_manager_descrs[i];
if (descr.type == (type_mask & descr.type))
{
OP_PROFILE_METHOD(descr.name);
GenericDesktopManager* manager = (*descr.creator)();
RETURN_OOM_IF_NULL(manager);
m_destroy_managers = true;
const OP_STATUS init_status = manager->Init();
OP_ASSERT(OpStatus::IsSuccess(init_status));
if (OpStatus::IsError(init_status))
{
char buf[256];
op_snprintf(buf, 256, "'%s' failed init: %d", descr.name, init_status);
#ifdef MSWIN
MessageBoxA(NULL, buf, "Opera", MB_OK | MB_ICONERROR);
#else
fputs("opera: ", stderr);
fputs(buf, stderr);
fputs("\n", stderr);
#endif
OP_PROFILE_MSG(buf);
}
RETURN_IF_ERROR(init_status);
}
}
return OpStatus::OK;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4 -*-
**
** Copyright (C) 1995-2012 Opera Software ASA. All rights reserved.
**
** This file is part of the Opera web browser. It may not be distributed
** under any circumstances.
*/
/**
On Compiling this file COMPILING_ENCODINGS_CHARCONV_TESTSUITE is
defined. On a windows or linux platform some system headers are
needed if FEATURE_SELFTEST is enabled.
On a WIN32 platform (i.e. WIN32 is defined), the header file
<windows.h> is included to use the functions ::VirtualAlloc()
and ::VirtualFree().
On a linux platform (i.e. linux is defined), the header file
<sys/mman.h> is included to use the function mprotect().
The platform's system.h might need to prepare for these system
header files to be included.
*/
#define COMPILING_ENCODINGS_CHARCONV_TESTSUITE
#include "core/pch_system_includes.h"
#if defined SELFTEST || defined ENCODINGS_REGTEST
#include "modules/encodings/testsuite/charconv/chartest.h"
#ifdef SELFTEST
// Input converters ------------------------------------------------------
#include "modules/encodings/decoders/inputconverter.h"
#include "modules/encodings/decoders/identityconverter.h"
#include "modules/encodings/decoders/iso-8859-1-decoder.h"
#include "modules/encodings/decoders/utf7-decoder.h"
#include "modules/encodings/decoders/utf8-decoder.h"
#include "modules/encodings/decoders/utf16-decoder.h"
#include "modules/encodings/decoders/big5-decoder.h"
#include "modules/encodings/decoders/big5hkscs-decoder.h"
#include "modules/encodings/decoders/euc-jp-decoder.h"
#include "modules/encodings/decoders/euc-kr-decoder.h"
#include "modules/encodings/decoders/euc-tw-decoder.h"
#include "modules/encodings/decoders/gbk-decoder.h"
#include "modules/encodings/decoders/hz-decoder.h"
#include "modules/encodings/decoders/iso-2022-cn-decoder.h"
#include "modules/encodings/decoders/iso-2022-jp-decoder.h"
#include "modules/encodings/decoders/sbcs-decoder.h"
#include "modules/encodings/decoders/sjis-decoder.h"
// Output converters -----------------------------------------------------
#include "modules/encodings/encoders/outputconverter.h"
#include "modules/encodings/encoders/utf7-encoder.h"
#include "modules/encodings/encoders/utf8-encoder.h"
#include "modules/encodings/encoders/utf16-encoder.h"
#include "modules/encodings/encoders/iso-8859-1-encoder.h"
#include "modules/encodings/encoders/big5hkscs-encoder.h"
#include "modules/encodings/encoders/dbcs-encoder.h"
#include "modules/encodings/encoders/euc-tw-encoder.h"
#include "modules/encodings/encoders/gb18030-encoder.h"
#include "modules/encodings/encoders/hz-encoder.h"
#include "modules/encodings/encoders/iso-2022-cn-encoder.h"
#include "modules/encodings/encoders/jis-encoder.h"
#include "modules/encodings/encoders/sbcs-encoder.h"
#endif // SELFTEST
#if defined WIN32
# ifdef ENCODINGS_REGTEST
# undef BOOL
# endif
# include <windows.h>
# ifdef ENCODINGS_REGTEST
# define BOOL bool
# endif
#endif // WIN32
#ifdef ENCODINGS_REGTEST
# include "tablemanager/tablemanager.h"
#endif
#if defined linux
# include <sys/mman.h>
#endif
#include "modules/encodings/testsuite/charconv/utility.h"
#ifdef OPMEMORY_VIRTUAL_MEMORY
# include "modules/pi/system/OpMemory.h"
#endif //OPMEMORY_VIRTUAL_MEMORY
#ifdef SELFTEST
# define encodings_buffer g_opera->encodings_module.buffer
# define encodings_bufferback g_opera->encodings_module.bufferback
#else
extern char *encodings_buffer, *encodings_bufferback;
#endif
int fliputf16endian(const void *src, void *dest, size_t bytes)
{
const char *input = reinterpret_cast<const char *>(src);
char *output = reinterpret_cast<char *>(dest);
encodings_check((bytes & 1) == 0);
while (bytes)
{
output[1] = *(input ++);
output[0] = *(input ++);
output += 2;
bytes -= 2;
}
return 1;
}
#ifdef SELFTEST
/** Factory for the test suite */
InputConverter *encodings_new_forward(const char *encoding)
{
InputConverter *out = NULL;
// Special handling for UTF-7
#ifdef ENCODINGS_HAVE_UTF7
# ifdef ENCODINGS_HAVE_UTF7IMAP
if (0 == op_strncmp(encoding, "utf-7-imap", 11))
{
out = OP_NEW(UTF7toUTF16Converter, (UTF7toUTF16Converter::IMAP));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
return out;
}
else
# endif // ENCODINGS_HAVE_UTF7IMAP
if (0 == op_strncmp(encoding, "utf-7-safe", 11))
{
out = OP_NEW(UTF7toUTF16Converter, (UTF7toUTF16Converter::STANDARD));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
return out;
}
else if (0 == op_strncmp(encoding, "utf-7", 6))
{
out = OP_NEW(UTF7toUTF16Converter, (UTF7toUTF16Converter::STANDARD));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
}
else
#endif // ENCODINGS_HAVE_UTF7
// For the rest, use the default factory
{
OP_STATUS rc = InputConverter::CreateCharConverter(encoding, &out);
if (OpStatus::IsError(rc))
{
TEST_FAILED(__FILE__, __LINE__, "Error received in encodings_new_forward");
}
}
if (out)
{
if (0 == op_strcmp(encoding, "iso-8859-1") || 0 == op_strcmp(encoding, "us-ascii"))
{
encodings_check(op_strcmp(out->GetCharacterSet(), encoding) == 0 || op_strcmp(out->GetCharacterSet(), "windows-1252") == 0);
}
else
{
encodings_check(op_strcmp(out->GetCharacterSet(), encoding) == 0);
}
encodings_check(op_strcmp(out->GetDestinationCharacterSet(), "utf-16") == 0);
return out;
}
TEST_FAILED(__FILE__, __LINE__, "Invalid encoding in encodings_new_forward");
return NULL;
}
OutputConverter *encodings_new_reverse(const char *encoding)
{
OutputConverter *out = NULL;
// Special handling for UTF-7
#ifdef ENCODINGS_HAVE_UTF7
if (0 == op_strncmp(encoding, "utf-7", 6))
{
out = OP_NEW(UTF16toUTF7Converter, (UTF16toUTF7Converter::STANDARD));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
}
else if (0 == op_strncmp(encoding, "utf-7-safe", 11))
{
out = OP_NEW(UTF16toUTF7Converter, (UTF16toUTF7Converter::SAFE));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
return out;
}
# ifdef ENCODINGS_HAVE_UTF7IMAP
else if (0 == op_strncmp(encoding, "utf-7-imap", 11))
{
out = OP_NEW(UTF16toUTF7Converter, (UTF16toUTF7Converter::IMAP));
if (out && OpStatus::IsError(out->Construct()))
{
OP_DELETE(out);
out = NULL;
}
return out;
}
# endif // ENCODINGS_HAVE_UTF7IMAP
else
#endif // ENCODINGS_HAVE_UTF7
{
OP_STATUS rc = OutputConverter::CreateCharConverter(encoding, &out, TRUE, TRUE);
if (OpStatus::IsError(rc))
{
TEST_FAILED(__FILE__, __LINE__, "Error received in encodings_new_reverse");
}
}
if (out)
{
if (0 == op_strcmp(encoding, "iso-8859-6") || 0 == op_strcmp(encoding, "iso-8859-8"))
{
encodings_check(op_strncmp(out->GetDestinationCharacterSet(), encoding, op_strlen(encoding)) == 0);
}
else
{
encodings_check(op_strcmp(out->GetDestinationCharacterSet(), encoding) == 0);
}
encodings_check(op_strcmp(out->GetCharacterSet(), "utf-16") == 0);
return out;
}
TEST_FAILED(__FILE__, __LINE__, "Invalid encoding in encodings_new_reverse");
return NULL;
}
#endif // SELFTEST
#ifdef HEXDUMP
void hexdump(const char *s, const void *_p, int n)
{
OUTPUT_STR("\n");
OUTPUT_STR(s);
OUTPUT_STR(": ");
const unsigned char *p = reinterpret_cast<const unsigned char *>(_p);
char o[4] = { 0, 0, ' ', 0 };
while (n --)
{
const unsigned char cur = *(p ++);
o[0] = (cur >> 4)["0123456789ABCDEF"];
o[1] = (cur & 15)["0123456789ABCDEF"];
OUTPUT_STR(o);
}
}
#endif // HEXDUMP
// Perform a test, converting in both directions
int encodings_perform_test(InputConverter *fw, OutputConverter *rev,
const void *input, int inputlen,
const void *expected, int expectedlen,
const void *expectback/* = NULL*/,
int expectbacklen/* = -1*/,
BOOL hasinvalid/* = FALSE*/,
const uni_char *invalids/* = NULL*/)
{
int read, written;
if (!expectback || expectbacklen < 0)
{
expectback = input;
expectbacklen = inputlen;
}
// Verify preconditions
encodings_check(fw && rev && input && inputlen > 0 && expected && expectedlen > 0 && expectback && expectbacklen > 0);
// Check forward conversion
written = fw->Convert(input, inputlen, encodings_buffer, ENC_TESTBUF_SIZE, &read);
#ifdef HEXDUMP
if (read != inputlen || written != expectedlen || op_memcmp(encodings_buffer, expected, expectedlen))
{
hexdump("input ", input, inputlen);
hexdump("expected", expected, expectedlen);
hexdump("output ", encodings_buffer, written);
}
#endif
encodings_check(read == inputlen);
encodings_check(written == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_HAVE_CHECK_ENDSTATE
encodings_check(fw->IsValidEndState());
#endif
// Check reverse conversion
written = rev->Convert(encodings_buffer, expectedlen, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
#ifdef HEXDUMP
if (read != expectedlen || written != expectbacklen || op_memcmp(encodings_bufferback, expectback, expectbacklen))
{
hexdump("expectback", expectback, expectbacklen);
hexdump("reverse ", encodings_bufferback, written);
}
#endif
encodings_check(read == expectedlen);
encodings_check(written == expectbacklen);
encodings_check(0 == op_memcmp(encodings_bufferback, expectback, expectbacklen));
if (hasinvalid) {
encodings_check(rev->GetNumberOfInvalid() > 0);
encodings_check(rev->GetFirstInvalidOffset() >= 0);
}
#ifdef ENCODINGS_HAVE_SPECIFY_INVALID
if (invalids) encodings_check(0 == op_memcmp(rev->GetInvalidCharacters(), invalids, uni_strlen(invalids) * sizeof (uni_char)));
#endif
OP_DELETE(fw);
OP_DELETE(rev);
return 1;
}
int encodings_perform_tests(const char *encoding,
const void *input, int inputlen,
const void *expected, int expectedlen,
const void *expectback/* = NULL*/,
int expectbacklen/* = -1*/,
BOOL hasinvalid/* = FALSE*/,
BOOL mayvary/* = FALSE*/,
const uni_char *invalids/* = NULL*/)
{
int read, read2, written;
const unsigned char *inp = reinterpret_cast<const unsigned char *>(input);
const unsigned char *exp = reinterpret_cast<const unsigned char *>(expected);
bool is_utf = !op_strcmp(encoding, "utf-32") || !op_strcmp(encoding, "utf-16");
if (!expectback || expectbacklen < 0)
{
expectback = input;
expectbacklen = inputlen;
}
// Verify preconditions
encodings_check(encoding && input && inputlen > 0 && expected && expectedlen > 0 && expectback && expectbacklen > 0);
// Create first encoder and decoder and check that encoding tags are
// correct.
InputConverter *fw1 = encodings_new_forward(encoding);
encodings_check(fw1 != NULL);
if (op_strncmp(fw1->GetCharacterSet(), encoding, op_strlen(fw1->GetCharacterSet())))
{
if (op_strcmp(encoding, "us-ascii") != 0 && op_strcmp(encoding, "iso-8859-1") != 0)
{
TEST_FAILED(__FILE__, __LINE__, "Asked for \"%s\" got \"%s\"", encoding, fw1->GetCharacterSet());
return 0;
}
}
encodings_check(0 == op_strcmp(fw1->GetDestinationCharacterSet(), "utf-16"));
OutputConverter *rev1 = encodings_new_reverse(encoding);
encodings_check(rev1 != NULL);
encodings_check(0 == op_strcmp(rev1->GetCharacterSet(), "utf-16"));
if (op_strncmp(rev1->GetDestinationCharacterSet(), encoding, op_strlen(rev1->GetDestinationCharacterSet())))
{
if (0 != op_strncmp(encoding, fw1->GetCharacterSet(), op_strlen(encoding) &&
0 != op_strcmp(fw1->GetCharacterSet() + op_strlen(encoding), "-i")))
{
encodings_check(0 == op_strncmp(rev1->GetDestinationCharacterSet(), encoding, op_strlen(rev1->GetDestinationCharacterSet())));
}
}
// Standard test
encodings_perform_test(fw1, rev1, input, inputlen,
expected, expectedlen, expectback, expectbacklen,
hasinvalid);
// Try to provoke a bus error
char *expectback_buserror = 0;
#ifdef SELFTEST
# define encodings_check_buserror(what) \
do { \
if (!(what)) { \
TEST_FAILED(__FILE__, __LINE__, "Condition failed: " #what); \
OP_DELETEA(input_buserror); \
OP_DELETEA(expected_buserror); \
OP_DELETEA(expectback_buserror); \
return 0; \
} \
} while(0)
#else
# define encodings_check_buserror(what) assert(what)
#endif
char *input_buserror = OP_NEWA(char, inputlen + 1);
encodings_check(input_buserror != NULL);
char *expected_buserror = OP_NEWA(char, expectedlen + 1);
encodings_check_buserror(expected_buserror != NULL);
expectback_buserror = OP_NEWA(char, expectbacklen + 1);
encodings_check_buserror(expectback_buserror != NULL);
op_memcpy(input_buserror + 1, input, inputlen);
op_memcpy(expected_buserror + 1, expected, expectedlen);
op_memcpy(expectback_buserror + 1, expectback, expectbacklen);
InputConverter *fw2 = encodings_new_forward(encoding);
encodings_check_buserror(fw2 != NULL);
OutputConverter *rev2 = encodings_new_reverse(encoding);
encodings_check_buserror(rev2 != NULL);
encodings_perform_test(fw2, rev2,
input_buserror + 1, inputlen,
expected_buserror + 1, expectedlen,
expectback_buserror + 1, expectbacklen,
hasinvalid);
OP_DELETEA(input_buserror);
OP_DELETEA(expected_buserror);
OP_DELETEA(expectback_buserror);
// Split boundary tests
// 1. Not entire input on first go
// a) forward conversion
for (int i = 1; i < inputlen; i ++)
{
InputConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
written = fw->Convert(input, i, encodings_buffer, ENC_TESTBUF_SIZE, &read);
encodings_check(read <= i);
encodings_check(written <= expectedlen);
if (read < i && !is_utf)
{
OUTPUT(__FILE__, __LINE__, 1, "Not all data read: %d < %d", read, i);
}
written += fw->Convert(&inp[read], inputlen - read, &encodings_buffer[written], ENC_TESTBUF_SIZE - written, &read2);
encodings_check(read + read2 == inputlen);
encodings_check(written == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_HAVE_CHECK_ENDSTATE
encodings_check(fw->IsValidEndState());
#endif
OP_DELETE(fw);
}
BOOL debug = FALSE;
// b) reverse conversion
for (int j = 1; j < expectedlen; j ++)
{
OutputConverter *rev = encodings_new_reverse(encoding);
encodings_check(rev != NULL);
written = rev->Convert(expected, j, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
encodings_check(read <= j);
encodings_check(written <= expectbacklen);
if (read < j && !(j & 1) && !is_utf)
{
OUTPUT(__FILE__, __LINE__, 1, "Not all data read: %d < %d", read, j);
}
written += rev->Convert(&exp[read], expectedlen - read, &encodings_bufferback[written], ENC_TESTBUF_SIZE - written, &read2);
encodings_check(read + read2 == expectedlen);
if (mayvary)
{
encodings_check(written >= expectbacklen);
if (written > expectbacklen || op_memcmp(encodings_bufferback, expectback, expectbacklen) != 0)
{
// If output is different, make sure it still converts to
// the same Unicode stream
CharConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
int written2 = fw->Convert(encodings_bufferback, written, encodings_buffer, ENC_TESTBUF_SIZE, &read2);
encodings_check(read2 == written);
encodings_check(written2 == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_REGTEST
output1(NULL, 0, " ... accepting \"%s\"\n", reinterpret_cast<char *>(encodings_bufferback));
#endif
debug = TRUE;
OP_DELETE(fw);
}
}
else
{
#ifdef HEXDUMP
if (written != expectbacklen)
{
hexdump("output", encodings_bufferback, written);
hexdump("expect", expectback, expectbacklen);
}
#endif
encodings_check(written == expectbacklen);
encodings_check(0 == op_memcmp(encodings_bufferback, expectback, expectbacklen));
}
if (hasinvalid) {
encodings_check(rev->GetNumberOfInvalid() > 0);
encodings_check(rev->GetFirstInvalidOffset() >= 0);
}
#ifdef ENCODINGS_HAVE_SPECIFY_INVALID
if (invalids) encodings_check(0 == op_memcmp(rev->GetInvalidCharacters(), invalids, uni_strlen(invalids) * sizeof (uni_char)));
#endif
OP_DELETE(rev);
}
// 2. Not enough space on first go
// a) forward conversion
for (int k = 1; k < expectedlen; k ++)
{
InputConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
written = fw->Convert(input, inputlen, encodings_buffer, k, &read);
encodings_check(read <= inputlen);
encodings_check(written <= k);
written += fw->Convert(&inp[read], inputlen - read, &encodings_buffer[written], ENC_TESTBUF_SIZE - written, &read2);
encodings_check(read + read2 == inputlen);
encodings_check(written == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_HAVE_CHECK_ENDSTATE
encodings_check(fw->IsValidEndState());
#endif
OP_DELETE(fw);
}
// b) reverse conversion
for (int l = 1; l < expectbacklen; l ++)
{
OutputConverter *rev = encodings_new_reverse(encoding);
encodings_check(rev != NULL);
written = rev->Convert(expected, expectedlen, encodings_bufferback, l, &read);
encodings_check(read <= expectedlen);
encodings_check(written <= l);
written += rev->Convert(&exp[read], expectedlen - read, &encodings_bufferback[written], ENC_TESTBUF_SIZE - written, &read2);
encodings_check(read + read2 == expectedlen);
if (mayvary)
{
encodings_check(written >= expectbacklen);
if (written > expectbacklen || op_memcmp(encodings_bufferback, expectback, expectbacklen) != 0)
{
// If output is different, make sure it still converts to
// the same Unicode stream
CharConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
int written2 = fw->Convert(encodings_bufferback, written, encodings_buffer, ENC_TESTBUF_SIZE, &read2);
encodings_check(read2 == written);
encodings_check(written2 == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_REGTEST
output1(NULL, 0, " ... accepting \"%s\"\n", reinterpret_cast<char *>(encodings_bufferback));
#endif
debug = TRUE;
OP_DELETE(fw);
}
}
else
{
encodings_check(written == expectbacklen);
encodings_check(0 == op_memcmp(encodings_bufferback, expectback, expectbacklen));
}
if (hasinvalid) {
encodings_check(rev->GetNumberOfInvalid() > 0);
encodings_check(rev->GetFirstInvalidOffset() >= 0);
}
#ifdef ENCODINGS_HAVE_SPECIFY_INVALID
if (invalids) encodings_check(0 == op_memcmp(rev->GetInvalidCharacters(), invalids, uni_strlen(invalids) * sizeof (uni_char)));
#endif
OP_DELETE(rev);
}
// Test return to initial state functionality
if (op_strcmp(encoding, "utf-16"))
{
OutputConverter *rev = encodings_new_reverse(encoding);
encodings_check(rev != NULL);
written = 0;
read = 0;
int retlen;
int longest;
while (read < expectedlen)
{
longest = rev->LongestSelfContainedSequenceForCharacter();
encodings_check(rev->ReturnToInitialState(NULL) < longest);
written += retlen = rev->ReturnToInitialState(&encodings_bufferback[written]);
encodings_check(retlen <= longest);
written += rev->Convert(&exp[read], sizeof (uni_char), &encodings_bufferback[written], ENC_TESTBUF_SIZE - written, &read2);
read += read2;
encodings_check(read <= expectedlen);
}
longest = rev->LongestSelfContainedSequenceForCharacter();
written += retlen = rev->ReturnToInitialState(&encodings_bufferback[written]);
encodings_check(retlen <= longest);
OP_DELETE(rev);
if (mayvary)
{
encodings_check(written >= expectbacklen);
if (written > expectbacklen || op_memcmp(encodings_bufferback, expectback, expectbacklen) != 0)
{
// If output is different, make sure it still converts to
// the same Unicode stream
CharConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
int written2 = fw->Convert(encodings_bufferback, written, encodings_buffer, ENC_TESTBUF_SIZE, &read2);
encodings_check(read2 == written);
encodings_check(written2 == expectedlen);
encodings_check(0 == op_memcmp(encodings_buffer, expected, expectedlen));
#ifdef ENCODINGS_REGTEST
output1(NULL, 0, " ... accepting \"%s\"\n", reinterpret_cast<char *>(encodings_bufferback));
#endif
debug = TRUE;
OP_DELETE(fw);
}
}
else
{
encodings_check(written == expectbacklen);
encodings_check(0 == op_memcmp(encodings_bufferback, expectback, expectbacklen));
}
}
// Test reset functionality
for (int m = 1; m <= expectedlen; m ++)
{
// Convert a part (or all) of the buffer
OutputConverter *rev = encodings_new_reverse(encoding);
encodings_check(rev != NULL);
written = rev->Convert(expected, m, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
encodings_check(read <= m);
encodings_check(written <= expectbacklen);
// Reset and convert all of the buffer, this behave the same
// if the previous call didn't happen
rev->Reset();
written = rev->Convert(expected, expectedlen, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
encodings_check(read == expectedlen);
encodings_check(written == expectbacklen);
encodings_check(0 == op_memcmp(encodings_bufferback, expectback, expectbacklen));
if (hasinvalid) {
encodings_check(rev->GetNumberOfInvalid() > 0);
encodings_check(rev->GetFirstInvalidOffset() >= 0);
}
#ifdef ENCODINGS_HAVE_SPECIFY_INVALID
if (invalids) encodings_check(0 == op_memcmp(rev->GetInvalidCharacters(), invalids, uni_strlen(invalids) * sizeof (uni_char)));
#endif
OP_DELETE(rev);
}
if (debug)
{
#ifdef ENCODINGS_REGTEST
output1(NULL, 0, " ... (instead of \"%s\")\n", reinterpret_cast<const char *>(expectback));
#endif
}
// Buffer overrun tests
encodings_test_buffers(encoding, input, inputlen, expected, expectedlen, expectback, expectbacklen);
return 1;
}
int encodings_test_buffers(const char *encoding,
const void *input, int inputlen,
const void *expected, int expectedlen,
const void *expectback, int expectbacklen)
{
#if defined WIN32 || defined linux
// Allocate two consecutive memory pages, where the second is
// write-protected.
# ifdef WIN32
static const size_t page_size = 65536;
char *inptr = reinterpret_cast<char *>(::VirtualAlloc(NULL, page_size * 2, MEM_RESERVE, PAGE_NOACCESS));
::VirtualAlloc(inptr, page_size, MEM_COMMIT, PAGE_READWRITE);
char *outptr = reinterpret_cast<char *>(::VirtualAlloc(NULL, page_size * 2, MEM_RESERVE, PAGE_NOACCESS));
::VirtualAlloc(outptr, page_size, MEM_COMMIT, PAGE_READWRITE);
# elif defined linux
static const size_t page_size =
# ifdef OPMEMORY_VIRTUAL_MEMORY
OpMemory::GetPageSize();
# elif defined(PAGESIZE)
PAGESIZE;
# else
4096;
# endif
void *real_inptr = op_malloc(page_size * 3);
char *inptr =
reinterpret_cast<char *>((reinterpret_cast<UINTPTR>(real_inptr) + page_size - 1) & ~(page_size - 1));
mprotect(inptr + page_size, page_size, PROT_NONE);
void *real_outptr = op_malloc(page_size * 3);
char *outptr =
reinterpret_cast<char *>((reinterpret_cast<UINTPTR>(real_outptr) + page_size - 1) & ~(page_size - 1));
mprotect(outptr + page_size, page_size, PROT_NONE);
# endif // linux
encodings_check(static_cast<size_t>(inputlen) <= page_size);
encodings_check(static_cast<size_t>(expectedlen) <= page_size);
void *new_input = inptr + page_size - inputlen;
op_memcpy(new_input, input, inputlen);
// Test InputConverter
for (int i = 1; i <= expectedlen; ++ i)
{
# ifdef NEEDS_RISC_ALIGNMENT
if (i % 2) ++ i;
# endif
InputConverter *fw = encodings_new_forward(encoding);
encodings_check(fw != NULL);
int read;
int written = fw->Convert(new_input, inputlen, outptr + page_size - i, i, &read);
encodings_check(read <= inputlen);
encodings_check(written <= i);
// Ignore conversion results, we've already checked that
OP_DELETE(fw);
}
if (expectback && expectbacklen != -1)
{
void *new_expected = inptr + page_size - expectedlen;
op_memcpy(new_expected, expected, expectedlen);
// Test OutputConverter
for (int j = 1; j <= expectbacklen; ++ j)
{
# ifdef NEEDS_RISC_ALIGNMENT
if (j % 2) ++ j;
# endif
OutputConverter *rev = encodings_new_reverse(encoding);
encodings_check(rev != NULL);
int read;
int written = rev->Convert(new_expected, expectedlen, outptr + page_size - j, j, &read);
encodings_check(read <= expectedlen);
encodings_check(written <= j);
// Ignore conversion results, we've already checked that
OP_DELETE(rev);
}
// Test OutputConverter using Reset() instead of recreating object
OutputConverter *rev2 = encodings_new_reverse(encoding);
encodings_check(rev2 != NULL);
for (int k = 1; k <= expectbacklen; ++ k)
{
# ifdef NEEDS_RISC_ALIGNMENT
if (k % 2) ++ k;
# endif
rev2->Reset();
int read;
int written = rev2->Convert(new_expected, expectedlen, outptr + page_size - k, k, &read);
encodings_check(read <= expectedlen);
encodings_check(written <= k);
// Ignore conversion results, we've already checked that
}
OP_DELETE(rev2);
}
// Clean up
# ifdef WIN32
::VirtualFree(inptr, page_size, MEM_DECOMMIT);
::VirtualFree(inptr, 0, MEM_RELEASE);
::VirtualFree(outptr, page_size, MEM_DECOMMIT);
::VirtualFree(outptr, 0, MEM_RELEASE);
# elif defined linux
mprotect(inptr + page_size, page_size, PROT_READ | PROT_WRITE);
op_free(real_inptr);
mprotect(outptr + page_size, page_size, PROT_READ | PROT_WRITE);
op_free(real_outptr);
# endif // linux
#else // neither WIN32 nor linux
# ifdef SELFTEST
// FIXME: For other platforms, we should just set up a bait around the
// allocated buffer, and check that it remains unchanged after the test
// run.
OUTPUT_STR("\nencodings_test_buffers() not ported to your platform; not testing for buffer overruns. ");
# endif
#endif // WIN32 || linux
return 1;
}
int encodings_test_invalid(const char *encoding,
const uni_char *input, size_t inplen,
const uni_char *invalids, size_t invlen,
int numinvalids, int firstinvalid,
const char *entitystring/* = NULL*/,
size_t entitylen/* = 0*/)
{
#if defined ENCODINGS_HAVE_SPECIFY_INVALID || defined ENCODINGS_HAVE_ENTITY_ENCODING
int read;
#endif
#ifdef ENCODINGS_HAVE_SPECIFY_INVALID
OutputConverter *iconv = encodings_new_reverse(encoding);
encodings_check(iconv != NULL);
int written = iconv->Convert(input, inplen, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
(void)written;
#ifdef HEXDUMP
if (iconv->GetNumberOfInvalid() != numinvalids ||
iconv->GetFirstInvalidOffset() != firstinvalid)
{
hexdump("input ", input, inplen);
hexdump("output ", encodings_bufferback, written);
OUTPUT(__FILE__, __LINE__, 1, "\ngot %d invalid, expected %d invalid ", iconv->GetNumberOfInvalid(), numinvalids);
}
#endif
encodings_check(read == int(inplen));
encodings_check(iconv->GetNumberOfInvalid() == numinvalids);
encodings_check(iconv->GetFirstInvalidOffset() == firstinvalid);
encodings_check(op_memcmp(iconv->GetInvalidCharacters(), invalids, invlen) == 0);
OP_DELETE(iconv);
#endif // ENCODINGS_HAVE_SPECIFY_INVALID
#ifdef ENCODINGS_HAVE_ENTITY_ENCODING
if (entitylen)
{
OutputConverter *iconv = encodings_new_reverse(encoding);
encodings_check(iconv != NULL);
iconv->EnableEntityEncoding(TRUE);
int written = iconv->Convert(input, inplen, encodings_bufferback, ENC_TESTBUF_SIZE, &read);
encodings_check(read == int(inplen) && written == int(entitylen) &&
op_memcmp(encodings_bufferback, entitystring, entitylen) == 0);
OP_DELETE(iconv);
}
#endif // ENCODINGS_HAVE_ENTITY_ENCODING
return 1;
}
#ifdef ENCODINGS_REGTEST
// Copied from core/unicode.cpp:
int strni_eq(const char * str1, const char *str2, size_t len)
{
while (len-- && *str1)
{
char c = *str1;
if (c >= 'a' && c <= 'z')
{
if (*str2 != (c & 0xDF))
return 0;
}
else if (*str2 != c)
return 0;
str1++, str2++;
}
return !*str2 || len == -1;
}
#endif // ENCODINGS_REGTEST
#endif // SELFTEST || ENCODINGS_REGTEST
|
#include <ros/ros.h>
#include <sensor_msgs/JointState.h>
#include <crustcrawler_core_msgs/EndEffectorCommand.h>
#include <crustcrawler_core_msgs/EndEffectorState.h>
#include <crustcrawler_core_msgs/EndpointState.h>
#include <std_msgs/Float64.h>
#include <actionlib_msgs/GoalStatusArray.h>
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Geometry>
#include <eigen3/Eigen/Dense>
#include <tf/tf.h>
#include <moveit/robot_model_loader/robot_model_loader.h>
#include <moveit/robot_state/robot_state.h>
class Crustcrawler_Gripper
{
public:
Crustcrawler_Gripper(std::string name){
/*Construct robot model to solve for endpoint pose topic*/
robot_model_loader_.reset(new robot_model_loader::RobotModelLoader("robot_description"));
robot_model_ = robot_model_loader_->getModel();
robot_state_.reset(new robot_state::RobotState(robot_model_));
/*As soon as the class is instantiated a gripper state publisher start publishing a dummy state with right and left fingers state
* First subsribe to joint_states and get fingers positions
*/
joint_state_sub_ = nh_.subscribe("/crustcrawler/joint_states", 1, &Crustcrawler_Gripper::fingers_position_cb, this);
gripper_state_pub_ = nh_.advertise<crustcrawler_core_msgs::EndEffectorState>("/crustcrawler/end_effector/gripper/state", 1, this);
/*Create a subscriber to the gripper action server to execute the commands*/
gripper_action_sub_ = nh_.subscribe("/crustcrawler/end_effector/gripper/command", 1, &Crustcrawler_Gripper::gripper_action_cb, this);
/*Create the publisher to the fingers joints, so commands could be executed (openning and closing)*/
right_finger_command_pub_ = nh_.advertise<std_msgs::Float64>("/crustcrawler/joint_right_finger_position_controller/command", 1, this);
left_finger_command_pub_ = nh_.advertise<std_msgs::Float64>("/crustcrawler/joint_left_finger_position_controller/command", 1, this);
/*Create publisher for the endpoint state*/
endpoint_state_pub_ = nh_.advertise<crustcrawler_core_msgs::EndpointState>("/crustcrawler/endpoint_state", 1, this);
/*Fill gripper joints names*/
gripper_joints_names_.resize(2);
fingers_positions_.resize(2);
gripper_joints_names_ = {"left_finger_joint", "right_finger_joint"};
nh_.getParam("/simulation", simulation_);
}
~Crustcrawler_Gripper(void)
{
}
/*getting and publishing end point state, mainly the pose*/
void get_publish_end_point_state(){
robot_state_->setVariablePositions(joints_names_, joints_positions_);
eef_global_transform_ = robot_state_->getGlobalLinkTransform("the_gripper");
eef_position_holder_ = eef_global_transform_.translation();
transform_ee_w_ = eef_global_transform_.matrix();
eef_rotation_holder_.reset(new tf::Matrix3x3(transform_ee_w_(0,0), transform_ee_w_(0,1), transform_ee_w_(0,2),
transform_ee_w_(1,0), transform_ee_w_(1,1), transform_ee_w_(1,2),
transform_ee_w_(2,0), transform_ee_w_(2,1), transform_ee_w_(2,2)));
eef_rotation_holder_->getRotation(quaterion_angles_);
//eef_rotation_holder_->getRPY(roll_, pitch_, yaw_);
//ROS_ERROR("the rotation is: ");
//ROS_ERROR_STREAM(quaterion_angles_.getW() << ", " << quaterion_angles_.getX() << ", " << quaterion_angles_.getY() << ", " << quaterion_angles_.getZ());
//ROS_ERROR_STREAM(roll_ << ", " << pitch_ << ", " << yaw_ );
eef_point_state_.header.stamp = ros::Time::now();
eef_point_state_.header.frame_id = "/world_base";
eef_point_state_.pose.position.x = eef_position_holder_(0);
eef_point_state_.pose.position.y = eef_position_holder_(1);
eef_point_state_.pose.position.z = eef_position_holder_(2);
eef_point_state_.pose.orientation.w = quaterion_angles_.getW();
eef_point_state_.pose.orientation.x = quaterion_angles_.getX();
eef_point_state_.pose.orientation.y = quaterion_angles_.getY();
eef_point_state_.pose.orientation.z = quaterion_angles_.getZ();
endpoint_state_pub_.publish(eef_point_state_);
}
/*As soon as you get fingers position fill a gripper state msg and publish it*/
void fingers_position_cb(const sensor_msgs::JointState::ConstPtr& fingers_state){
/*Set and publish endpoint state*/
joints_names_ = fingers_state->name;
joints_positions_ = fingers_state->position;
get_publish_end_point_state();
/*Extract right and left joints position */
for(size_t i = 0; i < gripper_joints_names_.size(); i++)
fingers_positions_[i] = fingers_state->position[distance(fingers_state->name.begin(),
find(fingers_state->name.begin(),
fingers_state->name.end(),
gripper_joints_names_[i]))];
left_finger_position_ = fingers_positions_[0];
right_finger_position_ = fingers_positions_[1];
gripper_state_msg_.id = 1;
gripper_state_msg_.position = (left_finger_position_ + right_finger_position_) / 2.0;
gripper_state_msg_.enabled = static_cast<uint8_t>(true);
gripper_state_msg_.error = static_cast<uint8_t>(false);
gripper_state_msg_.calibrated = static_cast<uint8_t>(true);
gripper_state_msg_.ready = static_cast<uint8_t>(true);
gripper_state_pub_.publish(gripper_state_msg_);
}
/*this is the call back for when the actions server wants to execute a new command (open/close)*/
void gripper_action_cb(const crustcrawler_core_msgs::EndEffectorCommand::ConstPtr& gripper_command){
//for(size_t i = 0; i < gripper_command->args.size(); i++)
// ROS_WARN_STREAM("element: " << i << " in gripper joint command args is: " << gripper_command->args[i]);
if(!simulation_)
gripper_command_index_ = 11;
if(gripper_command->args[gripper_command_index_] == '1'){
//ROS_ERROR_STREAM("I am suppose to open the gripper, cause the command is: " << gripper_command->args);
open_gripper();
}
if(gripper_command->args[gripper_command_index_] == '0'){
//ROS_ERROR_STREAM("I am suppose to close the gripper, cause the command is: " << gripper_command->args);
close_gripper();
}
}
void open_gripper(){
/*Simulation*/
if(simulation_){
left_cmd_.data = -0.8;
right_cmd_.data = 0.8;
}
/*real robot*/
else{
left_cmd_.data = -0.5;
right_cmd_.data = 0.5;
}
right_finger_command_pub_.publish(right_cmd_);
left_finger_command_pub_.publish(left_cmd_);
}
void close_gripper(){
/*Simulation*/
if(simulation_){
left_cmd_.data = 0.0;
right_cmd_.data = 0.0;
}
/*real robot*/
else{
left_cmd_.data = -0.25;
right_cmd_.data = 0.25;
}
right_finger_command_pub_.publish(right_cmd_);
left_finger_command_pub_.publish(left_cmd_);
}
protected:
ros::NodeHandle nh_;
ros::Subscriber joint_state_sub_, gripper_action_sub_;
ros::Publisher gripper_state_pub_, gripper_command_pub_,
right_finger_command_pub_, left_finger_command_pub_,
endpoint_state_pub_;
crustcrawler_core_msgs::EndEffectorState gripper_state_msg_;
robot_model_loader::RobotModelLoaderConstPtr robot_model_loader_;
robot_model::RobotModelPtr robot_model_;
boost::shared_ptr<robot_state::RobotState> robot_state_;
Eigen::Affine3d eef_global_transform_;
crustcrawler_core_msgs::EndpointState eef_point_state_;
Eigen::VectorXd eef_position_holder_;
boost::shared_ptr<tf::Matrix3x3> eef_rotation_holder_;
Eigen::Matrix4d transform_ee_w_;
tf::Quaternion quaterion_angles_;
double left_finger_position_, right_finger_position_, roll_, pitch_, yaw_;
std::vector<double> fingers_positions_, joints_positions_;
std::vector<std::string> gripper_joints_names_, joints_names_;
std_msgs::Float64 left_cmd_, right_cmd_;
bool simulation_ = false;
int gripper_command_index_ = 13;
};
int main(int argc, char **argv)
{
ros::init(argc, argv, "crustcrawler_gripper");
ROS_WARN("------------- initialized crustcrawler gripper handler node ---------------------");
Crustcrawler_Gripper crustcrawler_translator(ros::this_node::getName());
ros::spin();
return 0;
}
|
friend Stonewt operator*(double x, const Stonewt & s);
Stonewt operator*(double x, const Stonewt & s)
{
return Stonewt(mult * s.pounds);
}
|
#pragma once
#include "GcTemplateDockable.h"
class GcActorTemplateDockable : public GcTemplateDockable
{
public:
GcActorTemplateDockable(void);
~GcActorTemplateDockable(void);
Gt2DActorPtr mpsCurrentObject;
protected:
virtual void ReciveNotiyfiMessage(WPARAM wParam, LPARAM lParam);
Gt2DActor* GetActorObject(CString itemText );
void SelectItem(int iIndex);
virtual void DoNewTemplate();
virtual void DoDelTemplate();
virtual void DoOpenTemplate();
virtual const gchar* GetFileName() {
return "templatelist.lst";
}
};
|
class Solution {
public:
bool dfs(vector<vector<char> > &board, vector<vector<bool> > &visited,
string &word, int count, int i, int j){
if(i > board.size() || j > board[0].size() || i < 0 || j < 0){
return false;
}
if(visited[i][j] || board[i][j] != word[count]){
return false;
}
visited[i][j] = true;
if(count == int(word.size()) - 1){
return true;
}
if(dfs(board, visited, word, count + 1, i, j + 1)
|| dfs(board, visited, word, count + 1, i + 1, j)
|| dfs(board, visited, word, count + 1, i - 1, j)
|| dfs(board, visited, word, count + 1, i, j - 1)){
return true;
}
visited[i][j] = false;
return false;
}
bool exist(vector<vector<char> > &board, string word) {
if(board.size() == 0){
if(word.size() == 0){
return true;
}else{
return false;
}
}
int row = board.size();
int col = board[0].size();
vector<vector<bool> > visited(row, vector<bool>(col, false));
for(int i = 0; i < row; ++i){
for(int j = 0; j < col; ++j){
if(dfs(board, visited, word, 0, i, j)){
return true;
}
}
}
return false;
}
};
|
// Created by: Peter KURNEV
// Copyright (c) 2010-2014 OPEN CASCADE SAS
// Copyright (c) 2007-2010 CEA/DEN, EDF R&D, OPEN CASCADE
// Copyright (c) 2003-2007 OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN, CEDRAT,
// EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
// 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 _BOPAlgo_BuilderSolid_HeaderFile
#define _BOPAlgo_BuilderSolid_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <BOPAlgo_BuilderArea.hxx>
#include <NCollection_BaseAllocator.hxx>
#include <TopTools_DataMapOfShapeBox.hxx>
//! Solid Builder is the algorithm for building solids from set of faces.
//! The given faces should be non-intersecting, i.e. all coinciding parts
//! of the faces should be shared among them.
//!
//! The algorithm performs the following steps to build the solids:
//! 1. Find:
//! - faces orientated INTERNAL;
//! - alone faces given twice with different orientation;
//! 2. Build all possible closed shells from the rest of the faces
//! (*BOPAlgo_ShellSplitter* is used for that);
//! 3. Classify the obtained shells on the Holes and Growths;
//! 4. Build solids from the Growth shells, put Hole shells into closest Growth solids;
//! 5. Classify all unused faces relatively created solids and put them as internal
//! shells into the closest solids;
//! 6. Find all unclassified faces, i.e. faces outside of all created solids,
//! make internal shells from them and put these shells into a warning.
//!
//! It is possible to avoid all internal shells in the resulting solids.
//! For that it is necessary to use the method SetAvoidInternalShapes(true)
//! of the base class. In this case the steps 5 and 6 will not be performed at all.
//!
//! The algorithm may return the following warnings:
//! - *BOPAlgo_AlertShellSplitterFailed* in case the ShellSplitter algorithm has failed;
//! - *BOPAlgo_AlertSolidBuilderUnusedFaces* in case there are some faces outside of
//! created solids left.
//!
//! Example of usage of the algorithm:
//! ~~~~
//! const TopTools_ListOfShape& aFaces = ...; // Faces to build the solids
//! Standard_Boolean isAvoidInternals = ...; // Flag which defines whether to create the internal shells or not
//! BOPAlgo_BuilderSolid aBS; // Solid Builder tool
//! aBS.SetShapes(aFaces); // Set the faces
//! aBS.SetAvoidInternalShapes(isAvoidInternals); // Set the AvoidInternalShapesFlag
//! aBS.Perform(); // Perform the operation
//! if (!aBS.IsDone()) // Check for the errors
//! {
//! // error treatment
//! Standard_SStream aSStream;
//! aBS.DumpErrors(aSStream);
//! return;
//! }
//! if (aBS.HasWarnings()) // Check for the warnings
//! {
//! // warnings treatment
//! Standard_SStream aSStream;
//! aBS.DumpWarnings(aSStream);
//! }
//!
//! const TopTools_ListOfShape& aSolids = aBS.Areas(); // Obtaining the result solids
//! ~~~~
//!
class BOPAlgo_BuilderSolid : public BOPAlgo_BuilderArea
{
public:
DEFINE_STANDARD_ALLOC
public: //! @name Constructors
//! Empty constructor
Standard_EXPORT BOPAlgo_BuilderSolid();
Standard_EXPORT virtual ~BOPAlgo_BuilderSolid();
//! Constructor with allocator
Standard_EXPORT BOPAlgo_BuilderSolid(const Handle(NCollection_BaseAllocator)& theAllocator);
public: //! @name Performing the operation
//! Performs the construction of the solids from the given faces
Standard_EXPORT virtual void Perform(const Message_ProgressRange& theRange = Message_ProgressRange()) Standard_OVERRIDE;
public: //! @name Getting the bounding boxes of the created solids
//! For classification purposes the algorithm builds the bounding boxes
//! for all created solids. This method returns the data map of solid - box pairs.
const TopTools_DataMapOfShapeBox& GetBoxesMap() const
{
return myBoxes;
}
protected: //! @name Protected methods performing the operation
//! Collect the faces:
//! - with INTERNAL orientation;
//! - that are alone but given twice with different orientation.
//! These faces will be put into the map *myShapesToAvoid* and will be
//! avoided in shells construction, but will be classified later on.
Standard_EXPORT virtual void PerformShapesToAvoid(const Message_ProgressRange& theRange) Standard_OVERRIDE;
//! Build all possible closed shells from the given faces.
//! The method fills the following maps:
//! - myLoops - Created closed shells;
//! - myLoopsInternal - The shells created from unused faces.
Standard_EXPORT virtual void PerformLoops(const Message_ProgressRange& theRange) Standard_OVERRIDE;
//! Classifies the created shells on the Holes and Growths.
//! Creates the solids from the Growths shells.
//! Puts the Hole shells into the closest Growths solids.
Standard_EXPORT virtual void PerformAreas(const Message_ProgressRange& theRange) Standard_OVERRIDE;
//! Classifies the unused faces relatively the created solids.
//! Puts the classified faces into the closest solids as internal shells.
//! Warns the user about unclassified faces if any.
Standard_EXPORT virtual void PerformInternalShapes(const Message_ProgressRange& theRange) Standard_OVERRIDE;
private:
TopTools_DataMapOfShapeBox myBoxes; // Boxes of the produced solids
};
#endif // _BOPAlgo_BuilderSolid_HeaderFile
|
/*
ID: washirv1
PROG: dualpal
LANG: C++
*/
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
bool isPal(string s)
{
for (int f = 0, b = s.length() - 1; f < b; f++, b--)
{
if (s[f] != s[b])
return false;
}
return true;
}
void convert(int base, int num, string &result)
{
stringstream ss;
if (num < base)
{
ss << num;
result += ss.str();
}
else
{
convert(base, num / base, result);
ss << num % base;
result += ss.str();
}
}
int main()
{
ofstream fout("dualpal.out");
ifstream fin("dualpal.in");
// read in n and s
int n, s;
fin >> n >> s;
// starting at s, check each number against all bases
// stopping only when n palindromes have been found
for (s++; n > 0; s++)
{
int p = 0;
for (int b = 2; p < 2 && b <= 10; b++)
{
string r = "";
convert(b, s, r);
if (isPal(r))
p++;
}
if (p >= 2)
{
fout << s << endl;
n--;
}
}
return 0;
}
|
#include <stdio.h>
#include <iostream>
#include <math.h>
#include <algorithm>
#include <memory.h>
#include <set>
#include <map>
#include <queue>
#include <deque>
#include <string>
#include <string.h>
#include <vector>
typedef long long ll;
typedef long double ld;
typedef unsigned long long ull;
const ld PI = acos(-1.);
using namespace std;
const int N = 100003;
const int M = 303;
const int MOD = 1000000007;
int f[N][M][2];
int a[N];
int n;
int sum[M];
inline void relax(int& x, int y) {
x = (x + y) % MOD;
}
int main() {
freopen("sequence.in", "r", stdin);
freopen("sequence.out", "w", stdout);
scanf("%d", &n);
for (int i = 0; i < n; ++i) scanf("%d", a + i);
if (n == 1) {
cout << 1 << endl;
return 0;
}
for (int i = 0; i < min(a[0], a[1]); ++i) {
f[1][ a[1] - i ][0] = 1;
}
f[1][ a[1] - min(a[1], a[0]) ][1] = 1;
for (int i = 1; i + 1 < n; ++i) {
memset(sum, 0, sizeof(sum));
for (int j = 0; j <= a[i]; ++j) {
if (j <= a[i + 1]) {
relax(f[i + 1][ a[i + 1] - j ][1], f[i][j][0]);
}
int l = min(j, a[i + 1]);
if (f[i][j][1]) {
relax(f[i + 1][ a[i + 1] - l ][1], f[i][j][1]);
}
relax(sum[ a[i + 1] - l + 1 ], f[i][j][1]);
}
int add = 0;
for (int j = 0; j <= a[i + 1]; ++j) {
relax(add, sum[j]);
relax(f[i + 1][j][0], add);
}
}
int ans = 0;
for (int j = 0; j <= a[n - 1]; ++j) {
relax(ans, f[n - 1][j][1]);
}
cout << ans << endl;
return 0;
}
|
#include <iostream>
#include <fstream>
using namespace std;
struct StudentData
{
int fn;
char name[100];
};
struct SubjectData
{
int code;
char name[100];
char teacher[100];
};
struct GradeData
{
int studentFn, subjectCode;
int d,m,y;
double value;
};
void createStudents ()
{
ifstream inpStud ("students.txt");
ofstream StudBinO ("binaryout.bin",ios::binary);
StudentData student;
while (inpStud >> student.fn)
{
inpStud.getline (student.name,100);
cout << "Read stundet:" << student.name << endl;
StudBinO.seekp((student.fn-1000)*sizeof(StudentData));
StudBinO.write ((char*)&student,sizeof(StudentData));
}
inpStud.close();
}
void readStudent(int fn,ostream& outpStud )
{
StudentData student;
ifstream StudBinI ("binaryout.bin",ios::binary);
StudBinI.seekg((fn-1000)*sizeof(StudentData));
StudBinI.read((char*)&student,sizeof(StudentData));
outpStud<<student.fn;
outpStud<<student.name<<endl;
StudBinI.close();
}
void createSubjects ()
{
ifstream inpSubj ("subjects.txt");
ofstream outpSubj ("subjects.bin",ios::binary);
SubjectData subj;
while (inpSubj >> subj.code)
{
inpSubj.getline (subj.name,100);
inpSubj.getline (subj.teacher,100);
//cout << "Read subject:" << subj.name << endl;
outpSubj.seekp (subj.code*sizeof(SubjectData));
outpSubj.write ((char*)&subj,sizeof(SubjectData));
}
}
int main()
{
ofstream outpStud ("studentsOut.txt");
createStudents();
createSubjects();
readStudent(1000,outpStud);
readStudent(1002,outpStud);
outpStud.close();
return 0;
}
|
//
// Created by archtao on 2021/5/31.
//
#include <iostream>
#include <string>
using std::cout;
using std::endl;
using std::string;
void GetNext(string, int*); // 获取next数组
void GetNextVal(string, int*); // next数组优化
int IndexKMP(string, string, const int*); // KMP算法
int main()
{
string s = "$abaacaabcabaabc";
string t = "$abaabc";
int next[t.length()];
GetNext(t, next);
for (int i = 1; i < t.length(); ++i) {
cout << next[i] << "\t";
}
cout << endl;
cout << "Position: " << IndexKMP(s, t, next) << endl;
return 0;
}
void GetNext(string t, int* next) {
int i = 1, j = 0;
next[1] = 0;
while (i < t.length()) {
if (0 == j || t[i] == t[j]) {
++i;
++j;
next[i] = j;
} else {
j = next[j];
}
}
}
int IndexKMP(string s, string t, const int* next) {
int i = 1, j = 1;
while (i <= s.length() && j <= t.length()) {
if (0 == j || s[i] == t[j]) {
++i;
++j;
} else {
j = next[j];
}
}
if (j > t.length())
return i - t.length();
else
return 0;
}
|
// <copyright header>
#include "modules/hardcore/keys/opkeys.h"
/* static */ const uni_char*
OpKey::ToString(OpKey::Code key)
{
switch (key)
{
// <key to string>
}
return NULL;
}
/* static */ OpKey::Code
OpKey::FromString(const uni_char* str)
{
// <string to key>
return OP_KEY_FIRST;
}
/* static */ BOOL
OpKey::IsInValueSet(OpKey::Code key)
{
switch (key)
{
// <has no key value>
return FALSE;
default:
return TRUE;
}
}
/* static */ uni_char
OpKey::CharValue(OpKey::Code key)
{
switch (key)
{
// <with char value>
}
return 0;
}
/* static */ BOOL
OpKey::IsModifier(OpKey::Code key)
{
switch (key)
{
// <is modifier cases>
return TRUE;
default:
return FALSE;
}
}
/* static */ BOOL
OpKey::IsFunctionKey(OpKey::Code key)
{
switch (key)
{
// <is function key>
return TRUE;
}
return FALSE;
}
/* static */ OpKey::Location
OpKey::ToLocation(OpKey::Code key)
{
switch (key)
{
// <location cases>
}
return LOCATION_STANDARD;
}
#ifdef MOUSE_SUPPORT
/* static */ BOOL
OpKey::IsMouseButton(OpKey::Code key)
{
switch (key)
{
// <is mouse button cases>
return TRUE;
default:
return FALSE;
}
}
#endif // MOUSE_SUPPORT
/* static */ BOOL
OpKey::IsGesture(OpKey::Code key)
{
switch (key)
{
// <is gesture cases>
return TRUE;
default:
return FALSE;
}
}
/* static */ BOOL
OpKey::IsFlip(OpKey::Code key)
{
switch (key)
{
// <is flip cases>
return TRUE;
default:
return FALSE;
}
}
/* static */ OpKey::Code
OpKey::FromASCIIToKeyCode(char ch, ShiftKeyState &modifiers)
{
modifiers = SHIFTKEY_NONE;
if (ch >= 'a' && ch <= 'z')
return static_cast<OpKey::Code>(OP_KEY_A + (ch - 'a'));
else if (ch >= '0' && ch <= '9')
return static_cast<OpKey::Code>(OP_KEY_0 + (ch - '0'));
else if (ch >= 'A' && ch <= 'Z')
{
modifiers |= SHIFTKEY_SHIFT;
return static_cast<OpKey::Code>(OP_KEY_A + (ch - 'A'));
}
else
/* US-ASCII means US keyboard layout. */
switch (ch)
{
#if OP_KEY_BACKSPACE_ENABLED
case 8: return OP_KEY_BACKSPACE;
#endif // OP_KEY_BACKSPACE_ENABLED
#if OP_KEY_TAB_ENABLED
case '\t': return OP_KEY_TAB;
#endif // OP_KEY_TAB_ENABLED
#if OP_KEY_ENTER_ENABLED
case '\r':
case '\n': return OP_KEY_ENTER;
#endif // OP_KEY_ENTER_ENABLED
#if OP_KEY_ESCAPE_ENABLED
case 27: return OP_KEY_ESCAPE;
#endif // OP_KEY_ESCAPE_ENABLED
#if OP_KEY_SPACE_ENABLED
case ' ': return OP_KEY_SPACE;
#endif // OP_KEY_SPACE_ENABLED
case '!':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_1;
#ifdef OP_KEY_OEM_7_ENABLED
case '"':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_7;
#endif // OP_KEY_OEM_7_ENABLED
case '#':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_3;
case '$':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_4;
case '%':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_5;
case '&':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_7;
#if OP_KEY_OEM_7_ENABLED
case '\'':
return OP_KEY_OEM_7;
#endif // OP_KEY_OEM_7_ENABLED
case '(':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_9;
case ')':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_0;
case '*':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_8;
#if OP_KEY_OEM_PLUS_ENABLED
case '+':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_PLUS;
#endif // OP_KEY_OEM_PLUS_ENABLED
#if OP_KEY_OEM_COMMA_ENABLED
case ',':
return OP_KEY_OEM_COMMA;
#endif // OP_KEY_OEM_COMMA_ENABLED
#if OP_KEY_OEM_MINUS_ENABLED
case '-':
return OP_KEY_OEM_MINUS;
#endif // OP_KEY_OEM_MINUS_ENABLED
#if OP_KEY_OEM_PERIOD_ENABLED
case '.':
return OP_KEY_OEM_PERIOD;
#endif // OP_KEY_OEM_PERIOD_ENABLED
#if OP_KEY_OEM_2_ENABLED
case '/':
return OP_KEY_OEM_2;
#endif // OP_KEY_OEM_2_ENABLED
#if OP_KEY_OEM_1_ENABLED
case ':':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_1;
#endif // OP_KEY_OEM_1_ENABLED
#if OP_KEY_OEM_1_ENABLED
case ';':
return OP_KEY_OEM_1;
#endif // OP_KEY_OEM_1_ENABLED
#if OP_KEY_OEM_COMMA_ENABLED
case '<':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_COMMA;
#endif // OP_KEY_OEM_COMMA_ENABLED
#if OP_KEY_OEM_PLUS_ENABLED
case '=':
return OP_KEY_OEM_PLUS;
#endif // OP_KEY_OEM_PLUS_ENABLED
#if OP_KEY_OEM_PERIOD_ENABLED
case '>':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_PERIOD;
#endif // OP_KEY_OEM_PERIOD_ENABLED
#if OP_KEY_OEM_2_ENABLED
case '?':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_2;
#endif // OP_KEY_OEM_2_ENABLED
case '@':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_2;
#if OP_KEY_OEM_4_ENABLED
case '[':
return OP_KEY_OEM_4;
#endif // OP_KEY_OEM_4_ENABLED
#if OP_KEY_OEM_5_ENABLED
case '\\':
return OP_KEY_OEM_5;
#endif // OP_KEY_OEM_5_ENABLED
#if OP_KEY_OEM_6_ENABLED
case ']':
return OP_KEY_OEM_6;
#endif // OP_KEY_OEM_6_ENABLED
case '^':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_6;
#if OP_KEY_OEM_MINUS_ENABLED
case '_':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_MINUS;
#endif // OP_KEY_OEM_MINUS_ENABLED
#if OP_KEY_OEM_3_ENABLED
case '`':
return OP_KEY_OEM_3;
#endif // OP_KEY_OEM_3_ENABLED
#if OP_KEY_OEM_4_ENABLED
case '{':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_4;
#endif // OP_KEY_OEM_4_ENABLED
#if OP_KEY_OEM_5_ENABLED
case '|':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_5;
#endif // OP_KEY_OEM_5_ENABLED
#if OP_KEY_OEM_6_ENABLED
case '}':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_6;
#endif // OP_KEY_OEM_6_ENABLED
#if OP_KEY_OEM_3_ENABLED
case '~':
modifiers |= SHIFTKEY_SHIFT;
return OP_KEY_OEM_3;
#endif // OP_KEY_OEM_3_ENABLED
#if OP_KEY_DELETE_ENABLED
case 0x7f:
return OP_KEY_DELETE;
#endif // OP_KEY_DELETE_ENABLED
}
return OP_KEY_FIRST;
}
|
/********************************************************************************
** Form generated from reading UI file 'rigidpropertywidget.ui'
**
** Created by: Qt User Interface Compiler version 5.7.0
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/
#ifndef UI_RIGIDPROPERTYWIDGET_H
#define UI_RIGIDPROPERTYWIDGET_H
#include <QtCore/QVariant>
#include <QtWidgets/QAction>
#include <QtWidgets/QApplication>
#include <QtWidgets/QButtonGroup>
#include <QtWidgets/QCheckBox>
#include <QtWidgets/QDoubleSpinBox>
#include <QtWidgets/QFrame>
#include <QtWidgets/QGridLayout>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QSpacerItem>
#include <QtWidgets/QWidget>
QT_BEGIN_NAMESPACE
class Ui_RigidPropertyWidget
{
public:
QWidget *layout;
QGridLayout *gridLayout;
QLabel *label_2;
QSpacerItem *verticalSpacer;
QDoubleSpinBox *rotY;
QCheckBox *static_2;
QFrame *line_2;
QCheckBox *kinematic;
QDoubleSpinBox *posZ;
QDoubleSpinBox *posY;
QDoubleSpinBox *rotZ;
QDoubleSpinBox *rotX;
QLabel *label;
QDoubleSpinBox *posX;
QFrame *line;
QLabel *label_3;
QDoubleSpinBox *scaleX;
QDoubleSpinBox *scaleY;
QDoubleSpinBox *scaleZ;
void setupUi(QWidget *RigidPropertyWidget)
{
if (RigidPropertyWidget->objectName().isEmpty())
RigidPropertyWidget->setObjectName(QStringLiteral("RigidPropertyWidget"));
RigidPropertyWidget->resize(400, 300);
layout = new QWidget(RigidPropertyWidget);
layout->setObjectName(QStringLiteral("layout"));
layout->setGeometry(QRect(70, 70, 291, 141));
gridLayout = new QGridLayout(layout);
gridLayout->setObjectName(QStringLiteral("gridLayout"));
label_2 = new QLabel(layout);
label_2->setObjectName(QStringLiteral("label_2"));
gridLayout->addWidget(label_2, 5, 0, 1, 1);
verticalSpacer = new QSpacerItem(20, 40, QSizePolicy::Minimum, QSizePolicy::Expanding);
gridLayout->addItem(verticalSpacer, 7, 0, 1, 1);
rotY = new QDoubleSpinBox(layout);
rotY->setObjectName(QStringLiteral("rotY"));
rotY->setDecimals(4);
rotY->setMinimum(-360);
rotY->setMaximum(360);
gridLayout->addWidget(rotY, 5, 2, 1, 1);
static_2 = new QCheckBox(layout);
static_2->setObjectName(QStringLiteral("static_2"));
gridLayout->addWidget(static_2, 1, 0, 1, 1);
line_2 = new QFrame(layout);
line_2->setObjectName(QStringLiteral("line_2"));
line_2->setFrameShape(QFrame::HLine);
line_2->setFrameShadow(QFrame::Sunken);
gridLayout->addWidget(line_2, 3, 0, 1, 4);
kinematic = new QCheckBox(layout);
kinematic->setObjectName(QStringLiteral("kinematic"));
gridLayout->addWidget(kinematic, 2, 0, 1, 1);
posZ = new QDoubleSpinBox(layout);
posZ->setObjectName(QStringLiteral("posZ"));
posZ->setDecimals(4);
posZ->setMinimum(-100);
posZ->setMaximum(100);
gridLayout->addWidget(posZ, 4, 3, 1, 1);
posY = new QDoubleSpinBox(layout);
posY->setObjectName(QStringLiteral("posY"));
posY->setDecimals(4);
posY->setMinimum(-100);
posY->setMaximum(100);
gridLayout->addWidget(posY, 4, 2, 1, 1);
rotZ = new QDoubleSpinBox(layout);
rotZ->setObjectName(QStringLiteral("rotZ"));
rotZ->setDecimals(4);
rotZ->setMinimum(-360);
rotZ->setMaximum(360);
gridLayout->addWidget(rotZ, 5, 3, 1, 1);
rotX = new QDoubleSpinBox(layout);
rotX->setObjectName(QStringLiteral("rotX"));
rotX->setDecimals(4);
rotX->setMinimum(-360);
rotX->setMaximum(360);
gridLayout->addWidget(rotX, 5, 1, 1, 1);
label = new QLabel(layout);
label->setObjectName(QStringLiteral("label"));
gridLayout->addWidget(label, 4, 0, 1, 1);
posX = new QDoubleSpinBox(layout);
posX->setObjectName(QStringLiteral("posX"));
posX->setDecimals(4);
posX->setMinimum(-100);
posX->setMaximum(100);
gridLayout->addWidget(posX, 4, 1, 1, 1);
line = new QFrame(layout);
line->setObjectName(QStringLiteral("line"));
line->setFrameShape(QFrame::HLine);
line->setFrameShadow(QFrame::Sunken);
gridLayout->addWidget(line, 0, 0, 1, 4);
label_3 = new QLabel(layout);
label_3->setObjectName(QStringLiteral("label_3"));
gridLayout->addWidget(label_3, 6, 0, 1, 1);
scaleX = new QDoubleSpinBox(layout);
scaleX->setObjectName(QStringLiteral("scaleX"));
scaleX->setDecimals(4);
scaleX->setMinimum(0.0001);
scaleX->setValue(1);
gridLayout->addWidget(scaleX, 6, 1, 1, 1);
scaleY = new QDoubleSpinBox(layout);
scaleY->setObjectName(QStringLiteral("scaleY"));
scaleY->setDecimals(4);
scaleY->setMinimum(0.0001);
scaleY->setValue(1);
gridLayout->addWidget(scaleY, 6, 2, 1, 1);
scaleZ = new QDoubleSpinBox(layout);
scaleZ->setObjectName(QStringLiteral("scaleZ"));
scaleZ->setDecimals(4);
scaleZ->setMinimum(0.0001);
scaleZ->setValue(1);
gridLayout->addWidget(scaleZ, 6, 3, 1, 1);
retranslateUi(RigidPropertyWidget);
QMetaObject::connectSlotsByName(RigidPropertyWidget);
} // setupUi
void retranslateUi(QWidget *RigidPropertyWidget)
{
RigidPropertyWidget->setWindowTitle(QApplication::translate("RigidPropertyWidget", "Form", 0));
label_2->setText(QApplication::translate("RigidPropertyWidget", "Rotation", 0));
static_2->setText(QApplication::translate("RigidPropertyWidget", "Static", 0));
kinematic->setText(QApplication::translate("RigidPropertyWidget", "Kinematic", 0));
label->setText(QApplication::translate("RigidPropertyWidget", "Position", 0));
label_3->setText(QApplication::translate("RigidPropertyWidget", "Scale", 0));
} // retranslateUi
};
namespace Ui {
class RigidPropertyWidget: public Ui_RigidPropertyWidget {};
} // namespace Ui
QT_END_NAMESPACE
#endif // UI_RIGIDPROPERTYWIDGET_H
|
/****************************************************************************
** Copyright (C) 2017 Olaf Japp
**
** This file is part of FlatSiteBuilder.
**
** FlatSiteBuilder is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** FlatSiteBuilder is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with FlatSiteBuilder. If not, see <http://www.gnu.org/licenses/>.
**
****************************************************************************/
#ifndef MENU_H
#define MENU_H
#include <QObject>
#include "menuitem.h"
class Menu : public QObject
{
Q_OBJECT
public:
Menu();
void setName(QString name) {m_name = name;}
QString name() {return m_name;}
void addMenuitem(MenuItem *item) {m_items.append(item);}
QList<MenuItem *> items() {return m_items;}
void removeItem(MenuItem *item) {m_items.removeOne(item);}
int id() {return m_id;}
void setId(int id) {m_id = id;}
private:
QString m_name;
QList<MenuItem *> m_items;
int m_id;
};
#endif // MENU_H
|
// ConsoleLog.cpp : implementation file
//
#include "stdafx.h"
#include "BHMonitor.h"
#include "ConsoleLog.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CConsoleLog
CConsoleLog::CConsoleLog()
{
}
CConsoleLog::~CConsoleLog()
{
}
BEGIN_MESSAGE_MAP(CConsoleLog, CEdit)
//{{AFX_MSG_MAP(CConsoleLog)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CConsoleLog message handlers
|
#ifndef VULKANLAB_MATERIAL_H
#define VULKANLAB_MATERIAL_H
#include "../Assets/Asset.h"
class Shader;
class Material : public Asset {
public:
/**
* Material constructor.
* @param name
*/
Material(const char *name);
/**
* Material destructor.
*/
~Material();
/**
* Return the name of the material.
* @return
*/
inline const char *getName() {
return name;
}
/**
* Set the name of the material.
* @param value
*/
inline void setName(const char *value) {
this->name = value;
}
/**
* Return the material shader.
* @return
*/
inline Shader *getShader() const {
return this->shader;
}
/**
* Set the material shader.
* @param shader
*/
inline void setShader(Shader *shader) {
this->shader = shader;
}
private:
const char *name;
Shader* shader;
};
#endif //VULKANLAB_MATERIAL_H
|
//
// FILE: radar.h
// AUTHOR: Rob Tillaart
// VERSION: see RADAR_LIB_VERSION
// PURPOSE: pan tilt radar framework
// URL:
//
// Released to the public domain
//
#ifndef Radar_h
#define Radar_h
#if defined(ARDUINO) && ARDUINO >= 100
#include "Arduino.h"
#include "SoftwareSerial.h"
#else
#include "WProgram.h"
#include "NewSoftSerial.h"
#endif
#define RADAR_LIB_VERSION "0.1.00"
#define PAN_PER_SEC 20 // TODO determine emperically
#define TILT_PER_SEC 10 // TODO determine emperically
class RADAR
{
public:
RADAR(int, int);
void setPan(int pan);
int getPan();
void setTilt(int tilt);
int getTilt();
void setHomePosition(int pan, int tilt);
void home();
bool ready();
unsigned long ping();
unsigned long ping(int pan, int tilt);
private:
int _pinPan;
int _pinTilt;
int _prevPan;
int _pan;
int _homePan;
unsigned long _lastPanTime
int _prevTilt;
int _tilt;
int _homeTilt;
unsigned long _lastTiltTime
};
#endif
// -- END OF FILE --
|
# include <iostream>
using namespace std;
class Human
{
int age;
string Name;
public:
Human(string Name="UnNamed",int age=0): Name(Name) , age(age){ };
void Tellme()
{
cout<<Name<<endl<<age<<endl;
}
friend void Display(Human man);
};
void Display(Human man)
{
cout<<man.Name<<endl<<man.age<<endl;
}
main()
{
Human h("Haseeb",20);
Display(h);
}
|
#pragma once
#include <map>
namespace HW
{
// a wrapper for map list iterator .
template<typename Tkey,typename Tval>
class mapIterator
{
typedef typename std::map<Tkey,Tval>::iterator IterType;
IterType iter;
public:
// should never be used.
mapIterator(){}
// constructor
mapIterator(const IterType &it)
{
this->iter = it;
}
// copy constructor
mapIterator(const mapIterator<Tkey,Tval> &other)
{
this->iter = other.iter;
}
Tval get() const
{
return iter->second;
}
mapIterator<Tkey,Tval>& operator++()
{
this->iter++;
return *this;
}
mapIterator<Tkey,Tval> operator++(int)
{
mapIterator<Tkey,Tval> tmp = *this;
this->iter++;
return tmp;
}
mapIterator<Tkey,Tval>& operator=(const mapIterator<Tkey,Tval> &other)
{
this->iter = other.iter;
return *this;
}
bool operator!=(const mapIterator<Tkey,Tval>& other) const
{
return (this->iter != other.iter);
}
};
}
|
//: C13:ArrayOperatorNew.cpp
// Kod zrodlowy pochodzacy z ksiazki
// "Thinking in C++. Edycja polska"
// (c) Bruce Eckel 2000
// Informacje o prawie autorskim znajduja sie w pliku Copyright.txt
// Operator new dla tablic
#include <new> // Definicja size_t
#include <fstream>
using namespace std;
ofstream trace("ArrayOperatorNew.out");
class Widget {
enum { sz = 10 };
int i[sz];
public:
Widget() { trace << "*"; }
~Widget() { trace << "~"; }
void* operator new(size_t sz) {
trace << "Widget::new: "
<< sz << " bajtow" << endl;
return ::new char[sz];
}
void operator delete(void* p) {
trace << "Widget::delete" << endl;
::delete []p;
}
void* operator new[](size_t sz) {
trace << "Widget::new[]: "
<< sz << " bajtow" << endl;
return ::new char[sz];
}
void operator delete[](void* p) {
trace << "Widget::delete[]" << endl;
::delete []p;
}
};
int main() {
trace << "new Widget" << endl;
Widget* w = new Widget;
trace << "\ndelete Widget" << endl;
delete w;
trace << "\nnew Widget[25]" << endl;
Widget* wa = new Widget[25];
trace << "\ndelete []Widget" << endl;
delete []wa;
} ///:~
|
#include <iostream>
#include <string>
using namespace std;
int main() {
int first_number = GetInputNumber();
char operator = GetInputOperator();
int second_number = GetInputNumber();
int running_total = 0;
if (operator == '+') {
running_total = first_number + second_number;
}
if (operator == '%') {
running_total = first_number % second_number;
}
cout << " = " << running_total << endl;
operator = GetInputOperator();
int third_number = GetInputNumber();
if (operator == '*') {
running_total = running_total * third_number;
}
if (operator == '/') {
running_total = running_total / third_number;
}
cout << " = " << running_total << endl;
}
|
#ifndef SMART_PTR_H
#define SMART_PTR_H 1
#include <cstddef>
#include <utility>
#include "hf2_control_block.hpp"
namespace HF2 {
/// Skaláris okospointer alaposztály
template<class T>
class Abstract_SmartPointer {
protected:
/// Pointer kontrollblokkra
ControlBlock<T>* ctrl_;
/// "új" pointer inicializálás
explicit Abstract_SmartPointer(T* t): ctrl_{ new ControlBlock<T>{t} } {}
/// létező pointerrel osztozkodás
Abstract_SmartPointer(ControlBlock<T>* ctrl): ctrl_{ ctrl } {}
public:
/// virtuális destruktor, hogy biztosan meghívódjon a leszármazotté
virtual ~Abstract_SmartPointer() {}
/// ctrl_->referenceCount() facade
inline std::size_t referenceCount() const { return ctrl_->referenceCount(); }
/// új ControlBlock inicializálása a példánynak
virtual void newPointer(T* t) = 0;
/// új pointer beállítása az összes pointernek ami ezt a ControlBlock -ot használja
virtual void reassignPointer(T* t) = 0;
/// arrow
inline T* operator->() { return ctrl_->ptr(); }
/// dereferálás
inline T& operator*() { return *(ctrl_->ptr()); }
/// t == ctrl_->t
inline bool operator==(const T* t) const { return t == ctrl_->ptr(); }
/// t != ctrl_->t
inline bool operator!=(const T* t) const { return t != ctrl_->ptr(); }
/// sp.ctrl_->t != ctrl_->t
inline bool operator==(const Abstract_SmartPointer<T>& sp) const { return sp.ctrl_->ptr() == ctrl_->ptr(); }
/// sp.ctrl_->t != ctrl_->t
inline bool operator!=(const Abstract_SmartPointer<T>& sp) const { return sp.ctrl_->ptr() != ctrl_->ptr(); }
/// sp.ctrl_->t + offset == ctrl_->t
inline bool operator==(const Abstract_SmartPointer<T[]>& sp) const { return sp.ctrl_->ptr() + sp.offset() == ctrl_->ptr(); }
/// sp.ctrl_->t + offset != ctrl_->t
inline bool operator!=(const Abstract_SmartPointer<T[]>& sp) const { return sp.ctrl_->ptr() + sp.offset() != ctrl_->ptr(); }
};
/// Vektorális okospointer alaposztály
/**
* javallott a ++/-- operátorokat csak loopokon belül használni
* és a végén 0-ba állítani
*/
template<class T>
class Abstract_SmartPointer <T[]> {
protected:
/// Pointer kontrollblokkra
ControlBlock<T[]>* ctrl_;
/// Bármikor módosítható offset
mutable std::size_t offset_;
/// "új" pointer inicializálás
Abstract_SmartPointer(T* t, std::size_t size) : ctrl_{ new ControlBlock<T[]>{t, size} }, offset_{ 0U } {}
/// létező pointerrel osztozkodás
Abstract_SmartPointer(ControlBlock<T[]>* ctrl): ctrl_{ ctrl }, offset_{ 0U } {}
public:
/// virtuális destruktor, hogy biztosan meghívódjon a leszármazotté
virtual ~Abstract_SmartPointer() {}
/// ctrl_->referenceCount() facade
inline std::size_t referenceCount() const { return ctrl_->referenceCount(); }
/// ctrl_->size() facade
inline std::size_t size() const { return ctrl_->size(); }
/// offset_ getter
inline std::size_t offset() const { return offset_; }
/// offset_ setter
inline void setOffset(std::size_t offset) const {
if (offset >= ctrl_->size())
throw "New offset is too big";
offset_ = offset;
}
/// új ControlBlock<T[]> inicializálása a példánynak
//* érdemes az offsetet 0-ra állítani
virtual void newPointer(T* t, std::size_t size) = 0;
/// új pointer beállítása az összes pointernek ami ezt a ControlBlock<T[]> -ot használja
//* Ki-indexeléshez vezethet, ha az új size
//* kisebb mint a this->size_ és az offset_ kilóg
virtual void reassignPointer(T* t, std::size_t size) = 0;
/// indexelés 0. elemtől | const *char exception-t dob túlindexelésnél
inline T& operator[](const std::size_t idx) {
if (idx < ctrl_->size())
return ctrl_->ptr()[idx];
throw "Index out of range";
}
/// Pont arra jó mint a másik csak ez még const is.
inline const T& operator[](const std::size_t idx) const {
if (idx < ctrl_->size())
return ctrl_->ptr()[idx];
throw "Index out of range";
}
/// ++offset_ | nincs post-increment | ha eléri a ctrl_->size() -t akkor 0-ra áll vissza és false-t dob
bool operator++() const {
if (++offset_ < ctrl_->size())
return true;
offset_ = 0U;
return false;
}
/// --offset_ | nincs post-decrement | ha elérné a -1 -t akkor size() - 1-re áll vissza és false-t dob
bool operator--() const {
if (offset_ == 0) {
offset_ = ctrl_->size() - 1;
return false;
}
--offset_;
return true;
}
/// jelenleg offsettel kiválaszott elem tagjának hozzáférése
inline T* operator->() const { return ctrl_->ptr() + offset_; }
/// jelenleg offsettel kiválaszott elem dereferálása
inline T& operator*() const { return *(ctrl_->ptr() + offset_); }
/// t != ctrl_->t + offset
inline bool operator==(const T* t) const { return t == ctrl_->ptr() + offset_; }
/// t != ctrl_->t + offset
inline bool operator!=(const T* t) const { return t != ctrl_->ptr() + offset_; }
/// sp.ctrl_->t == ctrl_->t + offset
inline bool operator==(const Abstract_SmartPointer<T>& sp) const { return sp.ctrl_->ptr() == ctrl_->ptr(); }
/// sp.ctrl_->t != ctrl_->t + offset
inline bool operator!=(const Abstract_SmartPointer<T>& sp) const { return sp.ctrl_->ptr() != ctrl_->ptr(); }
/// sp.ctrl_->t + sp.offset == ctrl_->t + offset
inline bool operator==(const Abstract_SmartPointer<T[]>& sp) const { return sp.ctrl_->ptr() + sp.offset() == ctrl_->ptr() + offset_; }
/// sp.ctrl_->t + sp.offset != ctrl_->t + offset
inline bool operator!=(const Abstract_SmartPointer<T[]>& sp) const { return sp.ctrl_->ptr() + sp.offset() != ctrl_->ptr() + offset_; }
};
}
#endif // !SMART_PTR_Hl
|
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <memory.h>
using namespace std;
typedef unsigned long long ULL;
int A[555][555];
int minim[555][555][555];
int main() {
freopen(".in", "r", stdin);
int a, b, n, m;
cin >> a >> b >> n >> m;
for (int i = 1; i <= n; ++i) {
for (int j = 1; j <= m; ++j) {
cin >> A[i][j];
}
for (int j = 1; j <= m; ++j) {
int mi = 2e9;
for (int k = j; k <= m; ++k) {
mi = min(mi, A[i][k]);
minim[j][k][i] = mi;
}
}
}
int So = n * m;
int ans = 0;
for (int bb = 1; bb <= b || bb <= a; ++bb) {
for (int j = 1; j + bb - 1 <= m; ++j) {
const int l = j;
const int r = j + bb - 1;
for (int i = 1; i <= n; ++i) {
int mi = 2e9;
for (int aa = 1; i + aa - 1 <= n && aa <= a || aa <= b; ++aa) if (aa <= a && bb <= b || aa <= b && bb <= a) {
mi = min(mi, minim[l][r][i + aa - 1]);
const int nu = mi * So;
const int denu = So - aa * bb;
const int V = ((nu - 1) / denu) * aa * bb;
if (V > ans)
ans = V;
}
}
}
}
cout << ans << endl;
return 0;
}
|
//
// C++ Implementation: wrapper
//
// Description:
//
//
// Author: Jally <jallyx@163.com>, (C) 2008
//
// Copyright: See COPYING file that comes with this distribution
//
//
#include "wrapper.h"
#include "deplib.h"
/**
* 写出数据.
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区有效数据长度
* @return 成功写出的数据长度
*/
ssize_t xwrite(int fd, const void *buf, size_t count)
{
size_t offset;
ssize_t size;
size = -1;
offset = 0;
while ((offset != count) && (size != 0)) {
if ((size = write(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
offset += size;
}
return offset;
}
/**
* 读取数据.
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区长度
* @return 成功读取的数据长度
*/
ssize_t xread(int fd, void *buf, size_t count)
{
size_t offset;
ssize_t size;
size = -1;
offset = 0;
while ((offset != count) && (size != 0)) {
if ((size = read(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
offset += size;
}
return offset;
}
/**
* 读取ipmsg消息前缀.
* Ver(1):PacketNo:SenderName:SenderHost:CommandNo:AdditionalSection.\n
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区长度
* @return 成功读取的消息长度,-1表示读取消息出错
*/
ssize_t read_ipmsg_prefix(int fd, void *buf, size_t count)
{
uint number;
size_t offset;
ssize_t size;
size = -1;
offset = 0;
number = 0;
while ((offset != count) && (size != 0)) {
if ((size = read(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
offset += size;
const char *endptr = (const char *)buf + offset;
for (const char *curptr = endptr - size; curptr < endptr; ++curptr) {
if (*curptr == ':')
++number;
}
if (number >= 5)
break;
}
return offset;
}
/**
* 读取ipmsg文件请求消息前缀.
* packetID:fileID:offset.\n
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区长度
* @param offset 缓冲区无效数据偏移量
* @return 成功读取的消息长度,-1表示读取消息出错
*/
ssize_t read_ipmsg_filedata(int fd, void *buf, size_t count, size_t offset)
{
const char *curptr;
uint number;
ssize_t size;
size = -1;
number = 0;
curptr = (const char *)buf;
while ((offset != count) && (size != 0)) {
const char *endptr = (const char *)buf + offset;
for (; curptr < endptr; ++curptr) {
if (*curptr == ':')
++number;
}
if (number > 2 || (number == 2 && *(curptr - 1) != ':'))
break;
if ((size = read(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
offset += size;
}
return offset;
}
/**
* 读取ipmsg目录请求消息前缀.
* packetID:fileID.\n
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区长度
* @param offset 缓冲区无效数据偏移量
* @return 成功读取的消息长度,-1表示读取消息出错
*/
ssize_t read_ipmsg_dirfiles(int fd, void *buf, size_t count, size_t offset)
{
const char *curptr;
uint number;
ssize_t size;
size = -1;
number = 0;
curptr = (const char *)buf;
while ((offset != count) && (size != 0)) {
const char *endptr = (const char *)buf + offset;
for (; curptr < endptr; ++curptr) {
if (*curptr == ':')
++number;
}
if (number > 1 || (number == 1 && *(curptr - 1) != ':'))
break;
if ((size = read(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
continue;
return -1;
}
offset += size;
}
return offset;
}
/**
* 读取ipmsg文件头信息.
* 本函数的退出条件为: \n
* 1.缓冲区内必须要有数据; \n
* 2.文件头长度必须能够被获得; \n
* 3.文件头长度必须小于或等于缓冲区内已有数据长度; \n
* 4.读取数据出错(晕,这还值得怀疑吗?). \n
* @param fd 文件描述符
* @param buf 缓冲区
* @param count 缓冲区长度
* @param offset 缓冲区无效数据偏移量
* @return 成功读取的信息长度
*/
ssize_t read_ipmsg_fileinfo(int fd, void *buf, size_t count, size_t offset)
{
ssize_t size;
uint32_t headsize;
if (offset < count) //注意不要写到缓冲区外了
((char *)buf)[offset] = '\0';
while (!offset || !strchr((char *)buf, ':')
|| sscanf((char *)buf, "%" SCNx32, &headsize) != 1
|| headsize > offset) {
mark: if ((size = read(fd, (char *)buf + offset, count - offset)) == -1) {
if (errno == EINTR)
goto mark;
return -1;
} else if (size == 0)
return -1;
if ((offset += size) == count)
break;
((char *)buf)[offset] = '\0';
}
return offset;
}
|
#include <iostream>
#include <boost/make_shared.hpp>
#include <boost/program_options.hpp>
namespace po = boost::program_options;
#include <bs/frame_range.hpp>
#include <bs/utils.hpp>
#include <bs/adaptive_median.hpp>
#include <options.hpp>
#include <run.hpp>
//
// options_t::options_t is specific to each example:
//
options_t::options_t (int argc, char** argv) {
{
auto tmp = std::make_pair (
"program", po::variable_value (std::string (argv [0]), false));
map_.insert (tmp);
}
po::options_description generic ("Generic options");
po::options_description config ("Configuration options");
generic.add_options ()
("version", "version")
("help", "this");
config.add_options ()
("display,d", "display frames.")
("input,i", po::value< std::string > ()->default_value ("0"),
"input (file or stream index).")
("frame-interval,f", po::value< size_t > ()->default_value (10),
"frame sampling interval.")
("threshold,t", po::value< size_t > ()->default_value (15),
"threshold value");
desc_ = boost::make_shared< po::options_description > ();
desc_->add (generic);
desc_->add (config);
store (po::command_line_parser (argc, argv).options (*desc_).run (), map_);
notify (map_);
}
////////////////////////////////////////////////////////////////////////
static void
program_options_from (int& argc, char** argv) {
bool complete_invocation = false;
options_t program_options (argc, argv);
if (program_options.have ("version")) {
std::cout << "OpenCV v3.1\n";
complete_invocation = true;
}
if (program_options.have ("help")) {
std::cout << program_options.description () << std::endl;
complete_invocation = true;
}
if (complete_invocation)
exit (0);
global_options (program_options);
}
////////////////////////////////////////////////////////////////////////
static void
process_adaptive_median (cv::VideoCapture& cap, const options_t& opts) {
const bool display = opts.have ("display");
//
// Bootstrap from the first frame:
//
cv::Mat background = bs::scale_frame (*bs::getframes_from (cap).begin ());
bs::adaptive_median_t adaptive_median (
background,
opts ["frame-interval"].as< size_t > (),
opts ["threshold"].as< size_t > ());
for (auto& frame : bs::getframes_from (cap)) {
bs::frame_delay temp { 10 };
auto mask = adaptive_median (bs::scale_frame (frame));
if (display)
imshow ("Adaptive median difference", mask);
if (temp.wait_for_key (27))
break;
}
}
////////////////////////////////////////////////////////////////////////
int main (int argc, char** argv) {
program_options_from (argc, argv);
return run_with (process_adaptive_median, global_options ()), 0;
}
|
#include "stdafx.h"
#include "Vector2d.h"
Vector2d::Vector2d()
{
this->x = 0;
this->y = 0;
}
Vector2d::Vector2d(double x, double y)
{
this->x = x;
this->y = y;
}
Vector2d::Vector2d(double x0, double x1, double y0, double y1)
{
this->x = x1 - x0;
this->y = y1 - y0;
}
Vector2d::Vector2d(const Vector2d& vector)
{
this->x = vector.x;
this->y = vector.y;
}
Vector2d::~Vector2d()
{
}
void Vector2d::setx(double x)
{
this->x = x;
}
double Vector2d::getx()
{
return this->x;
}
void Vector2d::sety(double y)
{
this->y = y;
}
double Vector2d::gety()
{
return this->y;
}
Vector2d Vector2d::operator+(const Vector2d& vector) const
{
return Vector2d(this->x + vector.x, this->y + vector.y);
}
Vector2d Vector2d::operator-(const Vector2d& vector) const
{
return Vector2d(this->x - vector.x, this->y - vector.y);
}
Vector2d Vector2d::operator*(double a) const
{
return Vector2d(this->x * a, this->y * a);
}
Vector2d operator*(double a, Vector2d& vector)
{
return vector * a;
}
double Vector2d::operator*(const Vector2d& vector) const
{
return this->x * vector.x + this->y * vector.y;
}
Vector2d& Vector2d::operator++()
{
x++;
y++;
return *this;
}
Vector2d Vector2d::operator++(int)
{
Vector2d temp(x, y);
x++;
y++;
return temp;
}
Vector2d& Vector2d::operator--()
{
x--;
y--;
return *this;
}
Vector2d Vector2d::operator--(int)
{
Vector2d temp(x, y);
x--;
y--;
return temp;
}
const Vector2d& Vector2d::operator+=(const Vector2d &vector)
{
x += vector.x;
y += vector.y;
return *this;
}
const Vector2d& Vector2d::operator-=(const Vector2d &vector)
{
x -= vector.x;
y -= vector.y;
return *this;
}
const Vector2d& Vector2d::operator*=(double a)
{
x *= a;
y *= a;
return *this;
}
Vector2d::operator std::string()
{
std::string s = "(" + std::to_string(x) + ";" + std::to_string(y) + ")";
return s;
}
double Vector2d::length()
{
return sqrt(this->x * this->x + this->y * this->y);
}
double Vector2d::Cos(Vector2d other)
{
return this->operator*(other) / (this->length() * other.length());
}
double Vector2d::tangent(Vector2d vector)
{
return tan(acos(this->Cos(vector)));
}
|
#pragma once
class AI_SpiderBotBehavior : public Hourglass::IAction
{
public:
void LoadFromXML(tinyxml2::XMLElement* data);
void Init(hg::Entity* entity);
IBehavior::Result Update(hg::Entity* entity);
IBehavior* MakeCopy() const;
private:
// Test if ready to jump
bool SpiderJump_CheckCondition(hg::Entity* entity) const;
void SpiderJump_Update(hg::Entity* entity);
void SpiderChase_Update(hg::Entity* entity);
bool SpiderAttack_CheckCondition(hg::Entity* entity) const;
void SpiderAttack_Update(hg::Entity* entity);
void Attack(hg::Entity* owner);
private:
//struct Anims
//{
// // full body
// StrID idle;
// StrID walk;
// StrID jump;
// StrID bigJump;
//} m_Anims;
//hg::Animation* animation = nullptr;
hg::Entity* m_Target;
hg::Animation* m_Animation;
bool m_Deployed;
float m_JumpStartTime;
float m_JumpTimer;
Vector3 m_JumpStartPoint;
Vector3 m_JumpEndPoint;
float m_AttackStartTime;
float m_AttackTimer;
float m_VelocityY;
float m_ClickSoundTimer;
uint8_t m_State;
};
|
#include "space.h"
#include <time.h>
#include <cmath>
#include <thread>
space::space(unsigned int number_of_planets){
srand( time(0) );
zoom = 1;
generate(number_of_planets);
start();
}
space::space(){
zoom = 1;
srand( time(0) );
}
void space::generate(unsigned int number_of_planets){
std::lock_guard<std::mutex> lock(planets_access_mutex);
object temp;
planets.reserve(number_of_planets);
for (int i(0); i < number_of_planets; i++) {
temp.pos_x = rand() % CONSTS::width + 1;
temp.pos_y = rand() % CONSTS::height + 1;
planets.push_back(temp);
}
}
void space::start(){
window = new sf::RenderWindow(sf::VideoMode(CONSTS::width, CONSTS::height), "Gravity++");
std::thread physics_thread(&space::logic_loop, this);
render_event_loop();
if (physics_thread.joinable()) physics_thread.join();
}
void space::clear(){
std::lock_guard<std::mutex> lock(planets_access_mutex);
planets.clear();
}
void space::render_planet(object planet){
sf::CircleShape circle;
circle.setRadius(planet.radius);
circle.setFillColor(sf::Color::White);
circle.setPosition(planet.pos_x, planet.pos_y);
window->draw(circle);
}
void space::draw_all_planets(){
std::lock_guard<std::mutex> lock(planets_access_mutex);
for(int i(0); i != planets.size(); ++i){
render_planet(planets[i]);
}
}
void space::process_all_planets(){
std::vector<object> new_planets_state;
{
std::lock_guard<std::mutex> lock(planets_access_mutex);
new_planets_state = planets;
}
for(int i = 0; i < new_planets_state.size(); ++i){
for(int j = 0; j < new_planets_state.size(); ++j){
if(i == j) continue;
// TODO: Is distance computation expensive?
if( object::distance(new_planets_state[i], new_planets_state[j]) <=
(new_planets_state[i].radius + new_planets_state[j].radius) ||
object::distance(new_planets_state[i], new_planets_state[j]) == 0){
if(new_planets_state[j].mas > new_planets_state[i].mas){
new_planets_state[j].merge(new_planets_state[i]);
auto it_i = new_planets_state.begin() + i;
new_planets_state.erase(it_i);
} else {
new_planets_state[i].merge(new_planets_state[j]);
auto it_j = new_planets_state.begin() + j;
// TODO: Does it worth optimizing out this costly erase?
new_planets_state.erase(it_j);
}
// it is possible that we are shrink our vector and i become out-of-bounds.
if (i >= new_planets_state.size()) {
break;
}
} else {
new_planets_state[j].acceleration(new_planets_state[i]);
new_planets_state[i].acceleration(new_planets_state[j]);
}
} //for(j)
new_planets_state[i].pos_x += new_planets_state[i].acceleration_x;
new_planets_state[i].pos_y += new_planets_state[i].acceleration_y;
} //for (i)
std::lock_guard<std::mutex> lock(planets_access_mutex);
planets = new_planets_state;
}
void space::logic_loop(){
static const unsigned tps_limit_base = 1000;
sf::Clock tps_counter_reset;
unsigned tps = 0;
while (window->isOpen()){
if (tps_counter_reset.getElapsedTime() >= sf::seconds(1)){
tps = 0;
tps_counter_reset.restart();
}
sf::sleep(sf::seconds(1.0/(tps_limit_base * tps_limit_multipler)));
process_all_planets();
++tps;
}
}
void space::render_event_loop(){
while (window->isOpen()){
sf::Event event;
while (window->pollEvent(event)){
if (event.type == sf::Event::Closed)
window->close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::F5)){
this->clear();
this->generate(200);
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape)){
window->close();
break;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Equal)){
if(zoom < 10)
zoom = zoom + 0.1;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Dash)){
if(zoom > 0)
zoom = zoom - 0.1;
}
window->clear();
draw_all_planets();
sf::View view = window->getDefaultView();
view.zoom(zoom);
window->setView(view);
window->display();
}
}
|
#include "window.h"
Window::Window(int w, int h)
: w(w), h(h) , shaderManager("shaders/", ".glsl", true)
{
if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_AUDIO | SDL_INIT_TIMER)) {
std::cerr << "SDL_Init() failed" << std::endl;
assert(0);
}
SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24);
SDL_GL_SetAttribute(SDL_GL_RED_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_GREEN_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_BLUE_SIZE, 8);
SDL_GL_SetAttribute(SDL_GL_ALPHA_SIZE, 8);
Uint32 flags = SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN;
sdlWindow = SDL_CreateWindow("CG", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, w, h, flags );
assert(sdlWindow);
context = SDL_GL_CreateContext( sdlWindow );
assert(context);
// Setup glew
if (glewInit() != GLEW_OK) {
std::cerr << "glewInit() failed." << std::endl;
SDL_Quit();
assert(0);
}
std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;
imgui.init(sdlWindow);
}
Window::~Window()
{
SDL_Quit();
}
void Window::startMainLoop()
{
int startTime = SDL_GetTicks();
int previousTime = startTime;
// Mainloop
bool running = true;
while (running) {
int currentTime = SDL_GetTicks() - startTime;
SDL_Event event;
while (SDL_PollEvent(&event) > 0) {
imgui.processEvent(event);
if (event.type == SDL_QUIT || (event.type == SDL_KEYDOWN && event.key.keysym.sym == SDLK_ESCAPE)) {
running = false;
break;
}
}
if (!running) break;
float dt = (currentTime - previousTime) / 1000.0f;
update(dt);
render();
imgui.beginFrame();
renderGui();
imgui.endFrame();
SDL_GL_SwapWindow( sdlWindow );
previousTime = currentTime;
}
}
|
#ifndef GETSEARCHBIN_H
#define GETSEARCHBIN_H
#include "units.hh"
#include "TypeDefinitions.h"
#include "PhotonTools.h"
#include "SusyAnaTools/Tools/NTupleReader.h"
#include "SusyAnaTools/Tools/customize.h"
#include "SusyAnaTools/Tools/searchBins.h"
#include "SusyAnaTools/Tools/SB2018.h"
#include "SusyAnaTools/Tools/SusyUtility.h"
#include "ScaleFactors.h"
#include "ScaleFactorsttBar.h"
#include <vector>
#include <iostream>
#include <string>
#include <set>
#include <fstream>
// Repo for json.hpp: https://github.com/nlohmann/json/tree/master
#include "nlohmann/json.hpp"
using json = nlohmann::json;
namespace plotterFunctions
{
class GetSearchBin
{
private:
// json file containing unit mapping
json json_;
std::string suffix_;
std::string met_name_ = "MET_pt";
std::map<std::string, std::string> prefixMap = {
{"/binNum", "bin_"},
{"/unitCRNum/qcdcr", "bin_qcdcr_"},
{"/unitCRNum/lepcr", "bin_lepcr_"},
{"/unitCRNum/phocr", "bin_phocr_"},
{"/unitSRNum", "bin_"},
};
void getSearchBin(NTupleReader& tr)
{
bool doUnits = true;
// --- determine MET variable --- //
std::string met_label = "MET_pt";
if (suffix_.find("drPhotonCleaned") != std::string::npos)
{
met_label = "metWithPhoton";
}
else if (suffix_.find("METUnClustUp") != std::string::npos)
{
met_label = "MET_pt_unclustEnUp";
}
else if (suffix_.find("METUnClustDown") != std::string::npos)
{
met_label = "MET_pt_unclustEnDown";
}
// --- JES --- //
if (suffix_.find("jesTotalUp") != std::string::npos)
{
met_label = met_label + "_jesTotalUp";
}
else if (suffix_.find("jesTotalDown") != std::string::npos)
{
met_label = met_label + "_jesTotalUp";
}
// For photon CR, we need to use _drPhotonCleaned for all variables and metWithPhoton
const auto& run = tr.getVar<unsigned int>("run");
const auto& luminosityBlock = tr.getVar<unsigned int>("luminosityBlock");
const auto& event = tr.getVar<unsigned long long>("event");
const auto& met = tr.getVar<data_t>(met_label);
const auto& Pass_PhoCR = tr.getVar<bool>("passPhotonSelection");
const auto& SAT_Pass_Baseline = tr.getVar<bool>("SAT_Pass_Baseline" + suffix_);
const auto& SAT_Pass_lowDM = tr.getVar<bool>("SAT_Pass_lowDM" + suffix_);
const auto& SAT_Pass_highDM = tr.getVar<bool>("SAT_Pass_highDM" + suffix_);
const auto& nJets = tr.getVar<int>("nJets" + suffix_);
const auto& nBottoms = tr.getVar<int>("nBottoms" + suffix_);
const auto& nSoftBottoms = tr.getVar<int>("nSoftBottoms" + suffix_);
const auto& nMergedTops = tr.getVar<int>("nMergedTops" + suffix_);
const auto& nResolvedTops = tr.getVar<int>("nResolvedTops" + suffix_);
const auto& nWs = tr.getVar<int>("nWs" + suffix_);
const auto& ht = tr.getVar<data_t>("HT" + suffix_);
const auto& ptb = tr.getVar<data_t>("ptb" + suffix_);
const auto& mtb = tr.getVar<data_t>("mtb" + suffix_);
const auto& ISRJetPt = tr.getVar<data_t>("ISRJetPt" + suffix_);
//------------------------------------------------//
//--- Updated Search Bins: SBv4 (October 2019) ---//
//------------------------------------------------//
// int SBv4_lowdm(int njets, int nb, int nSV, float ISRpt, float bottompt_scalar_sum, float met)
// int SBv4_highdm(float mtb, int njets, int nb, int ntop, int nw, int nres, float ht, float met)
int nSearchBinLowDM = SBv4_lowdm(nJets, nBottoms, nSoftBottoms, ISRJetPt, ptb, met);
int nSearchBinHighDM = SBv4_highdm(mtb, nJets, nBottoms, nMergedTops, nWs, nResolvedTops, ht, met);
//------------------------------------------------------//
//--- Updated Validation Bins: SBv3 (September 2019) ---//
//------------------------------------------------------//
// int SBv3_lowdm_validation(int njets, int nb, int nSV, float ISRpt, float bottompt_scalar_sum, float met)
// int SBv3_lowdm_validation_high_MET(int nb, int nSV, float ISRpt, float met)
// int SBv3_highdm_validation(float mtb, int njets, int ntop, int nw, int nres, int nb, float met)
int nValidationBinLowDM = SBv3_lowdm_validation(nJets, nBottoms, nSoftBottoms, ISRJetPt, ptb, met);
int nValidationBinLowDMHighMET = SBv3_lowdm_validation_high_MET(nBottoms, nSoftBottoms, ISRJetPt, met);
int nValidationBinHighDM = SBv3_highdm_validation(mtb, nJets, nMergedTops, nWs, nResolvedTops, nBottoms, met);
//-------------------------------------------------------//
//--- MET Study Validation Bins: SBv3 (February 2020) ---//
//-------------------------------------------------------//
// New validation bins for MET study:
// - low dm MET binning. Use them under low dm med dPhi cuts, same as the last 4 bins of low dm validation:
// - https://github.com/susy2015/SusyAnaTools/blob/hui_nanoAOD/Tools/SB2018.h#L868-L876
// - high dm MET binning. Use them under high dm med dPhi cuts, same as all the high dm validation bins:
// - https://github.com/susy2015/SusyAnaTools/blob/hui_nanoAOD/Tools/SB2018.h#L942-L951
// int lowdm_validation_MET(float ISRpt, float met)
// int highdm_validation_MET(float mtb, int ntop, int nw, int nres, float met)
int nValidationBinLowDM_METStudy = lowdm_validation_MET(ISRJetPt, met);
int nValidationBinHighDM_METStudy = highdm_validation_MET(mtb, nMergedTops, nWs, nResolvedTops, met);
//----------------------------------------//
//--- Updated Unit Bins (December 2019) ---//
//----------------------------------------//
int nSBLowDM = -1;
int nSBHighDM = -1;
int nCRUnitLowDM = -1;
int nCRUnitHighDM = -1;
int nSRUnitLowDM = -1;
int nSRUnitHighDM = -1;
// ---------------------------- Fast version from Jon
// syntax
//int SRbin(Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, HighDM, LowDM, nb, mtb, ptb, MET, nSoftB, njets, ISRpt, HT, nres, ntop, nw);
//int SRunit(Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, HighDM, LowDM, nb, mtb, ptb, MET, nSoftB, njets, ISRpt, HT, nres, ntop, nw);
//int QCDCRunit(Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, HighDM, LowDM, nb, mtb, ptb, MET, nSoftB, njets, ISRpt, HT, nres, ntop, nw);
//int lepCRunit(Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, HighDM, LowDM, nb, mtb, ptb, MET, nSoftB, njets, ISRpt, HT, nres, ntop, nw);
//int phoCRunit(Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, HighDM, LowDM, nb, mtb, ptb, MET, nSoftB, njets, ISRpt, HT, nres, ntop, nw);
if (doUnits)
{
const bool Pass_QCDCR = false;
const bool Pass_LepCR = false;
int nSB = SRbin( SAT_Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, SAT_Pass_highDM, SAT_Pass_lowDM, nBottoms, mtb, ptb, met, nSoftBottoms, nJets, ISRJetPt, ht, nResolvedTops, nMergedTops, nWs);
int nCRUnit = phoCRunit( SAT_Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, SAT_Pass_highDM, SAT_Pass_lowDM, nBottoms, mtb, ptb, met, nSoftBottoms, nJets, ISRJetPt, ht, nResolvedTops, nMergedTops, nWs);
int nSRUnit = SRunit( SAT_Pass_Baseline, Pass_QCDCR, Pass_LepCR, Pass_PhoCR, SAT_Pass_highDM, SAT_Pass_lowDM, nBottoms, mtb, ptb, met, nSoftBottoms, nJets, ISRJetPt, ht, nResolvedTops, nMergedTops, nWs);
// --- testing
//bool isFavoriteBin = bool(nCRUnit >= 53 && nCRUnit <= 60);
//if (isFavoriteBin)
//{
// printf("Found a favorite bin: nCRUnit = %d; SAT_Pass_lowDM = %d, SAT_Pass_highDM = %d\n", nCRUnit, SAT_Pass_lowDM, SAT_Pass_highDM);
//}
if (SAT_Pass_lowDM)
{
nSBLowDM = nSB;
nCRUnitLowDM = nCRUnit;
nSRUnitLowDM = nSRUnit;
}
else if (SAT_Pass_highDM)
{
nSBHighDM = nSB;
nCRUnitHighDM = nCRUnit;
nSRUnitHighDM = nSRUnit;
}
}
// check selection in search region
//if (suffix_.compare("_drPhotonCleaned_jetpt30") == 0)
if (suffix_.compare("_jetpt30") == 0)
{
// compare search bins (hui) vs. search bin units (matt)
//if (SAT_Pass_lowDM)
//{
// if (! (nSearchBinLowDM < 0 && nSBLowDM < 0))
// {
// printf("LowDM; %s; nSB_hui = %d; nSB_matt = %d, nCRUnit = %d, nSRUnit = %d", suffix_.c_str(), nSearchBinLowDM, nSBLowDM, nCRUnitLowDM, nSRUnitLowDM);
// if(nSearchBinLowDM != nSBLowDM) printf(" --- nSB are different --- ");
// printf("\n");
// }
//}
//if (SAT_Pass_highDM)
//{
// if (! (nSearchBinHighDM < 0 && nSBHighDM < 0))
// {
// printf("HighDM; %s; nSB_hui = %d; nSB_matt = %d, nCRUnit = %d, nSRUnit = %d", suffix_.c_str(), nSearchBinHighDM, nSBHighDM, nCRUnitHighDM, nSRUnitHighDM);
// if(nSearchBinHighDM != nSBHighDM) printf(" --- nSB are different --- ");
// printf("\n");
// }
//}
// print if search bin numbers calculated using different methods are not equal
if (SAT_Pass_lowDM && (nSearchBinLowDM != nSBLowDM))
{
printf("CMS_event=%llu; LowDM; %s; nSB_hui = %d; nSB_matt = %d --- nSB are different --- \n", event, suffix_.c_str(), nSearchBinLowDM, nSBLowDM);
}
if (SAT_Pass_highDM && (nSearchBinHighDM != nSBHighDM))
{
printf("CMS_event=%llu; HighDM; %s; nSB_hui = %d; nSB_matt = %d --- nSB are different --- \n", event, suffix_.c_str(), nSearchBinHighDM, nSBHighDM);
}
// get event info to show event displays
//if (SAT_Pass_lowDM && nSearchBinLowDM >= 0)
//{
// printf("lowdm_sb=%d; run=%d; luminosityBlock=%d; CMS_event=%llu; ntuple_event=%d\n", nSearchBinLowDM, run, luminosityBlock, event, tr.getEvtNum());
//}
//if (SAT_Pass_highDM && nSearchBinHighDM >= 0)
//{
// printf("highdm_sb=%d; run=%d; luminosityBlock=%d; CMS_event=%llu; ntuple_event=%d\n", nSearchBinHighDM, run, luminosityBlock, event, tr.getEvtNum());
//}
}
// search bins
tr.registerDerivedVar("nSearchBinLowDM" + suffix_, nSearchBinLowDM);
tr.registerDerivedVar("nSearchBinHighDM" + suffix_, nSearchBinHighDM);
// validation bins
tr.registerDerivedVar("nValidationBinLowDM" + suffix_, nValidationBinLowDM);
tr.registerDerivedVar("nValidationBinLowDMHighMET" + suffix_, nValidationBinLowDMHighMET);
tr.registerDerivedVar("nValidationBinHighDM" + suffix_, nValidationBinHighDM);
// validation bins MET study
tr.registerDerivedVar("nValidationBinLowDM_METStudy" + suffix_, nValidationBinLowDM_METStudy);
tr.registerDerivedVar("nValidationBinHighDM_METStudy" + suffix_, nValidationBinHighDM_METStudy);
// unit bins
tr.registerDerivedVar("nSBLowDM" + suffix_, nSBLowDM);
tr.registerDerivedVar("nSBHighDM" + suffix_, nSBHighDM);
tr.registerDerivedVar("nCRUnitLowDM" + suffix_, nCRUnitLowDM);
tr.registerDerivedVar("nCRUnitHighDM" + suffix_, nCRUnitHighDM);
tr.registerDerivedVar("nSRUnitLowDM" + suffix_, nSRUnitLowDM);
tr.registerDerivedVar("nSRUnitHighDM" + suffix_, nSRUnitHighDM);
}
public:
GetSearchBin(std::string suffix = "") : suffix_(suffix)
{
bool print = false;
const std::string fileName = "dc_BkgPred_BinMaps_master.json";
loadJson(fileName);
// print json file for testing
if (print)
{
// void printJson(const std::string& fileName, const std::string& key, const std::string& title)
SusyUtility::printJson(fileName, "binNum", "Search Bins");
SusyUtility::printJson(fileName, "unitCRNum", "Control Region Units");
SusyUtility::printJson(fileName, "unitSRNum", "Search Region Units");
}
}
~GetSearchBin(){}
// load json file
void loadJson(const std::string& fileName)
{
// check if file exists
bool file_exists = SusyUtility::fileExists(fileName);
if(file_exists)
{
// read json file
std::ifstream i(fileName);
i >> json_;
}
else
{
std::cout << "Failed to open the file " << fileName << ". This file is needed in GetSearchBin.h to apply unit bin selection." << std::endl;
}
}
// See this link for cut definitions
// https://github.com/mkilpatr/EstToolsSUSY/blob/SBv4/SUSYNano19/SRParameters_dc.hh#L122
// 11 variables: 11 pass fuctions
// also 1 function for using total number of top/W
// 12 pass functions in total
bool pass_njets(const std::string& cut, int value)
{
if (cut.compare("nj2to5") == 0) return bool(value >= 2 && value <= 5);
else if (cut.compare("nj6") == 0) return bool(value >= 6);
else if (cut.compare("nj7") == 0) return bool(value >= 7);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_nb(const std::string& cut, int value)
{
if (cut.compare("nb0") == 0) return bool(value == 0);
else if (cut.compare("nb1") == 0) return bool(value == 1);
else if (cut.compare("nbgeq1") == 0) return bool(value >= 1);
else if (cut.compare("nb2") == 0) return bool(value >= 2);
else if (cut.compare("nbeq2") == 0) return bool(value == 2);
else if (cut.compare("nb3") == 0) return bool(value >= 3);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_nsv(const std::string& cut, int value)
{
if (cut.compare("nivf0") == 0) return bool(value == 0);
else if (cut.compare("nivf1") == 0) return bool(value >= 1);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
// note: nrtntnw* and nrt* both start with nrt; be careful about this case
// check for nrtntnw* before nrt*
bool pass_nTotalTopW(const std::string& cut, int value)
{
if (cut.compare("nrtntnwgeq2") == 0) return bool(value >= 2);
else if (cut.compare("nrtntnwgeq3") == 0) return bool(value >= 3);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_ntop(const std::string& cut, int value)
{
if (cut.compare("nt0") == 0) return bool(value == 0);
else if (cut.compare("nt1") == 0) return bool(value == 1);
else if (cut.compare("nt2") == 0) return bool(value == 2);
else if (cut.compare("ntgeq1") == 0) return bool(value >= 1);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_nw(const std::string& cut, int value)
{
if (cut.compare("nw0") == 0) return bool(value == 0);
else if (cut.compare("nw1") == 0) return bool(value == 1);
else if (cut.compare("nw2") == 0) return bool(value == 2);
else if (cut.compare("nwgeq1") == 0) return bool(value >= 1);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_nres(const std::string& cut, int value)
{
if (cut.compare("nrt0") == 0) return bool(value == 0);
else if (cut.compare("nrt1") == 0) return bool(value == 1);
else if (cut.compare("nrt2") == 0) return bool(value == 2);
else if (cut.compare("nrtgeq1") == 0) return bool(value >= 1);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_ISRpt(const std::string& cut, float value)
{
if (cut.compare("lowptisr") == 0) return bool(value >= 300 && value < 500);
else if (cut.compare("medptisr") == 0) return bool(value >= 300);
else if (cut.compare("highptisr") == 0) return bool(value >= 500);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_mtb(const std::string& cut, float value)
{
if (cut.compare("lowmtb") == 0) return bool(value < 175);
else if (cut.compare("highmtb") == 0) return bool(value >= 175);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_ptb(const std::string& cut, float value)
{
if (cut.compare("lowptb") == 0) return bool(value < 40);
else if (cut.compare("medptb") == 0) return bool(value >= 40 && value < 70);
else if (cut.compare("highptb") == 0) return bool(value >= 70);
else if (cut.compare("lowptb12") == 0) return bool(value < 80);
else if (cut.compare("medptb12") == 0) return bool(value >= 80 && value < 140);
else if (cut.compare("highptb12") == 0) return bool(value >= 140);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_ht(const std::string& cut, float value)
{
if (cut.compare("htlt1000") == 0) return bool(value < 1000);
else if (cut.compare("htgt1000") == 0) return bool(value >= 1000);
else if (cut.compare("ht1000to1500") == 0) return bool(value >= 1000 && value < 1500);
else if (cut.compare("htgt1500") == 0) return bool(value >= 1500);
else if (cut.compare("htlt1300") == 0) return bool(value < 1300);
else if (cut.compare("htgt1300") == 0) return bool(value >= 1300);
else if (cut.compare("ht1000to1300") == 0) return bool(value >= 1000 && value < 1300);
else if (cut.compare("ht1300to1500") == 0) return bool(value >= 1300 && value < 1500);
else std::cout << "ERROR in " << __func__ << ": No string match found for " << cut << std::endl;
return false;
}
bool pass_met(const std::string& cut, float value)
{
// example: MET_pt450to550, MET_pt550to650, MET_pt650to750, MET_pt750toinf
std::string separator = "to";
// check that string begins with met name
if (cut.find(met_name_) != 0)
{
std::cout << "ERROR in " << __func__ << ": The cut " << cut << " does not being with " << met_name_ << std::endl;
return false;
}
int met_len = met_name_.length();
int sep_len = separator.length();
int sep_pos = cut.find(separator);
int min_len = sep_pos - met_len;
std::string min = cut.substr(met_len, min_len);
std::string max = cut.substr(sep_pos + sep_len);
//printf("%s: [%s, %s]\n", cut.c_str(), min.c_str(), max.c_str());
// if max in inf, only apply min cut
if (max.compare("inf") == 0)
{
float min_val = std::stoi(min);
return bool(value >= min_val);
}
// otherwise, apply both min and max cuts
else
{
float min_val = std::stoi(min);
float max_val = std::stoi(max);
return bool(value >= min_val && value < max_val);
}
}
// return vector of strings of cuts from unit string
// split out beginning of unit name
// note that MET_pt has '_' in name
std::vector<std::string> getCutVec(const std::string& unit, const std::string& start)
{
std::vector<std::string> cuts;
const char delim = '_';
int start_len = start.length();
int met_pos = unit.find(met_name_);
int final_len = met_pos - start_len - 1;
std::string parsedUnit = unit.substr(start_len, final_len);
std::string met_cut = unit.substr(met_pos);
SusyUtility::splitString(parsedUnit, delim, cuts);
cuts.push_back(met_cut);
return cuts;
}
// return true if event passes unit selection, otherwise return false
bool passUnitLowDM(const std::string& unit, const std::string& prefix, int njets, int nb, int nsv, float ISRpt, float ptb, float met)
{
//printf("%s: %s\n", __func__, unit.c_str());
// check if unit is low dm
if (unit.find(prefix) == 0)
{
std::vector<std::string> cuts = getCutVec(unit, prefix);
//printf("%s: ", unit.c_str());
//for (const auto& c : cuts)
//{
// printf("%s, ", c.c_str());
//}
//printf("\n");
for (const auto& c : cuts)
{
// note; be careful about order as some cuts may begin with the same string
// optimization: if we do not pass a cut, return false
//printf("%s, ", c.c_str());
if (c.find("nj") == 0)
{
if (! pass_njets(c, njets))
{
return false;
}
}
else if (c.find("nb") == 0)
{
if (! pass_nb(c, nb))
{
return false;
}
}
else if (c.find("nivf") == 0)
{
if (! pass_nsv(c, nsv))
{
return false;
}
}
else if (c.find("isr") != std::string::npos)
{
if (! pass_ISRpt(c, ISRpt))
{
return false;
}
}
else if (c.find("ptb") != std::string::npos)
{
if (! pass_ptb(c, ptb))
{
return false;
}
}
else if (c.find("MET_pt") == 0)
{
if (! pass_met(c, met))
{
return false;
}
}
// skip lowmtb
// - lowmtb appears in some, but not all low dm search bins
// - lowmtb does not need to be applied for low dm search bins as it is included in low dm baseline
else if (c.compare("lowmtb") == 0)
{
;//null statement, similar to pass in python; no operation required
}
// if cut is not matched to any variable, print error and return false
else
{
std::cout << "ERROR in " << __func__ << ": No string match found for " << c << std::endl;
return false;
}
}
// if we reach the end then no cut is false; return true
//printf("\n");
return true;
}
// if unit is not low dm, return false
else
{
return false;
}
}
// return true if event passes unit selection, otherwise return false
bool passUnitHighDM(const std::string& unit, const std::string& prefix, float mtb, int njets, int nb, int ntop, int nw, int nres, float ht, float met)
{
//printf("%s: %s\n", __func__, unit.c_str());
// check if unit is low dm
if (unit.find(prefix) == 0)
{
int nTotalTopW = ntop + nw + nres;
std::vector<std::string> cuts = getCutVec(unit, prefix);
//printf("%s: ", unit.c_str());
//for (const auto& c : cuts)
//{
// printf("%s, ", c.c_str());
//}
//printf("\n");
for (const auto& c : cuts)
{
// note; be careful about order as some cuts may begin with the same string
// optimization: if we do not pass a cut, return false
//printf("%s, ", c.c_str());
// note: nrtntnw* and nrt* both start with nrt; be careful about this case
// check for nrtntnw* before nrt*
if (c.find("nrtntnw") == 0)
{
if (! pass_nTotalTopW(c, nTotalTopW))
{
return false;
}
}
else if (c.find("mtb") != std::string::npos)
{
if (! pass_mtb(c, mtb))
{
return false;
}
}
else if (c.find("nj") == 0)
{
if (! pass_njets(c, njets))
{
return false;
}
}
else if (c.find("nb") == 0)
{
if (! pass_nb(c, nb))
{
return false;
}
}
else if (c.find("nt") == 0)
{
if (! pass_ntop(c, ntop))
{
return false;
}
}
else if (c.find("nw") == 0)
{
if (! pass_nw(c, nw))
{
return false;
}
}
else if (c.find("nrt") == 0)
{
if (! pass_nres(c, nres))
{
return false;
}
}
else if (c.find("ht") == 0)
{
if (! pass_ht(c, ht))
{
return false;
}
}
else if (c.find("MET_pt") == 0)
{
if (! pass_met(c, met))
{
return false;
}
}
// if cut is not matched to any variable, print error and return false
else
{
std::cout << "ERROR in " << __func__ << ": No string match found for " << c << std::endl;
return false;
}
}
// if we reach the end then no cut is false; return true
//printf("\n");
return true;
}
// if unit is not low dm, return false
else
{
return false;
}
}
// return unit number: can be used for search bins, CR units and SR units
int getUnitNumLowDM(const std::string& key, int njets, int nb, int nsv, float ISRpt, float ptb, float met)
{
bool verbose = false;
std::string prefix = prefixMap[key];
prefix = prefix + "lm_";
//printf("njets = %d, nb = %d, nsv = %d, ISRpt = %f, ptb = %f, met = %f\n", njets, nb, nsv, ISRpt, ptb, met);
for (const auto& element : json_[json::json_pointer(key)].items())
{
std::string unit = element.key();
// only check units with prefix
if (unit.find(prefix) == 0)
{
bool pass = passUnitLowDM(unit, prefix, njets, nb, nsv, ISRpt, ptb, met);
//printf("%s: pass = %s\n", unit.c_str(), pass ? "true" : "false");
if (pass)
{
int bin = std::stoi(std::string(element.value()));
if (verbose)
{
printf("pass selection for unit %d, %s; njets = %d, nb = %d, nsv = %d, ISRpt = %f, ptb = %f, met = %f\n", bin, unit.c_str(), njets, nb, nsv, ISRpt, ptb, met);
}
return bin;
}
}
}
return -1;
}
// return unit number: can be used for search bins, CR units and SR units
int getUnitNumHighDM(const std::string& key, float mtb, int njets, int nb, int ntop, int nw, int nres, float ht, float met)
{
bool verbose = false;
std::string prefix = prefixMap[key];
prefix = prefix + "hm_";
//printf("njets = %d, nb = %d, nsv = %d, ISRpt = %f, ptb = %f, met = %f\n", njets, nb, nsv, ISRpt, ptb, met);
for (const auto& element : json_[json::json_pointer(key)].items())
{
std::string unit = element.key();
// only check units with prefix
if (unit.find(prefix) == 0)
{
bool pass = passUnitHighDM(unit, prefix, mtb, njets, nb, ntop, nw, nres, ht, met);
//printf("%s: pass = %s\n", unit.c_str(), pass ? "true" : "false");
if (pass)
{
int bin = std::stoi(std::string(element.value()));
if (verbose)
{
printf("pass selection for unit %d, %s; mtb = %f, njets = %d, nb = %d, ntop = %d, nw = %d, nres = %d, ht = %f, met = %f\n", bin, unit.c_str(), mtb, njets, nb, ntop, nw, nres, ht, met);
}
return bin;
}
}
}
return -1;
}
void operator()(NTupleReader& tr)
{
getSearchBin(tr);
}
};
}
#endif
|
#ifndef THIRDPERSONCONTROLLER_H
#define THIRDPERSONCONTROLLER_H
#include <btBulletDynamicsCommon.h>
#include "BulletDynamics/Character/btKinematicCharacterController.h"
#include "BulletCollision/CollisionDispatch/btGhostObject.h"
#include "math.h"
#include "Ogre.h"
#include "BtOgrePG.h"
#include "CollisionFilter.h"
class ThirdPersonController
{
public:
ThirdPersonController(Ogre::Vector3 pOffset, Ogre::Quaternion rOffset, btKinematicCharacterController* charController,
btPairCachingGhostObject* ghostObj, Ogre::Node* prntNode, int resolX, int resolY,btDiscreteDynamicsWorld* world);
void updateCamera(Ogre::Camera* mCamera,int mouseX, int mouseY);
void updateCharacter(bool gLeft, bool gRight, bool gForward, bool gBackward, const btScalar& dt);
void setOffsetPosition(const Ogre::Vector3& offset);
void setOffsetRotation(const Ogre::Quaternion& offset);
void setCameraCollisionLayer(int layer);
private:
int camCollideLayer;
Ogre::Vector3 cPosOffset;
Ogre::Quaternion cRotOffset;
btKinematicCharacterController* m_character;
btPairCachingGhostObject* m_ghostObject;
Ogre::Node* cPrntNode;
btScalar cAngle;
int resX;
int resY;
btDiscreteDynamicsWorld* mWorld;
};
#endif // THIRDPERSONCONTROLLER_H
|
#include "bits/stdc++.h"
using namespace std;
void show (vector < int > v )
{
for_each (v.begin(), v.end(),[](int x)
{
cout<<x<<" ";
});
cout<<endl;
}
int main ()
{ // v.size()= O(1)
vector < int > v (10,2); // intialize with 2
// size vs empty
bool is_nonempty_notgood = (v.size() >= 0);
bool is_nonempty_good = !v.empty();
// size() is unsigned
// not all size() return size in O(1)
// For inserting in vector
// push_back()
v.push_back(11);
// resize() make vector contains required numbers of element
v.resize(10);
// now push back will insert after 10 size
v.push_back(11);
v.pop_back();
show(v);
// many initalizatoin of vector
vector < int > v2 = v;
vector < int > v3 = v;
// both are same
vector < int > data(1000); // vector of 1000 element value 0
// 2-D vector
int n=3,m=4;
vector < vector < int > > matrix(n, vector < int > (m,-1));
// always pass vector by reference as it doesn't create a copy
// Pairs
pair < string , pair < int, int > > P ("vivek", {2, 3} );
string s= P.first; // extract string
int x = P.second.first; // extract first int
int y= P.second.second; // extract second int
cout<<s<<" "<<x<<" "<<y<<endl;
//vector of pairs
vector < pair < int, int > > vp ={ {1,3}, {2,4} };
// printing vector-pair
for (int i=0; i < vp.size(); i++)
{
cout << vp[i].first << " " << vp[i].second << endl;
}
//vector of vector
vector < vector < int > > vov;
// vov empty so vov.push_back needs a vector
vov.push_back({1,2,4});
cout << vov[0][0] << " " << vov[0][1] << endl;
return 0;
}
|
void phase1(){
String str = serial_read();
if (str.length() > 0) {
serial_write_debug("MSG = ");
serial_write_debug(str);
}
/* The ESP has sent the MOV_1 command.
* Arduino will command the motors to move the robot
* following the black line.
* When the movement has ended, send END_MOV_1 to the ESP
*/
if (str == MOV_1) {
serial_write_debug("Ricevuto MOV");
delay(20); //sicurezza per Laser??
digitalWrite(LASER_PIN_L, HIGH); //Laser ON
digitalWrite(LASER_PIN_R, HIGH); //Laser ON
draw_scanning_R();
draw_scanning_L();
t = millis();
while (millis() - t < T_straight) {
following_forward();
}
Stop();
delay(200);
serial_write(END_MOV_1);
serial_write_debug("Invio END_MOV");
draw_openclose();
}
/* The robot has reached a "point of interest" namenely a rock.
* The ESP has recievd END_MOV_1 and responded with ROCK_INT
* which signals the start of the interaction.
* The interaction now consists in "scanning" the rock with
* the laser ponters and reproducing a track.
* Once the interaction has finished, send END_ROCK_INT to the ESP
*/
if (str == ROCK_INT) {
serial_write_debug("Ricevuto ROCK_INT");
play(ROCK_SONG);
draw_surprised_start();
delay(5000);
digitalWrite(LASER_PIN_L, LOW); //Laser OFF
digitalWrite(LASER_PIN_R, LOW); //Laser OFF
draw_surprised_end();
serial_write(END_ROCK_INT);
serial_write_debug("Invio END_ROCK_INT");
}
/* The ESP has found a person, the robot now needs to speak
* and promote the exibition. If the person leaves the ESP will
* send STOP_SPEAK. In that case the robot will have to show
* sadness. Regardless of any message recieved, at the end of the
* interaction Arduino will have to send END_SPEAK_1
*/
if (str == SPEAK_1) {
bool end_sp = false;
// Keep playing the track until the thing finishes or we recieve a STOP_SPEAK
serial_write_debug("Ricevuto SPEAK");
draw_openclose();
int noPlayCount = 0;
Track track = GREETINGS;
play(track);
draw_happy_start();
draw_happy_open();
delay(1500);
t = millis();
do
{
if (serial_read() == STOP_SPEAK_1)
{
//we read a stop signal from esp
stop_play();
play(SADNESS);
draw_sad_start();
noPlayCount = 0;
while (noPlayCount < 2) //check end of track
{
if (df_not_playing())
noPlayCount++;
if (millis() - t > 4000)
{
t = millis();
draw_sad_blink();
}
delay(500);
}
end_sp = true;
draw_sad_end();
}
else
{
if (noPlayCount < 2) //margin is needed for false positive when a track starts
{
if (df_not_playing())
noPlayCount++;
if (millis() - t > 4000)
{
t = millis();
if (track < 3)
draw_happy_blink();
else
{
draw_openclose();
}
}
delay(500);
}
else //track ended
{
//down here it's track++;
track = static_cast<Track>(static_cast<int>(track) + 1);
if (track < 5)
{
noPlayCount = 0;
play(track);
if (track == 3)
{
draw_happy_close();
draw_happy_end();
}
}
else
{
end_sp = true;
}
}
}
} while (!end_sp);
serial_write(END_SPEAK_1);
serial_write_debug("Invio END_SPEAK");
}
/* The ESP has finished tracking the person, now it's required that the robot
* resets (it should be a small movemnt to move past the stopping point).
* Once the movement has ended notify the ESP with the END_RES_POS message.
*/
if (str == RES_POS_1) {
serial_write_debug("Riccevuto RES_POS");
draw_openclose();
t = millis();
while (millis() - t < T_straight) {
following_backward();
}
Stop();
delay(200);
draw_openclose();
serial_write(END_RES_POS_1);
serial_write_debug("Invio END_RES_POS");
}
//default blinking
draw_openclose();
}
|
//By SCJ
//#include<iostream>
#include<bits/stdc++.h>
using namespace std;
#define endl '\n'
#define maxn 10005
int f[maxn],p[maxn];
pair<int,int> ans[maxn*2];
void sp(int aa,int bb)
{
int d=(bb-aa+1)/2;
// cout<<" aa="<<aa<<" bb="<<bb<<endl;
for(int i=0;i<d;++i)
{
int a=aa+i,b=bb-d+i+1;
// cout<<" a="<<a<<" b="<<b<<endl;
int x=f[a],y=f[b];
swap(f[a],f[b]);
swap(p[x],p[y]);
}
}
int main()
{
ios::sync_with_stdio(0);
cin.tie(0);
// freopen("1611.in","r",stdin);
// freopen("1611.out","w",stdout);
int T;cin>>T;//cout<<T<<endl;
while(T--)
{
int n,ct=0;cin>>n;//cout<<n<<endl;
for(int i=1;i<=n;++i) cin>>f[i],p[f[i]]=i;//,cout<<f[i]<<' ';
//cout<<endl;
for(int r=1;r<=n;++r)
{
if(r==p[r]) continue;
int d=p[r]-r+1;
if(d%2){
ans[ct++]={r+1,p[r]};
sp(r+1,p[r]);
}
else{
ans[ct++]={r,p[r]};
sp(r,p[r]);
}
if(r==p[r]) continue;
d=p[r]-r-1;int pos=p[r];
ans[ct++]={r,p[r]+d};
sp(r,p[r]+d);
}
cout<<ct<<endl;
for(int i=0;i<ct;++i)
cout<<ans[i].first<<' '<<ans[i].second<<endl;
// cout<<min(ans[i].first,ans[i].second)
// <<' '<<max(ans[i].first,ans[i].second)<<endl;
}
}
|
// Problem No. 05 => 1. Merge Overlapping Subintervals
class Solution {
public:
vector<vector<int>> merge(vector<vector<int>>& intervals) {
vector<vector<int>> mergedIntervals;
if(intervals.size() == 0){
return mergedIntervals;
}
sort(intervals.begin(), intervals.end());
vector<int> tempInterval = intervals[0];
for(auto it : intervals){
if(it[0] <= tempInterval[1]) {
tempInterval[1] = max(it[1], tempInterval[1]);
} else{
mergedIntervals.push_back(tempInterval);
tempInterval = it;
}
}
mergedIntervals.push_back(tempInterval);
return mergedIntervals;
}
};
/*
1. First thing while solving this quesrion is that ask that, whether all the
intervals are in the sorted manner or not.
2. Our first approcah will be brute force approach in which we will first sort the array.
@ After sorting the array, we will store the merged array in a new data structure, if we find an overlapping array.
@ Time complexity for this approach will be O(nlog(n))
@ Space complexity of this approach will be O(n^2)
3. In our second and optimised approach we will again sort the array.
@ Now we will select the first array from the list of array, and compare that whether the second
array overlaps it, if yes than we merge them and continue.
@ If No, than we put the selected array in new data structure and select the next array from the list,
and we will then repeat the same task, until we get desired answer.
@ Time complexity for this approach will be O(nlog(n)) [For sorting the array] + O(n) [for lineraly tarversing through the array]
@ Space complexity will be O(n)
*/
|
/************************************************************************/
/*
17、有一个由大小写组成的字符串,现在需要对他进行修改,将其中的所有小写字母排在
大写字母的前面(大写或小写字母之间不要求保持原来次序),如有可能尽量选择时间和空
间效率高的算法 c 语言函数原型 void proc(char *str) 也可以采用你自己熟悉的语言
*/
/************************************************************************/
/************************************************************************/
/* 解题思路:
采用类似快排的思想,时间为:n, 空间为:1*/
/************************************************************************/
#include <string.h>
#include <stdio.h>
void proc(char *str){
int nStartPos = 0;
int nEndPos = strlen(str) - 1;
while (nStartPos < nEndPos){
while (str[nStartPos] <= 'z' && str[nStartPos] >= 'a' && nStartPos < strlen(str)){
++nStartPos;
}
while (str[nEndPos] <= 'Z' && str[nEndPos] >= 'A' && nEndPos >= 0){
--nEndPos;
}
if(nStartPos >= nEndPos){
return;
}
else{
char temp = str[nStartPos];
str[nStartPos] = str[nEndPos];
str[nEndPos] = temp;
}
}
}
//int main(){
// char str[] = "dafaHUGiiuSDoijudOIdpoiIOIOdIOHOIHIH";
// proc(str);
// printf("%s", str);
// return 0;
//}
|
#include <iostream>
#include <queue>
#include <deque>
#include <algorithm>
#include <string>
#include <vector>
#include <stack>
#include <set>
#include <map>
#include <math.h>
#include <string.h>
#include <bitset>
#include <cmath>
using namespace std;
int C = 0;
int calc(int r, int c)
{
return (r - 1) * C + c;
}
vector<int> solution(int rows, int columns, vector<vector<int>> queries)
{
vector<int> maps;
vector<int> answer;
C = columns;
for (int i = 0; i <= rows * columns; i++)
{
maps.push_back(i);
}
for (auto q : queries)
{
vector<int> index;
int x1 = q[0], y1 = q[1], x2 = q[2], y2 = q[3];
int minnum = 98765;
for (int i = y1; i < y2; i++)
index.push_back(calc(x1, i));
for (int i = x1; i < x2; i++)
index.push_back(calc(i, y2));
for (int i = y2; i > y1; i--)
index.push_back(calc(x2, i));
for (int i = x2; i > x1; i--)
index.push_back(calc(i, y1));
/*
for (auto i : index)
{
cout << i << " ";
}
cout << endl;
*/
int tmp = maps[index[index.size() - 1]];
minnum = min(minnum, tmp);
for (int i = index.size() - 2; i >= 0; i--)
{
minnum = min(minnum, maps[index[i]]);
maps[index[i + 1]] = maps[index[i]];
}
maps[index[0]] = tmp;
/*
for (int i = 0; i <= 36; i++)
cout << maps[i] << " ";
cout << endl;
*/
answer.push_back(minnum);
}
return answer;
}
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
vector<vector<int>> quer = {{2, 2, 5, 4},
{3, 3, 6, 6},
{5, 1, 6, 3}};
vector<int> sol = solution(6, 6, quer);
for (auto x : sol)
cout << x << " ";
return 0;
}
|
/*
RC Remote Echo:
ECHO a Remote RC Controller
by Rick Anderson (ricklon)
*/
#include <Arduino.h>
#include <SoftPWMServo.h>
const int PIN_KILL = 23;
const int PIN_THR = 12;
const int PIN_STR = 13;
const int PIN_AUX = 23;
#define STR 0
#define THR 1
#define KILL 2
#define AUX 3
//Setup RC Controller
const int channels = 4;
/*
What are the channels:
0: thr: throttle
1: str, steering
2: aux1: pos1: OK, pos:2 Emergency Stop
3: aux2:
*/
int ch1; // Here's where we'll keep our channel values
int ch2;
int ch3;
int ch4;
int ch[4];
int chmin[4];
int chmid[4];
int chmax[4];
/*
RC Controller states
out of range or off
kill
enable
*/
#define ACTION 0
void doRCAction() {
ch[STR] = pulseIn(PIN_STR, HIGH, 25000); // Read the pulse width of
ch[THR] = pulseIn(PIN_THR, HIGH, 25000); // each channel
ch[KILL] = pulseIn(PIN_KILL, HIGH, 25000);
ch[AUX] = pulseIn(PIN_AUX, HIGH, 25000);
// RC Actions
if (ch[KILL] > 1500 ) {
Serial.println("AUTO ON");
}
else {
Serial.println("AUTO OFF");
}
if (ch[STR] == 0 )
{
Serial.printf("Out of Range or Powered Off\n");
Serial.println("This should be the same as a kill switch");
//set brake
//kill the machine
}
else
{
Serial.println("COMMANDS");
}
}
// Function: get The RC Control infomration
void getRCInfo() {
ch[STR] = pulseIn(PIN_STR, HIGH, 25000); // Read the pulse width of
ch[THR] = pulseIn(PIN_THR, HIGH, 25000); // each channel
ch[KILL] = pulseIn(PIN_KILL, HIGH, 25000);
ch[AUX] = pulseIn(PIN_AUX, HIGH, 25000);
//check for out of range or controller off
for (int ii = 0; ii < channels; ii++)
{
if (ch[ii] > chmax[ii]) {
chmax[ii] = ch[ii];
}
if (ch[ii] < chmin[ii]) {
chmin[ii] = ch[ii];
}
chmid[ii] = (chmin[ii] + chmax[ii]) / 2;
Serial.printf("Channel %d: %d, min: %d, mid: %d, max: %d\n", ii, ch[ii], chmin[ii], chmid[ii], chmax[ii]); // Print the value of
}
}
void setup() {
Serial.begin(9600);
pinMode(PIN_STR, INPUT);
pinMode(PIN_THR, INPUT);
pinMode(PIN_KILL, INPUT);
pinMode(PIN_AUX, INPUT);
getRCInfo();
}
void loop() {
getRCInfo();
doRCAction();
delay(250);
}
|
#ifndef UI_ACTION_INSTANTACTIONS_PLACE_H_
#define UI_ACTION_INSTANTACTIONS_PLACE_H_
#pragma once
namespace ui
{
class UILIB_API Place : public InstantAction
{
public:
static Place* Create(const CPoint& left_top);
virtual void Update(float time) override;
virtual Place* Reverse() const override;
virtual Place* Clone() const override;
protected:
Place() = default;
bool InitWithPoint(const CPoint& left_top);
private:
CPoint left_top_;
};
}
#endif
|
/*====================================================================
Copyright(c) 2018 Adam Rankin
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files(the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and / or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions :
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL
THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
====================================================================*/
#pragma once
// Local includes
#include "TransferFunctionLookupTable.h"
#include "RenderingCommon.h"
// STL includes
#include <atomic>
#include <vector>
namespace HoloIntervention
{
namespace Rendering
{
class BaseTransferFunction
{
struct ControlPoint
{
ControlPoint(uint32 uid, float inputValue, DirectX::XMFLOAT4 outputValue)
: m_uid(uid)
, m_inputValue(inputValue)
, m_outputValue(outputValue) {}
uint32 m_uid;
float m_inputValue;
DirectX::XMFLOAT4 m_outputValue;
};
typedef std::vector<ControlPoint> ControlPointList;
public:
virtual ~BaseTransferFunction();
virtual TransferFunctionLookupTable& GetTFLookupTable();
virtual void SetLookupTableSize(uint32 size);
virtual float GetMaximumXValue();
virtual bool IsValid() const;
virtual void Update() = 0;
virtual uint32 AddControlPoint(float pixelValue, float r, float g, float b);
virtual uint32 AddControlPoint(float pixelValue, float alphaValue);
virtual bool RemoveControlPoint(uint32 controlPointUid);
protected:
virtual uint32 AddControlPoint(float pixelValue, float r, float g, float b, float alpha);
BaseTransferFunction();
protected:
uint32_t m_nextUid = 0;
ControlPointList m_controlPoints;
TransferFunctionLookupTable m_lookupTable;
std::atomic_bool m_isValid = false;
};
}
}
|
#ifndef NODODT_H
#define NODODT_H
#include <iostream>
using namespace std;
template <typename T>
class NodoDT
{
private:
NodoDT<T>* anterior;
NodoDT<T>* siguiente;
T valor;
public:
NodoDT<T>(T v, NodoDT<T>* ant = NULL, NodoDT<T>* sig = NULL){ // Constructor por omision:
valor = v; // CASO 1: solo se pasa valor
anterior = ant; // CASO 2: se pasa valor y referencia
siguiente = sig; // CASO 3: se pasa valor y dos referencias
}
T dameTuValor(void){ // Regresa el valor del nodo
return valor;
}
NodoDT<T>* dameTuAnterior(void){ // Regresa la referencia ANTERIOR del nodo
return anterior;
}
NodoDT<T>* dameTuSiguiente(void){ // Regresa la referencia SIGUIENTE del nodo
return siguiente;
}
void modificaTuValor(T v){ // Modifica el valor del nodo
valor = v;
}
void modificaTuAnterior(NodoDT<T>* ant){ // Modifica el apuntador ANTERIOR
anterior = ant;
}
void modificaTuSiguiente(NodoDT<T>* sig){ // Modifica el apuntador SIGUIENTE
siguiente = sig;
}
void muestraTusDatos(void){ // Imprime los atributos del objeto
cout << "Valor: " << valor << endl
<< "Anterior: " << anterior << endl
<< "Siguiente: " << siguiente << endl;
}
};
#endif // NODODT_H
|
#include <iostream>
#include <vector>
#include "Player.h"
#include "Warrior.h"
#include "Priest.h"
#include "Mage.h"
Type getCharacterType();
Race getCharacterRace();
std::string getCharacterName();
int main()
{
Type type;
Race race;
char choice;
std::string name;
Player* playerPtr; // = new Warrior("Brad", HUMAN);
std::vector<Player*> playerPtrVector;
std::cout << "Hello RPG!\n\n";
do
{
type = getCharacterType();
race = getCharacterRace();
name = getCharacterName();
switch (type)
{
case WARRIOR:
playerPtr = new Warrior(name, race);
break;
case PRIEST:
playerPtr = new Priest(name, race);
break;
case MAGE:
playerPtr = new Mage(name, race);
break;
}
playerPtrVector.push_back(playerPtr);
std::cout << "Would you like to create another character? (y/n): ";
std::cin >> choice;
}
while (choice == 'y' || choice == 'Y');
for (Player* playerPtr : playerPtrVector)
{
std::cout << "I'm a " << playerPtr->whatRace() << " "
<< playerPtr->whatType() << " named " << playerPtr->getName()
<< " and my attack is: \"" << playerPtr->attack() << "\"\n";
}
delete playerPtr;
playerPtr = nullptr;
return 0;
}
Type getCharacterType()
{
int input;
Type type;
std::cout << "Pick your character type:\n"
<< " 1. Warrior\n"
<< " 2. Priest\n"
<< " 3. Mage\n"
<< "Enter your choice: ";
std::cin >> input;
std::cout << "\n";
switch (input)
{
case 1:
type = WARRIOR;
break;
case 2:
type = PRIEST;
break;
case 3:
type = MAGE;
break;
}
return type;
}
Race getCharacterRace()
{
int input;
Race race;
std::cout << "Pick your character race:\n"
<< " 1. Human\n"
<< " 2. Elf\n"
<< " 3. Dwarf\n"
<< " 4. Orc\n"
<< " 5. Troll\n"
<< "Enter your choice: ";
std::cin >> input;
std::cout << "\n";
switch (input)
{
case 1:
race = HUMAN;
break;
case 2:
race = ELF;
break;
case 3:
race = DWARF;
break;
case 4:
race = ORC;
break;
case 5:
race = TROLL;
break;
}
return race;
}
std::string getCharacterName()
{
std::string name;
std::cin.clear();
std::cin.ignore();
std::cout << "Enter your character's name: ";
getline(std::cin, name);
std::cout << "\n";
return name;
}
|
#include "AABB.h"
AABB::AABB(const glm::vec2 & pPosition, const glm::vec2 & pSize)
:
mPosition(pPosition),
mSize(pSize)
{
}
AABB::AABB(float pX, float pY, float pWidth, float pHeight)
:
mPosition(pX,pY),
mSize(pWidth,pHeight)
{
}
AABB::~AABB()
{
}
void AABB::init(const glm::vec2 & pPosition, const glm::vec2 & pSize)
{
mPosition = pPosition;
mSize = pSize;
}
void AABB::destroy()
{
}
void AABB::update(const glm::vec2 & pPosition, const glm::vec2 & pSize)
{
mPosition = pPosition;
mSize = pSize;
}
bool AABB::colliding_with(const AABB & other) const
{
bool xCollision = mPosition.x + mSize.x >= other.mPosition.x
&&
other.mPosition.x + other.mSize.x >= mPosition.x;
bool yCollision = mPosition.y + mSize.y >= other.mPosition.y
&&
other.mPosition.y + other.mSize.y >= mPosition.y;
return xCollision && yCollision;
}
|
#ifndef MYFACEWIDGET_H
#define MYFACEWIDGET_H
#include <QListWidget>
#include <QInputDialog>
#include <QDialog>
#include <QFormLayout>
#include <QLabel>
#include <QList>
#include <QDialogButtonBox>
#include <QIntValidator>
#include <QDropEvent>
#include <sstream>
#include <string>
#include <math.h>
#include <QMessageBox>
#include <QTimer>
#include "face.h"
#include "halfedge.h"
#include "vertex.h"
class MyFaceWidget : public QListWidget
{
Q_OBJECT
public:
MyFaceWidget(QWidget *parent);
public slots:
void addFaceItem(QListWidgetItem *item);
void selectFace(QListWidgetItem *item);
void splitQuad();
void sharedVertexToEdge();
void changeColor();
void clearItems();
void sortItems();
void editText();
signals:
void sendFace(Face*);
void sendFaces(Face*, Face*);
};
#endif // MYFACEWIDGET_H
|
//
// main.cpp
// Stack_LinkedList
//
// Created by 王宗祥 on 2020/11/27.
//
#include <iostream>
using namespace std;
class StackNode {
private:
int data;
StackNode* next;
public:
StackNode() :data(0), next(nullptr) {};
StackNode(int data) :data(data), next(nullptr) {};
StackNode(int data, StackNode* next) :data(data), next(next) {};
friend class StackList;
};
class StackList {
private:
StackNode* Top;
int num;
public:
StackList() :Top(nullptr), num(0) {};
void push(int elt);
void pop();
bool empty();
int top();
int size();
};
void StackList::push(int elt) {
StackNode* newNode = new StackNode(elt, Top);
Top = newNode;
num++;
return;
};
void StackList::pop() {
if (empty()) {
cout << "Stack is empty.\n";
return;
}
StackNode* temp = Top;
Top = Top->next;
delete temp;
temp = 0;
num--;
return;
};
bool StackList::empty() {
return num == 0;
};
int StackList::top() {
if (empty()) {
cout << "Stack is empty.\n";
return -1;
}
return Top->data;
};
int StackList::size() {
return num;
};
|
#pragma once
#include <tuple>
#include <string>
#include <vector>
#include <gsl/span>
#include <boost/filesystem.hpp>
//#include <sndfile.h> // SF_VIRTUAL_IO
#include "PticaGovorunCore.h" // PG_EXPORTS
#include "ClnUtils.h"
#include "TranscriberUI/FileWorkspaceWidget.h"
namespace PticaGovorun {
#if PG_HAS_LIBSNDFILE
PG_EXPORTS bool readAllSamplesWav(const boost::filesystem::path& filePath, std::vector<short>& result, float *sampleRate, ErrMsgList* errMsg);
PG_EXPORTS std::tuple<bool, std::string> writeAllSamplesWav(const short* sampleData, int sampleCount, const std::string& fileName, int sampleRate);
PG_EXPORTS bool writeAllSamplesWav(gsl::span<const short> samples, int sampleRate, const boost::filesystem::path& filePath, ErrMsgList* errMsg);
//PG_EXPORTS std::tuple<bool, std::string> writeAllSamplesWavVirtual(short* sampleData, int sampleCount, int sampleRate, const SF_VIRTUAL_IO& virtualIO, void* userData);
#endif
/// Reads audio file in any supported format (wav, flac).
PG_EXPORTS bool readAllSamplesFormatAware(const boost::filesystem::path& filePath, std::vector<short>& result, float *sampleRate, ErrMsgList* errMsg);
// Checks whether the audio file format is supported.
bool isSupportedAudioFile(const wchar_t* fileName);
PG_EXPORTS bool resampleFrames(gsl::span<const short> audioSamples, float inputSampleRate, float outSampleRate, std::vector<short>& outSamples, ErrMsgList* errMsg);
}
|
#include <core/types.h>
#include <core/maths.h>
#include <core/platform.h>
#include <graphics/rendergl/glutil.h>
#ifndef WIN32
#include <opengl/opengl.h>
#endif
#include <iostream>
using namespace std;
const uint32_t kHeight = 600;
const uint32_t kWidth = 600;
const float kWorldSize = 4.0f;
const float kZoom = kWorldSize + 0.0f;
struct Particle
{
Particle(Vec2 p, Vec2 v, float r) : position(p), velocity(v), radius(r) {}
Vec2 position;
Vec2 velocity;
Vec2 force;
float radius;
};
std::vector<Vec3> g_planes;
std::vector<Particle> g_particles;
Vec2 g_gravity(0.0f, -9.8f);
void Init()
{
g_planes.push_back(Vec3(0.0f, 1.0f, 0.0f));
g_planes.push_back(Vec3(-1.0f, 0.0f, -2.0f));
g_planes.push_back(Vec3(1.0f, 0.0f, -2.0f));
// fixed world particle
g_particles.push_back(Particle(Vec2(), Vec2(), 0.0f));
float radius = 0.2f;
for (int i=0; i < 50; ++i)
g_particles.push_back(Particle(Vec2(0.0f, radius + i*2.0f*radius), Vec2(0.0f, 0.0f), radius));
//g_particles[1].velocity += Vec2(1.0f, 0.0f);
}
void ApplyForces(float dt)
{
for (int i=1; i < g_particles.size(); ++i)
{
Particle& p = g_particles[i];
p.force = g_gravity;//f*(p.velocity);
}
}
struct Contact
{
Contact() : x(0.0f, 0.0f), n(0.0f, 0.0f), j(0.0f), tj(0.0f), d(0.0f), a(0), b(0) {}
Vec2 x;
Vec2 n;
float j;
float tj;
float d;
int a;
int b;
};
void CollidePlanes(const std::vector<Vec3>& planes, const std::vector<Particle>& particles, std::vector<Contact>& contacts)
{
// collide with planes
for (int i=0; i < planes.size(); ++i)
{
Vec3 p = planes[i];
for (int r=1; r < particles.size(); ++r)
{
Vec2 x = particles[r].position;
float radius = particles[r].radius;
// distance to plane
float d = x.x*p.x + x.y*p.y - p.z;
float mtd = d - radius;
if (mtd < 0.0f)
{
Contact c;
c.n = Vec2(p.x, p.y);
c.d = mtd;
c.a = r;
c.b = 0;
contacts.push_back(c);
}
}
}
}
// takes an array of particles and planes and returns a list of contacts
void CollideParticles(const std::vector<Particle>& particles, std::vector<Contact>& contacts)
{
// collide with particles
for (int i=1; i < particles.size(); ++i)
{
const Particle& a = particles[i];
for (int j=i+1; j < particles.size(); ++j)
{
const Particle& b = particles[j];
Vec2 pd = a.position - b.position;
float l = Length(pd);
float mtd = l - a.radius - b.radius;
/*
void SolveImpulse(const std::vector<Contact>& contacts, float dt)
{
// apply penalty forces for each contact
for (int i=0; i < contacts.size(); ++i)
{
const Contact& c = contacts[i];
assert(c.d < 0.0f);
float me = 1.0f / (c.a->invmass + c.b->invmass);
Vec2 va = c.a->GetVelocityAtPoint(c.x);
Vec2 vb = c.b->GetVelocityAtPoint(c.x);
float rvn = Dot(c.n, va-vb);
float fdamp = 0.004f*k*rvn;
// apply a penalty force to bodies
c.a->ApplyForce(-c.n*(f+fdamp), c.x);
c.b->ApplyForce( c.n*(f+fdamp), c.x);
}
}
*/
class Matrix
{
public:
if (mtd < 0.0f)
{
Contact c;
c.n = n;
c.d = mtd;
c.a = i;
c.b = j;
contacts.push_back(c);
}
}
}
}
void Solve(std::vector<Contact>& contacts, std::vector<Contact>& prevContacts, std::vector<Particle>& particles, float dt)
{
const float kOverlap = 0.01f;
const float kBaumgarte = 0.2f / dt;
const int kIterations = 10;
if (1)
{
for (int i=0; i < contacts.size(); ++i)
{
Contact& c = contacts[i];
for (int j=0; j < prevContacts.size(); ++j)
{
Contact& pc = prevContacts[j];
if (pc.a == c.a && pc.b == c.b)
{
// apply previous frames impulse
Particle& a = particles[c.a];
Particle& b = particles[c.b];
// treat radius as 1.0/mass
float ma = c.a?1.0f:0.0f;
float mb = c.b?1.0f:0.0f;
float msum = ma + mb;
assert(msum > 0.0f);
// impulse
a.velocity -= pc.tj*ma*c.n/msum;
b.velocity += pc.tj*mb*c.n/msum;
c.tj = pc.tj;
}
}
}
}
for (int s=0; s < kIterations; ++s)
{
for (int i=0; i < contacts.size(); ++i)
{
Contact& c = contacts[i];
Particle& a = particles[c.a];
Particle& b = particles[c.b];
Vec2 vd = a.velocity-b.velocity;
// calculate relative normal velocity
float vn = Dot(vd, c.n);
// Baumgarte stabilisation
float bias = kBaumgarte*min(c.d+kOverlap, 0.0f);
float l = vn + bias;
float j = min(c.tj + l, 0.0f);
l = j - c.tj;
c.tj = j;
c.j = l;
//c.tj += c.j;
/*
}
// update all particles velocities
for (int i=0; i < contacts.size(); ++i)
{
Contact& c = contacts[i];
Particle& a = particles[c.a];
Particle& b = particles[c.b];
*/
// treat radius as 1.0/mass
float ma = c.a?1.0f:0.0f;
float mb = c.b?1.0f:0.0f;
float msum = ma + mb;
assert(msum > 0.0f);
// impulse
a.velocity -= c.j*ma*c.n/msum;
b.velocity += c.j*mb*c.n/msum;
//c.j = 0.0f;
}
}
}
void Integrate(float dt)
{
// v += a*dt
for (int i=1; i < g_particles.size(); ++i)
{
Particle& p = g_particles[i];
p.velocity += p.force*dt;
}
std::vector<Contact> contacts;
CollideParticles(g_particles, contacts);
CollidePlanes(g_planes, g_particles, contacts);
static std::vector<Contact> prevContacts;
// solve
Solve(contacts, prevContacts, g_particles, dt);
swap(contacts, prevContacts);
// p += v*dt
for (int i=1; i < g_particles.size(); ++i)
{
Particle& p = g_particles[i];
p.position += p.velocity*dt;
}
static int counter = 0;
counter++;
// calc error
float error = fabsf(g_particles.back().position.y - (1 + 2*(g_particles.size()-1))*g_particles.back().radius);
static float maxerror;
maxerror = max(error, maxerror);
cout << error << " max=" << maxerror << endl;
//if (counter == 300)
// exit(0);
}
// printf("\nA:\n");
// A.print();
// solve
Matrix x = GaussSeidel(A, b, 30, false);
CollideParticles(g_particles, contacts);
CollidePlanes(g_planes, g_particles, contacts);
for (int i=0; i < contacts.size(); ++i)
{
Contact& c = contacts[i];
const float kStiff = 20000.0f;
const float kDamp = 100.0f;
float rv = Dot(g_particles[c.a].velocity - g_particles[c.b].velocity, c.n);
if (rv < 0.0f)
{
g_particles[c.a].force -= (kStiff*c.d + kDamp*rv)*c.n;
g_particles[c.b].force += (kStiff*c.d + kDamp*rv)*c.n;
}
}
for (int i=1; i < g_particles.size(); ++i)
{
Particle& p = g_particles[i];
p.velocity += p.force*dt;
p.position += p.velocity*dt;
}
static int counter = 0;
counter++;
// calc error
float error = fabsf(g_particles.back().position.y - (1 + 2*(g_particles.size()-1))*g_particles.back().radius);
static float maxerror;
maxerror = max(error, maxerror);
RigidBody* b = new RigidBody(Vec2(x, y), radius, 1.0f, &points[0], &points[0] + count);
g_bodies.push_back(b);
}
void CreateBalls()
{
const float kRadius = 0.05f;
const int kBalls = 40;
Vec2 points(0.0f);
for (int i=0; i < kBalls; ++i)
{
g_bodies.push_back(new RigidBody(Vec2(0.0f, kRadius + kRadius * (2.0f*i)), kRadius, 1.0f, &points, &(points)+1));
}
}
void Init()
{
g_planes.resize(0);
g_forces.resize(0);
g_bodies.resize(0);
g_mouseSpring = NULL;
}
void TickSim(float dt)
{
dt = 1.0f / 30.0f;
// cout << dt << endl;
const int kSubsteps = 1;
dt /= kSubsteps;
for (int i=0; i < kSubsteps; ++i)
{
ApplyForces(dt);
Integrate(dt);
}
}
void DrawCircle(const Vec2& c, float r)
{
glBegin(GL_TRIANGLE_FAN);
glVertex2fv(c);
const int kSegments = 40;
for (int i=0; i < kSegments+1; ++i)
{
float theta = k2Pi*float(i)/kSegments;
float y = c.y + r*Cos(theta);
float x = c.x + r*Sin(theta);
glVertex2f(x, y);
}
glEnd();
}
void DrawString(int x, int y, const char* s)
{
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, kWidth, kHeight, 0);
glRasterPos2d(x, y);
while (*s)
{
glutBitmapCharacter(GLUT_BITMAP_8_BY_13, *s);
++s;
}
}
bool g_step = false;
void GLUTUpdate()
{
//glEnable(GL_LINE_SMOOTH);
//glEnable(GL_BLEND);
//glLineWidth(1.0f);
//glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);
//glHint(GL_LINE_SMOOTH_HINT,GL_NICEST);
glDisable(GL_CULL_FACE);
glClear(GL_COLOR_BUFFER_BIT);
glDisable(GL_DEPTH_TEST);
glPointSize(5.0f);
float aspect = float(kWidth)/kHeight;
glMatrixMode(GL_PROJECTION);
glLoadMatrixf(OrthographicMatrix(-kZoom*aspect, kZoom*aspect, -kZoom, kZoom, 0.0f, 1.0f));
double t = GetSeconds();
if (1 || g_step)
{
TickSim(1.0f/60.0f);
g_step = false;
}
float dt = GetSeconds()-t;
for (int i=0; i < g_planes.size(); ++i)
{
Vec2 p = g_planes[i].z * Vec2(g_planes[i].x, g_planes[i].y);
Vec2 d = Vec2(-g_planes[i].y, g_planes[i].x);
glBegin(GL_LINES);
glColor3f(1.0f, 1.0f, 1.0f);
glVertex2fv(p - d*1000.0);
glVertex2fv(p + d*1000.0);
glEnd();
}
for (int i=0; i < g_particles.size(); ++i)
{
DrawCircle(g_particles[i].position, g_particles[i].radius);
}
int x = 10;
int y = 15;
char line[1024];
glColor3f(1.0f, 1.0f, 1.0f);
sprintf(line, "Frame: %.2fms", dt*1000.0f);
DrawString(x, y, line); y += 13;
glutSwapBuffers();
}
void GLUTReshape(int width, int height)
{
}
void GLUTArrowKeys(int key, int x, int y)
{
}
void GLUTArrowKeysUp(int key, int x, int y)
{
}
void GLUTKeyboardDown(unsigned char key, int x, int y)
{
switch (key)
{
case 'e':
{
break;
}
case 'r':
{
Init();
break;
}
case 't':
{
break;
}
case 's':
{
g_step = true;
break;
}
case 27:
exit(0);
break;
};
}
void GLUTKeyboardUp(unsigned char key, int x, int y)
{
switch (key)
{
case 'e':
{
break;
}
}
}
static int lastx;
static int lasty;
Vec2 ScreenToScene(int x, int y)
{
return Vec2(-kZoom, -kZoom) + 2.0f*kZoom*Vec2(float(x)/kWidth, 1.0f-float(y)/kHeight);
}
void GLUTMouseFunc(int b, int state, int x, int y)
{
switch (state)
{
case GLUT_UP:
{
lastx = x;
lasty = y;
break;
}
case GLUT_DOWN:
{
lastx = x;
lasty = y;
}
}
}
void GLUTMotionFunc(int x, int y)
{
int dx = x-lastx;
int dy = y-lasty;
lastx = x;
lasty = y;
}
int main(int argc, char* argv[])
{
RandInit();
Init();
// init gl
glutInit(&argc, argv);
glutInitDisplayMode(GLUT_RGBA | GLUT_ALPHA | GLUT_DOUBLE | GLUT_DEPTH);
glutInitWindowSize(kWidth, kHeight);
glutCreateWindow("Granular");
glutPositionWindow(200, 200);
glutMouseFunc(GLUTMouseFunc);
glutReshapeFunc(GLUTReshape);
glutDisplayFunc(GLUTUpdate);
glutKeyboardFunc(GLUTKeyboardDown);
glutKeyboardUpFunc(GLUTKeyboardUp);
glutIdleFunc(GLUTUpdate);
glutSpecialFunc(GLUTArrowKeys);
glutSpecialUpFunc(GLUTArrowKeysUp);
glutMotionFunc(GLUTMotionFunc);
#ifndef WIN32
int swap_interval = 1;
CGLContextObj cgl_context = CGLGetCurrentContext();
CGLSetParameter(cgl_context, kCGLCPSwapInterval, &swap_interval);
#endif
glutMainLoop();
}
|
// 问题的描述:打印两个链表的公共值
// 给定两个升序的链表,且链表中无重复元素。打印两个链表的公共值部分
// 同时遍历,相等就打印
// 测试用例有3组:
// 1、空链表(至少一个为空链表)
// 输入:NULL NULL
// 输出:NULL
// 2、非空链表
// 输入:{1,2,3,4,5,6,7} {2,4,6,8,10}
// 输出:2,4,6
// 3、非空链表
// 输入:{1,3,5,7} {2,4,6,8}
// 输出:NULL
#include <iostream>
#include <vector>
using namespace std;
// 链表结点的定义
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :val(x), next(nullptr) {}
};
// 创建一个链表
ListNode* CreateList(vector<int> &nums) {
if (nums.empty())
return nullptr;
ListNode *head = new ListNode(nums[0]);
ListNode *temp_node = head, *new_node = nullptr;
for (int i = 1; i < nums.size(); ++i) {
new_node = new ListNode(nums[i]);
temp_node->next = new_node;
temp_node = new_node;
}
return head;
}
// 回收链表的内存
void FreeList(ListNode *head) {
if (head == nullptr)
return;
ListNode *free_node = nullptr;
while (head != nullptr) {
free_node = head;
head = head->next;
delete free_node;
}
}
// 打印链表公共部分
vector<int> FindCommonPart(ListNode *head1, ListNode *head2) {
if (head1 == nullptr || head2 == nullptr)
return{};
vector<int> result;
while (head1 != nullptr && head2 != nullptr) {
if (head1->val < head2->val)
head1 = head1->next;
else if (head1->val > head2->val)
head2 = head2->next;
else {
result.push_back(head1->val);
head1 = head1->next;
head2 = head2->next;
}
}
return result;
}
int main() {
// 空链表
//vector<int> nums1;
//vector<int> nums2;
// 非空链表
//vector<int> nums1 = { 1,2,3,4,5,6,7 };
//vector<int> nums2 = { 2,4,6,8,10 };
// 非空链表
vector<int> nums1 = { 1,3,5,7 };
vector<int> nums2 = { 2,4,6,8 };
ListNode *head1 = CreateList(nums1);
ListNode *head2 = CreateList(nums2);
vector<int> result = FindCommonPart(head1, head2);
for (int i = 0; i < result.size(); ++i)
cout << result[i] << "\t";
cout << endl;
FreeList(head1);
FreeList(head2);
system("pause");
return 0;
}
|
/* -*- Mode: c++; tab-width: 4; indent-tabs-mode: t; c-basic-offset: 4; c-file-style: "stroustrup" -*-
*
* Copyright (C) 2003-2011 Opera Software ASA. All rights reserved.
*
* This file is part of the Opera web browser.
* It may not be distributed under any circumstances.
*/
#include "core/pch.h"
#ifdef USER_JAVASCRIPT
#include "modules/dom/src/domcore/element.h"
#include "modules/dom/src/domenvironmentimpl.h"
#include "modules/dom/src/domevents/domevent.h"
#include "modules/dom/src/domevents/domeventdata.h"
#include "modules/dom/src/domevents/domeventlistener.h"
#include "modules/dom/src/domevents/domeventtarget.h"
#include "modules/dom/src/domevents/domeventthread.h"
#include "modules/dom/src/domglobaldata.h"
#include "modules/dom/src/userjs/userjsevent.h"
#include "modules/dom/src/userjs/userjsmanager.h"
#include "modules/doc/frm_doc.h"
#include "modules/ecmascript_utils/esasyncif.h"
#include "modules/ecmascript_utils/essched.h"
#include "modules/ecmascript_utils/esthread.h"
#include "modules/util/excepts.h"
#include "modules/util/glob.h"
#include "modules/util/opfile/opfile.h"
#include "modules/util/tempbuf.h"
#include "modules/logdoc/htm_elm.h"
#include "modules/logdoc/datasrcelm.h"
#include "modules/logdoc/htm_ldoc.h"
#include "modules/url/url_sn.h"
#include "modules/encodings/detector/charsetdetector.h"
#ifdef USER_JAVASCRIPT_ADVANCED
# include "modules/encodings/decoders/inputconverter.h"
# include "modules/encodings/decoders/utf16-decoder.h"
# include "modules/prefs/prefsmanager/collections/pc_js.h"
# include "modules/windowcommander/src/WindowCommander.h"
# include "modules/dochand/win.h"
#else // USER_JAVASCRIPT_ADVANCED
# include "modules/prefs/prefsmanager/collections/pc_files.h"
#endif // USER_JAVASCRIPT_ADVANCED
#ifdef USER_JAVASCRIPT_ADVANCED
# ifdef DOM_BROWSERJS_SUPPORT
# include "modules/dom/src/userjs/browserjs_key.h"
# ifdef CRYPTO_VERIFY_SIGNED_TEXTFILE_SUPPORT
# include "modules/libcrypto/include/CryptoVerifySignedTextFile.h"
# else // CRYPTO_VERIFY_SIGNED_TEXTFILE_SUPPORT
# include "modules/libssl/tools/signed_textfile.h"
# endif // CRYPTO_VERIFY_SIGNED_TEXTFILE_SUPPORT
# endif // DOM_BROWSERJS_SUPPORT
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
#include "modules/dom/src/storage/storage.h"
#endif //WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
#ifdef OPERA_CONSOLE
# include "modules/util/OpHashTable.h"
#endif // OPERA_CONSOLE
#ifdef EXTENSION_SUPPORT
# include "modules/gadgets/OpGadgetManager.h"
# include "modules/dom/src/extensions/domextensionmanager.h"
#endif // EXTENSION_SUPPORT
class DOM_UserJSScript;
class DOM_UserJSSource;
class DOM_UserJSRule
{
#ifdef EXTENSION_SUPPORT
friend class DOM_UserJSSource;
#endif // EXTENSION_SUPPORT
private:
DOM_UserJSRule() : matches_all(FALSE), next(NULL) { }
OpString pattern;
BOOL matches_all;
DOM_UserJSRule *next;
public:
~DOM_UserJSRule();
static OP_STATUS Make(DOM_UserJSRule *&rule, const uni_char *pattern, unsigned pattern_length);
BOOL Match(const uni_char *uri);
};
/**
* Contains the (decoded) source code for a UserJS file. This class also
* processes the special comment blocks, and extracts information from them.
*/
class DOM_UserJSSource
: public ListElement<DOM_UserJSSource>
{
public:
~DOM_UserJSSource();
/**< Cleans up include/exclude patterns, and other information extracted
from the special comment block. */
static OP_BOOLEAN Make(DOM_UserJSSource *&out, const uni_char* filename, DOM_UserJSManager::UserJSType type);
/**< Make a new DOM_UserJSSource instance.
*
* @param out Set to point to the created object.
* @param filename The absolute path to the file from which JS source will be read.
* @param type Type of the JS (extension, browserjs etc.)
* @return
* - IS_TRUE - in case of success.
* - IS_FALSE - there was a read error.
* - other errors.
*/
static OP_BOOLEAN Make(DOM_UserJSSource *&out, OpFile &file, DOM_UserJSManager::UserJSType type);
/**< Make a new DOM_UserJSSource instance.
*
* @param out Set to point to the created object.
* @param file The file from which JS source will be read.
* @param type Type of the JS (extension, browserjs etc.).
* @return
* - IS_TRUE - in case of success.
* - IS_FALSE - there was a read error.
* - ERR_NO_MEMORY - no memory.
* - ERR - if reading or decoding the file does not succeed.
*/
OP_BOOLEAN Reload(OpFile &file);
/**< Reloads the file contents.
*
* Reads the file contents and decodes it into memory.
* Useful especially after Empty has been called and the source text
* is needed again.
*
* @param file The file from which JS source will be read.
* @return
* - IS_TRUE - in case of success
* - IS_FALSE - there was a read error
* - ERR_NO_MEMORY - no memory
* - other errors if decoding of the file fails
*/
BOOL WouldUse(FramesDocument *frames_doc);
BOOL WouldUse(DOM_EnvironmentImpl *environment);
/**< @return TRUE if this environment would use this script (based on included/excluded
domain directives). */
const OpString &GetSource() const { return decoded; }
/**< @return the decoded source code. */
void Empty() { decoded.Empty(); }
/**< Call this when the decoded source code is no longer needed. Future calls to
to GetSource will result in an empty string. Calls to WouldUse will still
work. */
BOOL IsEmpty() const { return decoded.IsEmpty(); }
/**< Is the decoded source code in memory? If so, calls to GetSource will result
in an empty string. */
OP_BOOLEAN IsStale() const;
/**< Checks if this object is still valid.
The object becomes stale if the file from which source has been
loaded is modified, in which case data needs to be reloaded. */
const uni_char *GetFilename() const { return filename; }
time_t GetModified() const { return modified; }
/**< Get modification date of the loaded source. */
DOM_UserJSManager::UserJSType GetType() const { return type; }
static void IncRef(DOM_UserJSSource *source);
static void DecRef(DOM_UserJSSource *source);
/** Computes a hash value based on the file's name and modification time. */
unsigned GetFileHash() const;
#ifdef EXTENSION_SUPPORT
BOOL CheckIfAlwaysEnabled();
/**< Returns TRUE if the given UserJS is known to always activate. Used
to determine if creating a DOM environment ahead of time is required
to guarantee that it (and others) will get to run. */
#endif // EXTENSION_SUPPORT
private:
DOM_UserJSSource();
/**< Client code should not use this directly. Use DOM_UserJSSource::Make instead. */
static OP_STATUS LoadFile(OpFile &file, char *&source, OpFileLength &source_length, time_t &last_modified);
static OP_STATUS Decode(char *source, OpFileLength source_length, OpString &decoded_output);
// Let Make access this class through an OpAutoPtr.
friend class OpAutoPtr<DOM_UserJSScript>;
OP_STATUS ProcessComment(const uni_char *comment);
/**< Extract information from the special comment block. */
OP_STATUS ProcessCommentIfPresent();
/**< Verify that a special comment block is present, then extract information
from it. */
void ResetComments();
/**< Clear out all fields that are set by the UserJS comment section. Called
upon reload. */
OpString decoded;
DOM_UserJSRule *include, *exclude;
uni_char *name, *ns, *description;
time_t modified;
const uni_char *filename;
DOM_UserJSManager::UserJSType type;
unsigned refcount;
}; // DOM_UserJSSource
class DOM_UserJSScript
: public ListElement<DOM_UserJSScript>
{
protected:
DOM_UserJSSource *source;
ES_Static_Program *static_program;
URL filename_url;
unsigned refcount;
DOM_UserJSScript();
~DOM_UserJSScript();
friend class OpAutoPtr<DOM_UserJSScript>;
public:
/**
* @returns OpStatus::OK if a DOM_UserJSScript was created,
* OpStatus::ERR_NO_MEMORY if we ran out of memory and OpStatus::ERR
* if the source wasn't enough to create a script (for instance too
* short (i.e. empty) or not decodable by the charset decoder).
*/
static OP_STATUS Make(DOM_UserJSScript *&script, ES_Program *&program, ES_Runtime *runtime, DOM_UserJSSource *source, DOM_UserJSManager::UserJSType type);
DOM_UserJSManager::UserJSType GetType() const { return source->GetType(); }
BOOL WouldUse(FramesDocument *frames_doc);
BOOL WouldUse(DOM_EnvironmentImpl *environment);
OP_STATUS Use(DOM_EnvironmentImpl *environment, ES_Program *&program, ES_Thread *interrupt_thread, DOM_UserJSManager::UsedScript *usedscript);
OP_STATUS GetProgram(ES_Program *&program, ES_Runtime *runtime);
DOM_UserJSSource *GetUserJSSource() { return source; }
const uni_char *GetFilename() const { return source->GetFilename(); }
OP_BOOLEAN IsStale() const { return source->IsStale(); }
static DOM_UserJSScript *IncRef(DOM_UserJSScript *script);
static void DecRef(DOM_UserJSScript *script);
};
DOM_UserJSThread::DOM_UserJSThread(ES_Context *context, DOM_UserJSManager *manager, DOM_UserJSScript *script, DOM_UserJSManager::UserJSType type)
: ES_Thread(context),
manager(manager),
script(DOM_UserJSScript::IncRef(script)),
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
script_storage(NULL),
#endif // WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
type(type)
{
}
DOM_UserJSThread::~DOM_UserJSThread()
{
DOM_UserJSScript::DecRef(script);
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
SetScriptStorage(NULL);
#endif // WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
}
/* virtual */ OP_STATUS
DOM_UserJSThread::Signal(ES_ThreadSignal signal)
{
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
SetScriptStorage(NULL);
#endif // WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
switch (signal)
{
case ES_SIGNAL_FINISHED:
case ES_SIGNAL_FAILED:
case ES_SIGNAL_CANCELLED:
if (type != DOM_UserJSManager::GREASEMONKEY)
manager->ScriptFinished();
}
return ES_Thread::Signal(signal);
}
#ifdef WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
void DOM_UserJSThread::SetScriptStorage(DOM_Storage *ss)
{
if (script_storage != NULL)
{
script_storage->GetRuntime()->Unprotect(*script_storage);
script_storage = NULL;
};
if (ss && IsSignalled())
{
OP_ASSERT(!"Whoops, this thread has ended, no point in calling this function");
return;
}
script_storage = ss;
if (script_storage && !script_storage->GetRuntime()->Protect(*script_storage))
script_storage = NULL;
}
const uni_char*
DOM_UserJSThread::GetScriptFileName() const
{
return script->GetFilename();
}
#endif // WEBSTORAGE_USER_SCRIPT_STORAGE_SUPPORT
/* virtual */ const uni_char *
DOM_UserJSThread::GetInfoString()
{
return UNI_L("User Javascript thread");
}
/* static */ OP_STATUS
DOM_UserJSRule::Make(DOM_UserJSRule *&rule, const uni_char *pattern, unsigned pattern_length)
{
DOM_UserJSRule *new_rule = OP_NEW(DOM_UserJSRule, ());
RETURN_OOM_IF_NULL(new_rule);
OpAutoPtr<DOM_UserJSRule> new_rule_anchor(new_rule);
RETURN_IF_ERROR(new_rule->pattern.Set(pattern, pattern_length));
new_rule->pattern.MakeLower();
new_rule->matches_all = new_rule->pattern.Compare("*") == 0;
new_rule->next = rule;
rule = new_rule_anchor.release();
return OpStatus::OK;
}
DOM_UserJSRule::~DOM_UserJSRule()
{
OP_DELETE(next);
}
BOOL
DOM_UserJSRule::Match(const uni_char *uri)
{
if (matches_all || OpGlob(uri, pattern, FALSE, FALSE))
return TRUE;
if (next)
return next->Match(uri);
else
return FALSE;
}
DOM_UserJSScript::DOM_UserJSScript()
: source(NULL),
static_program(NULL),
refcount(1)
{
}
DOM_UserJSScript::~DOM_UserJSScript()
{
if (static_program)
ES_Runtime::DeleteStaticProgram(static_program);
DOM_UserJSSource::DecRef(source);
}
static BOOL
DOM_IsWhitespace(uni_char ch)
{
if (ch == 32)
return TRUE;
else if (ch < 0xA0)
return ch >= 9 && ch <= 13;
else
switch (ch)
{
case 0x00A0: // NO-BREAK SPACE
case 0x200B: // ZERO WIDTH SPACE
case 0xFEFF: // ZERO WIDTH NO-BREAK SPACE / BYTE ORDER MARK
case 0xFFFE: // 0xFFEF in wrong byte-order
return TRUE;
default:
return uni_isspace(ch);
}
}
static BOOL
DOM_GetNextCommentLine(const uni_char *&comment, unsigned &comment_length, const uni_char *&source)
{
while (*source)
{
while (*source && DOM_IsWhitespace(*source))
++source;
if (!*source)
return FALSE;
const uni_char *line = source;
while (*source && *source != 10 && *source != 13)
++source;
if (line != source)
{
const uni_char *line_end = source;
while (line_end != line && DOM_IsWhitespace(line_end[-1]))
--line_end;
if (line_end - line > 2)
if (line[0] == '/' && line[1] == '/')
{
line += 2;
while (line != line_end && DOM_IsWhitespace(*line))
++line;
comment = line;
comment_length = line_end - line;
return TRUE;
}
}
}
return FALSE;
}
static BOOL
DOM_IsCommentKeyword(const uni_char *&comment, unsigned &comment_length, const uni_char *keyword)
{
unsigned length = uni_strlen(keyword);
if (comment_length > length && uni_strncmp(comment, keyword, length) == 0 && DOM_IsWhitespace(comment[length]))
{
comment += length;
comment_length -= length;
while (comment_length && DOM_IsWhitespace(*comment))
{
++comment;
--comment_length;
}
return comment_length != 0;
}
else
return FALSE;
}
static void
DOM_InsertUserJSSourceIntoCache(DOM_UserJSSource *source)
{
source->Into(&g_DOM_userScriptSources);
DOM_UserJSSource::IncRef(source);
}
/* static */ OP_STATUS
DOM_UserJSScript::Make(DOM_UserJSScript *&script, ES_Program *&program, ES_Runtime *runtime, DOM_UserJSSource *source, DOM_UserJSManager::UserJSType type)
{
const OpString &decoded = source->GetSource();
if (!decoded.IsEmpty())
{
script = OP_NEW(DOM_UserJSScript, ());
if (!script)
return OpStatus::ERR_NO_MEMORY;
OpAutoPtr<DOM_UserJSScript> script_anchor(script);
ES_ProgramText program_text;
program_text.program_text = decoded.CStr();
program_text.program_text_length = decoded.Length();
const uni_char *script_basename = uni_strrchr(source->GetFilename(), PATHSEPCHAR);
if (script_basename)
script->filename_url = g_url_api->GetURL(script_basename+1);
ES_Runtime::CompileProgramOptions options;
options.privilege_level = ES_Runtime::PRIV_LVL_USERJS;
#if defined(DOM_USER_JAVASCRIPT) && defined(OPERA_CONSOLE)
if (g_opera->dom_module.missing_userjs_files.Find(static_cast<INT32>(source->GetFileHash())) != -1)
options.report_error = FALSE;
else
#endif // DOM_USER_JAVASCRIPT && OPERA_CONSOLE
options.context = DOM_UserJSManager::GetErrorString(type, TRUE);
options.script_url = script_basename ? &script->filename_url : NULL;
options.script_type = DOM_UserJSManager::GetScriptType(type);
#ifdef ECMASCRIPT_DEBUGGER
options.reformat_source = g_ecmaManager->GetWantReformatScript(runtime, program_text.program_text, program_text.program_text_length);
#endif // ECMASCRIPT_DEBUGGER
OP_STATUS status = runtime->CompileProgram(&program_text, 1, &program, options);
if (OpStatus::IsError(status))
{
source->Empty();
#if defined(DOM_USER_JAVASCRIPT) && defined(OPERA_CONSOLE)
if (options.report_error)
RETURN_IF_MEMORY_ERROR(g_opera->dom_module.missing_userjs_files.Add(source->GetFileHash()));
#endif // DOM_USER_JAVASCRIPT && OPERA_CONSOLE
return status;
}
status = runtime->ExtractStaticProgram(script->static_program, program);
if (OpStatus::IsError(status))
{
ES_Runtime::DeleteProgram(program);
source->Empty();
return status;
}
script_anchor.release();
script->source = source;
source->Empty(); // Done with the original source.
DOM_UserJSSource::IncRef(source);
return OpStatus::OK;
}
return OpStatus::ERR;
}
BOOL
DOM_UserJSScript::WouldUse(FramesDocument *frames_doc)
{
return (source && source->WouldUse(frames_doc));
}
BOOL
DOM_UserJSScript::WouldUse(DOM_EnvironmentImpl *environment)
{
return (source && source->WouldUse(environment));
}
OP_STATUS
DOM_UserJSScript::Use(DOM_EnvironmentImpl *environment, ES_Program *&program, ES_Thread *interrupt_thread, DOM_UserJSManager::UsedScript *usedscript)
{
if (WouldUse(environment))
{
ES_Context *userjs_context;
ES_Runtime *userjs_runtime;
ES_ThreadScheduler *userjs_scheduler;
#ifdef EXTENSION_SUPPORT
if (usedscript->execution_context)
{
userjs_runtime = usedscript->execution_context->GetESEnvironment()->GetRuntime();
userjs_scheduler = usedscript->execution_context->GetESEnvironment()->GetScheduler();
}
else if (usedscript->script->GetType() != DOM_UserJSManager::EXTENSIONJS)
{
userjs_runtime = environment->GetRuntime();
userjs_scheduler = environment->GetScheduler();
}
else
{
DOM_UserJSExecutionContext *userjs_context = environment->GetUserJSManager()->FindExecutionContext(usedscript->owner);
if (!userjs_context)
return OpStatus::ERR;
/* By construction, only same-document UserJSs should share execution context (and DOM environment.) */
userjs_context->IncRef();
usedscript->execution_context = userjs_context;
ES_Environment *userjs_environment = userjs_context->GetESEnvironment();
userjs_runtime = userjs_environment->GetRuntime();
userjs_scheduler = userjs_environment->GetScheduler();
}
#else
userjs_runtime = environment->GetRuntime();
userjs_scheduler = environment->GetScheduler();
#endif // EXTENSION_SUPPORT
if ((userjs_context = userjs_runtime->CreateContext(NULL)) != NULL)
{
DOM_UserJSManager *manager = environment->GetUserJSManager();
DOM_UserJSThread *thread;
if (!program)
{
OP_STATUS status = userjs_runtime->CreateProgramFromStatic(program, static_program);
if (OpStatus::IsError(status))
{
ES_Runtime::DeleteContext(userjs_context);
return OpStatus::ERR_NO_MEMORY;
}
}
OP_STATUS status = userjs_runtime->PushProgram(userjs_context, program);
ES_Runtime::DeleteProgram(program);
program = NULL;
if (OpStatus::IsError(status) || !(thread = OP_NEW(DOM_UserJSThread, (userjs_context, manager, this, source->GetType()))))
{
ES_Runtime::DeleteContext(userjs_context);
return OpStatus::ERR_NO_MEMORY;
}
OP_BOOLEAN result = userjs_scheduler->AddRunnable(thread, interrupt_thread);
RETURN_IF_ERROR(result);
if (result == OpBoolean::IS_TRUE && source->GetType() != DOM_UserJSManager::GREASEMONKEY)
manager->ScriptStarted();
}
else
return OpStatus::ERR_NO_MEMORY;
}
return OpStatus::OK;
}
/* static */ DOM_UserJSScript *
DOM_UserJSScript::IncRef(DOM_UserJSScript *script)
{
if (script)
++script->refcount;
return script;
}
/* static */ void
DOM_UserJSScript::DecRef(DOM_UserJSScript *script)
{
if (script && --script->refcount == 0)
OP_DELETE(script);
}
DOM_UserJSSource::DOM_UserJSSource()
: include(NULL),
exclude(NULL),
name(NULL),
ns(NULL),
description(NULL),
modified(0),
filename(NULL),
type(DOM_UserJSManager::NORMAL_USERJS),
refcount(0)
{
}
DOM_UserJSSource::~DOM_UserJSSource()
{
OP_ASSERT(refcount == 0);
Out();
ResetComments();
OP_DELETEA(filename);
}
void
DOM_UserJSSource::ResetComments()
{
OP_DELETE(include);
include = NULL;
OP_DELETE(exclude);
exclude = NULL;
OP_DELETEA(name);
name = NULL;
OP_DELETEA(ns);
ns = NULL;
OP_DELETEA(description);
description = NULL;
}
/* static */ void
DOM_UserJSSource::IncRef(DOM_UserJSSource *source)
{
source->refcount++;
}
/* static */ void
DOM_UserJSSource::DecRef(DOM_UserJSSource *source)
{
if (source && --source->refcount == 0)
OP_DELETE(source);
}
/* static */ OP_STATUS
DOM_UserJSSource::LoadFile(OpFile &file, char *&source, OpFileLength &source_length, time_t &last_modified)
{
RETURN_IF_ERROR(file.Open(OPFILE_READ | OPFILE_TEXT));
RETURN_IF_ERROR(file.GetLastModified(last_modified));
RETURN_IF_ERROR(file.GetFileLength(source_length));
if (source_length > 0)
{
if (source_length >= INT_MAX)
return OpStatus::ERR; // Too large file since we store it in memory.
source = OP_NEWA(char, static_cast<int>(source_length) + 1);
RETURN_OOM_IF_NULL(source);
OpAutoArray<char> source_anchor(source);
char *ptr = source;
OpFileLength remaining_length = source_length;
while (!file.Eof() && remaining_length != static_cast<OpFileLength>(0))
{
OpFileLength bytes_read;
RETURN_IF_ERROR(file.Read(ptr, remaining_length, &bytes_read));
ptr += bytes_read;
remaining_length -= bytes_read;
}
/* The source might be in a multi-byte encoding, but in that
case we won't depend on the null-termination in
DOM_UserJSScript::Make. */
*ptr = 0;
source_anchor.release();
}
return OpStatus::OK;
}
/* static */ OP_STATUS
DOM_UserJSSource::Decode(char *source, OpFileLength source_length, OpString &decoded_output)
{
const char *encoding = CharsetDetector::GetJSEncoding(source, static_cast<unsigned long>(source_length), TRUE/*UserJS*/);
if (encoding)
{
InputConverter *converter;
OP_STATUS valid = InputConverter::CreateCharConverter(encoding, &converter);
if (OpStatus::IsSuccess(valid))
{
OpAutoPtr<InputConverter> anchor(converter);
RETURN_IF_ERROR(SetFromEncoding(&decoded_output, converter, source, static_cast<int>(source_length), NULL));
}
else
RETURN_IF_MEMORY_ERROR(valid);
}
if (decoded_output.IsEmpty())
/* If attempt failed, fall back to UTF-8. */
RETURN_IF_MEMORY_ERROR(decoded_output.SetFromUTF8(source, static_cast<int>(source_length)));
return OpStatus::OK;
}
/* static */ OP_BOOLEAN
DOM_UserJSSource::Make(DOM_UserJSSource *&out, const uni_char* filename, DOM_UserJSManager::UserJSType type)
{
OpFile file;
RETURN_IF_ERROR(file.Construct(filename));
return Make(out, file, type);
}
/* static */ OP_BOOLEAN
DOM_UserJSSource::Make(DOM_UserJSSource *&out, OpFile &file, DOM_UserJSManager::UserJSType type)
{
OP_PROBE3(OP_PROBE_DOM_USERJSSOURCE_MAKE);
char *source = NULL;
OpFileLength length;
time_t modified;
OP_STATUS status = LoadFile(file, source, length, modified);
// Delete source unconditionally.
OpAutoArray<char> source_deleter(source);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsSuccess(status))
{
if (length > 0)
{
OpAutoPtr<DOM_UserJSSource> dom_source_auto(OP_NEW(DOM_UserJSSource, ()));
RETURN_OOM_IF_NULL(dom_source_auto.get());
dom_source_auto->filename = UniSetNewStr(file.GetFullPath());
RETURN_OOM_IF_NULL(dom_source_auto->filename);
dom_source_auto->type = type;
dom_source_auto->modified = modified;
RETURN_IF_ERROR(Decode(source, length, dom_source_auto->decoded));
RETURN_IF_ERROR(dom_source_auto->ProcessCommentIfPresent());
out = dom_source_auto.release();
return OpBoolean::IS_TRUE;
}
}
return OpBoolean::IS_FALSE;
}
OP_BOOLEAN
DOM_UserJSSource::Reload(OpFile &file)
{
char *source = NULL;
OpFileLength length;
time_t last_modified;
OP_STATUS status = LoadFile(file, source, length, last_modified);
// Delete source unconditionally.
OpAutoArray<char> source_deleter(source);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsSuccess(status))
{
modified = last_modified;
if (length > 0)
{
RETURN_IF_ERROR(Decode(source, length, decoded));
ResetComments();
RETURN_IF_ERROR(ProcessCommentIfPresent());
return OpBoolean::IS_TRUE;
}
}
return OpBoolean::IS_FALSE;
}
BOOL
DOM_UserJSSource::WouldUse(DOM_EnvironmentImpl *environment)
{
return WouldUse(environment->GetFramesDocument());
}
BOOL
DOM_UserJSSource::WouldUse(FramesDocument *frames_doc)
{
OP_PROBE3(OP_PROBE_DOM_USERJSSCRIPT_WOULDUSE);
if (!exclude && !include)
return TRUE;
URL url = frames_doc->GetURL();
const uni_char *uri = url.GetAttribute(URL::KUniName).CStr();
OpString lowercase_uri;
OP_STATUS status = lowercase_uri.Set(uri);
if (OpStatus::IsError(status))
{
if (OpStatus::IsMemoryError(status))
g_memory_manager->RaiseCondition(status);
return FALSE;
}
lowercase_uri.MakeLower();
if (!exclude || !exclude->Match(lowercase_uri.CStr()))
if (!include || include->Match(lowercase_uri.CStr()))
return TRUE;
return FALSE;
}
OP_BOOLEAN
DOM_UserJSSource::IsStale() const
{
OpFile file;
RETURN_IF_ERROR(file.Construct(filename, OPFILE_ABSOLUTE_FOLDER));
BOOL exists;
RETURN_IF_ERROR(file.Exists(exists));
if (!exists)
return OpBoolean::IS_TRUE;
time_t new_modified;
RETURN_IF_ERROR(file.GetLastModified(new_modified));
if (new_modified != modified)
return OpBoolean::IS_TRUE;
return OpBoolean::IS_FALSE;
}
unsigned
DOM_UserJSSource::GetFileHash() const
{
return static_cast<unsigned>(OpGenericStringHashTable::HashString(GetFilename(), TRUE))
+ static_cast<unsigned>(GetModified() % UINT_MAX)
+ static_cast<unsigned>(GetModified() / UINT_MAX);
}
OP_STATUS
DOM_UserJSSource::ProcessComment(const uni_char *source)
{
const uni_char *comment;
unsigned comment_length;
BOOL in_userscript = FALSE;
while (DOM_GetNextCommentLine(comment, comment_length, source))
{
if (!in_userscript)
{
if (comment_length == 14 && uni_strncmp(comment, UNI_L("==UserScript=="), 14) == 0)
in_userscript = TRUE;
}
else
{
if (comment_length == 15 && uni_strncmp(comment, UNI_L("==/UserScript=="), 15) == 0)
break;
else if (DOM_IsCommentKeyword(comment, comment_length, UNI_L("@name")))
{
if (!name)
RETURN_OOM_IF_NULL(name = UniSetNewStrN(comment, comment_length));
}
else if (DOM_IsCommentKeyword(comment, comment_length, UNI_L("@namespace")))
{
if (!ns)
RETURN_OOM_IF_NULL(ns = UniSetNewStrN(comment, comment_length));
}
else if (DOM_IsCommentKeyword(comment, comment_length, UNI_L("@description")))
{
if (!description)
RETURN_OOM_IF_NULL(description = UniSetNewStrN(comment, comment_length));
}
else if (DOM_IsCommentKeyword(comment, comment_length, UNI_L("@include")))
RETURN_IF_ERROR(DOM_UserJSRule::Make(include, comment, comment_length));
else if (DOM_IsCommentKeyword(comment, comment_length, UNI_L("@exclude")))
RETURN_IF_ERROR(DOM_UserJSRule::Make(exclude, comment, comment_length));
}
}
return OpStatus::OK;
}
OP_STATUS
DOM_UserJSSource::ProcessCommentIfPresent()
{
int start = decoded.Find("==UserScript==");
if (start != KNotFound)
{
int end = decoded.Find("==/UserScript==");
if (end != KNotFound)
{
const uni_char *str = decoded.CStr();
while (start > 0 && str[start - 1] != 0x0a && str[start - 1] != 0x0d)
--start;
while (str[end] && str[end] != 0x0a && str[end] != 0x0d)
++end;
OpString comment;
RETURN_IF_ERROR(comment.Set(str + start, end - start));
return ProcessComment(comment.CStr());
}
}
return OpStatus::OK;
}
#ifdef EXTENSION_SUPPORT
BOOL
DOM_UserJSSource::CheckIfAlwaysEnabled()
{
if (exclude)
return FALSE;
DOM_UserJSRule *rule = include;
BOOL matches_all = rule == NULL;
while (rule && !matches_all)
{
matches_all = rule->matches_all;
rule = rule->next;
}
return matches_all;
}
#endif // EXTENSION_SUPPORT
#else // USER_JAVASCRIPT_ADVANCED
class DOM_UserJSCallback
: public ES_AsyncCallback
{
protected:
DOM_UserJSManager *manager;
public:
DOM_UserJSCallback(DOM_UserJSManager *manager)
: manager(manager)
{
}
OP_STATUS HandleCallback(ES_AsyncOperation operation, ES_AsyncStatus status, const ES_Value &result)
{
manager->ScriptFinished();
return OpStatus::OK;
}
};
#endif // USER_JAVASCRIPT_ADVANCED
#ifdef DOM3_EVENTS
OP_BOOLEAN
DOM_UserJSManager::SendEventEvent(DOM_EventType type, const uni_char *namespaceURI, const uni_char *type_string, DOM_Event *real_event, ES_Object *listener, ES_Thread *interrupt_thread)
{
if (event_target->HasListeners(type, namespaceURI, type_string, ES_PHASE_AT_TARGET))
{
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, real_event, type_string, listener));
return environment->SendEvent(event, interrupt_thread);
}
else
return OpBoolean::IS_FALSE;
}
#else // DOM3_EVENTS
OP_BOOLEAN
DOM_UserJSManager::SendEventEvent(DOM_EventType type, const uni_char *type_string, DOM_Event *real_event, ES_Object *listener, ES_Thread *interrupt_thread)
{
if (event_target->HasListeners(type, type_string, ES_PHASE_AT_TARGET))
{
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, real_event, type_string, listener));
return environment->SendEvent(event, interrupt_thread);
}
else
return OpBoolean::IS_FALSE;
}
#endif // DOM3_EVENTS
/* virtual */ DOM_Object *
DOM_UserJSManager::GetOwnerObject()
{
OP_ASSERT(FALSE);
return NULL;
}
class DOM_UserJSAnchor
: public DOM_Object
{
protected:
DOM_UserJSManager *manager;
public:
DOM_UserJSAnchor(DOM_UserJSManager *manager)
: manager(manager)
{
}
virtual void GCTrace()
{
manager->GetEventTarget()->GCTrace();
}
};
DOM_UserJSManager::DOM_UserJSManager(DOM_EnvironmentImpl *environment, BOOL user_js_enabled, BOOL is_https)
: environment(environment),
#ifndef USER_JAVASCRIPT_ADVANCED
callback(NULL),
#endif // USER_JAVASCRIPT_ADVANCED
anchor(NULL),
is_enabled(FALSE),
only_browserjs(!user_js_enabled),
is_https(is_https),
queued_run_greasemonkey(FALSE),
is_active(0),
handled_external_script(NULL),
handled_script(NULL),
handled_stylesheet(NULL)
{
}
#ifdef EXTENSION_SUPPORT
DOM_UserJSExecutionContext::~DOM_UserJSExecutionContext()
{
OP_ASSERT(ref_count == 0);
Out();
if (es_environment)
{
/* A non-standalone ES_Environment, hence shutdown is manual. */
OP_DELETE(es_environment->GetAsyncInterface());
ES_ThreadScheduler *scheduler = es_environment->GetScheduler();
if (scheduler)
{
scheduler->RemoveThreads(TRUE, TRUE);
OP_ASSERT(!scheduler->IsActive());
OP_DELETE(scheduler);
}
if (DOM_Runtime *runtime = static_cast<DOM_Runtime *>(es_environment->GetRuntime()))
{
runtime->SetESScheduler(NULL);
runtime->SetESAsyncInterface(NULL);
runtime->Detach();
}
ES_Environment::Destroy(es_environment);
}
}
/* static */OP_STATUS
DOM_UserJSExecutionContext::Make(DOM_UserJSExecutionContext *&userjs_context, DOM_UserJSManager *manager, DOM_EnvironmentImpl *environment, OpGadget *owner)
{
userjs_context = OP_NEW(DOM_UserJSExecutionContext, (owner));
if (!userjs_context)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS status = OpStatus::OK;
DOM_Runtime *dom_runtime = NULL;
ES_ThreadScheduler *scheduler = NULL;
ES_AsyncInterface *asyncif = NULL;
FramesDocument *frames_doc = environment->GetFramesDocument();
if (!(dom_runtime = OP_NEW(DOM_Runtime, ())))
goto return_on_error;
if (OpStatus::IsError(status = dom_runtime->Construct(DOM_Runtime::TYPE_EXTENSION_JS, environment, "Window", frames_doc->GetMutableOrigin(), FALSE, environment->GetRuntime())))
goto return_on_error;
if (!(scheduler = ES_ThreadScheduler::Make(dom_runtime, FALSE, TRUE)))
goto oom_error;
if (!(asyncif = OP_NEW(ES_AsyncInterface, (dom_runtime, scheduler))))
goto oom_error;
if (OpStatus::IsError(status = ES_Environment::Create(userjs_context->es_environment, dom_runtime, scheduler, asyncif, FALSE, frames_doc ? &frames_doc->GetURL() : NULL)))
goto return_on_error;
dom_runtime->SetESAsyncInterface(asyncif);
dom_runtime->SetESScheduler(scheduler);
RETURN_IF_ERROR(environment->GetRuntime()->MergeHeapWith(dom_runtime));
return DOM_ExtensionScope::Initialize(userjs_context->es_environment, owner);
oom_error:
status = OpStatus::ERR_NO_MEMORY;
return_on_error:
OP_DELETE(scheduler);
OP_DELETE(asyncif);
if (dom_runtime)
dom_runtime->Detach();
userjs_context->DecRef();
return status;
}
void
DOM_UserJSExecutionContext::BeforeDestroy()
{
if (DOM_ExtensionScope *global_scope = DOM_ExtensionScope::GetGlobalScope(es_environment))
global_scope->BeforeDestroy();
}
#endif // EXTENSION_SUPPORT
DOM_UserJSManager::~DOM_UserJSManager()
{
#ifndef USER_JAVASCRIPT_ADVANCED
OP_DELETE(callback);
#endif // USER_JAVASCRIPT_ADVANCED
while (UsedScript *usedscript = (UsedScript *) usedscripts.First())
{
usedscript->Out();
DOM_UserJSScript::DecRef(usedscript->script);
ES_Runtime::DeleteProgram(usedscript->program);
OP_DELETE(usedscript);
}
#ifdef EXTENSION_SUPPORT
UnreferenceExecutionContexts();
OP_ASSERT(userjs_execution_contexts.Empty());
#endif // EXTENSION_SUPPORT
if (anchor)
anchor->GetRuntime()->Unprotect(*anchor);
DOM_UserJSManagerLink::Out();
}
#ifdef EXTENSION_SUPPORT
DOM_UserJSExecutionContext*
DOM_UserJSManager::FindExecutionContext(OpGadget *owner)
{
for(DOM_UserJSExecutionContext *c = userjs_execution_contexts.First(); c; c = c->Suc())
if (c->GetOwner() == owner)
return c;
return NULL;
}
OpGadget*
DOM_UserJSManager::FindRuntimeGadget(DOM_Runtime *runtime)
{
for (DOM_UserJSExecutionContext *c = userjs_execution_contexts.First(); c; c = c->Suc())
if (c->GetESEnvironment()->GetRuntime() == runtime)
return c->GetOwner();
return NULL;
}
void
DOM_UserJSManager::UnreferenceExecutionContexts()
{
DOM_UserJSExecutionContext *c = userjs_execution_contexts.First();
while (c)
{
DOM_UserJSExecutionContext *d = c;
c = c->Suc();
d->DecRef();
}
}
#endif // EXTENSION_SUPPORT
#ifdef USER_JAVASCRIPT_ADVANCED
OP_STATUS
#ifdef EXTENSION_SUPPORT
DOM_UserJSManager::UseScript(DOM_UserJSScript *script, ES_Program *program, OpGadget *owner)
#else
DOM_UserJSManager::UseScript(DOM_UserJSScript *script, ES_Program *program)
#endif // EXTENSION_SUPPORT
{
UsedScript *usedscript = OP_NEW(UsedScript, ());
if (!usedscript)
{
ES_Runtime::DeleteProgram(program);
return OpStatus::ERR_NO_MEMORY;
}
usedscript->script = DOM_UserJSScript::IncRef(script);
usedscript->program = program;
#ifdef EXTENSION_SUPPORT
usedscript->owner = owner;
#endif // EXTENSION_SUPPORT
/* Insert script sorted in usedscripts. */
Link *existing = usedscripts.First();
while (existing)
{
const uni_char *existing_file_name = static_cast<UsedScript *>(existing)->script->GetFilename();
int cmp = uni_stricmp(script->GetFilename(), existing_file_name);
if (cmp > 0 || cmp == 0 && uni_strcmp(script->GetFilename(), existing_file_name) > 0)
existing = existing->Suc();
else
break;
}
if (existing)
usedscript->Precede(existing);
else
usedscript->Into(&usedscripts);
return OpStatus::OK;
}
OP_BOOLEAN
#ifdef EXTENSION_SUPPORT
DOM_UserJSManager::LoadFile(OpFile &file, UserJSType type, BOOL cache, OpGadget *owner)
#else
DOM_UserJSManager::LoadFile(OpFile &file, UserJSType type, BOOL cache)
#endif
{
OP_PROBE3(OP_PROBE_DOM_USERJSMANAGER_LOADFILE);
DOM_UserJSScript *script = cache ? GetCachedScript(file.GetFullPath(), type) : NULL;
ES_Program *program = NULL;
#ifdef EXTENSION_SUPPORT
ES_Runtime* es_extension_runtime = NULL;
if (type == EXTENSIONJS && owner)
{
DOM_UserJSExecutionContext *userjs_context = FindExecutionContext(owner);
if (!userjs_context)
{
RETURN_IF_ERROR(DOM_UserJSExecutionContext::Make(userjs_context, this, environment, owner));
userjs_context->Into(&userjs_execution_contexts);
}
es_extension_runtime = userjs_context->GetESEnvironment()->GetRuntime();
}
#endif // EXTENSION_SUPPORT
if (!script)
{
DOM_UserJSSource *dom_source = GetLoadedSource(file.GetFullPath(), type);
if (!dom_source)
{
OP_BOOLEAN loaded = DOM_UserJSSource::Make(dom_source, file, type);
if (loaded != OpBoolean::IS_TRUE)
return loaded;
#ifdef EXTENSION_SUPPORT
if (dom_source->GetType() == EXTENSIONJS && dom_source->CheckIfAlwaysEnabled())
g_DOM_have_always_enabled_extension_js = TRUE;
#endif // EXTENSION_SUPPORT
DOM_InsertUserJSSourceIntoCache(dom_source);
}
else if (dom_source->IsEmpty())
{
OP_BOOLEAN loaded = dom_source->Reload(file);
if (loaded != OpBoolean::IS_TRUE)
return loaded;
}
ES_Runtime *runtime = environment->GetRuntime();
#ifdef EXTENSION_SUPPORT
if (type == EXTENSIONJS && es_extension_runtime)
runtime = es_extension_runtime;
#endif // EXTENSION_SUPPORT
// When caching is disabled, only compile the script if it
// would be used. If caching is enabled, however, compile it
// now, so it can fetched from cache later.
if (!cache && !dom_source->WouldUse(environment))
return OpStatus::OK;
OP_STATUS status = DOM_UserJSScript::Make(script, program, runtime, dom_source, type);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsError(status))
script = NULL;
else if (cache)
script->Into(&g_DOM_userScripts);
}
if (script)
{
#ifdef EXTENSION_SUPPORT
OP_STATUS status = UseScript(script, program, owner);
#else
OP_STATUS status = UseScript(script, program);
#endif // EXTENSION_SUPPORT
// If caching is disabled, the reference held by usedscripts
// should be the only reference. Or, if UseScript failed, then
// this will delete the script.
if (!cache)
DOM_UserJSScript::DecRef(script);
if (OpStatus::IsError(status))
return status;
}
return OpBoolean::IS_TRUE;
}
#ifdef DOM_BROWSERJS_SUPPORT
/* Also used from dom/src/domenvironmentimpl.cpp. */
OP_BOOLEAN
DOM_CheckBrowserJSSignature(const OpFile &file)
{
OpString resolved;
OpString path;
OP_MEMORY_VAR BOOL successful;
RETURN_IF_ERROR(path.Append("file:"));
RETURN_IF_ERROR(path.Append(file.GetFullPath()));
RETURN_IF_LEAVE(successful = g_url_api->ResolveUrlNameL(path, resolved));
if (!successful || resolved.Find("file://") != 0)
return OpStatus::ERR;
URL url = g_url_api->GetURL(resolved.CStr());
if (!url.QuickLoad(TRUE))
return OpStatus::ERR;
#ifdef CRYPTO_VERIFY_SIGNED_TEXTFILE_SUPPORT
if (!CryptoVerifySignedTextFile(url, "//", DOM_BROWSERJS_KEY, sizeof DOM_BROWSERJS_KEY))
#else
if (!VerifySignedTextFile(url, "//", DOM_BROWSERJS_KEY, sizeof DOM_BROWSERJS_KEY))
#endif // CRYPTO_VERIFY_SIGNED_TEXTFILE_SUPPORT
return OpBoolean::IS_FALSE;
else
return OpBoolean::IS_TRUE;
}
static OP_STATUS
DOM_CheckBrowserJSSignatureDelux(const OpFile &file)
{
OP_BOOLEAN result = DOM_CheckBrowserJSSignature(file);
if (result == OpBoolean::IS_FALSE)
{
#ifdef PREFS_WRITE
RETURN_IF_LEAVE(OpStatus::Ignore(g_pcjs->WriteIntegerL(PrefsCollectionJS::BrowserJSSetting, 1)));
#endif // PREFS_WRITE
return OpStatus::ERR;
}
else if (result == OpBoolean::IS_TRUE)
return OpStatus::OK;
else
return result;
}
#endif // DOM_BROWSERJS_SUPPORT
#ifdef DOM_USER_JAVASCRIPT
static OP_STATUS WarnLoadFailure(const uni_char *filename, DOM_UserJSManager::UserJSType type)
{
#ifdef OPERA_CONSOLE
/* A hash is used as a signature for the filename; collisions a possibility. Effect would be
that the new entry is not reported as failing. Problems surrounding overly large sets of
errant filenames not considered very likely, so no mitigations. */
INT32 hashed_filename = static_cast<INT32>(OpGenericStringHashTable::HashString(filename, TRUE));
if (g_opera->dom_module.missing_userjs_files.Find(hashed_filename) == -1)
{
RETURN_IF_MEMORY_ERROR(g_opera->dom_module.missing_userjs_files.Add(hashed_filename));
const uni_char *provenance = DOM_UserJSManager::GetErrorString(type, FALSE/*not compiling => loading*/);
ES_ErrorInfo error_info(provenance);
uni_snprintf(error_info.error_text, ARRAY_SIZE(error_info.error_text), UNI_L("Failed to load path/file: %s\n"), filename);
/* URL: in this context isn't meaningful, leave as empty. */
RETURN_IF_ERROR(DOM_EnvironmentImpl::PostError(NULL, error_info, provenance, NULL));
}
#endif // OPERA_CONSOLE
return OpStatus::OK;
}
#endif // DOM_USER_JAVASCRIPT
#ifdef DOM_BROWSERJS_SUPPORT
static OP_STATUS GetBrowserJSPath(OpString &result)
{
RETURN_IF_ERROR(g_folder_manager->GetFolderPath(OPFILE_HOME_FOLDER, result));
return result.Append(UNI_L("browser.js"));
}
#endif // DOM_BROWSERJS_SUPPORT
OP_STATUS
DOM_UserJSManager::LoadScripts()
{
OP_PROBE3(OP_PROBE_DOM_USERJSMANAGER_LOADSCRIPTS);
BOOL cache = TRUE;
#ifdef ECMASCRIPT_DEBUGGER
// We want to disable cache if debugging is enabled for this ES_Runtime. This ensures
// that the debugger always received the NewScript event on the correct ES_Runtime.
cache = !g_ecmaManager->IsDebugging(environment->GetRuntime());
#endif // ECMASCRIPT_DEBUGGER
#ifdef DOM_BROWSERJS_SUPPORT
if (g_pcjs->GetIntegerPref(PrefsCollectionJS::BrowserJSSetting) == 2)
{
if (DOM_UserJSScript *browserjs = cache ? GetCachedScript(NULL, BROWSERJS) : NULL)
RETURN_IF_ERROR(UseScript(browserjs, NULL));
else
{
OpFile file;
OP_STATUS status;
OpString browserjs_path;
RETURN_IF_ERROR(GetBrowserJSPath(browserjs_path));
if (OpStatus::IsSuccess(status = file.Construct(browserjs_path.CStr(), OPFILE_ABSOLUTE_FOLDER)))
{
BOOL exists = FALSE;
RETURN_IF_ERROR(file.Exists(exists));
if (exists)
{
status = DOM_CheckBrowserJSSignatureDelux(file);
if (OpStatus::IsMemoryError(status))
return status;
else if (OpStatus::IsSuccess(status))
status = LoadFile(file, BROWSERJS, cache);
}
#ifdef PREFS_WRITE
else
TRAP_AND_RETURN(status, OpStatus::Ignore(g_pcjs->WriteIntegerL(PrefsCollectionJS::BrowserJSSetting, 0)));
#endif // PREFS_WRITE
}
if (OpStatus::IsMemoryError(status))
return status;
}
}
#endif // DOM_BROWSERJS_SUPPORT
#ifdef DOM_USER_JAVASCRIPT
const uni_char *filenames = g_pcjs->GetStringPref(PrefsCollectionJS::UserJSFiles, DOM_EnvironmentImpl::GetHostName(environment->GetFramesDocument())).CStr();
# if defined REVIEW_USER_SCRIPTS
OpString reviewed_filenames;
Window *window = environment->GetFramesDocument()->GetWindow();
if (window)
{
WindowCommander *wc = window->GetWindowCommander();
if(wc->GetDocumentListener()->OnReviewUserScripts(wc, environment->GetFramesDocument()->GetHostName(), filenames, reviewed_filenames))
filenames = reviewed_filenames.DataPtr();// or CStr
}
# endif // REVIEW_USER_SCRIPTS
if (filenames)
while (*filenames)
{
while (*filenames == ' ' || *filenames == ',')
++filenames;
const uni_char *filename = filenames, *options = NULL;
while (*filenames && *filenames != ',')
{
if (!options && *filenames == ';')
options = filenames;
++filenames;
}
if (filename != filenames)
{
const uni_char *filename_end = options;
BOOL opera = FALSE, greasemonkey = FALSE;
if (options)
while (TRUE)
{
const uni_char *option_end = options + 1;
while (*option_end && *option_end != ';' && *option_end != ',' && *option_end != ' ')
++option_end;
unsigned option_length = option_end - options;
if (option_length == 6 && uni_strncmp(options, UNI_L(";opera"), 6) == 0)
opera = TRUE;
else if (option_length == 13 && uni_strncmp(options, UNI_L(";greasemonkey"), 13) == 0)
greasemonkey = TRUE;
if (!*option_end || *option_end == ',')
break;
else
options = option_end;
}
else
filename_end = filenames;
while (filename_end > filename && *(filename_end-1) == ' ')
--filename_end;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append(filename, filename_end - filename));
filename = buffer.GetStorage();
OpFile file;
OP_STATUS status;
/* For constructing the file, we use here OPFILE_SERIALIZED_FOLDER. It was not used before,
because the INI parser was also expanding environment variables, and CORE-36151 changed it.
If the user js path contains any environment variables, these will have to be expanded
when constructing the file. Using OPFILE_SERIALIZED_FOLDER will allow the platform
implementation of OpLowLevelFile to expand environment variables, while previously used
OPFILE_ABSOLUTE_FOLDER would cause treating the path as a proper path without any more
work needed, and the error log would contain then entries like:
User JS loading
Failed to load path/file: $OPERA_HOME/userjs/
It looks like expanding environment varialbes in other prefs is still working well
(eg. User Prefs|Console Error Log=$OPERA_HOME/error.log will cause saving the log
in the proper place) so the change is needed only in places, where User Prefs|User JavaScript File
pref value is used. */
if (OpStatus::IsError(status = file.Construct(filename, OPFILE_SERIALIZED_FOLDER)))
if (OpStatus::IsMemoryError(status))
return status;
else
{
RETURN_IF_MEMORY_ERROR(WarnLoadFailure(filename, greasemonkey ? GREASEMONKEY : NORMAL_USERJS));
continue;
}
BOOL exists = FALSE;
if (OpStatus::IsError(status = file.Exists(exists)))
if (OpStatus::IsMemoryError(status))
return status;
else
{
RETURN_IF_MEMORY_ERROR(WarnLoadFailure(filename, greasemonkey ? GREASEMONKEY : NORMAL_USERJS));
continue;
}
OP_BOOLEAN result = OpBoolean::IS_FALSE;
OpFileInfo::Mode mode;
if (!exists)
{
RETURN_IF_MEMORY_ERROR(WarnLoadFailure(filename, greasemonkey ? GREASEMONKEY : NORMAL_USERJS));
continue;
}
else
{
RETURN_IF_ERROR(file.GetMode(mode));
if (filename[buffer.Length() - 1] != PATHSEPCHAR && mode != OpFileInfo::DIRECTORY)
{
BOOL use_greasemonkey = greasemonkey;
if (!opera && !greasemonkey)
{
unsigned filename_length = uni_strlen(filename);
if (filename_length > 8 && uni_str_eq(filename + filename_length - 8, ".user.js"))
use_greasemonkey = TRUE;
}
RETURN_IF_MEMORY_ERROR(result = LoadFile(file, use_greasemonkey ? GREASEMONKEY : NORMAL_USERJS, cache));
/* Report warning, but continue. */
if (OpStatus::IsError(result))
{
RETURN_IF_MEMORY_ERROR(WarnLoadFailure(filename, use_greasemonkey ? GREASEMONKEY : NORMAL_USERJS));
continue;
}
}
}
/* Process the directory, but ignoring problematic files. */
if (result == OpBoolean::IS_FALSE && mode != OpFileInfo::FILE)
{
OpFolderLister *lister = OpFile::GetFolderLister(OPFILE_ABSOLUTE_FOLDER, UNI_L("*.js"), file.GetFullPath());
if (!lister)
return OpStatus::ERR_NO_MEMORY;
OP_STATUS status = OpStatus::OK;
while (lister->Next())
{
if ((filename = lister->GetFullPath()) == NULL)
continue;
BOOL use_greasemonkey = greasemonkey;
if (!opera && !greasemonkey)
{
unsigned filename_length = uni_strlen(filename);
if (filename_length > 8 && uni_str_eq(filename + filename_length - 8, ".user.js"))
use_greasemonkey = TRUE;
}
OpFile file;
if (OpStatus::IsMemoryError(status = file.Construct(filename)) ||
OpStatus::IsMemoryError(status = LoadFile(file, use_greasemonkey ? GREASEMONKEY : NORMAL_USERJS, cache)))
{
OP_DELETE(lister);
return status;
}
/* An error, but report it as a warning and continue. */
if (OpStatus::IsError(status) && OpStatus::IsMemoryError(WarnLoadFailure(filename, use_greasemonkey ? GREASEMONKEY : NORMAL_USERJS)))
{
OP_DELETE(lister);
return OpStatus::ERR_NO_MEMORY;
}
}
OP_DELETE(lister);
}
}
}
#endif // DOM_USER_JAVASCRIPT
#ifdef EXTENSION_SUPPORT
// Add any files defined by active extensions
if (AllowExtensionJS(environment, NULL))
for (OpGadgetExtensionUserJS *extension_userjs = g_gadget_manager->GetFirstActiveExtensionUserJS();
extension_userjs; extension_userjs = extension_userjs->Suc())
{
OpFile userjs_file;
RETURN_IF_ERROR(userjs_file.Construct(extension_userjs->userjs_filename, OPFILE_ABSOLUTE_FOLDER, OPFILE_FLAGS_ASSUME_ZIP));
BOOL exists;
RETURN_IF_ERROR(userjs_file.Exists(exists));
if (exists)
{
OP_ASSERT(extension_userjs->owner);
OP_BOOLEAN result;
RETURN_IF_ERROR(result = AllowExtensionJS(environment, extension_userjs->owner));
if (result == OpBoolean::IS_TRUE)
RETURN_IF_ERROR(LoadFile(userjs_file, EXTENSIONJS, cache, extension_userjs->owner));
}
}
#endif // EXTENSION_SUPPORT
return OpStatus::OK;
}
/* static */ DOM_UserJSScript *
DOM_UserJSManager::GetCachedScript(const uni_char *filename, DOM_UserJSManager::UserJSType type)
{
for (DOM_UserJSScript *script = g_DOM_userScripts.First(); script; script = script->Suc())
{
if (type == BROWSERJS)
{
if (type == script->GetType())
return script;
}
else if (uni_str_eq(filename, script->GetFilename()))
{
OP_ASSERT(script->GetType() == type);
return script;
}
}
return NULL;
}
/* static */ DOM_UserJSSource *
DOM_UserJSManager::GetLoadedSource(const uni_char *filename, DOM_UserJSManager::UserJSType type)
{
for (DOM_UserJSSource *source = g_DOM_userScriptSources.First(); source; source = source->Suc())
{
if (type == BROWSERJS && type == source->GetType())
return source;
else if (uni_str_eq(filename, source->GetFilename()))
{
OP_ASSERT(source->GetType() == type);
return source;
}
}
return NULL;
}
OP_STATUS
DOM_UserJSManager::Construct()
{
DOM_Object *object;
RETURN_IF_ERROR(GetObject(object));
event_target = OP_NEW(DOM_EventTarget, (object));
if (!event_target)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsMemoryError(DOM_Object::DOMSetObjectRuntime(anchor = OP_NEW(DOM_UserJSAnchor, (this)), environment->GetDOMRuntime())) ||
!anchor->GetRuntime()->Protect(*anchor))
{
anchor = NULL;
return OpStatus::ERR_NO_MEMORY;
}
OP_STATUS status = OpStatus::OK;
#ifdef EXTENSION_SUPPORT
/* Create the support object for an extension background (NULL if this
* is no such thing) + assign ownership to the environment. */
DOM_ExtensionBackground *extension_background = NULL;
if (FramesDocument *frames_doc = GetEnvironment()->GetFramesDocument())
{
status = g_extension_manager->AddExtensionContext(frames_doc->GetWindow(), GetEnvironment()->GetDOMRuntime(), &extension_background);
if (OpStatus::IsSuccess(status) && extension_background)
GetEnvironment()->SetExtensionBackground(extension_background);
}
#endif // EXTENSION_SUPPORT
if (OpStatus::IsSuccess(status) && OpStatus::IsSuccess(status = ReloadScripts()))
{
is_enabled = TRUE;
status = RunScripts(FALSE);
}
if (OpStatus::IsError(status))
{
#ifdef EXTENSION_SUPPORT
/* If we don't have an extension background then the manager we were trying
* to construct here was for a separate extension-associated window, so
* remove the extension context from the environment instead of effectively
* shutting down the extension as RemoveExtensionContext(DOM_ExtensionSupport *) would do.
*
* Refer to the DOM_ExtensionManager documentation for more details. */
if (extension_background)
g_extension_manager->RemoveExtensionContext(extension_background->GetExtensionSupport());
else
g_extension_manager->RemoveExtensionContext(GetEnvironment());
GetEnvironment()->SetExtensionBackground(NULL);
#endif // EXTENSION_SUPPORT
BeforeDestroy();
}
return status;
}
void
DOM_UserJSManager::BeforeDestroy()
{
#ifdef EXTENSION_SUPPORT
for(DOM_UserJSExecutionContext *c = userjs_execution_contexts.First(); c; c = c->Suc())
c->BeforeDestroy();
#endif // EXTENSION_SUPPORT
}
#ifdef EXTENSION_SUPPORT
OP_STATUS
DOM_UserJSManager::GetExtensionESRuntimes(OpVector<ES_Runtime> &es_runtimes)
{
DOM_UserJSExecutionContext *c = userjs_execution_contexts.First();
while (c)
{
if (c->GetESEnvironment())
RETURN_IF_ERROR(es_runtimes.Add(c->GetESEnvironment()->GetRuntime()));
c = c->Suc();
}
return OpStatus::OK;
}
/* static */ OP_BOOLEAN
DOM_UserJSManager::AllowExtensionJS(DOM_EnvironmentImpl *environment, OpGadget *owner)
{
FramesDocument *frames_doc = environment->GetFramesDocument();
BOOL allowed = FALSE;
RETURN_IF_ERROR(OpSecurityManager::CheckSecurity(OpSecurityManager::DOM_EXTENSION_ALLOW, OpSecurityContext(frames_doc), OpSecurityContext(frames_doc->GetURL(), owner), allowed));
return (allowed ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE);
}
#endif // EXTENSION_SUPPORT
OP_STATUS
DOM_UserJSManager::RunScripts(BOOL greasemonkey)
{
OP_PROBE3(OP_PROBE_DOM_USERJSMANAGER_RUNSCRIPTS);
#ifdef DOM_USER_JAVASCRIPT
if (DOM_UserJSManagerLink::InList())
{
OP_ASSERT(greasemonkey);
queued_run_greasemonkey = TRUE;
return OpStatus::OK;
}
BOOL execute_regular_scripts = !only_browserjs;
if (execute_regular_scripts && is_https)
execute_regular_scripts = g_pcjs->GetIntegerPref(PrefsCollectionJS::UserJSEnabledHTTPS, DOM_EnvironmentImpl::GetHostName(environment->GetFramesDocument())) != 0;
#else
const BOOL execute_regular_scripts = FALSE;
#endif // DOM_USER_JAVASCRIPT
for (UsedScript *usedscript = (UsedScript *) usedscripts.First(); usedscript; usedscript = (UsedScript *) usedscript->Suc())
{
if (usedscript->script->GetType() == EXTENSIONJS)
{
#ifdef EXTENSION_SUPPORT
OP_BOOLEAN result;
RETURN_IF_ERROR(result = AllowExtensionJS(environment, usedscript->owner));
if (result == OpBoolean::IS_FALSE)
#endif // EXTENSION_SUPPORT
continue;
}
if ((usedscript->script->GetType() == BROWSERJS ||
usedscript->script->GetType() == EXTENSIONJS ||
execute_regular_scripts) && !greasemonkey == (usedscript->script->GetType() != GREASEMONKEY))
RETURN_IF_ERROR(usedscript->script->Use(environment, usedscript->program, NULL, usedscript));
}
#ifdef DOM_USER_JAVASCRIPT
if (queued_run_greasemonkey)
{
queued_run_greasemonkey = FALSE;
return RunScripts(TRUE);
}
#endif // DOM_USER_JAVASCRIPT
return OpStatus::OK;
}
#else // USER_JAVASCRIPT_ADVANCED
static OP_STATUS
DOM_GetUserJSFile(OpFile &file, DOM_EnvironmentImpl *environment = NULL)
{
TRAP_AND_RETURN(status, g_pcfiles->GetFileL(PrefsCollectionFiles::UserJSFile, file, environment ? DOM_EnvironmentImpl::GetHostName(environment->GetFramesDocument()) : NULL));
return OpStatus::OK;
}
static OP_STATUS
DOM_OpenUserJSFile(OpFile &file, DOM_EnvironmentImpl *environment)
{
RETURN_IF_ERROR(DOM_GetUserJSFile(file, environment));
return file.Open(OPFILE_READ | OPFILE_TEXT);
}
OP_STATUS
DOM_UserJSManager::Construct()
{
DOM_Object *object;
RETURN_IF_ERROR(GetObject(object));
event_target = OP_NEW(DOM_EventTarget, (object));
if (!event_target)
return OpStatus::ERR_NO_MEMORY;
callback = OP_NEW(DOM_UserJSCallback, (this));
if (!callback)
return OpStatus::ERR_NO_MEMORY;
if (OpStatus::IsMemoryError(DOM_Object::DOMSetObjectRuntime(anchor = OP_NEW(DOM_UserJSAnchor, (this)), environment->GetDOMRuntime())) ||
!anchor->GetRuntime()->Protect(*anchor))
{
anchor = NULL;
return OpStatus::ERR_NO_MEMORY;
}
OpFile file;
RETURN_IF_ERROR(DOM_OpenUserJSFile(file, environment));
TempBuffer buffer;
char buffer8[1024]; // ARRAY OK 2008-02-28 jl
buffer.SetExpansionPolicy(TempBuffer::AGGRESSIVE);
buffer.SetCachedLengthPolicy(TempBuffer::TRUSTED);
while (!file.Eof())
{
OpFileLength bytes_read;
RETURN_IF_ERROR(file.Read(buffer8, sizeof buffer8, &bytes_read));
RETURN_IF_ERROR(buffer.Append(buffer8, bytes_read));
}
if (buffer.Length() != 0)
{
ES_ProgramText program;
program.program_text = buffer.GetStorage();
program.program_text_length = buffer.Length();
RETURN_IF_ERROR(environment->GetAsyncInterface()->Eval(&program, 1, NULL, 0, callback, NULL));
is_enabled = TRUE;
++is_active;
}
return OpStatus::OK;
}
#endif // USER_JAVASCRIPT_ADVANCED
#ifdef DOM3_EVENTS
# define EVENT_TYPE(name) DOM_EVENT_CUSTOM, UNI_L("http://www.opera.com/userjs"), UNI_L(name)
# define EVENT_TYPE_BUFFER(buffer) DOM_EVENT_CUSTOM, UNI_L("http://www.opera.com/userjs"), buffer.GetStorage()
#else // DOM3_EVENTS
# define EVENT_TYPE(name) DOM_EVENT_CUSTOM, UNI_L(name)
# define EVENT_TYPE_BUFFER(buffer) DOM_EVENT_CUSTOM, buffer.GetStorage()
#endif // DOM3_EVENTS
OP_BOOLEAN
DOM_UserJSManager::BeforeScriptElement(DOM_Element *element, ES_Thread *interrupt_thread)
{
if (element == handled_script || !is_active && !event_target->HasListeners(EVENT_TYPE("BeforeScript"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, element, UNI_L("BeforeScript")));
return environment->SendEvent(event, interrupt_thread);
}
OP_BOOLEAN
DOM_UserJSManager::AfterScriptElement(DOM_Element *element, ES_Thread *interrupt_thread)
{
if (!event_target->HasListeners(EVENT_TYPE("AfterScript"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, element, UNI_L("AfterScript")));
return environment->SendEvent(event, interrupt_thread);
}
OP_BOOLEAN
DOM_UserJSManager::BeforeExternalScriptElement(DOM_Element *element, ES_Thread *interrupt_thread)
{
if (element == handled_external_script || !is_active && !event_target->HasListeners(EVENT_TYPE("BeforeExternalScript"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, element, UNI_L("BeforeExternalScript")));
return environment->SendEvent(event, interrupt_thread);
}
#ifdef _PLUGIN_SUPPORT_
OP_BOOLEAN
DOM_UserJSManager::PluginInitializedElement(DOM_Element *element)
{
if (!event_target->HasListeners(EVENT_TYPE("PluginInitialized"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, element, UNI_L("PluginInitialized")));
return environment->SendEvent(event);
}
#endif // _PLUGIN_SUPPORT_
OP_BOOLEAN
DOM_UserJSManager::BeforeEvent(DOM_Event *real_event, ES_Thread *interrupt_thread)
{
if (real_event->IsA(DOM_TYPE_USERJSEVENT) || !event_target)
return OpBoolean::IS_FALSE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append("BeforeEvent."));
if (real_event->GetKnownType() == DOM_EVENT_CUSTOM)
RETURN_IF_ERROR(buffer.Append(real_event->GetType()));
else
RETURN_IF_ERROR(buffer.Append(DOM_EVENT_NAME(real_event->GetKnownType())));
OP_BOOLEAN result1, result2;
RETURN_IF_ERROR(result1 = SendEventEvent(EVENT_TYPE_BUFFER(buffer), real_event, NULL, interrupt_thread));
RETURN_IF_ERROR(result2 = SendEventEvent(EVENT_TYPE("BeforeEvent"), real_event, NULL, interrupt_thread));
return (result1 == OpBoolean::IS_TRUE || result2 == OpBoolean::IS_TRUE) ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE;
}
OP_BOOLEAN
DOM_UserJSManager::AfterEvent(DOM_Event *real_event, ES_Thread *interrupt_thread)
{
if (real_event->IsA(DOM_TYPE_USERJSEVENT) || !event_target)
return OpBoolean::IS_FALSE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append("AfterEvent."));
if (real_event->GetKnownType() == DOM_EVENT_CUSTOM)
RETURN_IF_ERROR(buffer.Append(real_event->GetType()));
else
RETURN_IF_ERROR(buffer.Append(DOM_EVENT_NAME(real_event->GetKnownType())));
OP_BOOLEAN result1, result2;
RETURN_IF_ERROR(result1 = SendEventEvent(EVENT_TYPE_BUFFER(buffer), real_event, NULL, interrupt_thread));
RETURN_IF_ERROR(result2 = SendEventEvent(EVENT_TYPE("AfterEvent"), real_event, NULL, interrupt_thread));
return (result1 == OpBoolean::IS_TRUE || result2 == OpBoolean::IS_TRUE) ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE;
}
OP_BOOLEAN
DOM_UserJSManager::BeforeEventListener(DOM_Event *real_event, ES_Object *listener, ES_Thread *interrupt_thread)
{
if (real_event->IsA(DOM_TYPE_USERJSEVENT) || !event_target)
return OpBoolean::IS_FALSE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append("BeforeEventListener."));
if (real_event->GetKnownType() == DOM_EVENT_CUSTOM)
RETURN_IF_ERROR(buffer.Append(real_event->GetType()));
else
RETURN_IF_ERROR(buffer.Append(DOM_EVENT_NAME(real_event->GetKnownType())));
OP_BOOLEAN result1, result2;
RETURN_IF_ERROR(result1 = SendEventEvent(EVENT_TYPE_BUFFER(buffer), real_event, listener, interrupt_thread));
RETURN_IF_ERROR(result2 = SendEventEvent(EVENT_TYPE("BeforeEventListener"), real_event, listener, interrupt_thread));
return (result1 == OpBoolean::IS_TRUE || result2 == OpBoolean::IS_TRUE) ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE;
}
OP_BOOLEAN
DOM_UserJSManager::CreateAfterEventListener(DOM_UserJSEvent *&event1, DOM_UserJSEvent *&event2, DOM_Event *real_event, ES_Object *listener)
{
if (real_event->IsA(DOM_TYPE_USERJSEVENT))
return OpBoolean::IS_FALSE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append("AfterEventListener."));
if (real_event->GetKnownType() == DOM_EVENT_CUSTOM)
RETURN_IF_ERROR(buffer.Append(real_event->GetType()));
else
RETURN_IF_ERROR(buffer.Append(DOM_EVENT_NAME(real_event->GetKnownType())));
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event1, this, real_event, UNI_L("AfterEventListener"), listener));
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event2, this, real_event, buffer.GetStorage(), listener));
if (event1->GetRuntime()->Protect(*event1))
{
if (event2->GetRuntime()->Protect(*event2))
return OpBoolean::IS_TRUE;
else
event1->GetRuntime()->Unprotect(*event1);
}
return OpStatus::ERR_NO_MEMORY;
}
OP_BOOLEAN
DOM_UserJSManager::SendAfterEventListener(DOM_UserJSEvent *event1, DOM_UserJSEvent *event2, ES_Thread *interrupt_thread)
{
if (!event_target)
return OpBoolean::IS_FALSE;
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Append("AfterEventListener."));
DOM_Event *real_event = event1->GetEvent();
if (real_event->GetKnownType() == DOM_EVENT_CUSTOM)
RETURN_IF_ERROR(buffer.Append(real_event->GetType()));
else
RETURN_IF_ERROR(buffer.Append(DOM_EVENT_NAME(real_event->GetKnownType())));
OP_BOOLEAN result1 = OpBoolean::IS_FALSE, result2 = OpBoolean::IS_FALSE;
if (event_target->HasListeners(EVENT_TYPE("AfterEventListener"), ES_PHASE_AT_TARGET))
RETURN_IF_ERROR(result1 = environment->SendEvent(event1, interrupt_thread));
if (event_target->HasListeners(EVENT_TYPE_BUFFER(buffer), ES_PHASE_AT_TARGET))
RETURN_IF_ERROR(result2 = environment->SendEvent(event2, interrupt_thread));
return (result1 == OpBoolean::IS_TRUE || result2 == OpBoolean::IS_TRUE) ? OpBoolean::IS_TRUE : OpBoolean::IS_FALSE;
}
OP_STATUS
DOM_UserJSManager::BeforeJavascriptURL(ES_JavascriptURLThread *thread)
{
if (!event_target)
return OpStatus::OK;
if (!event_target->HasListeners(EVENT_TYPE("BeforeJavascriptURL"), ES_PHASE_AT_TARGET))
return OpStatus::OK;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, thread, UNI_L("BeforeJavascriptURL")));
OP_BOOLEAN result = environment->SendEvent(event, thread);
return OpStatus::IsError(result) ? result : OpStatus::OK;
}
OP_STATUS
DOM_UserJSManager::AfterJavascriptURL(ES_JavascriptURLThread *thread)
{
if (!event_target)
return OpStatus::OK;
if (!event_target->HasListeners(EVENT_TYPE("AfterJavascriptURL"), ES_PHASE_AT_TARGET))
return OpStatus::OK;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, thread, UNI_L("AfterJavascriptURL")));
OP_BOOLEAN result = environment->SendEvent(event, thread);
return OpStatus::IsError(result) ? result : OpStatus::OK;
}
OP_BOOLEAN
DOM_UserJSManager::BeforeCSS(DOM_Node *node, ES_Thread *interrupt_thread)
{
if (node == handled_stylesheet || !is_active && !event_target->HasListeners(EVENT_TYPE("BeforeCSS"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
if (node->GetIsWaitingForBeforeCSS())
return OpBoolean::IS_TRUE;
node->SetIsWaitingForBeforeCSS(TRUE);
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, node, UNI_L("BeforeCSS")));
OP_BOOLEAN res = environment->SendEvent(event, interrupt_thread);
if (res == OpBoolean::IS_TRUE)
environment->GetFramesDocument()->IncWaitForStyles();
return res;
}
OP_BOOLEAN
DOM_UserJSManager::AfterCSS(DOM_Node *node, ES_Thread *interrupt_thread)
{
if (node != handled_stylesheet || !event_target->HasListeners(EVENT_TYPE("AfterCSS"), ES_PHASE_AT_TARGET))
return OpBoolean::IS_FALSE;
DOM_UserJSEvent *event;
RETURN_IF_ERROR(DOM_UserJSEvent::Make(event, this, node, UNI_L("AfterCSS")));
return environment->SendEvent(event, interrupt_thread);
}
OP_STATUS
DOM_UserJSManager::EventFinished(DOM_UserJSEvent *event)
{
const uni_char *type = event->GetType();
ES_Thread *interrupt_thread = event->GetThread()->GetInterruptedThread();
if (uni_str_eq(type, UNI_L("BeforeScript")) || uni_str_eq(type, UNI_L("BeforeExternalScript")))
{
/* Default action: start the script (execute it or load the external
source and then execute it). Preventing the default action means
cancelling that and just pretend the script element wasn't there. */
// BeforeScript/AfterScript events are only sent to script elements
// which are ensured to always be at least DOM_TYPE_ELEMENT.
OP_ASSERT(event->GetNode()->IsA(DOM_TYPE_ELEMENT));
DOM_Element *dom_element = static_cast<DOM_Element *>(event->GetNode());
HTML_Element *html_element = dom_element->GetThisElement();
HLDocProfile *hld_profile = environment->GetFramesDocument()->GetHLDocProfile();
if (event->GetPreventDefault())
html_element->CancelScriptElement(hld_profile);
else
{
if (!hld_profile->GetESLoadManager()->HasScript(html_element))
{
// Script canceled for some reason while waiting for
// the user.js to run, or by some action performed
// by the user.js
return OpStatus::OK;
}
OP_BOOLEAN result;
// Interrupt a thread to make sure the script is
// handled before the queued ONLOAD event is processed.
ES_Thread *thread = event->GetThread();
if (uni_str_eq(type, UNI_L("BeforeScript")))
{
handled_script = dom_element;
result = html_element->HandleScriptElement(hld_profile, thread);
handled_script = NULL;
}
else
{
handled_external_script = dom_element;
result = html_element->HandleScriptElement(hld_profile, thread);
handled_external_script = NULL;
}
return OpStatus::IsMemoryError(result) ? result : OpStatus::OK;
}
}
else if (uni_str_eq(type, UNI_L("AfterJavascriptURL")))
{
if (event->GetPreventDefault())
event->GetJavascriptURLThread()->SetResult(NULL);
}
else if (uni_str_eq(type, UNI_L("BeforeJavascriptURL")) || uni_strni_eq(type, "BEFOREEVENT", 11) || uni_strni_eq(type, "BEFOREEVENTLISTENER", 19))
{
/* Default action: fire the event (BeforeEvent) or call the listener
(BeforeEventListener). Both these events are evaluated by threads
interrupting an already started thread performing the default
action, so preventing the default action means cancelling the
interrupted thread. */
if (event->GetPreventDefault())
environment->GetScheduler()->CancelThread(interrupt_thread);
}
else if (uni_str_eq(type, UNI_L("BeforeCSS")))
{
DOM_Node *dom_node = event->GetNode();
HTML_Element *html_element = dom_node->GetThisElement();
FramesDocument *doc = environment->GetFramesDocument();
dom_node->SetIsWaitingForBeforeCSS(FALSE);
if (event->GetPreventDefault())
{
if (html_element)
if (DataSrc *data_src = html_element->GetDataSrc())
data_src->DeleteAll();
}
else if (doc->GetDocRoot()->IsAncestorOf(html_element))
{
handled_stylesheet = dom_node;
OP_STATUS status = html_element->LoadStyle(doc, FALSE);
handled_stylesheet = NULL;
doc->DecWaitForStyles();
return status;
}
doc->DecWaitForStyles();
}
else if (uni_strni_eq(type, "AFTEREVENTLISTENER", 18))
{
/* Default action: respect calls to event.stopPropagation. */
#ifdef DOM3_EVENTS
if (event->GetPreventDefault() && !event->WasStoppedBefore() && event->GetEvent()->GetStopPropagation(event->GetCurrentGroup()))
event->GetEvent()->SetStopPropagation(FALSE, FALSE);
#else // DOM3_EVENTS
if (event->GetPreventDefault() && !event->WasStoppedBefore() && event->GetEvent()->GetStopPropagation())
event->GetEvent()->SetStopPropagation(FALSE);
#endif // DOM3_EVENTS
}
else if (uni_strni_eq(type, "AFTEREVENT", 10))
{
/* Default action: respect calls to event.preventDefault. */
if (event->GetPreventDefault())
event->GetEvent()->SetPreventDefault(FALSE);
}
return OpStatus::OK;
}
OP_STATUS
DOM_UserJSManager::EventCancelled(DOM_UserJSEvent *event)
{
if (uni_str_eq(event->GetType(), UNI_L("BeforeCSS")))
{
environment->GetFramesDocument()->DecWaitForStyles();
}
return OpStatus::OK;
}
OP_BOOLEAN
DOM_UserJSManager::HasListener(const uni_char *base, const char *specific8, const uni_char *specific16)
{
TempBuffer buffer;
RETURN_IF_ERROR(buffer.Expand(uni_strlen(base) + 2));
OpStatus::Ignore(buffer.Append(base)); // Buffer is successfully expanded above
if (event_target->HasListeners(EVENT_TYPE_BUFFER(buffer), ES_PHASE_AT_TARGET))
return OpBoolean::IS_TRUE;
OpStatus::Ignore(buffer.Append('.'));
if (specific8)
RETURN_IF_ERROR(buffer.Append(specific8));
else
RETURN_IF_ERROR(buffer.Append(specific16));
if (event_target->HasListeners(EVENT_TYPE_BUFFER(buffer), ES_PHASE_AT_TARGET))
return OpBoolean::IS_TRUE;
return OpBoolean::IS_FALSE;
}
OP_BOOLEAN
DOM_UserJSManager::HasListeners(const uni_char *base1, const uni_char *base2, DOM_EventType known_type, const uni_char *type)
{
if (!event_target)
return OpBoolean::IS_FALSE;
const char *specific8 = NULL;
const uni_char *specific16 = NULL;
if (known_type == DOM_EVENT_CUSTOM)
specific16 = type;
else
specific8 = DOM_EVENT_NAME(known_type);
OP_BOOLEAN result = HasListener(base1, specific8, specific16);
if (result != OpBoolean::IS_FALSE)
return result;
return HasListener(base2, specific8, specific16);
}
OP_BOOLEAN
DOM_UserJSManager::HasBeforeOrAfterEvent(DOM_EventType type, const uni_char *type_string)
{
return HasListeners(UNI_L("BeforeEvent"), UNI_L("AfterEvent"), type, type_string);
}
OP_BOOLEAN
DOM_UserJSManager::HasBeforeOrAfterEventListener(DOM_EventType type, const uni_char *type_string)
{
return HasListeners(UNI_L("BeforeEventListener"), UNI_L("AfterEventListener"), type, type_string);
}
BOOL
DOM_UserJSManager::GetIsActive(ES_Runtime *origining_runtime)
{
if (is_enabled)
if (origining_runtime)
{
ES_Thread *thread = DOM_Object::GetCurrentThread(origining_runtime);
while (thread)
{
if (ES_Context *context = thread->GetContext())
if (!ES_Runtime::HasPrivilegeLevelAtLeast(context, ES_Runtime::PRIV_LVL_USERJS))
return FALSE;
#ifdef USER_JAVASCRIPT_ADVANCED
if (thread->Type() == ES_THREAD_EVENT && ((DOM_EventThread *) thread)->GetEvent()->IsA(DOM_TYPE_USERJSEVENT) ||
thread->Type() == ES_THREAD_COMMON && uni_str_eq(thread->GetInfoString(), "User Javascript thread") && ((DOM_UserJSThread *) thread)->GetType() != GREASEMONKEY)
#else // USER_JAVASCRIPT_ADVANCED
if (thread->Type() == ES_THREAD_EVENT && ((DOM_EventThread *) thread)->GetEvent()->IsA(DOM_TYPE_USERJSEVENT))
#endif // USER_JAVASCRIPT_ADVANCED
return TRUE;
else
thread = thread->GetInterruptedThread();
}
}
else
return is_active != 0;
return FALSE;
}
BOOL
DOM_UserJSManager::GetIsHandlingScriptElement(ES_Runtime *origining_runtime, HTML_Element *element)
{
if (is_enabled && origining_runtime && element)
{
ES_Thread *thread = DOM_Object::GetCurrentThread(origining_runtime);
while (thread)
{
if (thread->Type() == ES_THREAD_EVENT)
{
DOM_Event *event = ((DOM_EventThread *) thread)->GetEvent();
if (event->IsA(DOM_TYPE_USERJSEVENT))
if (uni_str_eq(event->GetType(), "BeforeExternalScript") || uni_str_eq(event->GetType(), "BeforeScript"))
if (static_cast<DOM_UserJSEvent *>(event)->GetNode()->GetThisElement() == element)
return TRUE;
}
thread = thread->GetInterruptedThread();
}
}
return FALSE;
}
OP_STATUS
DOM_UserJSManager::GetObject(DOM_Object *&object)
{
ES_Value value;
DOM_Object *window = environment->GetWindow();
OP_BOOLEAN result = window->GetPrivate(DOM_PRIVATE_opera, &value);
if (result == OpBoolean::IS_TRUE)
{
object = DOM_VALUE2OBJECT(value, DOM_Object);
return OpStatus::OK;
}
else if (result == OpBoolean::IS_FALSE)
return OpStatus::ERR;
else
return result;
}
OP_STATUS
DOM_UserJSManager::ReloadScripts()
{
#ifdef USER_JAVASCRIPT_ADVANCED
RETURN_IF_ERROR(SanitizeScripts());
RETURN_IF_MEMORY_ERROR(LoadScripts());
#endif // USER_JAVASCRIPT_ADVANCED
return OpStatus::OK;
}
/* static */ unsigned
DOM_UserJSManager::GetFilesCount()
{
#ifdef USER_JAVASCRIPT_ADVANCED
return g_DOM_userScripts.Cardinal();
#else // USER_JAVASCRIPT_ADVANCED
OpFile file;
if (OpStatus::IsSuccess(DOM_GetUserJSFile(file)))
{
BOOL exists = FALSE;
OP_STATUS status = file.Exists(exists);
if (OpStatus::IsSuccess(status) && exists)
return 1;
}
return 0;
#endif // USER_JAVASCRIPT_ADVANCED
}
/* static */ const uni_char *
DOM_UserJSManager::GetFilename(unsigned index)
{
#ifdef USER_JAVASCRIPT_ADVANCED
DOM_UserJSScript *script = g_DOM_userScripts.First();
while (index != 0 && script)
{
script = script->Suc();
--index;
}
if (script)
return script->GetFilename();
#else // USER_JAVASCRIPT_ADVANCED
OpFile file;
if (OpStatus::IsSuccess(DOM_GetUserJSFile(file)))
{
TempBuffer &buffer = g_DOM_tempbuf;
buffer.Clear();
if (OpStatus::IsSuccess(buffer.Append(file.GetFullPath())))
return buffer.GetStorage();
}
#endif // USER_JAVASCRIPT_ADVANCED
return UNI_L("");
}
/* static */ OP_STATUS
DOM_UserJSManager::SanitizeScripts()
{
#ifdef USER_JAVASCRIPT_ADVANCED
for (DOM_UserJSScript *script = g_DOM_userScripts.First(), *nextscript; script; script = nextscript)
{
nextscript = script->Suc();
OP_BOOLEAN isstale = script->IsStale();
RETURN_IF_ERROR(isstale);
if (isstale == OpBoolean::IS_TRUE)
{
script->Out();
DOM_UserJSScript::DecRef(script);
}
}
return OpStatus::OK;
#endif // USER_JAVASCRIPT_ADVANCED
}
/* static */ void
DOM_UserJSManager::RemoveScripts()
{
#ifdef USER_JAVASCRIPT_ADVANCED
while (DOM_UserJSScript *script = g_DOM_userScripts.First())
{
script->Out();
DOM_UserJSScript::DecRef(script);
}
while (DOM_UserJSSource *source = g_DOM_userScriptSources.First())
{
source->Out();
DOM_UserJSSource::DecRef(source);
}
#endif // USER_JAVASCRIPT_ADVANCED
}
/* static */ ES_ScriptType
DOM_UserJSManager::GetScriptType(UserJSType type)
{
switch (type)
{
case GREASEMONKEY:
return SCRIPT_TYPE_USER_JAVASCRIPT_GREASEMONKEY;
case BROWSERJS:
return SCRIPT_TYPE_BROWSER_JAVASCRIPT;
case EXTENSIONJS:
return SCRIPT_TYPE_EXTENSION_JAVASCRIPT;
default:
return SCRIPT_TYPE_USER_JAVASCRIPT;
}
}
/* static */ const uni_char *
DOM_UserJSManager::GetErrorString(UserJSType type, BOOL when_compiling)
{
switch (type)
{
case GREASEMONKEY:
return when_compiling ? UNI_L("Greasemonkey JS compilation") : UNI_L("Greasemonkey JS loading");
case BROWSERJS:
return when_compiling ? UNI_L("Browser JS compilation") : UNI_L("Browser JS loading");
case EXTENSIONJS:
return when_compiling ? UNI_L("Extension JS compilation") : UNI_L("Extension JS loading");
default:
return when_compiling ? UNI_L("User JS compilation") : UNI_L("User JS loading");
}
}
/* static */ BOOL
DOM_UserJSManager::IsActiveInRuntime(ES_Runtime *runtime)
{
if (DOM_UserJSManager *user_js_manager = static_cast<DOM_Runtime *>(runtime)->GetEnvironment()->GetUserJSManager())
return user_js_manager->GetIsActive(runtime);
return FALSE;
}
#ifdef EXTENSION_SUPPORT
/* static */ BOOL
DOM_UserJSManager::CheckExtensionScripts(FramesDocument *frames_doc)
{
OP_PROBE3(OP_PROBE_DOM_USERJSMANAGER_WOULDACTIVATEEXTENSION);
BOOL would_activate = FALSE;
for (DOM_UserJSSource *source = g_DOM_userScriptSources.First(); source; source = source->Suc())
if (source->GetType() == EXTENSIONJS && source->WouldUse(frames_doc))
{
would_activate = TRUE;
break;
}
if (g_gadget_manager->HasUserJSUpdates())
{
g_DOM_have_always_enabled_extension_js = FALSE;
for (OpGadgetExtensionUserJS *extension_userjs = g_gadget_manager->GetFirstActiveExtensionUserJS();
extension_userjs; extension_userjs = extension_userjs->Suc())
{
if (GetCachedScript(extension_userjs->userjs_filename, EXTENSIONJS)
|| GetLoadedSource(extension_userjs->userjs_filename, EXTENSIONJS))
continue;
DOM_UserJSSource *source;
OP_BOOLEAN loaded = DOM_UserJSSource::Make(source, extension_userjs->userjs_filename, EXTENSIONJS);
if (!OpStatus::IsSuccess(loaded) || loaded == OpBoolean::IS_FALSE)
{
WarnLoadFailure(extension_userjs->userjs_filename, EXTENSIONJS);
continue;
}
if (source->WouldUse(frames_doc))
would_activate = TRUE;
else
source->Empty(); // Don't store the source in memory, it will be reloaded if needed.
if (source->CheckIfAlwaysEnabled())
g_DOM_have_always_enabled_extension_js = TRUE;
DOM_InsertUserJSSourceIntoCache(source);
}
g_gadget_manager->ResetUserJSUpdated();
}
if (g_DOM_have_always_enabled_extension_js)
return TRUE;
if (!would_activate)
for (DOM_UserJSScript *script = g_DOM_userScripts.First(); script; script = script->Suc())
if (script->GetType() == EXTENSIONJS && script->WouldUse(frames_doc))
return TRUE;
return would_activate;
}
#endif // EXTENSION_SUPPORT
#endif // USER_JAVASCRIPT
|
// Created on: 1993-02-05
// Created by: Jacques GOUSSARD
// Copyright (c) 1993-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 _Contap_TheIWalking_HeaderFile
#define _Contap_TheIWalking_HeaderFile
#include <Adaptor3d_Surface.hxx>
#include <IntSurf_SequenceOfPathPoint.hxx>
#include <math_Vector.hxx>
#include <IntWalk_VectorOfWalkingData.hxx>
#include <IntWalk_VectorOfInteger.hxx>
#include <IntSurf_PntOn2S.hxx>
#include <gp_Vec.hxx>
#include <gp_Dir2d.hxx>
#include <TColStd_SequenceOfInteger.hxx>
#include <TColStd_DataMapOfIntegerListOfInteger.hxx>
#include <Contap_SequenceOfIWLineOfTheIWalking.hxx>
#include <IntSurf_SequenceOfInteriorPoint.hxx>
#include <TColStd_SequenceOfReal.hxx>
#include <IntWalk_StatusDeflection.hxx>
#include <Bnd_Range.hxx>
class IntSurf_PathPoint;
class IntSurf_PathPointTool;
class IntSurf_InteriorPoint;
class IntSurf_InteriorPointTool;
class Adaptor3d_HSurfaceTool;
class Contap_SurfFunction;
class Contap_TheIWLineOfTheIWalking;
class math_FunctionSetRoot;
class Contap_TheIWalking
{
public:
DEFINE_STANDARD_ALLOC
//! Deflection is the maximum deflection admitted between two
//! consecutive points on a resulting polyline.
//! Step is the maximum increment admitted between two
//! consecutive points (in 2d space).
//! Epsilon is the tolerance beyond which 2 points
//! are confused.
//! theToFillHoles is the flag defining whether possible holes
//! between resulting curves are filled or not
//! in case of Contap walking theToFillHoles is True
Standard_EXPORT Contap_TheIWalking(const Standard_Real Epsilon, const Standard_Real Deflection, const Standard_Real Step,
const Standard_Boolean theToFillHoles = Standard_False);
//! Deflection is the maximum deflection admitted between two
//! consecutive points on a resulting polyline.
//! Step is the maximum increment admitted between two
//! consecutive points (in 2d space).
//! Epsilon is the tolerance beyond which 2 points
//! are confused
void SetTolerance (const Standard_Real Epsilon, const Standard_Real Deflection, const Standard_Real Step);
//! Searches a set of polylines starting on a point of Pnts1
//! or Pnts2.
//! Each point on a resulting polyline verifies F(u,v)=0
Standard_EXPORT void Perform (const IntSurf_SequenceOfPathPoint& Pnts1, const IntSurf_SequenceOfInteriorPoint& Pnts2, Contap_SurfFunction& Func, const Handle(Adaptor3d_Surface)& S, const Standard_Boolean Reversed = Standard_False);
//! Searches a set of polylines starting on a point of Pnts1.
//! Each point on a resulting polyline verifies F(u,v)=0
Standard_EXPORT void Perform (const IntSurf_SequenceOfPathPoint& Pnts1, Contap_SurfFunction& Func, const Handle(Adaptor3d_Surface)& S, const Standard_Boolean Reversed = Standard_False);
//! Returns true if the calculus was successful.
Standard_Boolean IsDone() const;
//! Returns the number of resulting polylines.
//! An exception is raised if IsDone returns False.
Standard_Integer NbLines() const;
//! Returns the polyline of range Index.
//! An exception is raised if IsDone is False.
//! An exception is raised if Index<=0 or Index>NbLines.
const Handle(Contap_TheIWLineOfTheIWalking)& Value (const Standard_Integer Index) const;
//! Returns the number of points belonging to Pnts on which no
//! line starts or ends.
//! An exception is raised if IsDone returns False.
Standard_Integer NbSinglePnts() const;
//! Returns the point of range Index .
//! An exception is raised if IsDone returns False.
//! An exception is raised if Index<=0 or
//! Index > NbSinglePnts.
const IntSurf_PathPoint& SinglePnt (const Standard_Integer Index) const;
protected:
Standard_EXPORT Standard_Boolean Cadrage (math_Vector& BornInf, math_Vector& BornSup, math_Vector& UVap, Standard_Real& Step, const Standard_Integer StepSign) const;
Standard_EXPORT Standard_Boolean TestArretPassage (const TColStd_SequenceOfReal& Umult, const TColStd_SequenceOfReal& Vmult, Contap_SurfFunction& Section, math_Vector& UV, Standard_Integer& Irang);
Standard_EXPORT Standard_Boolean TestArretPassage (const TColStd_SequenceOfReal& Umult, const TColStd_SequenceOfReal& Vmult, const math_Vector& UV, const Standard_Integer Index, Standard_Integer& Irang);
Standard_EXPORT Standard_Boolean TestArretAjout (Contap_SurfFunction& Section, math_Vector& UV, Standard_Integer& Irang, IntSurf_PntOn2S& PSol);
Standard_EXPORT void FillPntsInHoles (Contap_SurfFunction& Section,
TColStd_SequenceOfInteger& CopySeqAlone,
IntSurf_SequenceOfInteriorPoint& PntsInHoles);
Standard_EXPORT void TestArretCadre (const TColStd_SequenceOfReal& Umult, const TColStd_SequenceOfReal& Vmult, const Handle(Contap_TheIWLineOfTheIWalking)& Line, Contap_SurfFunction& Section, math_Vector& UV, Standard_Integer& Irang);
Standard_EXPORT IntWalk_StatusDeflection TestDeflection (Contap_SurfFunction& Section, const Standard_Boolean Finished, const math_Vector& UV, const IntWalk_StatusDeflection StatusPrecedent, Standard_Integer& NbDivision, Standard_Real& Step, const Standard_Integer StepSign);
Standard_EXPORT void ComputeOpenLine (const TColStd_SequenceOfReal& Umult, const TColStd_SequenceOfReal& Vmult, const IntSurf_SequenceOfPathPoint& Pnts1, Contap_SurfFunction& Section, Standard_Boolean& Rajout);
Standard_EXPORT void OpenLine (const Standard_Integer N, const IntSurf_PntOn2S& Psol, const IntSurf_SequenceOfPathPoint& Pnts1, Contap_SurfFunction& Section, const Handle(Contap_TheIWLineOfTheIWalking)& Line);
Standard_EXPORT Standard_Boolean IsValidEndPoint (const Standard_Integer IndOfPoint, const Standard_Integer IndOfLine);
Standard_EXPORT void RemoveTwoEndPoints (const Standard_Integer IndOfPoint);
Standard_EXPORT Standard_Boolean IsPointOnLine (const gp_Pnt2d& theP2d, const Standard_Integer Irang);
Standard_EXPORT void ComputeCloseLine (const TColStd_SequenceOfReal& Umult, const TColStd_SequenceOfReal& Vmult, const IntSurf_SequenceOfPathPoint& Pnts1, const IntSurf_SequenceOfInteriorPoint& Pnts2, Contap_SurfFunction& Section, Standard_Boolean& Rajout);
Standard_EXPORT void AddPointInCurrentLine (const Standard_Integer N, const IntSurf_PathPoint& PathPnt, const Handle(Contap_TheIWLineOfTheIWalking)& CurrentLine) const;
Standard_EXPORT void MakeWalkingPoint (const Standard_Integer Case, const Standard_Real U, const Standard_Real V, Contap_SurfFunction& Section, IntSurf_PntOn2S& Psol);
//! Clears up internal containers
Standard_EXPORT void Clear();
//! Returns TRUE if thePOn2S is in one of existing lines.
Standard_EXPORT Standard_Boolean IsPointOnLine(const IntSurf_PntOn2S& thePOn2S,
const math_Vector& theInfBounds,
const math_Vector& theSupBounds,
math_FunctionSetRoot& theSolver,
Contap_SurfFunction& theFunc);
private:
Standard_Boolean done;
IntSurf_SequenceOfPathPoint seqSingle;
Standard_Real fleche;
Standard_Real pas;
math_Vector tolerance;
Standard_Real epsilon;
Standard_Boolean reversed;
IntWalk_VectorOfWalkingData wd1;
IntWalk_VectorOfWalkingData wd2;
IntWalk_VectorOfInteger nbMultiplicities;
Bnd_Range mySRangeU; // Estimated U-range for section curve
Bnd_Range mySRangeV; // Estimated V-range for section curve
Standard_Real Um;
Standard_Real UM;
Standard_Real Vm;
Standard_Real VM;
IntSurf_PntOn2S previousPoint;
gp_Vec previousd3d;
gp_Dir2d previousd2d;
TColStd_SequenceOfInteger seqAjout;
TColStd_SequenceOfInteger seqAlone;
TColStd_DataMapOfIntegerListOfInteger PointLineLine;
Contap_SequenceOfIWLineOfTheIWalking lines;
Standard_Boolean ToFillHoles;
};
#define ThePointOfPath IntSurf_PathPoint
#define ThePointOfPath_hxx <IntSurf_PathPoint.hxx>
#define ThePointOfPathTool IntSurf_PathPointTool
#define ThePointOfPathTool_hxx <IntSurf_PathPointTool.hxx>
#define ThePOPIterator IntSurf_SequenceOfPathPoint
#define ThePOPIterator_hxx <IntSurf_SequenceOfPathPoint.hxx>
#define ThePointOfLoop IntSurf_InteriorPoint
#define ThePointOfLoop_hxx <IntSurf_InteriorPoint.hxx>
#define ThePointOfLoopTool IntSurf_InteriorPointTool
#define ThePointOfLoopTool_hxx <IntSurf_InteriorPointTool.hxx>
#define ThePOLIterator IntSurf_SequenceOfInteriorPoint
#define ThePOLIterator_hxx <IntSurf_SequenceOfInteriorPoint.hxx>
#define ThePSurface Handle(Adaptor3d_Surface)
#define ThePSurface_hxx <Adaptor3d_Surface.hxx>
#define ThePSurfaceTool Adaptor3d_HSurfaceTool
#define ThePSurfaceTool_hxx <Adaptor3d_HSurfaceTool.hxx>
#define TheIWFunction Contap_SurfFunction
#define TheIWFunction_hxx <Contap_SurfFunction.hxx>
#define IntWalk_TheIWLine Contap_TheIWLineOfTheIWalking
#define IntWalk_TheIWLine_hxx <Contap_TheIWLineOfTheIWalking.hxx>
#define IntWalk_SequenceOfIWLine Contap_SequenceOfIWLineOfTheIWalking
#define IntWalk_SequenceOfIWLine_hxx <Contap_SequenceOfIWLineOfTheIWalking.hxx>
#define Handle_IntWalk_TheIWLine Handle(Contap_TheIWLineOfTheIWalking)
#define IntWalk_IWalking Contap_TheIWalking
#define IntWalk_IWalking_hxx <Contap_TheIWalking.hxx>
#include <IntWalk_IWalking.lxx>
#undef ThePointOfPath
#undef ThePointOfPath_hxx
#undef ThePointOfPathTool
#undef ThePointOfPathTool_hxx
#undef ThePOPIterator
#undef ThePOPIterator_hxx
#undef ThePointOfLoop
#undef ThePointOfLoop_hxx
#undef ThePointOfLoopTool
#undef ThePointOfLoopTool_hxx
#undef ThePOLIterator
#undef ThePOLIterator_hxx
#undef ThePSurface
#undef ThePSurface_hxx
#undef ThePSurfaceTool
#undef ThePSurfaceTool_hxx
#undef TheIWFunction
#undef TheIWFunction_hxx
#undef IntWalk_TheIWLine
#undef IntWalk_TheIWLine_hxx
#undef IntWalk_SequenceOfIWLine
#undef IntWalk_SequenceOfIWLine_hxx
#undef Handle_IntWalk_TheIWLine
#undef IntWalk_IWalking
#undef IntWalk_IWalking_hxx
#endif // _Contap_TheIWalking_HeaderFile
|
#pragma once
#include "typedefs.h"
class EquilFns
{
public:
#if ASSETSTATE
vector<vector<vector<vector<vector<vector<vector<VecDoub>>>>>>> value_fn;
vector<vector<vector<vector<vector<vector<vector<VecDoub>>>>>>> consumption;
vector<vector<vector<vector<vector<vector<vector<vector<VecDoub>>>>>>>> policy_fn;
#else
VecDoub *******value_fn; //Could be just a double and haven't changed yet
VecDoub *******consumption;//Could be just a double and haven't changed yet
VecDoub *******policy_fn;
#endif
EquilFns();
~EquilFns();
EquilFns& operator=(const EquilFns& fnSource);
};
|
#include "dataDNA.h"
void dataDNA::addDna(Dna* newDna)
{
m_mapIdDna.insert(std::pair<size_t, Dna*>(Dna::getId(),newDna));
m_mapNameDna.insert(std::pair<std::string, size_t>(newDna->getName(), Dna::getId()));
}
void dataDNA::delDna(size_t id)
{
m_mapNameDna.erase(m_mapIdDna[id]->getName());
delete m_mapIdDna[id];
m_mapIdDna[id] = NULL;
m_mapIdDna.erase(id);
}
dataDNA::~dataDNA()
{
std::map<size_t, Dna*>::iterator iter;
for(iter = m_mapIdDna.begin();iter!=m_mapIdDna.end();++iter)
{
delete iter->second;
}
}
Dna*dataDNA::findInIdMap(size_t id)
{
return m_mapIdDna[id];
}
Dna*dataDNA::findInNameMap(const std::string& name)
{
return m_mapIdDna[m_mapNameDna[name]];
}
bool dataDNA::isexistName(const std::string& name)
{
return m_mapNameDna.find(name)!=m_mapNameDna.end();
}
bool dataDNA::isexistId(size_t id)
{
return m_mapIdDna.find(id)!=m_mapIdDna.end();
}
size_t dataDNA::findIdByName(const std::string& name)
{
return m_mapNameDna[name];
}
void dataDNA::setName(size_t id, const std::string& newName)
{
m_mapNameDna.erase(m_mapIdDna[id]->getName());
m_mapNameDna[newName] = id;
m_mapIdDna[id]->setName(newName);
}
std::vector<size_t> dataDNA::getIdsDna()
{
std::vector<size_t> vecIds;
std::map<size_t ,Dna*>::iterator iter;
for(iter = m_mapIdDna.begin();iter!=m_mapIdDna.end();++iter)
{
vecIds.push_back(iter->first);
}
return vecIds;
}
|
#include "stdafx.h"
#include "CNetMessage.h"
#include <QByteArray>
CNetMessageWrapper::CNetMessageWrapper()
{
}
CNetMessageWrapper::~CNetMessageWrapper()
{
}
//根据输入信息得到NetMessage bDecode - true 解密msgBuffer信息 netMessage中的buffer需要手动释放
bool CNetMessageWrapper::GetNetMessage(const char* inputBuffer, unsigned long bufLen, NetMessage& netMessage)
{
char* pBuffer = new char[bufLen + 1];
if(NULL == pBuffer)
return false;
memset(pBuffer, 0, bufLen + 1);
memcpy(pBuffer, inputBuffer, bufLen);
QByteArray result;
result.append(pBuffer);
//执行ZIP解压
result = qUncompress(QByteArray::fromBase64(result));
delete pBuffer;
pBuffer = NULL;
if(result.size() < 12) // 长度必须大于16个字节
return false;
//消息头
QByteArray temp = result.left(4);
netMessage.msgHead = (MsgHead)QByteArrayToInt(temp);
//消息长度
result = result.mid(4);
temp = result.left(8);
netMessage.msgLen = QByteArrayToULong(temp);
//消息
netMessage.msgBuffer = new char[netMessage.msgLen + 1];
memset(netMessage.msgBuffer, 0, netMessage.msgLen + 1);
result = result.mid(8);
memcpy(netMessage.msgBuffer, result.data(), netMessage.msgLen);
return true;
}
//解密netMessage
bool CNetMessageWrapper::GetDecodeBuffer(NetMessage& netMessage)
{
return true;
}
//将netMessage中的数据取出到inputBuffer 需要手动释放
bool CNetMessageWrapper::GetNetMessageToBuffer(NetMessage& netMessage, char*& inputBuffer, unsigned long& bufLen)
{
QString strEncryBuffer = "";
//拼装数据
QByteArray byteArray;
byteArray.append(IntToQByteArray(netMessage.msgHead));
byteArray.append(ULongToQByteArray(netMessage.msgLen));
byteArray.append(netMessage.msgBuffer);
//执行ZIP 压缩后,转成BASE64编码
QByteArray result = qCompress(byteArray);
strEncryBuffer = result.toBase64();
//QString strBuffer = QString::fromLocal8Bit("Begin##%1##End").arg(strEncryBuffer);
bufLen = strlen(strEncryBuffer.toStdString().c_str());
inputBuffer = new char[bufLen + 1];
memset(inputBuffer, 0, bufLen + 1);
memcpy(inputBuffer, strEncryBuffer.toStdString().c_str(), bufLen);
return true;
}
//4字节整数转为字符串
QString CNetMessageWrapper::IntToString(int nNum)
{
return IntToQByteArray(nNum).toBase64();
}
//8自己整数转为字符串
QString CNetMessageWrapper::ULongToString(unsigned long lNum)
{
return ULongToQByteArray(lNum).toBase64();
}
//字符串转为4字节整数
int CNetMessageWrapper::StringToInt(const QString& strNum)
{
QByteArray temp;
temp.append(strNum);
return QByteArrayToInt(temp);
}
//字符串转为8自己整数
unsigned long CNetMessageWrapper::StringToULong(const QString& strNum)
{
QByteArray temp;
temp.append(strNum);
return QByteArrayToULong(temp);
}
//4字节整数转为QByteArray
QByteArray CNetMessageWrapper::IntToQByteArray(int nNum)
{
QByteArray abyte0;
abyte0.resize(4);
abyte0[0] = (uchar) (0x000000ff & nNum);
abyte0[1] = (uchar) ((0x0000ff00 & nNum) >> 8);
abyte0[2] = (uchar) ((0x00ff0000 & nNum) >> 16);
abyte0[3] = (uchar) ((0xff000000 & nNum) >> 24);
return abyte0;
}
//8自己整数转为QByteArray
QByteArray CNetMessageWrapper::ULongToQByteArray(unsigned long lNum)
{
QByteArray abyte0;
abyte0.resize(8);
abyte0[0] = (uchar) (0x00000000000000ff & lNum);
abyte0[1] = (uchar) ((0x000000000000ff00 & lNum) >> 8);
abyte0[2] = (uchar) ((0x0000000000ff0000 & lNum) >> 16);
abyte0[3] = (uchar) ((0x00000000ff000000 & lNum) >> 24);
abyte0[4] = (uchar) ((0x000000ff00000000 & lNum) >> 32);
abyte0[5] = (uchar) ((0x0000ff0000000000 & lNum) >> 40);
abyte0[6] = (uchar) ((0x00ff000000000000 & lNum) >> 48);
abyte0[7] = (uchar) ((0xff00000000000000 & lNum) >> 56);
return abyte0;
}
//QByteArray转为4字节整数
int CNetMessageWrapper::QByteArrayToInt(const QByteArray& strNum)
{
int addr = strNum[0] & 0x000000FF;
addr |= ((strNum[1] << 8) & 0x0000FF00);
addr |= ((strNum[2] << 16) & 0x00FF0000);
addr |= ((strNum[3] << 24) & 0xFF000000);
return addr;
}
//QByteArray转为8自己整数
unsigned long CNetMessageWrapper::QByteArrayToULong(const QByteArray& strNum)
{
unsigned long addr = strNum[0] & 0x00000000000000ff;
addr |= ((strNum[1] << 8) & 0x000000000000FF00);
addr |= ((strNum[2] << 16) & 0x0000000000FF0000);
addr |= ((strNum[3] << 24) & 0x00000000FF000000);
addr |= ((strNum[4] << 32) & 0x000000FF00000000);
addr |= ((strNum[5] << 40) & 0x0000FF0000000000);
addr |= ((strNum[6] << 48) & 0x00FF000000000000);
addr |= ((strNum[7] << 56) & 0xFF00000000000000);
return addr;
}
|
/*
* CharactorLogin.h
*
* Created on: Jun 17, 2017
* Author: root
*/
#ifndef CHARACTORMGR_CHARACTORLOGIN_H_
#define CHARACTORMGR_CHARACTORLOGIN_H_
#include "Network/MessageHandler.h"
#include "MsgDefineMacro.h"
#include "ServerMsgDefine.h"
using namespace CommBaseOut;
class CharactorLogin : public Message_Handler, public Request_Handler, public Ack_Handler
{
public:
~CharactorLogin();
static CharactorLogin *GetInstance()
{
if(m_instance == 0)
{
m_instance = new CharactorLogin();
}
return m_instance;
}
DEF_MSG_REQUEST_DECLARE_FUN_H(MSG_REQ_LS2GT_WILLLOGIN);
DEF_MSG_REQUEST_DECLARE_FUN_H(MSG_REQ_C2GT_HEARTBEAT);
DEF_MSG_REQUEST_DECLARE_FUN_H(MSG_REQ_C2GT_PLAYERINFO);
DEF_MSG_ACK_DECLARE_FUN_H(MSG_REQ_GT2GM_PLAYERINFO);
DEF_MSG_REQUEST_DECLARE_FUN_H(MSG_REQ_C2GT_CLIENTIN);
DEF_MSG_ACK_DECLARE_FUN_H(MSG_REQ_GT2GM_CLIENTIN);
DEF_MSG_REQUEST_DECLARE_FUN_H(MSG_REQ_C2GT_SYN_ATTR);
DEF_MSG_ACK_DECLARE_FUN_H(MSG_REQ_GT2GM_SYN_ATTR);
virtual void Handle_Message(Safe_Smart_Ptr<Message> &message);
virtual void Handle_Request(Safe_Smart_Ptr<Message> &message);
virtual void Handle_Ack(Safe_Smart_Ptr<Message> &message);
void DestroyInstance()
{
if(m_instance)
{
delete m_instance;
m_instance = 0;
}
}
//通知登录服此次登录失败
void sendToLoginFail(int64 charid);
private:
CharactorLogin();
private:
static CharactorLogin * m_instance;
};
#endif /* CHARACTORMGR_CHARACTORLOGIN_H_ */
|
#pragma once
#include <string>
#include <vector>
#include <iostream>
#include <algorithm>
#define GLM_ENABLE_EXPERIMENTAL
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#define PI 3.14159265358979323846
class Bone_Animation
{
public:
Bone_Animation();
~Bone_Animation();
void init();
void update(float delta_time);
void reset();
float deg_to_rad = 2 * PI / 360;
public:
// Here the head of each vector is the root bone
std::vector<glm::vec3> scale_vector;
std::vector<glm::vec3> rotation_degree_vector;
std::vector<glm::vec4> colors;
glm::vec3 root_position;
std::vector<glm::vec3> rotate_bones;
glm::vec3 upper_position;
glm::vec3 middle_position;
glm::vec3 bottom_position;
glm::vec3 root_upper_joint;
glm::vec3 upper_root_joint;
glm::vec3 upper_middle_joint;
glm::vec3 middle_upper_joint;
glm::vec3 middle_bottom_joint;
glm::vec3 bottom_middle_joint;
glm::vec3 upper_trans_position;
glm::vec3 middle_trans_position;
glm::vec3 bottom_trans_position;
std::vector<glm::vec3> axis_origin = { { 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f } };
std::vector<glm::vec3> axis_upper = { { 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f } };
std::vector<glm::vec3> axis_middle = { { 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f } };
std::vector<glm::vec3> axis_bottom = { { 1.0f, 0.0f, 0.0f },
{ 0.0f, 1.0f, 0.0f },
{ 0.0f, 0.0f, 1.0f } };
};
|
#ifndef SUBCALLBACK_H
#define SUBCALLBACK_H
#include <mqtt/subscriber/sub_action_listener.h>
#include <mqtt/subscriber/subscriber.h>
#include <deque>
#include <iostream>
#include <mqtt/xorcipher.h>
/*
* subCallback
*/
class SubCallback : public virtual mqtt::callback,
public virtual mqtt::iaction_listener {
int qos_;
int nretry_;
mqtt::async_client &cli_;
std::vector<Subscriber *> subscribers_;
sub_action_listener &listener_;
void reconnect();
// Re-connection failure
virtual void on_failure(const mqtt::itoken &);
// Re-connection success
virtual void on_success(const mqtt::itoken &tok);
virtual void connection_lost(const std::string &cause);
virtual void message_arrived(const std::string &topic,
mqtt::message_ptr msg);
virtual void delivery_complete(mqtt::idelivery_token_ptr);
public:
void addSubscriber(Subscriber *s);
SubCallback(mqtt::async_client &cli, sub_action_listener &listener, int qos,
std::vector<Subscriber *> subscribers)
: qos_(qos), cli_(cli), subscribers_(subscribers), listener_(listener) {
}
};
#endif // SUBCALLBACK_H
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.