blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
11cee9e4ea83e240206f73918d4f3e7f5801b000 | 002033b136c071715d96aa29bed28c8722968330 | /Fft.cpp | 2bbae0251ecb896115f87f633ab9eff67c1de420 | [] | no_license | adityasriteja4u/SpeechWave | ac31ee32f2c1e3ebec278d27f6f9dce927de79c0 | 135df91367cf8e130f115f0c2f23cb547a27991d | refs/heads/master | 2021-01-16T22:14:30.770238 | 2014-04-09T08:30:26 | 2014-04-09T08:30:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,520 | cpp | //
// FileName: fft.cpp By YANG Jian 1995.1.25
//
#include "stdafx.h"
//#include "VS.h"
#include <math.h>
#include "fft.h"
// construct function of class TFft.
TFft::TFft(int npoint)
{
IsOk = 0;
nM = (int)(log((double)npoint) / log(2.0) + 0.5);
nPoint = npoint;
nPoint2 = nPoint / 2;
fwCos = new float [nPoint2];
fwSin = new float [nPoint2];
iTable = new int [nPoint];
if(fwCos && fwSin && iTable && (PowOf2(nM)==nPoint)) {
SetInit();
IsOk = 1;
}
}
// deconstruct function of class TFft.
TFft::~TFft()
{
delete[] iTable;
delete[] fwSin;
delete[] fwCos;
}
// SetInit() uses to compute iTable[], fwCos[], fwSin[] and fHamming[].
void TFft::SetInit()
{
int i, j, k;
// compute coefficients.
double pi = 4.0*atan(1.0);
double temp = 2.0 * pi / (float)nPoint;
for(i=0; i<nPoint2; i++) {
fwCos[i] = cos(i*temp);
fwSin[i] = sin(i*temp);
}
// construct bit reversal table.
j = 0;
iTable[0] = 0;
iTable[nPoint-1] = nPoint - 1 ;
for(i=1; i<nPoint-1; i++) {
k = nPoint / 2;
while( k<= j) {
j -= k;
k /= 2;
}
j += k;
iTable[i] = j;
}
}
// Powof2() uses to compute 2^i.
int TFft::PowOf2(int i)
{
int j, k;
k = 1;
for(j=0; j<i; j++) k *= 2;
return k;
}
// Function Transform() compute FFT.
void TFft::Transform(float *xr, float *xi)
{
int l, i, j, m, le, le1, ip;
int unit, iwt;
float tr, ti;
// rearragne array xr[], xi[].
for(i=1; i<nPoint-1; i++) {
j = iTable[i];
if(i<j) {
tr = xr[i];
ti = xi[i];
xr[i] = xr[j];
xi[i] = xi[j];
xr[j] = tr;
xi[j] = ti;
}
}
// compute.
m = nM;
for(l=1; l<=m; l++) {
le = PowOf2(l);
le1 = le / 2;
unit = nPoint / le;
iwt = 0;
for(j=0; j<le1; j++) {
for(i=j; i<nPoint; i += le) {
ip = i + le1;
tr = xr[ip]*fwCos[iwt] + xi[ip]*fwSin[iwt];
ti = xi[ip]*fwCos[iwt] - xr[ip]*fwSin[iwt];
xr[ip] = xr[i] - tr;
xi[ip] = xi[i] - ti;
xr[i] = xr[i] + tr;
xi[i] = xi[i] + ti;
}
iwt += unit;
}
}
}
// Function InverseTransform() compute inverse FFT.
void TFft::InverseTransform(float *xr, float *xi)
{
int l, i, j, m, le, le1, ip;
int unit, iwt;
float tr, ti;
// rearragne array xr[], xi[].
for(i=1; i<nPoint-1; i++) {
j = iTable[i];
if(i<j) {
tr = xr[i];
ti = xi[i];
xr[i] = xr[j];
xi[i] = xi[j];
xr[j] = tr;
xi[j] = ti;
}
}
// compute.
m = nM;
for(l=1; l<=m; l++) {
le = PowOf2(l);
le1 = le / 2;
unit = nPoint / le;
iwt = 0;
for(j=0; j<le1; j++) {
for(i=j; i<nPoint; i += le) {
ip = i + le1;
tr = xr[ip]*fwCos[iwt] - xi[ip]*fwSin[iwt];
ti = xi[ip]*fwCos[iwt] + xr[ip]*fwSin[iwt];
xr[ip] = xr[i] - tr;
xi[ip] = xi[i] - ti;
xr[i] = xr[i] + tr;
xi[i] = xi[i] + ti;
}
iwt += unit;
}
}
tr = 1.0 / (float)nPoint;
for(i=0; i<nPoint; i++) {
xr[i] = tr * xr[i];
xi[i] = tr * xi[i];
}
}
// Function Tran2RealSequence() compute two real sequence with one FFT.
// Defaultly, nfreq = nPoint / 2.
void TFft::Tran2RealSequence(float *x1,
float *x2,
float *mag1,
float *mag2,
int nfreq )
{
float x1r, x1i, x2r, x2i;
int j, jj, jpoint;
// compute DFT with FFT.
Transform(x1, x2);
// compute power spectrum.
jpoint = (nfreq <= nPoint) ? nfreq : nPoint;
mag1[0] = x1[0]*x1[0];
mag2[0] = x2[0]*x2[0];
for(j=1; j<jpoint; j++) {
jj = nPoint - j;
x1r = x1[j] + x1[jj];
x1i = x2[j] - x2[jj];
x2r = x2[j] + x2[jj];
x2i = x1[jj] - x1[j];
mag1[j] = 0.25*(x1r*x1r + x1i*x1i);
mag2[j] = 0.25*(x2r*x2r + x2i*x2i);
}
}
| [
"lsx20071060081@hotmail.com"
] | lsx20071060081@hotmail.com |
5cb55177c412fdf81878ddaaac62ce9e930bd3c1 | fd57ede0ba18642a730cc862c9e9059ec463320b | /compile/mclinker/unittests/GCFactoryListTraitsTest.h | eecadc7103650c8076e79aaf69d6716a8be5fa31 | [
"NCSA"
] | permissive | kailaisi/android-29-framwork | a0c706fc104d62ea5951ca113f868021c6029cd2 | b7090eebdd77595e43b61294725b41310496ff04 | refs/heads/master | 2023-04-27T14:18:52.579620 | 2021-03-08T13:05:27 | 2021-03-08T13:05:27 | 254,380,637 | 1 | 1 | null | 2023-04-15T12:22:31 | 2020-04-09T13:35:49 | C++ | UTF-8 | C++ | false | false | 2,368 | h | //===- GCFactoryListTraitsTest.h ------------------------------------------===//
//
// The MCLinker Project
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
#ifndef MCLD_GC_FACTORY_LIST_TRAITS_TEST_H
#define MCLD_GC_FACTORY_LIST_TRAITS_TEST_H
#include <gtest.h>
#include "mcld/Support/GCFactoryListTraits.h"
#include <llvm/ADT/ilist_node.h>
#include "mcld/Support/GCFactory.h"
namespace mcldtest {
/** \class GCFactoryListTraitsTest
* \brief
*
* \see GCFactoryListTraits
*/
class GCFactoryListTraitsTest : public ::testing::Test {
public:
/** \class GCFactoryListTraitsTest
* \brief Node used in the test
*
*/
class NodeFactory;
class Node : public llvm::ilist_node<Node> {
friend class NodeFactory;
private:
unsigned m_Init;
unsigned m_Value;
public:
Node() : m_Init(0), m_Value(0) {}
Node(unsigned pInit) : m_Init(pInit), m_Value(pInit) {}
unsigned getInitialValue() const { return m_Init; }
inline unsigned getValue() const { return m_Value; }
inline void setValue(unsigned pValue) { m_Value = pValue; }
};
class NodeFactory : public mcld::GCFactory<Node, 0> {
public:
NodeFactory() : mcld::GCFactory<Node, 0>(16) {}
Node* produce(unsigned pInit) {
Node* result = allocate();
new (result) Node(pInit);
return result;
}
};
// Constructor can do set-up work for all test here.
GCFactoryListTraitsTest();
// Destructor can do clean-up work that doesn't throw exceptions here.
virtual ~GCFactoryListTraitsTest();
// SetUp() will be called immediately before each test.
virtual void SetUp();
// TearDown() will be called immediately after each test.
virtual void TearDown();
const llvm::iplist<Node, mcld::GCFactoryListTraits<Node> >& getNodeList()
const {
return m_pNodeList;
}
llvm::iplist<Node, mcld::GCFactoryListTraits<Node> >& getNodeList() {
return m_pNodeList;
}
protected:
NodeFactory m_NodeFactory;
Node** m_pNodesAlloc;
llvm::iplist<Node, mcld::GCFactoryListTraits<Node> > m_pNodeList;
};
} // namespace of mcldtest
#endif
| [
"541018378@qq.com"
] | 541018378@qq.com |
87fc50fbfe57accb8e616101d0f13f2c67ff70b2 | ae0ecf150d36eabec0d61ba546e9f727284c9e92 | /Lesson5/task3.cpp | 28b888416aff5347a050f257b14e370a85a6e549 | [] | no_license | kingstertime/parallel-programming-2020 | b49de37228d04f3b39fa8ac09ea06a9aef32567d | f120b57e83c3c45a2f69088c54d0d065a67f1312 | refs/heads/master | 2023-01-23T00:34:56.324096 | 2020-11-30T16:45:19 | 2020-11-30T16:45:19 | 294,218,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 593 | cpp | #include<mpi.h>
#include<iostream>
int main(int argc, char** argv) {
int rank, size;
const int N = 10;
int a[N];
MPI_Init(&argc, &argv);
MPI_Comm_size(MPI_COMM_WORLD, &size);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
for (int i = 0; i < N; i++) {
a[i] = rand() % 100 + 1;
}
MPI_Send(&a, N, MPI_INT, 1, 0, MPI_COMM_WORLD);
}
if (rank == 1) {
MPI_Recv(&a, N, MPI_INT, 0,
MPI_ANY_TAG, MPI_COMM_WORLD, MPI_STATUSES_IGNORE);
printf("processes: %d, Got\n", rank);
for (int i = 0; i < N; i++) {
printf("%d ", a[i]);
}
}
MPI_Finalize();
return 0;
} | [
"kingstertime@gmail.com"
] | kingstertime@gmail.com |
fca04a13d5bda67566eaff1e2aa8b474cdf6f4ab | 83921e08a63594fdeedcbe7866710b6f1a4c4d89 | /main/main.ino | d47271eb22f4a2b830845ee2b837e7d65c8b0a4c | [] | no_license | j3ven7/CurrentBikeCode | 106accd21393af2c566740b1ff0c40a5477192f4 | 97e68a54524f8088ee62d00531f46ebdd488d2b3 | refs/heads/master | 2021-01-25T07:02:16.294395 | 2017-05-07T17:29:10 | 2017-05-07T17:29:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,752 | ino | #include "Rear_Motor.h"
#include "Front_Motor.h"
#include "RC_Handler.h"
#include "Landing_Gear.h"
#include "Bike_State.h"
#include "IMU.h"
#include "Watchdog.h"
//============================ROS=================
#include <ros.h>
#include <std_msgs/Float32.h>
#include <std_msgs/Float32MultiArray.h>
ros::NodeHandle nh;
std_msgs::Float32MultiArray bike_state;
ros::Publisher state_pub("bike_state", &bike_state);
//============================END ROS===================
//Rear Motor
#define in_pin 11 //hall sensor pulse
#define pwm_rear 8 //rear motor PWM pin
#define v_pin 63 // Battery Voltage pin
#define reverse_pin 50
//Front Motor
#define PWM_front 9
#define DIR 46
//RC
#define RC_CH1 51 //Steer Angle
#define RC_CH2 28 //
#define RC_CH3 25 //Velocity
#define RC_CH4 33 //
#define RC_CH5 27 //Kill Switch
#define RC_CH6 32 //Landing Gear
//==========================Initialize Controllers===============
Bike_State bike;
void setup() {
attachInterrupt(digitalPinToInterrupt(in_pin), update_Rear_Motor_Speed, RISING);
attachInterrupt(RC_CH1, rc1, CHANGE);
attachInterrupt(RC_CH2, rc2, CHANGE);
attachInterrupt(RC_CH6, rc6, CHANGE);
bike.setupBike();
}
void loop() {
bike.processLoop();
bike_state.data[0] = bike.desired_velocity;
bike_state.data[1] = bike.current_velocity;
bike_state.data[2] = bike.lean_rate;
bike_state.data[3] = bike.lean_angle;
bike_state.data[4] = bike.encoder_position;
bike_state.data[5] = bike.desired_steer;
state_pub.publish( &bike_state );
nh.spinOnce();
}
void update_Rear_Motor_Speed() {
bike.rear->updateSpeed();
}
void rc1() {
bike.rc.calcSignal();
}
void rc2() {
bike.rc.calcSignal2();
}
void rc6() {
bike.rc.calcSignal6();
}
| [
"kwf37@cornell.edu"
] | kwf37@cornell.edu |
114f4400d24104b4fcf9e61ec1daace7e27aed61 | 5b28b26ff0cdbab49bf3d83f64f97d04e04b40b2 | /addons/Box2D/DebugDraw.h | 5fc9cdeefaad4c5c1695a8f61c5d0ef6e1493a2c | [] | no_license | q-depot/roxlu | 6381ae7cad9a568142838bb72968469cc7b3d6f2 | 0e77879c1d7ddcaedfb06e274be0aa7341dd61ce | refs/heads/master | 2021-01-21T02:02:20.351417 | 2012-08-02T21:00:00 | 2012-08-02T21:00:00 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 925 | h | #ifndef ROXLU_BOX2D_DEBUGDRAWH
#define ROXLU_BOX2D_DEBUGDRAWH
#include <Box2D/Box2D.h>
struct b2AABB;
class DebugDraw : public b2Draw {
public:
DebugDraw();
~DebugDraw();
void DrawPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
void DrawSolidPolygon(const b2Vec2* vertices, int32 vertexCount, const b2Color& color);
void DrawCircle(const b2Vec2& center, float32 radius, const b2Color& color);
void DrawSolidCircle(const b2Vec2& center, float32 radius, const b2Vec2& axis, const b2Color& color);
void DrawSegment(const b2Vec2& p1, const b2Vec2& p2, const b2Color& color);
void DrawTransform(const b2Transform& xf);
void DrawPoint(const b2Vec2& p, float32 size, const b2Color& color);
void DrawString(int x, int y, const char* string, ...);
void DrawString(const b2Vec2& p, const char* string, ...);
void DrawAABB(b2AABB* aabb, const b2Color& color);
};
#endif | [
"diederick@apollomedia.nl"
] | diederick@apollomedia.nl |
b63f9f4656ca324a610e36ffeb42f910ca9f5e70 | 0d79cdeadc76cc3250dee42feae52009259b66d4 | /CubeEngine/EngineSrc/3D/Effect/EffectMgr.h | 1679fdb474bb27eb6139ee22266a88ff039a6b0f | [
"MIT"
] | permissive | tigertv/Cube-Engine | 2ef4a49e031c375cb2368c04743dacdd793d0396 | 0677562bf1dfdb9dd0e35ee587874ac9788ad6ac | refs/heads/master | 2021-02-06T19:02:33.047381 | 2020-02-29T09:44:26 | 2020-02-29T09:51:07 | 243,941,293 | 0 | 0 | MIT | 2020-02-29T09:36:37 | 2020-02-29T09:36:37 | null | UTF-8 | C++ | false | false | 487 | h | #ifndef TZW_EFFECTMGR_H
#define TZW_EFFECTMGR_H
#include "EngineSrc/Engine/EngineDef.h"
#include "Effect.h"
#include <map>
namespace tzw {
class EffectMgr
{
public:
EffectMgr();
Effect * get(std::string name);
void initBuiltIn();
void addEffect(std::string name, Effect * theEffect);
void addEffect(std::string effectName);
private:
std::map<std::string, Effect *> m_effectMap;
TZW_SINGLETON_DECL(EffectMgr)
};
} // namespace tzw
#endif // TZW_EFFECTMGR_H
| [
"tzwtangziwen"
] | tzwtangziwen |
0536912289dd21446ed3dff5ef5258d625561fc3 | 71f226e79ab3c38da9562cf4dd4fe51d72665766 | /hummingbird_px4/src/modules/uavcan/libuavcan/libuavcan_drivers/stm32/driver/src/uc_stm32_thread.cpp | 9b9a0d2d795802954065f3ee88ce5b9b8313a987 | [
"MIT"
] | permissive | roseyangyu/hummingbird | db6b4bcc8e251fd475fc4cb4a326e5811157d6bf | 8420389e225baccebb8946405bd58a185805fa8e | refs/heads/master | 2020-08-14T15:57:53.680838 | 2019-10-11T20:37:02 | 2019-10-11T20:37:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,802 | cpp | /*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#include <uavcan_stm32/thread.hpp>
#include <uavcan_stm32/clock.hpp>
#include <uavcan_stm32/can.hpp>
#include "internal.hpp"
namespace uavcan_stm32
{
#if UAVCAN_STM32_CHIBIOS
/*
* BusEvent
*/
bool BusEvent::wait(uavcan::MonotonicDuration duration)
{
static const uavcan::int64_t MaxDelayMSec = 0x000FFFFF;
const uavcan::int64_t msec = duration.toMSec();
msg_t ret = msg_t();
if (msec <= 0)
{
# if (CH_KERNEL_MAJOR == 2)
ret = sem_.waitTimeout(TIME_IMMEDIATE);
# else // ChibiOS 3
ret = sem_.wait(TIME_IMMEDIATE);
# endif
}
else
{
# if (CH_KERNEL_MAJOR == 2)
ret = sem_.waitTimeout((msec > MaxDelayMSec) ? MS2ST(MaxDelayMSec) : MS2ST(msec));
# else // ChibiOS 3
ret = sem_.wait((msec > MaxDelayMSec) ? MS2ST(MaxDelayMSec) : MS2ST(msec));
# endif
}
# if (CH_KERNEL_MAJOR == 2)
return ret == RDY_OK;
# else // ChibiOS 3
return ret == MSG_OK;
# endif
}
void BusEvent::signal()
{
sem_.signal();
}
void BusEvent::signalFromInterrupt()
{
# if (CH_KERNEL_MAJOR == 2)
chSysLockFromIsr();
sem_.signalI();
chSysUnlockFromIsr();
# else // ChibiOS 3
chSysLockFromISR();
sem_.signalI();
chSysUnlockFromISR();
# endif
}
/*
* Mutex
*/
void Mutex::lock()
{
mtx_.lock();
}
void Mutex::unlock()
{
# if (CH_KERNEL_MAJOR == 2)
chibios_rt::BaseThread::unlockMutex();
# else // ChibiOS 3
mtx_.unlock();
# endif
}
#elif UAVCAN_STM32_FREERTOS
bool BusEvent::wait(uavcan::MonotonicDuration duration)
{
static const uavcan::int64_t MaxDelayMSec = 0x000FFFFF;
const uavcan::int64_t msec = duration.toMSec();
BaseType_t ret;
if (msec <= 0)
{
ret = xSemaphoreTake( sem_, ( TickType_t ) 0 );
}
else
{
ret = xSemaphoreTake( sem_, (msec > MaxDelayMSec) ? (MaxDelayMSec/portTICK_RATE_MS) : (msec/portTICK_RATE_MS));
}
return ret == pdTRUE;
}
void BusEvent::signal()
{
xSemaphoreGive( sem_ );
}
void BusEvent::signalFromInterrupt()
{
higher_priority_task_woken = pdFALSE;
xSemaphoreGiveFromISR( sem_, &higher_priority_task_woken );
}
void BusEvent::yieldFromISR()
{
portYIELD_FROM_ISR( higher_priority_task_woken );
}
/*
* Mutex
*/
void Mutex::lock()
{
xSemaphoreTake( mtx_, portMAX_DELAY );
}
void Mutex::unlock()
{
xSemaphoreGive( mtx_ );
}
#elif UAVCAN_STM32_NUTTX
const unsigned BusEvent::MaxPollWaiters;
const char* const BusEvent::DevName = "/dev/uavcan/busevent";
int BusEvent::openTrampoline(::file* filp)
{
return static_cast<BusEvent*>(filp->f_inode->i_private)->open(filp);
}
int BusEvent::closeTrampoline(::file* filp)
{
return static_cast<BusEvent*>(filp->f_inode->i_private)->close(filp);
}
int BusEvent::pollTrampoline(::file* filp, ::pollfd* fds, bool setup)
{
return static_cast<BusEvent*>(filp->f_inode->i_private)->poll(filp, fds, setup);
}
int BusEvent::open(::file* filp)
{
(void)filp;
return 0;
}
int BusEvent::close(::file* filp)
{
(void)filp;
return 0;
}
int BusEvent::poll(::file* filp, ::pollfd* fds, bool setup)
{
CriticalSectionLocker locker;
int ret = -1;
if (setup)
{
ret = addPollWaiter(fds);
if (ret == 0)
{
/*
* Two events can be reported via POLLIN:
* - The RX queue is not empty. This event is level-triggered.
* - Transmission complete. This event is edge-triggered.
* FIXME Since TX event is edge-triggered, it can be lost between poll() calls.
*/
fds->revents |= fds->events & (can_driver_.hasReadableInterfaces() ? POLLIN : 0);
if (fds->revents != 0)
{
(void)sem_post(fds->sem);
}
}
}
else
{
ret = removePollWaiter(fds);
}
return ret;
}
int BusEvent::addPollWaiter(::pollfd* fds)
{
for (unsigned i = 0; i < MaxPollWaiters; i++)
{
if (pollset_[i] == NULL)
{
pollset_[i] = fds;
return 0;
}
}
return -ENOMEM;
}
int BusEvent::removePollWaiter(::pollfd* fds)
{
for (unsigned i = 0; i < MaxPollWaiters; i++)
{
if (fds == pollset_[i])
{
pollset_[i] = NULL;
return 0;
}
}
return -EINVAL;
}
BusEvent::BusEvent(CanDriver& can_driver)
: can_driver_(can_driver)
, signal_(false)
{
std::memset(&file_ops_, 0, sizeof(file_ops_));
std::memset(pollset_, 0, sizeof(pollset_));
file_ops_.open = &BusEvent::openTrampoline;
file_ops_.close = &BusEvent::closeTrampoline;
file_ops_.poll = &BusEvent::pollTrampoline;
// TODO: move to init(), add proper error handling
if (register_driver(DevName, &file_ops_, 0666, static_cast<void*>(this)) != 0)
{
std::abort();
}
}
BusEvent::~BusEvent()
{
(void)unregister_driver(DevName);
}
bool BusEvent::wait(uavcan::MonotonicDuration duration)
{
// TODO blocking wait
const uavcan::MonotonicTime deadline = clock::getMonotonic() + duration;
while (clock::getMonotonic() < deadline)
{
{
CriticalSectionLocker locker;
if (signal_)
{
signal_ = false;
return true;
}
}
::usleep(1000);
}
return false;
}
void BusEvent::signalFromInterrupt()
{
signal_ = true; // HACK
for (unsigned i = 0; i < MaxPollWaiters; i++)
{
::pollfd* const fd = pollset_[i];
if (fd != NULL)
{
fd->revents |= fd->events & POLLIN;
if ((fd->revents != 0) && (fd->sem->semcount <= 0))
{
(void)sem_post(fd->sem);
}
}
}
}
#endif
}
| [
"jiashen.wang@rapyuta-robotics.com"
] | jiashen.wang@rapyuta-robotics.com |
6aee6f99d06a98d740e8a12b3214ae3d3323e77a | 95f4b2830dd02d0653e339329c5a08f8ad19e1ff | /Actors/ActorFactory.cpp | f55bb31a85bbdae35f0ec03e713c730519c19267 | [] | no_license | JDHDEV/AlphaEngine | d0459e760343f47b00d9e34be8f7e8d93d308c27 | 2c5602a4bbba966c7f31b06ce0c7eabaa97002ec | refs/heads/master | 2021-01-01T19:42:43.176631 | 2015-07-27T01:03:05 | 2015-07-27T01:03:05 | 39,701,364 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,857 | cpp | //========================================================================
// ActorFactory.cpp : Creates actors from components
//
// Part of the Alpha Application
//
// Alpha is the sample application that encapsulates much of the source code
// discussed in "Game Coding Complete - 4th Edition" by Mike McShaffry and David
// "Rez" Graham, published by Charles River Media.
// ISBN-10: 1133776574 | ISBN-13: 978-1133776574
//
// Justin Hunt
//========================================================================
#include "AlphaStd.h"
#include "ActorFactory.h"
#include "../ResourceCache/XmlResource.h"
#include "ActorComponent.h"
//#include "AudioComponent.h"
#include "TransformComponent.h"
#include "RenderComponent.h"
#include "PhysicsComponent.h"
#include "AmmoPickup.h"
//#include "HealthPickup.h"
#include "BaseScriptComponent.h"
#include "../Utilities/String.h"
//---------------------------------------------------------------------------------------------------------------------
// Factory class definition
// Chapter 6, page 161
//---------------------------------------------------------------------------------------------------------------------
ActorFactory::ActorFactory(void)
{
m_lastActorId = INVALID_ACTOR_ID;
m_componentFactory.Register<TransformComponent>(ActorComponent::GetIdFromName(TransformComponent::g_Name));
m_componentFactory.Register<MeshRenderComponent>(ActorComponent::GetIdFromName(MeshRenderComponent::g_Name));
m_componentFactory.Register<SphereRenderComponent>(ActorComponent::GetIdFromName(SphereRenderComponent::g_Name));
m_componentFactory.Register<PhysicsComponent>(ActorComponent::GetIdFromName(PhysicsComponent::g_Name));
m_componentFactory.Register<TeapotRenderComponent>(ActorComponent::GetIdFromName(TeapotRenderComponent::g_Name));
m_componentFactory.Register<GridRenderComponent>(ActorComponent::GetIdFromName(GridRenderComponent::g_Name));
m_componentFactory.Register<LightRenderComponent>(ActorComponent::GetIdFromName(LightRenderComponent::g_Name));
m_componentFactory.Register<SkyRenderComponent>(ActorComponent::GetIdFromName(SkyRenderComponent::g_Name));
m_componentFactory.Register<BrickRenderComponent>(ActorComponent::GetIdFromName(BrickRenderComponent::g_Name));
//m_componentFactory.Register<AudioComponent>(ActorComponent::GetIdFromName(AudioComponent::g_Name));
// FUTURE WORK - certainly don't need to do this now, but the following stuff should be in a TeapotWarsActorFactory, eh?
//m_componentFactory.Register<AmmoPickup>(ActorComponent::GetIdFromName(AmmoPickup::g_Name));
//m_componentFactory.Register<HealthPickup>(ActorComponent::GetIdFromName(HealthPickup::g_Name));
m_componentFactory.Register<BaseScriptComponent>(ActorComponent::GetIdFromName(BaseScriptComponent::g_Name));
}
StrongActorPtr ActorFactory::CreateActor(const char* actorResource, TiXmlElement *overrides, const Mat4x4 *pInitialTransform, const ActorId serversActorId)
{
// Grab the root XML node
TiXmlElement* pRoot = XmlResourceLoader::LoadAndReturnRootXmlElement(actorResource);
if (!pRoot)
{
AC_ERROR("Failed to create actor from resource: " + std::string(actorResource));
return StrongActorPtr();
}
// create the actor instance
ActorId nextActorId = serversActorId;
if (nextActorId == INVALID_ACTOR_ID)
{
nextActorId = GetNextActorId();
}
StrongActorPtr pActor(AC_NEW Actor(nextActorId));
if (!pActor->Init(pRoot))
{
AC_ERROR("Failed to initialize actor: " + std::string(actorResource));
return StrongActorPtr();
}
bool initialTransformSet = false;
// Loop through each child element and load the component
for (TiXmlElement* pNode = pRoot->FirstChildElement(); pNode; pNode = pNode->NextSiblingElement())
{
StrongActorComponentPtr pComponent(VCreateComponent(pNode));
if (pComponent)
{
pActor->AddComponent(pComponent);
pComponent->SetOwner(pActor);
}
else
{
// If an error occurs, we kill the actor and bail. We could keep going, but the actor is will only be
// partially complete so it's not worth it. Note that the pActor instance will be destroyed because it
// will fall out of scope with nothing else pointing to it.
return StrongActorPtr();
}
}
if (overrides)
{
ModifyActor(pActor, overrides);
}
// This is a bit of a hack to get the initial transform of the transform component set before the
// other components (like PhysicsComponent) read it.
shared_ptr<TransformComponent> pTransformComponent = MakeStrongPtr(pActor->GetComponent<TransformComponent>(TransformComponent::g_Name));
if (pInitialTransform && pTransformComponent)
{
pTransformComponent->SetPosition(pInitialTransform->GetPosition());
pTransformComponent->SetYawPitchRoll(pInitialTransform->GetYawPitchRoll());
}
// Now that the actor has been fully created, run the post init phase
pActor->PostInit();
return pActor;
}
StrongActorComponentPtr ActorFactory::VCreateComponent(TiXmlElement* pData)
{
const char* name = pData->Value();
StrongActorComponentPtr pComponent(m_componentFactory.Create(ActorComponent::GetIdFromName(name)));
// initialize the component if we found one
if (pComponent)
{
if (!pComponent->VInit(pData))
{
AC_ERROR("Component failed to initialize: " + std::string(name));
return StrongActorComponentPtr();
}
}
else
{
AC_ERROR("Couldn't find ActorComponent named " + std::string(name));
return StrongActorComponentPtr(); // fail
}
// pComponent will be NULL if the component wasn't found. This isn't necessarily an error since you might have a
// custom CreateComponent() function in a sub class.
return pComponent;
}
void ActorFactory::ModifyActor(StrongActorPtr pActor, TiXmlElement* overrides)
{
// Loop through each child element and load the component
for (TiXmlElement* pNode = overrides->FirstChildElement(); pNode; pNode = pNode->NextSiblingElement())
{
ComponentId componentId = ActorComponent::GetIdFromName(pNode->Value());
StrongActorComponentPtr pComponent = MakeStrongPtr(pActor->GetComponent<ActorComponent>(componentId));
if (pComponent)
{
pComponent->VInit(pNode);
// [mrmike] - added post press to ensure that components that need it have
// Events generated that can notify subsystems when changes happen.
// This was done to have SceneNode derived classes respond to RenderComponent
// changes.
pComponent->VOnChanged();
}
else
{
pComponent = VCreateComponent(pNode);
if (pComponent)
{
pActor->AddComponent(pComponent);
pComponent->SetOwner(pActor);
}
}
}
} | [
"JustinHunt@newagepavilions.com"
] | JustinHunt@newagepavilions.com |
57a5952cda4fb1e7a29c0a0191e360662949f089 | 9f72680b9da072cf1301248d15a617e06fd26df1 | /catkin_ws/src/RosLib/src/RosCameraPlugin.cpp | 7747bfbab332f481ea50dea863cdbd20667c8030 | [] | no_license | militaru92/JdeRobot2015 | d9fe21c0548d4ffc5a244fac15190c1b7a7a8125 | a843e63c232ade065180ba665cc26d6ed75e2501 | refs/heads/master | 2021-01-10T06:39:30.322484 | 2015-10-05T13:08:43 | 2015-10-05T13:08:43 | 36,067,808 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,275 | cpp | #include "RosCameraPlugin.h"
namespace gazebo
{
RosCameraPlugin::RosCameraPlugin()
{
}
RosCameraPlugin::~RosCameraPlugin()
{
delete ImagePublisher;
delete ImageNode;
//delete RosPublisher;
delete RosNode;
}
void RosCameraPlugin::Load(sensors::SensorPtr _parent, sdf::ElementPtr _sdf)
{
// Don't forget to load the camera plugin
CameraPlugin::Load(_parent,_sdf);
RosNode = new ros::NodeHandle;
ImageNode = new image_transport::ImageTransport(*RosNode);
ImagePublisher = new image_transport::Publisher(ImageNode->advertise(this->parentSensor->GetCamera()->GetName(), 500));
ROS_INFO("ROS Publisher Loaded: %s\n",this->parentSensor->GetCamera()->GetName().c_str());
}
void RosCameraPlugin::OnNewFrame(const unsigned char *_image, unsigned int _width, unsigned int _height, unsigned int _depth, const std::string &_format)
{
cv::Mat image(_height,_width,CV_8UC3,(void *) _image);
sensor_msgs::ImagePtr img_message = cv_bridge::CvImage(std_msgs::Header(), "rgb8", image).toImageMsg();
//sensor_msgs::Image img_message = *(cv_bridge::CvImage(std_msgs::Header(), "rgb8", image).toImageMsg());
ImagePublisher->publish(img_message);
//RosPublisher->publish(img_message);
//ROS_INFO("New Frame\n");
}
}
| [
"militaru.andrei92@gmail.com"
] | militaru.andrei92@gmail.com |
50c2c3b3ad45a642f9f8d930a628fe2f5d760a48 | 5bd25f9ed54adc9ab62a41521368774435b59b38 | /7-й семинар/7.1 functions.cpp | 1a37d5d5339490bcb4034e8a4895238dd15e77a6 | [] | no_license | gorshkovap/HW | 0cc51bfe64d44d5ab9d972aeb381ac49ec786048 | 620fec399d901109341af442416af164f36d9aca | refs/heads/master | 2023-01-12T21:48:35.876916 | 2020-11-23T23:24:45 | 2020-11-23T23:24:45 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,715 | cpp | #include "7.1 Header.hpp"
#include <cmath>
Point::Point() : x(0.0), y(0.0) {}
Point::Point(const double a,const double b) : x(a), y(b){}
std::ostream& operator<<(std::ostream& stream, const Point& point)
{
stream << '(' << point.x << ", " << point.y << ')';
return stream;
}
Vector::Vector() : x(0.0), y(0.0) {}
Vector::Vector(double a, double b) : x(a), y(b) {}
std::ostream& operator<<(std::ostream& stream, const Vector& vector)
{
stream << '(' << vector.x << ", " << vector.y << ')';
return stream;
}
double Vector::len() const
{
return std::sqrt(x * x + y * y);
}
double vec_mul(const Vector& v_1, const Vector& v_2)
{
return std::abs(v_1.x * v_2.y - v_1.y * v_2.x);
}
double scal_mul(const Vector& v_1, const Vector& v_2)
{
return v_1.x * v_2.x + v_1.y * v_2.y;
}
bool is_coll(const Vector& v_1, const Vector& v_2)
{
return is_equal(0, vec_mul(v_1, v_2));
}
bool is_perp(const Vector& v_1, const Vector& v_2)
{
return is_equal(0, scal_mul(v_1, v_2));
}
Vector operator-(const Vector& v_1, const Vector& v_2)
{
return {v_1.x - v_2.x, v_1.y - v_2.y};
}
Shape::Shape() : m_point(){}
Shape::Shape(const Point & point) : m_point(point){}
std::ostream& operator<<(std::ostream& stream, const Shape& shape)
{
shape.print(stream);
return stream;
}
Circle::Circle() : m_a(0.0){}
Circle::Circle(const Point & point, const double r): Shape(point), m_a(r) {}
void Circle::print(std::ostream& stream) const
{
stream << "Circle: O = " << m_point << " r = " << m_a << " P = " << P() << " S = " << S();
}
double Circle::P() const
{
return 2 * pi * m_a;
}
double Circle::S() const
{
return pi * m_a * m_a;
}
const double Circle::pi = 3.1416;
Ellipse::Ellipse() : m_b(0.0){}
Ellipse::Ellipse(const Point & point ,const double a,const double b) : Circle(point, a), m_b(b) {}
void Ellipse::print(std::ostream& stream) const
{
stream << "Ellipse: O = " << m_point << " a = " << Circle::m_a << " b = " << m_b << " P = " << P() << " S = " << S();
}
double Ellipse::P() const
{
return 4 * ((pi * m_a * m_b) + (m_a - m_b) * (m_a - m_b)) / (m_a + m_b);
}
double Ellipse::S() const
{
return pi * m_a * m_b;
}
Polygon::Polygon(const Point & point, const Vector & v_1, const Vector & v_2)
: Shape(point), side_1(v_1), side_2(v_2)
{
if (is_coll(v_1, v_2))
{
std::cerr << "\nerror: vectors are collinear\n";
std::abort();
}
}
Triangle::Triangle(const Point& point, const Vector &v_1, const Vector &v_2) : Polygon(point, v_1, v_2){}
void Triangle::print(std::ostream& stream) const
{
stream << "Triangle: Starting point = " << m_point << " vector of side 1 = " << side_1 << " vector of side 2 = " << side_2 <<
" P = " << P() << " S = " << S();
}
double Triangle::P() const
{
Vector side_3 = side_1 - side_2;
return side_1.len() + side_2.len() + side_3.len();
}
double Triangle::S() const
{
return vec_mul(side_1, side_2) / 2;
}
Square::Square(const Point& point, const Vector& v_1, const Vector& v_2) : Polygon(point, v_1, v_2)
{
if (!(is_equal(side_1.len(), side_2.len())) || !(is_perp(v_1, v_2)))
{
std::cerr << "\nerror: different lenght of square's sides or the angle isn't right\n";
std::abort();
}
}
void Square::print(std::ostream& stream) const
{
stream << "Square: Starting point = " << m_point << " vector of side 1 = " << side_1 << " vector of side 2 = " << side_2 <<
" lenght of sides = " << side_1.len() << " P = " << P() << " S = " << S();
}
double Square::P() const
{
return 4 * side_1.len();
}
double Square::S() const
{
return side_1.len() * side_1.len();
}
Rectangle::Rectangle(const Point& point, const Vector& v_1, const Vector& v_2) : Polygon(point, v_1, v_2)
{
if (!(is_perp(v_1, v_2)))
{
std::cerr << "\nerror: the angle isn't right\n";
std::abort();
}
}
void Rectangle::print(std::ostream& stream) const
{
stream << "Rectangle: Starting point = " << m_point << " vector of side 1 = " << side_1 << " vector of side 2 = " << side_2 <<
" lenght of side 1 = " << side_1.len() << " lenght of side 2 = " << side_2.len() << " P = " << P() << " S = " << S();
}
double Rectangle::P() const
{
return 2 * (side_1.len() + side_2.len());
}
double Rectangle::S() const
{
return side_1.len() * side_2.len();
}
Parallelogram::Parallelogram(const Point& point, const Vector& v_1, const Vector& v_2) : Polygon(point, v_1, v_2) {}
void Parallelogram::print(std::ostream& stream) const
{
stream << "Parallelogram: Starting point = " << m_point << " vector of side 1 = " << side_1 << " vector of side 2 = " << side_2 <<
" lenght of side 1 = " << side_1.len() << " lenght of side 2 = " << side_2.len() << " small angle = " <<
std::asin(S() / (side_1.len() * side_2.len())) << "rad" << " P = " << P() << " S = " << S();
}
double Parallelogram::P() const
{
return 2 * (side_1.len() + side_2.len());
}
double Parallelogram::S() const
{
return vec_mul(side_1, side_2);
}
Rhombus::Rhombus(const Point& point, const Vector& v_1, const Vector& v_2) : Polygon(point, v_1, v_2)
{
if (!(is_equal(side_1.len(), side_2.len())))
{
std::cerr << "error: different lenght of sides of rhombus";
std::abort();
}
}
void Rhombus::print(std::ostream& stream) const
{
stream << "Rhombus: Starting point = " << m_point << " vector of side 1 = " << side_1 << " vector of side 2 = " << side_2 <<
" lenght of side 1 = " << side_1.len() << " lenght of side 2 = " << side_2.len() << " small angle = " <<
std::asin(S() / (side_1.len() * side_2.len())) << "rad" << " P = " << P() << " S = " << S();
}
double Rhombus::P() const
{
return 2 * (side_1.len() + side_2.len());
}
double Rhombus::S() const
{
return vec_mul(side_1, side_2);
}
bool is_equal(double a, double b)
{
return std::abs(a - b) <= 10 * std::numeric_limits <double> ::epsilon();
} | [
"timurfakhrutdinov@gmail.com"
] | timurfakhrutdinov@gmail.com |
4b5a4f43b086b4f36e69ebbc788fd7f52b635665 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/d9/41ffa30dd0079e/main.cpp | 5e74f98bedbc85e5405c73cc5b77510de86f9262 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,029 | cpp | #include <iostream>
#include <vector>
#include <string>
using namespace std;
class Piece
{
private:
int x; //coordinate locations
int y;
char name;
public:
Piece(char, int, int);
};
Piece :: Piece(char name_, int x_, int y_)
{
x = x_;
y = y_;
name = name_;
}
class Game
{
private:
std::vector< std::vector<Piece> > board;
public:
void setup();
void movePiece(int, int, int, int);
};
void Game :: setup()
{
char names[] = "RPNPBPQPKPBPNPRP";
//create chess board
for (int j = 0; j < 8; j++){
std::vector<Piece> col;
for (int i = 0; i < 2; i++){//pieces at rows 1 and 2
col.push_back(Piece(i, j, names[i]));
}
board.push_back(col);
for (int i = 6; i < 8; i++){
col.push_back(Piece(i, j, names[i-6]));
}
board.push_back(col);
}
}
void Game :: movePiece(int xi, int yi, int xf, int yf)
{
xi -= 97;
xf -= 97;
board[xf].erase(board.begin()+yf -1);//erase the element at xf, yf
swap(board[xi][yi], board [xf][yf]);//move piece at xi, yi to xf, yf
}
}
| [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
5e4dd0e2125c8e93163609d2ab393a95136699ca | 1d14766f1b8081d2d4e6ed8c54965948e3bd23a4 | /RadarEchoTracking/TrackBoxDockList.cpp | 619bffa6435155268ef19482d81c8ef006de76c1 | [] | no_license | VeinySoft/BeiJingQiXiang2018 | 5e4f3ddff5619ca07c41d481de4bcdd65ebb7551 | 9fcfc81d9be091fb4bc44b653ebe9657a5efbd9b | refs/heads/master | 2023-01-19T03:51:16.528367 | 2020-11-24T05:55:46 | 2020-11-24T05:55:46 | 268,947,863 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 271 | cpp | #include "StdAfx.h"
#include "TrackBoxDockList.h"
TrackBoxDockList::TrackBoxDockList(void)
{
m_Setup.setupUi(this);
this->setWindowTitle(QString::fromLocal8Bit("¸ú×Ù¿ò"));
m_Setup.widget_2->setVisible(false);
}
TrackBoxDockList::~TrackBoxDockList(void)
{
}
| [
"veiny_yxy@163.com"
] | veiny_yxy@163.com |
c0e8a83971de5db21ed2226c858c2464335a06f1 | 05cfe269344177249ded9c18b3272a234a155292 | /include/GCApplication.h | ed6a9f14a40eed06727eb94ebe1aa083b21fb4c4 | [] | no_license | Robertwyq/Grab_Cut | 28222934723880e1011d75493cf160366a23cf76 | 1eafa8dc84fcecb9be0a0b4c12cb7df58cb61fbc | refs/heads/master | 2021-03-07T10:09:05.467996 | 2020-03-10T09:35:18 | 2020-03-10T09:35:18 | 246,259,220 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,101 | h | //
// Created by Robert on 2019/6/5.
//
#ifndef GRAB_CUT_GCAPPLICATION_H
#define GRAB_CUT_GCAPPLICATION_H
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#include "GrabCut.h"
#include <iostream>
#include "BorderMatting.h"
using namespace std;
using namespace cv;
const Scalar BLUE = Scalar(255,0,0); // Background
const Scalar GREEN = Scalar(0,255,0);//Foreground
const Scalar LIGHTBLUE = Scalar(255,255,160);//ProbBackground
const Scalar PINK = Scalar(230,130,255); //ProbBackground
const Scalar RED = Scalar(0,0,255);//color of Rectangle
const int BGD_KEY = CV_EVENT_FLAG_CTRLKEY;// When press "CTRL" key,the value of flags return.
const int FGD_KEY = CV_EVENT_FLAG_SHIFTKEY;// When press "SHIFT" key, the value of flags return.
//Copy the value of comMask to binMask
static void getBinMask( const Mat& comMask, Mat& binMask )
{
if( comMask.empty() || comMask.type()!=CV_8UC1 )
CV_Error( CV_StsBadArg, "comMask is empty or has incorrect type (not CV_8UC1)" );
if( binMask.empty() || binMask.rows!=comMask.rows || binMask.cols!=comMask.cols )
binMask.create( comMask.size(), CV_8UC1 );
binMask = comMask & 1;
}
class GCApplication {
public:
enum{ NOT_SET = 0, IN_PROCESS = 1, SET = 2 };
static const int radius = 5;
static const int thickness = -1;
void reset();
void setImageAndWinName( const Mat& _image, const string& _winName );
void showImage() const;
void mouseClick( int event, int x, int y, int flags, void* param );
int nextIter();
int getIterCount() const { return iterCount; }
BorderMatting bm;
void BoardMatting();
void showOriginalImage();
private:
void setRectInMask();
void setLblsInMask( int flags, Point p, bool isPr );
const string* winName;
const Mat* image;
Mat mask;
Mat bgdModel, fgdModel;
uchar rectState, lblsState, prLblsState;
bool isInitialized;
Rect rect;
vector<Point> fgdPixelVector, bgdPixelVector, prFgdPixelVector, prBgdPixelVector;
int iterCount;
GrabCut2D gc;
};
#endif //GRAB_CUT_GCAPPLICATION_H
| [
"wyq1997boy@163.com"
] | wyq1997boy@163.com |
9c15e1480273499dd04814efcabdc4031ed8ac18 | 3ffda7c2ff861311b26c4f318f689dddb19d2d72 | /v8_consumer/include/timer.h | c1c87a090a46d45df1d713521c69cca30478f3ea | [
"Apache-2.0"
] | permissive | nandsatya/eventing | f6334090c39ccafc59122e03c35881c2accdd5e2 | 3aca1f6f0907d57d4804f555fea0acdaa8dc7a69 | refs/heads/master | 2020-04-27T05:49:23.261582 | 2019-02-27T11:26:58 | 2019-03-06T07:11:32 | 148,102,605 | 0 | 0 | Apache-2.0 | 2018-09-10T05:16:49 | 2018-09-10T05:16:48 | null | UTF-8 | C++ | false | false | 1,621 | h | // Copyright (c) 2017 Couchbase, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an "AS IS"
// BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
// or implied. See the License for the specific language governing
// permissions and limitations under the License.
#ifndef TIMER_H
#define TIMER_H
#include <string>
#include <v8.h>
struct EpochInfo {
EpochInfo(bool is_valid) : is_valid(is_valid), epoch(0) {}
EpochInfo(bool is_valid, int64_t epoch) : is_valid(is_valid), epoch(epoch) {}
bool is_valid;
int64_t epoch;
};
struct TimerInfo {
TimerInfo() : epoch(0), vb(0), seq_num(0) {}
std::string ToJSON(v8::Isolate *isolate,
const v8::Local<v8::Context> &context);
int64_t epoch;
int64_t vb;
int64_t seq_num;
std::string callback;
std::string reference;
std::string context;
};
class Timer {
public:
Timer(v8::Isolate *isolate, const v8::Local<v8::Context> &context);
virtual ~Timer();
bool CreateTimerImpl(const v8::FunctionCallbackInfo<v8::Value> &args);
private:
EpochInfo Epoch(const v8::Local<v8::Value> &date_val);
bool ValidateArgs(const v8::FunctionCallbackInfo<v8::Value> &args);
v8::Isolate *isolate_;
v8::Persistent<v8::Context> context_;
};
void CreateTimer(const v8::FunctionCallbackInfo<v8::Value> &args);
#endif
| [
"abhishek@couchbase.com"
] | abhishek@couchbase.com |
4e3ef7eba2740db4dd6a48b4fa5c50763d62f2b7 | 9bb16f8fbf9f562f1171a3bbff8318a47113823b | /abc123/abc123_c/main.cpp | 73f4f6740cd28c8c85075eab8209b1492e5f2822 | [] | no_license | kyamashiro/atcoder | 83ab0a880e014c167b6e9fe9457e6972901353fc | 999a7852b70b0a022a4d64ba40d4048ee4cc0c9c | refs/heads/master | 2022-06-01T03:01:39.143632 | 2022-05-22T05:38:42 | 2022-05-22T05:38:42 | 464,391,209 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 796 | cpp | #include <bits/stdc++.h>
#define REP(i, n) for (int i = 0; (i) < (int)(n); ++ (i))
#define REP3(i, m, n) for (int i = (m); (i) < (int)(n); ++ (i))
#define REP_R(i, n) for (int i = (int)(n) - 1; (i) >= 0; -- (i))
#define REP3R(i, m, n) for (int i = (int)(n) - 1; (i) >= (int)(m); -- (i))
#define ALL(x) ::std::begin(x), ::std::end(x)
using namespace std;
int64_t solve(int64_t N, int64_t A, int64_t B, int64_t C, int64_t D, int64_t E) {
// TODO: edit here
}
// generated by oj-template v4.8.1 (https://github.com/online-judge-tools/template-generator)
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int64_t N, A, B, C, D, E;
std::cin >> N >> A >> B >> C >> D >> E;
auto ans = solve(N, A, B, C, D, E);
std::cout << ans << '\n';
return 0;
}
| [
"kyamashiro73@gmail.com"
] | kyamashiro73@gmail.com |
1ebd31e3c8dfba4b8a69fb061c9991e065f2b55f | edc5c44ab9249bc9c518c9875bdd1b39e52c0118 | /5/3.cc | e301ec28386b17db3f171cfe9320d201bab49d9f | [] | no_license | AlbandeCrevoisier/CtCI | cff4091e5d094cf02ee2f923ead30b1796ab0c25 | 946e14def6e3ee702094b380a48134ef62689b0c | refs/heads/master | 2020-03-23T18:17:03.284301 | 2018-12-04T15:44:44 | 2018-12-04T15:44:44 | 141,899,053 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,056 | cc | /* Flip Bit to Win
Integer, you can flip one bit from a 0 to a 1. Longest sequence of 1s you can
make?
Note: the problem is so simple and restrained, that the naive solution seems
to be a reasonable answer. */
#include <iostream>
namespace {
/* Computes the longest sequence of 1 in an integer. */
int Longest1(int m) {
int s = (int) 8 * sizeof(m);
int longest = 0, l = 0;
for (int i = 0; i <= s; i++) {
if (((m >> i) & 1) == 1) {
l++;
} else {
if (l > longest)
longest = l;
l = 0;
}
}
return longest;
}
int FlipBittoWin(int m) {
int s = (int) 8 * sizeof(m);
if (m == -1)
return s;
int longest = 0, l = 0;
for (int i = 0; i < s; i++) {
if (((m >> i) & 1) == 0) {
l = Longest1(m | (1 << i));
if (l > longest)
longest = l;
}
}
return longest;
}
} // namespace
int main(void) {
int m = 1012;
std::cout << "m:";
for (int i = 31; i >= 0; i--)
std::cout << ((m >> i) & 1);
std::cout << std::endl;
std::cout << FlipBittoWin(1012) << std::endl;
return 0;
}
| [
"albandecrevoisier@gmail.com"
] | albandecrevoisier@gmail.com |
0599dad6e9af3bb8e06e1a2347827e4df246c164 | 119b62ad0d04d38b74da09c62ac8c2bf2877aa09 | /tests/unit-tests/tests/logging/LogNameLayoutTests.cpp | 17d5ecef10400a7e244bac97bf86bf5aed77a4e6 | [] | no_license | AndrewLang/matrix-cpp-logging | f2329082cee86289158468ad7c238eee050f1786 | fe129eb90e4431d5fdc9dccf613530a0e7e8c9ab | refs/heads/master | 2023-02-20T21:38:18.183222 | 2021-01-27T22:47:44 | 2021-01-27T22:47:44 | 284,808,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 425 | cpp |
#include "pch.h"
#include "gtest/gtest.h"
#include "logging/LogNameLayout.h"
#include "logging/LogMessage.h"
#include "Messages.h"
namespace Logging
{
using namespace Tests;
TEST(LogNameLayoutTests, Constructor) {
LogNameLayout layout;
}
TEST(LogNameLayoutTests, Layout) {
LogNameLayout layout;
LogMessage msg = Messages::DebugMessage();
auto content = layout.layout(msg);
EXPECT_EQ("Jasoom", content);
}
} | [
"yu-xin_lang@keysight.com"
] | yu-xin_lang@keysight.com |
ccc562905f6aa7729092ff6277d72f12cca90875 | 2f32ccf88172c2148702195f862a9e3146e52429 | /ABC/34/c.cpp | 24de0c231a272b169357a400cd39653991e339c8 | [] | no_license | getty104/AtCoder | 85ab5fdffdcbce84962734280ea9240914ad687b | 708fba718bed4692eb169854c82a849e48e1b78b | refs/heads/master | 2021-01-12T14:24:59.246818 | 2018-05-21T04:41:59 | 2018-05-21T04:41:59 | 69,931,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,118 | cpp | #include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<ll, ll> P;
#define fi first
#define se second
#define repl(i,a,b) for(ll i=(ll)(a);i<(ll)(b);i++)
#define rep(i,n) repl(i,0,n)
#define each(itr,v) for(auto itr:v)
#define pb push_back
#define all(x) (x).begin(),(x).end()
#define dbg(x) cout<<#x"="<<x<<endl
#define mmax(x,y) (x>y?x:y)
#define mmin(x,y) (x<y?x:y)
#define maxch(x,y) x=mmax(x,y)
#define minch(x,y) x=mmin(x,y)
#define uni(x) x.erase(unique(all(x)),x.end())
#define exist(x,y) (find(all(x),y)!=x.end())
#define bcnt __builtin_popcount
#define INF INT_MAX/3
ll mod = pow(10,9)+7;
ll power(ll x, ll n){
ll tmp = 1;
if ( n > 0 ){
tmp = power(x, n/2)%mod;
if ( n%2 == 0 ) tmp = (tmp*tmp)%mod;
else tmp = (((tmp*tmp)%mod)*x)%mod;
}
return tmp;
}
int main(){
cin.sync_with_stdio(false);
ll w,h;
ll W=1, H=1,WH=1;
cin >> w >> h;
repl(i,1,w){
W*=i;
W %=mod;
}
repl(i,1,h){
H*=i;
H %= mod;
}
repl(i,1,h+w-1){
WH*=i;
WH %= mod;
}
cout << WH*power(W*H%mod,mod-2)%mod << endl;
} | [
"hayabusatoshihumi@gmail.com"
] | hayabusatoshihumi@gmail.com |
c3bbad71867692cc91a89c67afccf23814d81d70 | 2d1622f599876e45fcbd9ffbf592ea05f18cfe95 | /test/hello_test.cpp | 6c4ad3e44bf99c6d10ea0ef5351bc4277dddb014 | [] | no_license | muitimon/cmaketest | 22fa67adfb999f38e0623bef24294740e4500e7a | 5211d78aa93a9674f21d852c311cf6242e636431 | refs/heads/master | 2020-03-29T01:26:03.417053 | 2018-09-19T03:48:42 | 2018-09-19T03:48:42 | 149,388,724 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 176 | cpp | #include "hello.h"
#include "catch.hpp"
TEST_CASE("Hello Test", "[hello]"){
REQUIRE( greetings("kanegae") == "Hello, kanegae");
REQUIRE( greetings("") == "Hello, ");
} | [
"kanegae.yuka.kp1@is.naist.jp"
] | kanegae.yuka.kp1@is.naist.jp |
d22fac3c8fbed65ee3bfeb832de0b4eacc4e0d16 | fabafea14b6ba449e8745875b0ef66062808dbe9 | /Part_5/baxter/simple_baxter_arm_controller/src/simple_jnt_commander.cpp | eb030b07c32b3233bd83e344e8b5f68167a70255 | [] | no_license | wsnewman/learning_ros | fdfb3caac4bf99d53d9079f4f46212eb8b33d2ef | c98c8a02750eb4271bd1568a3c444c36fa984ee1 | refs/heads/noetic_devel | 2022-06-02T15:27:32.280923 | 2022-03-14T14:36:06 | 2022-03-14T14:36:06 | 49,152,692 | 362 | 246 | null | 2022-03-28T14:54:19 | 2016-01-06T18:12:19 | C++ | UTF-8 | C++ | false | false | 1,846 | cpp | #include <ros/ros.h> //Must include this for all ROS cpp projects
#include <ros/init.h>
#include <std_msgs/Float32.h> //Including the Float32 class from std_msgs
#include <baxter_core_msgs/JointCommand.h>
using namespace std;
ros::Publisher joint_cmd_pub_right; //define this publisher global, so fnc cmd_pose_right() can use it
//a simple function to send joint-angle commands to joint controllers using a Baxter message:
void cmd_pose_right(double qvec[]) {
//member var right_cmd_ already has joint names populated; just need to update the joint-angle commands
for (int i = 0; i < 7; i++) {
right_cmd.command[i] = qvec[i];
}
joint_cmd_pub_right.publish(right_cmd); //send result to joint controllers
}
int main(int argc, char** argv) {
ros::init(argc, argv, "rt_arm_pos_commander"); // name this node
ros::NodeHandle nh;
baxter_core_msgs::JointCommand right_cmd;
//point this publisher to Baxter's joint-command topic for right arm
joint_cmd_pub_right = nh.advertise<baxter_core_msgs::JointCommand>("/robot/limb/right/joint_command", 1);
//initialize fields of joint command message:
right_cmd.mode = 1; //specify position control
// define the joint angles 0-6 to be right arm, from shoulder out to wrist;
right_cmd.names.push_back("right_s0");
right_cmd.names.push_back("right_s1");
right_cmd.names.push_back("right_e0");
right_cmd.names.push_back("right_e1");
right_cmd.names.push_back("right_w0");
right_cmd.names.push_back("right_w1");
right_cmd.names.push_back("right_w2");
// do push-backs to establish desired vector size with valid joint angles
for (int i = 0; i < 7; i++) {
right_cmd.command.push_back(0.0); // start commanding 0 angle for right-arm 7 joints
}
//do interesting stuff here:
}
| [
"wsn@case.edu"
] | wsn@case.edu |
5e210aed4cbba09976467f691915a0ee6bd0ea56 | a461e3b0eb02d0eeaabe63c27175bf2991ff993e | /deps/boost/include/boost/spirit/home/qi/detail/permute_function.hpp | b098c030782520de7cff3fb26c7c2b4c568c7171 | [
"CC0-1.0",
"BSD-3-Clause",
"BSL-1.0"
] | permissive | TexelBox/wave-tool | 37999130d40eb45995383ddfc015b942c8096253 | 364d73eb7d83e65d5cfe469b6f923fe49c049684 | refs/heads/master | 2021-01-07T17:45:00.260890 | 2020-09-02T19:51:37 | 2020-09-02T19:51:37 | 241,771,443 | 3 | 2 | BSD-3-Clause | 2020-05-18T15:42:00 | 2020-02-20T02:05:19 | C++ | UTF-8 | C++ | false | false | 2,259 | hpp | /*=============================================================================
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(SPIRIT_PERMUTE_FUNCTION_MARCH_13_2007_1129AM)
#define SPIRIT_PERMUTE_FUNCTION_MARCH_13_2007_1129AM
#if defined(_MSC_VER)
#pragma once
#endif
#include <boost/spirit/home/support/unused.hpp>
#include <boost/optional.hpp>
namespace boost { namespace spirit { namespace qi { namespace detail
{
template <typename Iterator, typename Context, typename Skipper>
struct permute_function
{
permute_function(
Iterator& first_, Iterator const& last_
, Context& context_, Skipper const& skipper_)
: first(first_)
, last(last_)
, context(context_)
, skipper(skipper_)
{
}
template <typename Component, typename Attribute>
bool operator()(Component const& component, Attribute& attr)
{
// return true if the parser succeeds and the slot is not yet taken
if (!*taken && component.parse(first, last, context, skipper, attr))
{
*taken = true;
++taken;
return true;
}
++taken;
return false;
}
template <typename Component>
bool operator()(Component const& component)
{
// return true if the parser succeeds and the slot is not yet taken
if (!*taken && component.parse(first, last, context, skipper, unused))
{
*taken = true;
++taken;
return true;
}
++taken;
return false;
}
Iterator& first;
Iterator const& last;
Context& context;
Skipper const& skipper;
bool* taken;
// silence MSVC warning C4512: assignment operator could not be generated
BOOST_DELETED_FUNCTION(permute_function& operator= (permute_function const&))
};
}}}}
#endif
| [
"aaron.hornby@outlook.com"
] | aaron.hornby@outlook.com |
b4770e2ea5dc3d2fe7834bf9e53902a4fd9bf6ec | e8cec014c373a8599f9ac5d3768d87662528b28e | /meeting-qt/setup/UnInstall/src/base/synchronization/waitable_event_posix.cpp | f639ec58472ada4de28f388071883dde325a4de2 | [
"MIT"
] | permissive | xiaoge136/Meeting | ee69e309666b3132449476217033d34b92eb975d | 0b85c53ee3df6d5611c84dc2b9fe564590874563 | refs/heads/main | 2023-07-21T14:39:03.158711 | 2021-08-31T14:13:18 | 2021-08-31T14:13:18 | 401,727,185 | 0 | 1 | MIT | 2021-08-31T14:10:04 | 2021-08-31T14:10:04 | null | UTF-8 | C++ | false | false | 12,506 | cpp | /**
* @copyright Copyright (c) 2021 NetEase, Inc. All rights reserved.
* Use of this source code is governed by a MIT license that can be found in the LICENSE file.
*/
// Copyright (c) 2011, NetEase Inc. All rights reserved.
// All rights reserved.
//
// Author: Wang Rongtao <rtwang@corp.netease.com>
// Date: 2011/6/24
//
// The base class of a cross flatform waitable event
#include "base/synchronization/waitable_event.h"
#if defined(OS_POSIX)
#include "base/synchronization/condition_variable.h"
#include "base/synchronization/lock.h"
#include "base/framework/message_loop.h"
#include <vector>
// -----------------------------------------------------------------------------
// A WaitableEvent on POSIX is implemented as a wait-list. Currently we don't
// support cross-process events (where one process can signal an event which
// others are waiting on). Because of this, we can avoid having one thread per
// listener in several cases.
//
// The WaitableEvent maintains a list of waiters, protected by a lock. Each
// waiter is either an async wait, in which case we have a Task and the
// MessageLoop to run it on, or a blocking wait, in which case we have the
// condition variable to signal.
//
// Waiting involves grabbing the lock and adding oneself to the wait list. Async
// waits can be canceled, which means grabbing the lock and removing oneself
// from the list.
//
// Waiting on multiple events is handled by adding a single, synchronous wait to
// the wait-list of many events. An event passes a pointer to itself when
// firing a waiter and so we can store that pointer to find out which event
// triggered.
// -----------------------------------------------------------------------------
namespace nbase
{
WaitableEvent::WaitableEvent(bool manual_reset, bool initially_signaled)
: kernel_(new WaitableEventKernel(manual_reset, initially_signaled))
{
}
WaitableEvent::~WaitableEvent()
{
}
void WaitableEvent::Reset()
{
nbase::NAutoLock locked(&kernel_->lock_);
kernel_->signaled_ = false;
}
void WaitableEvent::Signal()
{
nbase::NAutoLock locked(&kernel_->lock_);
if (kernel_->signaled_)
return;
if (kernel_->manual_reset_)
{
SignalAll();
kernel_->signaled_ = true;
}
else
{
// In the case of auto reset, if no waiters were woken, we remain
// signaled.
if (!SignalOne())
kernel_->signaled_ = true;
}
}
bool WaitableEvent::IsSignaled()
{
nbase::NAutoLock locked(&(kernel_->lock_));
const bool result = kernel_->signaled_;
if (result && !kernel_->manual_reset_)
kernel_->signaled_ = false;
return result;
}
// -----------------------------------------------------------------------------
// Synchronous waits
// -----------------------------------------------------------------------------
// This is a synchronous waiter. The thread is waiting on the given condition
// variable and the fired flag in this object.
// -----------------------------------------------------------------------------
class SyncWaiter : public WaitableEvent::Waiter
{
public:
SyncWaiter()
: fired_(false),
signaling_event_(NULL),
lock_(),
cv_(&lock_)
{
}
bool Fire(WaitableEvent* signaling_event)
{
nbase::NAutoLock locked(&lock_);
if (fired_)
return false;
fired_ = true;
signaling_event_ = signaling_event;
cv_.Broadcast();
// Unlike AsyncWaiter objects, SyncWaiter objects are stack-allocated on
// the blocking thread's stack. There is no |delete this;| in Fire. The
// SyncWaiter object is destroyed when it goes out of scope.
return true;
}
WaitableEvent* signaling_event() const
{
return signaling_event_;
}
// ---------------------------------------------------------------------------
// These waiters are always stack allocated and don't delete themselves. Thus
// there's no problem and the ABA tag is the same as the object pointer.
// ---------------------------------------------------------------------------
bool Compare(void* tag)
{
return this == tag;
}
// ---------------------------------------------------------------------------
// Called with lock held.
// ---------------------------------------------------------------------------
bool fired() const
{
return fired_;
}
// ---------------------------------------------------------------------------
// During a TimedWait, we need a way to make sure that an auto-reset
// WaitableEvent doesn't think that this event has been signaled between
// unlocking it and removing it from the wait-list. Called with lock held.
// ---------------------------------------------------------------------------
void Disable()
{
fired_ = true;
}
nbase::NLock* lock()
{
return &lock_;
}
nbase::ConditionVariable* cv()
{
return &cv_;
}
private:
bool fired_;
WaitableEvent* signaling_event_; // The WaitableEvent which woke us
nbase::NLock lock_;
nbase::ConditionVariable cv_;
};
bool WaitableEvent::Wait()
{
return WaitTimeout(TimeDelta::FromSeconds(-1));
}
bool WaitableEvent::WaitTimeout(const TimeDelta& timeout)
{
const Time end_time(Time::Now() + timeout);
const bool finite_time = timeout.ToInternalValue() >= 0;
kernel_->lock_.Lock();
if (kernel_->signaled_)
{
if (!kernel_->manual_reset_)
{
// In this case we were signaled when we had no waiters. Now that
// someone has waited upon us, we can automatically reset.
kernel_->signaled_ = false;
}
kernel_->lock_.Unlock();
return true;
}
SyncWaiter sw;
sw.lock()->Lock();
Enqueue(&sw);
kernel_->lock_.Unlock();
// We are violating locking order here by holding the SyncWaiter lock but not
// the WaitableEvent lock. However, this is safe because we don't lock @lock_
// again before unlocking it.
for (;;)
{
const Time current_time(Time::Now());
if (sw.fired() || (finite_time && current_time >= end_time))
{
const bool return_value = sw.fired();
// We can't acquire @lock_ before releasing the SyncWaiter lock (because
// of locking order), however, in between the two a signal could be fired
// and @sw would accept it, however we will still return false, so the
// signal would be lost on an auto-reset WaitableEvent. Thus we call
// Disable which makes sw::Fire return false.
sw.Disable();
sw.lock()->Unlock();
kernel_->lock_.Lock();
kernel_->Dequeue(&sw, &sw);
kernel_->lock_.Unlock();
return return_value;
}
if (finite_time)
{
const TimeDelta max_wait(end_time - current_time);
sw.cv()->TimedWait(max_wait);
}
else
{
sw.cv()->Wait();
}
}
}
static bool cmp_fst_addr(const std::pair<WaitableEvent*,
unsigned> &a,
const std::pair<WaitableEvent*,
unsigned> &b)
{
return a.first < b.first;
}
// static
size_t WaitableEvent::WaitMultiple(WaitableEvent **events, size_t count)
{
assert(count > 0);
// We need to acquire the locks in a globally consistent order. Thus we sort
// the array of waitables by address. We actually sort a pairs so that we can
// map back to the original index values later.
std::vector<std::pair<WaitableEvent*, size_t> > waitables;
waitables.reserve(count);
for (size_t i = 0; i < count; ++i)
waitables.push_back(std::make_pair(events[i], i));
assert(count == waitables.size());
sort(waitables.begin(), waitables.end(), cmp_fst_addr);
// The set of waitables must be distinct. Since we have just sorted by
// address, we can check this cheaply by comparing pairs of consecutive
// elements.
for (size_t i = 0; i < waitables.size() - 1; ++i)
{
assert(waitables[i].first != waitables[i+1].first);
}
SyncWaiter sw;
const size_t r = EnqueueMultiple(&waitables[0], count, &sw);
if (r) {
// One of the events is already signaled. The SyncWaiter has not been
// enqueued anywhere. EnqueueMany returns the count of remaining waitables
// when the signaled one was seen, so the index of the signaled event is
// @count - @r.
return waitables[count - r].second;
}
// At this point, we hold the locks on all the WaitableEvents and we have
// enqueued our waiter in them all.
sw.lock()->Lock();
// Release the WaitableEvent locks in the reverse order
for (size_t i = 0; i < count; ++i)
{
waitables[count - (1 + i)].first->kernel_->lock_.Unlock();
}
for (;;)
{
if (sw.fired())
break;
sw.cv()->Wait();
}
sw.lock()->Unlock();
// The address of the WaitableEvent which fired is stored in the SyncWaiter.
WaitableEvent *const signaled_event = sw.signaling_event();
// This will store the index of the raw_waitables which fired.
size_t signaled_index = 0;
// Take the locks of each WaitableEvent in turn (except the signaled one) and
// remove our SyncWaiter from the wait-list
for (size_t i = 0; i < count; ++i)
{
if (events[i] != signaled_event)
{
events[i]->kernel_->lock_.Lock();
// There's no possible ABA issue with the address of the SyncWaiter here
// because it lives on the stack. Thus the tag value is just the pointer
// value again.
events[i]->kernel_->Dequeue(&sw, &sw);
events[i]->kernel_->lock_.Unlock();
}
else
{
signaled_index = i;
}
}
return signaled_index;
}
// -----------------------------------------------------------------------------
// If return value == 0:
// The locks of the WaitableEvents have been taken in order and the Waiter has
// been enqueued in the wait-list of each. None of the WaitableEvents are
// currently signaled
// else:
// None of the WaitableEvent locks are held. The Waiter has not been enqueued
// in any of them and the return value is the index of the first WaitableEvent
// which was signaled, from the end of the array.
// -----------------------------------------------------------------------------
// static
size_t WaitableEvent::EnqueueMultiple(std::pair<WaitableEvent*, size_t> *waitables,
size_t count,
Waiter *waiter)
{
if (!count)
return 0;
waitables[0].first->kernel_->lock_.Lock();
if (waitables[0].first->kernel_->signaled_) {
if (!waitables[0].first->kernel_->manual_reset_)
waitables[0].first->kernel_->signaled_ = false;
waitables[0].first->kernel_->lock_.Unlock();
return count;
}
const size_t r = EnqueueMultiple(waitables + 1, count - 1, waiter);
if (r)
{
waitables[0].first->kernel_->lock_.Unlock();
}
else
{
waitables[0].first->Enqueue(waiter);
}
return r;
}
WaitableEvent::WaitableEventKernel::WaitableEventKernel(bool manual_reset, bool initially_signaled)
: manual_reset_(manual_reset),
signaled_(initially_signaled)
{
}
WaitableEvent::WaitableEventKernel::~WaitableEventKernel()
{
}
// -----------------------------------------------------------------------------
// Wake all waiting waiters. Called with lock held.
// -----------------------------------------------------------------------------
bool WaitableEvent::SignalAll()
{
bool signaled_at_least_one = false;
for (std::list<Waiter*>::iterator
i = kernel_->waiters_.begin(); i != kernel_->waiters_.end(); ++i)
{
if ((*i)->Fire(this))
signaled_at_least_one = true;
}
kernel_->waiters_.clear();
return signaled_at_least_one;
}
// ---------------------------------------------------------------------------
// Try to wake a single waiter. Return true if one was woken. Called with lock
// held.
// ---------------------------------------------------------------------------
bool WaitableEvent::SignalOne()
{
for (;;)
{
if (kernel_->waiters_.empty())
return false;
const bool r = (*kernel_->waiters_.begin())->Fire(this);
kernel_->waiters_.pop_front();
if (r)
return true;
}
}
// -----------------------------------------------------------------------------
// Add a waiter to the list of those waiting. Called with lock held.
// -----------------------------------------------------------------------------
void WaitableEvent::Enqueue(Waiter* waiter)
{
kernel_->waiters_.push_back(waiter);
}
// -----------------------------------------------------------------------------
// Remove a waiter from the list of those waiting. Return true if the waiter was
// actually removed. Called with lock held.
// -----------------------------------------------------------------------------
bool WaitableEvent::WaitableEventKernel::Dequeue(Waiter *waiter, void *tag)
{
for (std::list<Waiter*>::iterator
i = waiters_.begin(); i != waiters_.end(); ++i)
{
if (*i == waiter && (*i)->Compare(tag))
{
waiters_.erase(i);
return true;
}
}
return false;
}
}
#endif // OS_POSIX
| [
"wangjianzhong@corp.netease.com"
] | wangjianzhong@corp.netease.com |
9530a9f9b0f609ea36b74b4660b51b9cae7bccb6 | 14d8e5d65f3a7352cc485fb74d4560df71671fd7 | /sjasm/errors.h | 78bd75f55c77619e0ffb081b277a5f4b5626965f | [] | no_license | KimWI/sjasmplus-1 | 2abdace8b2297557601d8021844d86f849d03b70 | 097e5fb57b7482c0cd28b25e5f7ad2b592e9f9cb | refs/heads/master | 2020-04-02T20:20:52.851839 | 2018-08-22T00:48:26 | 2018-08-22T00:48:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 921 | h | //
// Error handling
//
#ifndef SJASMPLUS_ERRORS_H
#define SJASMPLUS_ERRORS_H
#include <string>
#include <iostream>
#include <stack>
using namespace std::string_literals;
using std::cout;
using std::cerr;
using std::endl;
using std::flush;
using std::stack;
extern std::string ErrorStr;
extern int PreviousErrorLine;
extern int WarningCount;
enum EStatus {
ALL, PASS1, PASS2, PASS3, FATAL, CATCHALL, SUPPRESS
};
enum EReturn {
END, ELSE, ENDIF, ENDTEXTAREA, ENDM
};
void Error(const char *, const char *, int = PASS2);
void Error(const std::string &fout, const std::string &bd, int type = PASS2);
[[noreturn]] void Fatal(const std::string &errstr);
void Warning(const char *, const char *, int = PASS2);
void Warning(const std::string &fout, const std::string &bd, int type = PASS2);
// output
#define _COUT cout <<
#define _CMDL <<
#define _ENDL << endl
#define _END ;
#endif //SJASMPLUS_ERRORS_H
| [
"koloberdin@gmail.com"
] | koloberdin@gmail.com |
38f45b3524c81f465503c523750b7a3ac142ba4f | 20ee8c5562f7ce1c1a48408ffc4244c77f2343d1 | /.idea/ls.h | 93b45c799754f718134edbccfc5c3fae2d6717f7 | [] | no_license | OlyaBakay/shell_1 | ea9044a4bfd090d44eb62dd520214208e9134bc0 | 405a93babf83de1c71025038150711163e65b73b | refs/heads/master | 2021-01-18T20:04:23.044434 | 2017-04-01T22:02:52 | 2017-04-01T22:02:52 | 86,934,006 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,653 | h | //
// Created by arsen on 16.03.17.
//
#include <iostream>
#include <iterator>
#include <vector>
#include <algorithm>
#include <boost/filesystem.hpp>
using namespace std;
using namespace boost::filesystem;
int ls_func(boost::filesystem::path argv)
{
path p (argv); // p reads clearer than argv[1] in the following code
try
{
if (exists(p)) // does p actually exist?
{
if (is_regular_file(p)) // is p a regular file?
cout << p << " size is " << file_size(p) << '\n';
else if (is_directory(p)) // is p a directory?
{
cout << p << " is a directory containing:\n";
typedef vector<path> vec; // store paths,
vec v; // so we can sort them later
copy(directory_iterator(p), directory_iterator(), back_inserter(v));
sort(v.begin(), v.end()); // sort, since directory iteration
// is not ordered on some file systems
for (vec::const_iterator it(v.begin()), it_end(v.end()); it != it_end; ++it)
{
path fn = it->filename();// extract the filename from the path
cout << fn << "\n";
v.push_back(fn);
}
}
else
cout << p << " exists, but is neither a regular file nor a directory\n";
}
else
cout << p << " does not exist\n";
}
catch (const filesystem_error& ex)
{
cout << ex.what() << '\n';
}
return 0;
} | [
"olhabak@gmail.com"
] | olhabak@gmail.com |
32f9d0dc1932e14f16d2389b49634c723ddc8b60 | 6b550d3d0b182bcddda1f0a175d6b6cd07b60fb3 | /logdevice/common/test/DigestTest.cpp | 167419e06022697399ada0058913cabbc16300d6 | [
"BSD-3-Clause"
] | permissive | Rachelmorrell/LogDevice | 5bd04f7ab0bdf9cc6e5b2da4a4b51210cdc9a4c8 | 3a8d800033fada47d878b64533afdf41dc79e057 | refs/heads/master | 2021-06-24T09:10:20.240011 | 2020-04-21T14:10:52 | 2020-04-21T14:13:09 | 157,563,026 | 1 | 0 | NOASSERTION | 2020-04-21T19:20:55 | 2018-11-14T14:43:33 | C++ | UTF-8 | C++ | false | false | 30,011 | cpp | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/Digest.h"
#include <memory>
#include <folly/Memory.h>
#include <gtest/gtest.h>
#include "logdevice/common/protocol/RECORD_Message.h"
#include "logdevice/common/test/DigestTestUtil.h"
#include "logdevice/common/test/NodeSetTestUtil.h"
#include "logdevice/include/Record.h"
using namespace facebook::logdevice;
using namespace facebook::logdevice::NodeSetTestUtil;
namespace {
using RecordType = DigestTestUtil::RecordType;
// Convenient shortcuts for writing ShardIDs.
#define N0 ShardID(0, 0)
#define N1 ShardID(1, 0)
#define N2 ShardID(2, 0)
#define N3 ShardID(3, 0)
#define N4 ShardID(4, 0)
#define N5 ShardID(5, 0)
#define N6 ShardID(6, 0)
#define N7 ShardID(7, 0)
#define N8 ShardID(8, 0)
#define N9 ShardID(9, 0)
#define N10 ShardID(10, 0)
constexpr epoch_t TEST_EPOCH(42);
constexpr logid_t TEST_LOG(2);
std::unique_ptr<DataRecordOwnsPayload> create_record(
esn_t esn,
RecordType type,
uint32_t wave_or_seal_epoch,
std::chrono::milliseconds timestamp = std::chrono::milliseconds(0),
size_t payload_size = 128,
OffsetMap offsets_within_epoch = OffsetMap(),
OffsetMap offsets = OffsetMap()) {
return DigestTestUtil::create_record(TEST_LOG,
DigestTestUtil::lsn(TEST_EPOCH, esn),
type,
wave_or_seal_epoch,
timestamp,
payload_size,
std::move(offsets_within_epoch),
std::move(offsets));
}
class DigestTest : public ::testing::Test {
public:
void SetUp() override {
dbg::assertOnData = true;
// initialize the cluster config
Configuration::Nodes nodes;
addNodes(&nodes, 1, 1, "rg1.dc0.cl0.ro0.rk0", 1); // 0
addNodes(&nodes, 4, 1, "rg1.dc0.cl0.ro0.rk1", 2); // 1-4
addNodes(&nodes, 2, 1, "rg1.dc0.cl0..", 1); // 5-6
addNodes(&nodes, 2, 1, "rg2.dc0.cl0.ro0.rk1", 1); // 7-8
addNodes(&nodes, 2, 1, "....", 1); // 9-10
Configuration::NodesConfig nodes_config(std::move(nodes));
config_ =
ServerConfig::fromDataTest("digest_test", std::move(nodes_config));
}
void setUp() {
ld_check(config_ != nullptr);
digest_ = std::make_unique<Digest>(
TEST_LOG,
TEST_EPOCH,
EpochMetaData(nodeset_, replication_),
seal_epoch_,
config_->getNodesConfigurationFromServerConfigSource(),
Digest::Options({bridge_for_empty_epoch_}));
}
public:
const logid_t TEST_LOG{2};
std::shared_ptr<ServerConfig> config_;
StorageSet nodeset_{N0, N1, N2, N3};
ReplicationProperty replication_{{NodeLocationScope::NODE, 3}};
epoch_t seal_epoch_{50};
esn_t lng_ = ESN_INVALID;
esn_t tail_ = ESN_INVALID;
bool bridge_for_empty_epoch_ = false;
std::unique_ptr<Digest> digest_;
// check mutation result
bool needs_mutation_;
std::set<ShardID> successfully_stored_;
std::set<ShardID> amend_metadata_;
std::set<ShardID> conflict_copies_;
void onRecord(ShardID shard,
esn_t::raw_type esn,
RecordType type,
uint32_t wave_or_seal_epoch,
size_t payload_size = 128.,
OffsetMap offsets = OffsetMap()) {
ASSERT_NE(nullptr, digest_);
digest_->onRecord(shard,
create_record(esn_t(esn),
type,
wave_or_seal_epoch,
std::chrono::milliseconds(0),
payload_size,
std::move(offsets)));
}
void checkMutation(Digest::Entry& entry, bool complete_digest = false) {
successfully_stored_.clear();
amend_metadata_.clear();
conflict_copies_.clear();
ASSERT_NE(nullptr, digest_);
needs_mutation_ = digest_->needsMutation(entry,
&successfully_stored_,
&amend_metadata_,
&conflict_copies_,
complete_digest);
}
esn_t applyBridgeRecords() {
return digest_->applyBridgeRecords(lng_, &tail_);
}
};
#define ASSERT_RESULT_SET(_set_, ...) \
do { \
ASSERT_EQ(std::set<ShardID>({__VA_ARGS__}), (_set_)); \
} while (0)
#define ASSERT_SUCCESS_SET(...) \
ASSERT_RESULT_SET(successfully_stored_, __VA_ARGS__);
#define ASSERT_AMEND_SET(...) ASSERT_RESULT_SET(amend_metadata_, __VA_ARGS__);
#define ASSERT_CONFLICT_SET(...) \
ASSERT_RESULT_SET(conflict_copies_, __VA_ARGS__);
#define ASSERT_RECORD(_entry_, _rtype_, _wave_) \
do { \
ASSERT_NE(nullptr, (_entry_).record); \
ASSERT_NE(nullptr, (_entry_).record->extra_metadata_); \
ASSERT_EQ(_wave_, (_entry_).record->extra_metadata_->header.wave); \
auto flags = (_entry_).record->flags_; \
switch (_rtype_) { \
case RecordType::NORMAL: \
ASSERT_FALSE(flags& RECORD_Header::WRITTEN_BY_RECOVERY); \
ASSERT_FALSE(flags& RECORD_Header::HOLE); \
ASSERT_TRUE((_entry_).getPayload().size() > 0); \
break; \
case RecordType::MUTATED: \
ASSERT_TRUE(flags& RECORD_Header::WRITTEN_BY_RECOVERY); \
ASSERT_FALSE(flags& RECORD_Header::HOLE); \
ASSERT_TRUE((_entry_).getPayload().size() > 0); \
break; \
case RecordType::HOLE: \
ASSERT_TRUE(flags& RECORD_Header::WRITTEN_BY_RECOVERY); \
ASSERT_TRUE(flags& RECORD_Header::HOLE); \
ASSERT_TRUE((_entry_).isHolePlug()); \
break; \
case RecordType::BRIDGE: \
ASSERT_TRUE(flags& RECORD_Header::WRITTEN_BY_RECOVERY); \
ASSERT_TRUE(flags& RECORD_Header::HOLE); \
ASSERT_TRUE(flags& RECORD_Header::BRIDGE); \
ASSERT_TRUE((_entry_).isHolePlug()); \
break; \
} \
} while (0)
TEST_F(DigestTest, Basic) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
setUp();
// enough copies for esn 1, but records not written by recovery
onRecord(N0, /*esn=*/1, RecordType::NORMAL, /*wave=*/1);
onRecord(N2, 1, RecordType::NORMAL, 4);
onRecord(N3, 1, RecordType::NORMAL, 3);
// not enough copies for esn 2
onRecord(N1, 2, RecordType::NORMAL, 1);
// same thing for esn 3, but with two holes, one hole written by this recovery
// instance
onRecord(N1, 3, RecordType::HOLE, 45);
onRecord(N3, 3, RecordType::HOLE, seal_epoch_.val_);
// esn 4, hole/copy conflict
onRecord(N0, 4, RecordType::NORMAL, 99);
onRecord(N1, 4, RecordType::HOLE, 27);
onRecord(N2, 4, RecordType::MUTATED, 49);
onRecord(N3, 4, RecordType::HOLE, 45);
// esn 5, no mutation needed
onRecord(N0, 5, RecordType::MUTATED, seal_epoch_.val_);
onRecord(N1, 5, RecordType::MUTATED, seal_epoch_.val_);
onRecord(N2, 5, RecordType::MUTATED, seal_epoch_.val_);
size_t nentries = 0;
for (auto& it : *digest_) {
Digest::Entry& entry = it.second;
switch (it.first.val_) {
case 1:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N2, N3);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
// 4 is the largest wave received
ASSERT_RECORD(entry, RecordType::NORMAL, 4);
checkMutation(entry, /*complete_digest*/ true);
ASSERT_TRUE(needs_mutation_);
break;
case 2:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N1);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::NORMAL, 1);
break;
case 3:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N1);
ASSERT_SUCCESS_SET(N3);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::HOLE, seal_epoch_.val_);
break;
case 4:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N2);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N1, N3);
ASSERT_RECORD(entry, RecordType::MUTATED, 49);
break;
case 5:
checkMutation(entry);
ASSERT_FALSE(needs_mutation_);
ASSERT_AMEND_SET();
ASSERT_SUCCESS_SET(N0, N1, N2);
ASSERT_CONFLICT_SET();
// 4 is the largest wave received
ASSERT_RECORD(entry, RecordType::MUTATED, seal_epoch_.val_);
break;
default:
break;
}
++nentries;
}
EXPECT_EQ(5, nentries);
}
// in this test, our primary focus is on the failure doamin properties,
// so all digested records are written by recovery and with their seal epoch
// the same as the seal epoch of the digest
TEST_F(DigestTest, FailureDomainBasic) {
nodeset_ = {N0, N1, N2, N3, N4, N5, N6, N7, N8, N9, N10};
replication_.assign(
{{NodeLocationScope::NODE, 3}, {NodeLocationScope::RACK, 2}});
{
setUp();
// 1-4 are on the same rack
onRecord(N1, 1, RecordType::MUTATED, seal_epoch_.val_);
onRecord(N2, 1, RecordType::MUTATED, seal_epoch_.val_);
auto& entry = digest_->begin()->second;
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
onRecord(N3, 1, RecordType::MUTATED, seal_epoch_.val_);
onRecord(N4, 1, RecordType::MUTATED, seal_epoch_.val_);
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
onRecord(N5, 1, RecordType::MUTATED, seal_epoch_.val_);
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
onRecord(N9, 1, RecordType::MUTATED, seal_epoch_.val_);
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
// 7 is from a different rack, at this time digest does not need
// mutation
onRecord(N7, 1, RecordType::MUTATED, seal_epoch_.val_);
checkMutation(entry);
ASSERT_FALSE(needs_mutation_);
// receive a hole from another node, mutation is needed again
onRecord(N10, 1, RecordType::HOLE, 40);
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
}
{
// start a new digest
setUp();
// receive two hole plugs on two racks
onRecord(N1, 1, RecordType::HOLE, seal_epoch_.val_);
onRecord(N7, 1, RecordType::HOLE, seal_epoch_.val_);
auto& entry = digest_->begin()->second;
// mutation is still needed since replication factor is 3
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
// receive another hole plugs from a node that does not specify
// its rack
onRecord(N10, 1, RecordType::HOLE, seal_epoch_.val_);
// the plug is fully repliated, no need for muatation
checkMutation(entry);
ASSERT_FALSE(needs_mutation_);
}
}
TEST_F(DigestTest, CompleteDigest) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
setUp();
// enough copies for esn 1 with the same wave
onRecord(N0, /*esn=*/1, RecordType::NORMAL, /*wave=*/1);
onRecord(N2, 1, RecordType::NORMAL, 1);
onRecord(N3, 1, RecordType::NORMAL, 1);
// enough copies, written by different recovery instance
onRecord(N0, 2, RecordType::HOLE, 2);
onRecord(N1, 2, RecordType::HOLE, 2);
onRecord(N2, 2, RecordType::HOLE, 3);
// enough copies (N0, N1, N2) written by sequencer with same wave, but one
// copy (N3) with different wave
onRecord(N0, 3, RecordType::NORMAL, 3);
onRecord(N1, 3, RecordType::NORMAL, 3);
onRecord(N2, 3, RecordType::NORMAL, 3);
onRecord(N3, 3, RecordType::NORMAL, 1);
// enough copies written by the same recovery instance, but one other copy
// but still no conflict
onRecord(N0, 4, RecordType::MUTATED, 7);
onRecord(N1, 4, RecordType::MUTATED, 8);
onRecord(N2, 4, RecordType::MUTATED, 8);
onRecord(N3, 4, RecordType::MUTATED, 8);
// same case as above but has a conflict
onRecord(N0, 5, RecordType::HOLE, 1);
onRecord(N1, 5, RecordType::MUTATED, 8);
onRecord(N2, 5, RecordType::MUTATED, 8);
onRecord(N3, 5, RecordType::MUTATED, 8);
size_t nentries = 0;
for (auto& it : *digest_) {
Digest::Entry& entry = it.second;
switch (it.first.val_) {
case 1:
checkMutation(entry, /*complete_digest*/ true);
ASSERT_FALSE(needs_mutation_);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::NORMAL, 1);
checkMutation(entry, /*complete_digest*/ false);
ASSERT_TRUE(needs_mutation_);
break;
case 2:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N1, N2);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::HOLE, 3);
break;
case 3:
checkMutation(entry, true);
ASSERT_FALSE(needs_mutation_);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::NORMAL, 3);
checkMutation(entry, /*complete_digest*/ false);
ASSERT_TRUE(needs_mutation_);
break;
case 4:
checkMutation(entry, true);
ASSERT_FALSE(needs_mutation_);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::MUTATED, 8);
checkMutation(entry, /*complete_digest*/ false);
ASSERT_TRUE(needs_mutation_);
break;
case 5:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N1, N2, N3);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N0);
ASSERT_RECORD(entry, RecordType::MUTATED, 8);
break;
default:
break;
}
++nentries;
}
EXPECT_EQ(5, nentries);
}
// test the case that epoch recovery filters out mutation set from the
// set of nodes finished digesting
TEST_F(DigestTest, FilterDigest) {
nodeset_ = {N0, N1, N2, N3, N4, N5};
replication_.assign({{NodeLocationScope::NODE, 3}});
seal_epoch_ = epoch_t(50);
setUp();
// esn 1, only one copy from N0
onRecord(N0, /*esn=*/1, RecordType::NORMAL, /*wave=*/1);
// esn 2, one copy from N0, N2, one hole from N1;
// copy from N0 has precedence
onRecord(N0, 2, RecordType::MUTATED, 7);
onRecord(N1, 2, RecordType::HOLE, 5);
onRecord(N2, 2, RecordType::NORMAL, 28);
// remove N0 from the digest
digest_->removeNode(N0);
// target result should use copies from N0 even if it is removed
size_t nentries = 0;
for (auto& it : *digest_) {
Digest::Entry& entry = it.second;
switch (it.first.val_) {
case 1:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::NORMAL, 1);
break;
case 2:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N2);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N1);
ASSERT_RECORD(entry, RecordType::MUTATED, 7);
break;
default:
break;
}
++nentries;
}
EXPECT_EQ(2, nentries);
}
TEST_F(DigestTest, BridgeRecordBasic) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = esn_t(1);
setUp();
onRecord(N0, /*esn=*/2, RecordType::NORMAL, /*wave=*/1);
// apply and compute the new bridge ESN
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(esn_t(3), bridge_esn);
ASSERT_EQ(esn_t(2), tail_);
}
TEST_F(DigestTest, BridgeRecordBasic2) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = esn_t(1);
setUp();
onRecord(N0, /*esn=*/2, RecordType::NORMAL, /*wave=*/1);
onRecord(N1, /*esn=*/3, RecordType::HOLE, /*wave=*/2);
onRecord(N2, /*esn=*/4, RecordType::BRIDGE, /*wave=*/3);
// apply and compute the new bridge ESN
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(esn_t(3), bridge_esn);
ASSERT_EQ(esn_t(2), tail_);
}
// x_w: normal record, x(s) mutated record, o: hole, b: bridge
//
// 2 3 4 5 6
// N0 b(2)
// N1 x_3 b(7)
// N2 x(9)
// N3 x(4) o(3) x(6)
TEST_F(DigestTest, BridgeRecord) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = esn_t(1);
setUp();
onRecord(N0, /*esn=*/2, RecordType::BRIDGE, /*wave=*/2);
onRecord(N1, 2, RecordType::NORMAL, 3);
onRecord(N1, 3, RecordType::BRIDGE, 7);
onRecord(N3, 3, RecordType::MUTATED, 4);
onRecord(N2, 5, RecordType::MUTATED, 9);
onRecord(N3, 5, RecordType::HOLE, 3);
onRecord(N3, 6, RecordType::MUTATED, 6);
// apply and compute the new bridge ESN
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(esn_t(6), bridge_esn);
ASSERT_EQ(esn_t(5), tail_);
size_t nentries = 0;
for (auto& it : *digest_) {
Digest::Entry& entry = it.second;
switch (it.first.val_) {
case 2:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N1);
ASSERT_RECORD(entry, RecordType::HOLE, 2);
break;
case 3:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_SUCCESS_SET();
ASSERT_AMEND_SET(N1);
ASSERT_CONFLICT_SET(N3);
// the original bridge becomes a hole instead
ASSERT_RECORD(entry, RecordType::HOLE, 7);
break;
case 5:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_SUCCESS_SET();
ASSERT_AMEND_SET(N2);
// only N3 needs to fix the conflict! N0 and N1 has a
// implicit hole because of the bridge but should not need
// any real fix
ASSERT_CONFLICT_SET(N3);
ASSERT_RECORD(entry, RecordType::MUTATED, 9);
break;
case 6:
checkMutation(entry, true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET();
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N3);
// this should be the new bridge record
ASSERT_RECORD(entry, RecordType::BRIDGE, 7);
break;
default:
FAIL();
break;
}
++nentries;
}
EXPECT_EQ(4, nentries);
}
// Test a scenario where the digest does not contain *any* record for a
// particular esn. This is considered a hole and hence all stream reacords that
// occur after this must be marked as a hole.
TEST_F(DigestTest, WriteStreamRecoveryWithHole) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(2);
lng_ = esn_t(1);
setUp();
onRecord(N0, 2, RecordType::NORMAL, 2);
onRecord(N1, 2, RecordType::NORMAL, 3);
onRecord(N1, 3, RecordType::WRITE_STREAM, 7);
onRecord(N3, 3, RecordType::WRITE_STREAM, 4);
onRecord(N1, 4, RecordType::WRITE_STREAM, 6);
onRecord(N2, 4, RecordType::WRITE_STREAM, 7);
onRecord(N1, 6, RecordType::WRITE_STREAM, 6);
onRecord(N3, 6, RecordType::WRITE_STREAM, 6);
onRecord(N1, 8, RecordType::NORMAL, 6);
onRecord(N3, 8, RecordType::NORMAL, 9);
digest_->applyWriteStreamHoles(lng_);
for (auto& it : *digest_) {
auto& entry = it.second;
switch (it.first.val_) {
case 2:
case 3:
case 4:
case 8:
ASSERT_FALSE(entry.isHolePlug());
break;
case 6:
ASSERT_TRUE(entry.isHolePlug());
break;
default:
ADD_FAILURE();
}
}
}
// Test a scenario in which digest contains two records both stored by recovery,
// one is a stream record, other a hole. However, since the hole has a higher
// seal number it prevails. Overall it is declared a hole. Even in this case,
// stream records that follow the hole must be replaced with holes.
TEST_F(DigestTest, WriteStreamRecoveryWithHolePlug) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(2);
lng_ = esn_t(1);
setUp();
onRecord(N0, 2, RecordType::NORMAL, 2);
onRecord(N1, 2, RecordType::NORMAL, 3);
onRecord(N1, 3, RecordType::WRITE_STREAM, 7);
onRecord(N3, 3, RecordType::WRITE_STREAM, 4);
onRecord(N1, 4, RecordType::WRITE_STREAM, 6);
onRecord(N2, 4, RecordType::HOLE, 7);
onRecord(N1, 5, RecordType::WRITE_STREAM, 6);
onRecord(N3, 5, RecordType::WRITE_STREAM, 6);
onRecord(N1, 8, RecordType::NORMAL, 6);
onRecord(N3, 8, RecordType::NORMAL, 9);
digest_->applyWriteStreamHoles(lng_);
for (auto& it : *digest_) {
auto& entry = it.second;
switch (it.first.val_) {
case 2:
case 3:
case 8:
ASSERT_FALSE(entry.isHolePlug());
break;
case 4:
case 5:
ASSERT_TRUE(entry.isHolePlug());
break;
default:
ADD_FAILURE();
}
}
}
// Test a scenario in which a hole stored by a smaller epoch recovery is
// resolved by a higher epoch write stream record and hence we declare that to
// be not a hole. In this case, any stream record that occurs later in the
// continuous prefix must be left as is.
TEST_F(DigestTest, WriteStreamRecoveryWithResolvedHole) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(2);
lng_ = esn_t(1);
setUp();
onRecord(N0, 2, RecordType::NORMAL, 2);
onRecord(N1, 2, RecordType::NORMAL, 3);
onRecord(N1, 3, RecordType::WRITE_STREAM, 7);
onRecord(N3, 3, RecordType::WRITE_STREAM, 4);
onRecord(N1, 4, RecordType::WRITE_STREAM, 8);
onRecord(N2, 4, RecordType::HOLE, 6);
onRecord(N1, 5, RecordType::WRITE_STREAM, 6);
onRecord(N3, 5, RecordType::WRITE_STREAM, 6);
onRecord(N1, 6, RecordType::NORMAL, 6);
onRecord(N3, 6, RecordType::NORMAL, 9);
digest_->applyWriteStreamHoles(lng_);
for (auto& it : *digest_) {
auto& entry = it.second;
ASSERT_FALSE(entry.isHolePlug());
}
}
// do not plug bridge record for empty epoch
TEST_F(DigestTest, BridgeRecordEmptyEpoch1) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = ESN_INVALID;
bridge_for_empty_epoch_ = false;
setUp();
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(ESN_INVALID, bridge_esn);
ASSERT_EQ(ESN_INVALID, tail_);
}
TEST_F(DigestTest, BridgeRecordEmptyEpoch2) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = ESN_INVALID;
bridge_for_empty_epoch_ = true;
setUp();
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(0, digest_->size());
ASSERT_AMEND_SET();
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
ASSERT_EQ(ESN_MIN, bridge_esn);
ASSERT_EQ(ESN_INVALID, tail_);
}
// plug bridge for another case of empty epoch
// x_w: normal record, x(s) mutated record, o: hole, b: bridge
// 1 2
// N0 b(6) x(1)
// N1 o(2)
// N2
// N3 o(9)
TEST_F(DigestTest, BridgeRecordEmptyEpoch3) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = ESN_INVALID;
bridge_for_empty_epoch_ = true;
setUp();
onRecord(N0, /*esn=*/1, RecordType::BRIDGE, /*wave_or_recovery_epoch=*/6);
onRecord(N0, 2, RecordType::MUTATED, 1);
onRecord(N1, 1, RecordType::HOLE, 2);
onRecord(N3, 3, RecordType::HOLE, 9);
esn_t bridge_esn = applyBridgeRecords();
auto* entry = const_cast<Digest::Entry*>(digest_->findEntry(ESN_MIN));
ASSERT_NE(nullptr, entry);
checkMutation((*entry), true);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N1);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
ASSERT_RECORD(*entry, RecordType::BRIDGE, 6);
ASSERT_EQ(ESN_MIN, bridge_esn);
ASSERT_EQ(ESN_INVALID, tail_);
}
// plug bridge record at LNG + 1 for non-empty epochs
TEST_F(DigestTest, BridgeRecordNonEmptyEpochEmptyDigest) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
lng_ = esn_t(2333);
setUp();
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(esn_t(lng_.val_ + 1), bridge_esn);
ASSERT_EQ(lng_, tail_);
}
// do not plug bridge record if the last record is ESN_MAX
TEST_F(DigestTest, BridgeRecordESNMAX) {
nodeset_ = {N0, N1, N2, N3};
lng_ = esn_t(ESN_MAX.val_ - 1024);
setUp();
onRecord(N0, /*esn=*/ESN_MAX.val_, RecordType::NORMAL, /*wave=*/1);
esn_t bridge_esn = applyBridgeRecords();
ASSERT_EQ(ESN_INVALID, bridge_esn);
ASSERT_EQ(ESN_MAX, tail_);
}
TEST_F(DigestTest, recomputeOffsetWithinEpoch) {
nodeset_ = {N0, N1, N2, N3};
seal_epoch_ = epoch_t(50);
setUp();
digest_->setDigestStartEsn(esn_t(1));
size_t payload_size = 128;
OffsetMap payload_size_map({{BYTE_OFFSET, payload_size}});
// enough copies for esn 1, but records not written by recovery
onRecord(N0,
/*esn=*/1,
RecordType::NORMAL,
/*wave=*/1,
payload_size,
/*offsets*/ payload_size_map);
onRecord(N2, 1, RecordType::NORMAL, 4, payload_size, payload_size_map);
onRecord(N3, 1, RecordType::NORMAL, 3, payload_size, payload_size_map);
onRecord(N0,
2,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 2);
onRecord(N2,
2,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 2);
onRecord(N3,
2,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 2);
// number for the recovery epoch, just used for creating tailRecord
lng_ = esn_t(2);
// record after lng_ or tail_record may have the wrong byteoffset number
// same thing for esn 3, but with two holes, one hole written by this recovery
// instance
// byteoffset should be payload_size * 2
onRecord(N1, 3, RecordType::HOLE, 45, payload_size, payload_size_map * 2);
onRecord(N3,
3,
RecordType::HOLE,
seal_epoch_.val_,
payload_size,
payload_size_map * 2);
// esn 4, hole/copy conflict
// byteoffset should be payload_size * 3
onRecord(N0, 4, RecordType::NORMAL, 99, payload_size, payload_size_map * 4);
onRecord(N1, 4, RecordType::HOLE, 27, payload_size, payload_size_map * 3);
onRecord(N2, 4, RecordType::MUTATED, 49, payload_size, payload_size_map * 3);
onRecord(N3, 4, RecordType::HOLE, 45, payload_size, payload_size_map * 3);
// esn 5,
// byteoffset should be payload_size * 4
// since we changed byteoffset of 5 during recovery, we still needs mutation
// for its metadata
onRecord(N0,
5,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 5);
onRecord(N1,
5,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 5);
onRecord(N2,
5,
RecordType::MUTATED,
seal_epoch_.val_,
payload_size,
payload_size_map * 5);
digest_->recomputeOffsetsWithinEpoch(lng_);
size_t nentries = 0;
for (auto& it : *digest_) {
Digest::Entry& entry = it.second;
switch (it.first.val_) {
case 1:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N2, N3);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
// 4 is the largest wave received
ASSERT_RECORD(entry, RecordType::NORMAL, 4);
checkMutation(entry, /*complete_digest*/ true);
ASSERT_TRUE(needs_mutation_);
EXPECT_EQ(
payload_size,
entry.record->extra_metadata_->offsets_within_epoch.getCounter(
BYTE_OFFSET));
break;
case 2:
checkMutation(entry);
ASSERT_FALSE(needs_mutation_);
ASSERT_AMEND_SET();
ASSERT_SUCCESS_SET(N0, N2, N3);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::MUTATED, seal_epoch_.val_);
EXPECT_EQ(
payload_size * 2,
entry.record->extra_metadata_->offsets_within_epoch.getCounter(
BYTE_OFFSET));
break;
case 3:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N1);
ASSERT_SUCCESS_SET(N3);
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::HOLE, seal_epoch_.val_);
EXPECT_EQ(
payload_size * 2,
entry.record->extra_metadata_->offsets_within_epoch.getCounter(
BYTE_OFFSET));
break;
case 4:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N2);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET(N1, N3);
ASSERT_RECORD(entry, RecordType::MUTATED, 49);
EXPECT_EQ(
payload_size * 3,
entry.record->extra_metadata_->offsets_within_epoch.getCounter(
BYTE_OFFSET));
break;
case 5:
checkMutation(entry);
ASSERT_TRUE(needs_mutation_);
ASSERT_AMEND_SET(N0, N1, N2);
ASSERT_SUCCESS_SET();
ASSERT_CONFLICT_SET();
ASSERT_RECORD(entry, RecordType::MUTATED, seal_epoch_.val_);
EXPECT_EQ(
payload_size * 4,
entry.record->extra_metadata_->offsets_within_epoch.getCounter(
BYTE_OFFSET));
break;
default:
break;
}
++nentries;
}
EXPECT_EQ(5, nentries);
}
} // namespace
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
91c0664f62c94eb098f1460aedd6621e30be5b05 | f9dbecdaebc8f924606b59524e58f598874829ad | /clases/test.cpp | e303c3b2141c3662896176f91bfad9dad0c96f13 | [] | no_license | sebastianibam002/Algoritmos | 0b4ab84457f562af8f8ae31206839933f7a5131a | 6e5e4fc91ac695809fdc37d36b083af4430558fc | refs/heads/master | 2020-12-27T09:15:13.268206 | 2020-05-10T21:55:21 | 2020-05-10T21:55:21 | 237,848,071 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 93 | cpp | #include "lib.hpp"
int main() {
printf("This is a test...\n");
foo();
return 0;
}
| [
"sebastianibam@gmail.com"
] | sebastianibam@gmail.com |
36e7817611af9ba22b03b3da87661c71b21e750b | d1cf34b4d5280e33ebcf1cd788b470372fdd5a26 | /zoj/25/2548.cpp | 0fbd39bbf29bd26b0deef0abc97dfffaa26398f4 | [] | no_license | watashi/AlgoSolution | 985916ac511892b7e87f38c9b364069f6b51a0ea | bbbebda189c7e74edb104615f9c493d279e4d186 | refs/heads/master | 2023-08-17T17:25:10.748003 | 2023-08-06T04:34:19 | 2023-08-06T04:34:19 | 2,525,282 | 97 | 32 | null | 2020-10-09T18:52:29 | 2011-10-06T10:40:07 | C++ | WINDOWS-1252 | C++ | false | false | 1,320 | cpp | #include <cstdio>
#include <algorithm>
using namespace std;
int m, n, a[101], b[101];
inline int same_value(int m, int n, int a[], int b[])
{
int ret = 0, i = 0, j = 0;
// m > 0 && n > 0 ;else return 0!
// all element are diff
while(true) {
if(a[i] < b[j]) {
if(++i >= m) return ret;
}
else if(a[i] > b[j]) {
if(++j >= n) return ret;
}
else {
++ret;
if(++i >= m) return ret;
if(++j >= n) return ret;
}
}
}
int main(void)
{
bool flag;
int c, i, k;
while(scanf("%d", &m) != EOF && m > 0) {
scanf("%d", &k);
for (i = 0; i < m; i++)
scanf("%d", &a[i]);
sort(a, a + m);
flag = true;
while(k--) {
scanf("%d%d", &n, &c);
for (i = 0; i < n; i++)
scanf("%d", &b[i]);
if(!flag) continue;
sort(b, b + n);
if(same_value(m, n, a, b) < c) flag = false;
}
puts(flag ? "yes" : "no");
}
return 0;
}
/*
Run ID Submit time Judge Status Problem ID Language Run time Run memory User Name
2795765 2008-03-21 23:03:47 Accepted 2548 C++ 00:00.19 436K ¤ï¤¿¤·
*/
// 2012-09-07 01:27:52 | Accepted | 2548 | C++ | 60 | 180 | watashi | Source
| [
"zejun.wu@gmail.com"
] | zejun.wu@gmail.com |
80bb384009f2bced91761708d6e209b645b081fa | 5521a03064928d63cc199e8034e4ea76264f76da | /fboss/led_service/LedManager.h | 0a618cb68187709ed8f6d2bbc525e2f33dc5bc71 | [
"BSD-3-Clause",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | facebook/fboss | df190fd304e0bf5bfe4b00af29f36b55fa00efad | 81e02db57903b4369200eec7ef22d882da93c311 | refs/heads/main | 2023-09-01T18:21:22.565059 | 2023-09-01T15:53:39 | 2023-09-01T15:53:39 | 31,927,407 | 925 | 353 | NOASSERTION | 2023-09-14T05:44:49 | 2015-03-09T23:04:15 | C++ | UTF-8 | C++ | false | false | 3,141 | h | /*
* Copyright (c) 2018-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#pragma once
#include <folly/Format.h>
#include <folly/Synchronized.h>
#include <folly/io/async/EventBase.h>
#include <folly/logging/xlog.h>
#include <stdexcept>
#include "fboss/agent/FbossError.h"
#include "fboss/agent/gen-cpp2/switch_state_types.h"
#include "fboss/agent/platforms/common/PlatformMapping.h"
#include "fboss/fsdb/client/FsdbPubSubManager.h"
#include "fboss/led_service/FsdbSwitchStateSubscriber.h"
#include "fboss/lib/led/LedIO.h"
#include "fboss/lib/led/gen-cpp2/led_mapping_types.h"
namespace facebook::fboss {
/*
* LedManager class definiton:
*
* The LedManager class managing all LED in the system. The object is spawned
* by LED Service. This will subscribe to Fsdb to get Switch state update and
* then update the LED in hardware
*/
class LedManager {
using PortDisplayInfo = struct PortDisplayInfo {
std::string portName;
cfg::PortProfileID portProfileId;
bool operationStateUp{false};
bool neighborReachable{false};
bool cablingError{false};
bool forcedOn{false};
bool forcedOff{false};
led::LedColor currentLedColor{led::LedColor::UNKNOWN};
};
public:
using LedSwitchStateUpdate = struct LedSwitchStateUpdate {
short swPortId;
std::string portName;
std::string portProfile;
bool operState;
std::optional<PortLedExternalState> ledExternalState;
};
LedManager();
virtual ~LedManager();
// Initialize the Led Manager, get system container
virtual void initLedManager() {}
// On getting the update from FSDB, update portDisplayMap_
void updateLedStatus(std::map<short, LedSwitchStateUpdate> newSwitchState);
folly::EventBase* getEventBase() {
return eventBase_.get();
}
fsdb::FsdbPubSubManager* pubSubMgr() const {
return fsdbPubSubMgr_.get();
}
void setExternalLedState(int32_t portNum, PortLedExternalState ledState);
// Forbidden copy constructor and assignment operator
LedManager(LedManager const&) = delete;
LedManager& operator=(LedManager const&) = delete;
protected:
// Platform mapping to get SW Port -> Lane mapping
std::unique_ptr<PlatformMapping> platformMapping_;
// Port Name to PortDisplayInfo map, no lock needed
std::map<uint32_t, PortDisplayInfo> portDisplayMap_;
std::unique_ptr<FsdbSwitchStateSubscriber> fsdbSwitchStateSubscriber_;
std::unique_ptr<fsdb::FsdbPubSubManager> fsdbPubSubMgr_;
virtual led::LedColor calculateLedColor(
uint32_t /* portId */,
cfg::PortProfileID /* portProfiled */) const {
return led::LedColor::UNKNOWN;
}
virtual void setLedColor(
uint32_t /* portIdd */,
cfg::PortProfileID /* portProfiled */,
led::LedColor /* ledColord */) {}
private:
std::unique_ptr<std::thread> ledManagerThread_{nullptr};
std::unique_ptr<folly::EventBase> eventBase_;
};
} // namespace facebook::fboss
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
274b7bf168d2855069c36d5a2a188d2384efbe91 | 2fa764b33e15edd3b53175456f7df61a594f0bb5 | /appseed/aura/aura/charguess/MBCSGroupProber.cpp | a4eb505df3ea18d08b69ca64fa7c2041d7ce80b3 | [] | no_license | PeterAlfonsLoch/app | 5f6ac8f92d7f468bc99e0811537380fcbd828f65 | 268d0c7083d9be366529e4049adedc71d90e516e | refs/heads/master | 2021-01-01T17:44:15.914503 | 2017-07-23T16:58:08 | 2017-07-23T16:58:08 | 98,142,329 | 1 | 0 | null | 2017-07-24T02:44:10 | 2017-07-24T02:44:10 | null | UTF-8 | C++ | false | false | 3,931 | cpp | /*
libcharguess - Guess the encoding/charset of a string
Copyright (C) 2003 Stephane Corbe <noubi@users.sourceforge.net>
Based on Mozilla sources
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
//#include "framework.h"
#ifdef DEBUG_chardet
char *ProberName[] =
{
"UTF8",
"SJIS",
"EUCJP",
"GB18030",
"EUCKR",
"Big5",
"EUCTW",
};
#endif
nsMBCSGroupProber::nsMBCSGroupProber()
{
mProbers[0] = new nsUTF8Prober();
mProbers[1] = new nsSJISProber();
mProbers[2] = new nsEUCJPProber();
mProbers[3] = new nsGB18030Prober();
mProbers[4] = new nsEUCKRProber();
mProbers[5] = new nsBig5Prober();
mProbers[6] = new nsEUCTWProber();
Reset();
}
nsMBCSGroupProber::~nsMBCSGroupProber()
{
for (PRUint32 i = 0; i < NUM_OF_PROBERS; i++)
{
delete mProbers[i];
}
}
const char* nsMBCSGroupProber::GetCharSetName()
{
if (mBestGuess == -1)
{
GetConfidence();
if (mBestGuess == -1)
mBestGuess = 0;
}
return mProbers[mBestGuess]->GetCharSetName();
}
void nsMBCSGroupProber::Reset(void)
{
for (PRUint32 i = 0; i < NUM_OF_PROBERS; i++)
{
mProbers[i]->Reset();
mIsActive[i] = PR_TRUE;
}
mActiveNum = NUM_OF_PROBERS;
mBestGuess = -1;
mState = eDetecting;
}
nsProbingState nsMBCSGroupProber::HandleData(const char* aBuf, PRUint32 aLen)
{
nsProbingState st;
PRUint32 i;
//do filtering to reduce load to probers
char *highbyteBuf;
char *hptr;
PRBool keepNext = PR_TRUE; //assume previous is not ascii, it will do not harm except add some noise
hptr = highbyteBuf = (char*)PR_MALLOC(aLen);
for (i = 0; i < aLen; i++)
{
if (aBuf[i] & 0x80)
{
*hptr++ = aBuf[i];
keepNext = PR_TRUE;
}
else
{
//if previous is highbyte, keep this even it is a ASCII
if (keepNext)
{
*hptr++ = aBuf[i];
keepNext = PR_FALSE;
}
}
}
for (i = 0; i < NUM_OF_PROBERS; i++)
{
if (!mIsActive[i])
continue;
st = mProbers[i]->HandleData(highbyteBuf, (PRUint32)(hptr - highbyteBuf));
if (st == eFoundIt)
{
mBestGuess = i;
mState = eFoundIt;
break;
}
else if (st == eNotMe)
{
mIsActive[i] = PR_FALSE;
mActiveNum--;
if (mActiveNum <= 0)
{
mState = eNotMe;
break;
}
}
}
PR_FREEIF(highbyteBuf);
return mState;
}
float nsMBCSGroupProber::GetConfidence(void)
{
PRUint32 i;
float bestConf = 0.0, cf;
switch (mState)
{
case eFoundIt:
return (float)0.99;
case eNotMe:
return (float)0.01;
default:
for (i = 0; i < NUM_OF_PROBERS; i++)
{
if (!mIsActive[i])
continue;
cf = mProbers[i]->GetConfidence();
if (bestConf < cf)
{
bestConf = cf;
mBestGuess = i;
}
}
}
return bestConf;
}
#ifdef DEBUG_chardet
void
nsMBCSGroupProber::DumpStatus()
{
PRUint32 i;
float cf;
GetConfidence();
for (i = 0; i < NUM_OF_PROBERS; i++)
{
if (!mIsActive[i])
printf("[%s] is inactive(ie. cofidence is too low).\r\n", ProberName[i]);
else
{
cf = mProbers[i]->GetConfidence();
printf("[%s] prober has confidence %f\r\n", ProberName[i], cf);
}
}
}
#endif
| [
"camilo@ca2.email"
] | camilo@ca2.email |
b8d7bcc176284c13b9139f602fcc48fdc0e79d27 | 0eff74b05b60098333ad66cf801bdd93becc9ea4 | /second/download/squid/gumtree/squid_repos_function_913_squid-3.1.23.cpp | 76c614152cf89bd2de71f2221dc50b533cb94424 | [] | no_license | niuxu18/logTracker-old | 97543445ea7e414ed40bdc681239365d33418975 | f2b060f13a0295387fe02187543db124916eb446 | refs/heads/master | 2021-09-13T21:39:37.686481 | 2017-12-11T03:36:34 | 2017-12-11T03:36:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 670 | cpp | void
checkTimeouts(void)
{
int fd;
fde *F = NULL;
AsyncCall::Pointer callback;
for (fd = 0; fd <= Biggest_FD; fd++) {
F = &fd_table[fd];
if (AlreadyTimedOut(F))
continue;
debugs(5, 5, "checkTimeouts: FD " << fd << " Expired");
if (F->timeoutHandler != NULL) {
debugs(5, 5, "checkTimeouts: FD " << fd << ": Call timeout handler");
callback = F->timeoutHandler;
F->timeoutHandler = NULL;
ScheduleCallHere(callback);
} else {
debugs(5, 5, "checkTimeouts: FD " << fd << ": Forcing comm_close()");
comm_close(fd);
}
}
} | [
"993273596@qq.com"
] | 993273596@qq.com |
bf7932362e19e4b9b8b3316afabcfa5dccb6912a | c22c85b2509deccd0e8089e6aa86ab9cf009faf8 | /Rotations/sqct/numbersgen.cpp | ad96c524ec01d4420d2b02ec0f4bc25d1070ee84 | [
"BSD-2-Clause",
"LGPL-3.0-only",
"GPL-3.0-only"
] | permissive | teaguetomesh/ScaffCC | facc4be8cd82c4c34666b53a9154949f1c9d42b7 | 52b087a00ac19384a736b4c64631ca67bd1d8054 | refs/heads/master | 2020-04-15T13:01:13.873540 | 2019-03-05T19:50:06 | 2019-03-05T19:50:06 | 164,698,453 | 0 | 0 | BSD-2-Clause | 2019-01-08T17:19:10 | 2019-01-08T17:19:09 | null | UTF-8 | C++ | false | false | 5,691 | cpp | // Copyright (c) 2012 Vadym Kliuchnikov sqct(dot)software(at)gmail(dot)com, Dmitri Maslov, Michele Mosca
//
// This file is part of SQCT.
//
// SQCT is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// SQCT is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with SQCT. If not, see <http://www.gnu.org/licenses/>.
//
#include "numbersgen.h"
#include <cassert>
static const int sde_not_computed = -1;
template< int de >
void numbersGenerator<de>::init()
{
int& first = sdes[0][0];
int& last = sdes[ip_range - 1][ipQ_range - 1];
std::fill(&first ,&last + 1,sde_not_computed);
}
template< int de >
bool numbersGenerator<de>::isInRange(int ipxx, int ipQxx) const
{
return ( ipxx >= 0 ) && ( ipxx < ip_range ) &&
( ( ipQxx + ipQ_offset ) >= 0 ) &&
( ( ipQxx + ipQ_offset ) < ipQ_range );
}
template< int de >
void numbersGenerator<de>::add_number( int a, int b , int c, int d, int ipxx )
{
int m1 = ( a == 0 ? 1 : 2 );
int m2 = ( b == 0 ? 1 : 2 );
int m3 = ( c == 0 ? 1 : 2 );
int m4 = ( d == 0 ? 1 : 2 );
static const int s[2] = {1,-1};
for ( int i1 = 0; i1 < m1 ; ++i1 )
for ( int i2 = 0; i2 < m2 ; ++i2 )
for ( int i3 = 0; i3 < m3 ; ++i3 )
for ( int i4 = 0; i4 < m4 ; ++i4 )
{
ri x( a * s[i1], b * s[i2], c * s[i3], d * s[i4]);
int ipQxx = x.ipQxx();
static const double SQRT2 =
1.4142135623730950488016887242096980785696718753769;
ri abs2x( ipxx, ipQxx, 0, -ipQxx );
auto res = abs2x.toComplex( 2 * denom_exp );
if( abs( res ) <= 1.0000001 )
{
if( sdes[ ipxx ][ ipQxx + ipQ_offset ] == sde_not_computed )
sdes[ ipxx ][ ipQxx + ipQ_offset ]
= sde( 2 * denom_exp, abs2x.gde() );
vals[ ipxx ][ ipQxx + ipQ_offset ].push_back( x );
m_total_numbers++;
}
}
}
template< int de >
void numbersGenerator<de>::generate_all_numbers()
{
for( int i1 = 0; i1 <= max_val; ++i1 )
{
int ipxx1 = i1 * i1;
for( int i2 = 0; i2 <= max_val; ++i2 )
{
int ipxx2 = ipxx1 + i2 * i2;
if( ipxx2 > max_val2 )
break;
for( int i3 = 0; i3 <= max_val; ++i3 )
{
int ipxx3 = ipxx2 + i3 * i3;
if( ipxx3 > max_val2 )
break;
for( int i4 = 0; i4 <= max_val; ++i4 )
{
int ipxx4 = ipxx3 + i4 * i4;
if( ipxx4 > max_val2 )
break;
add_number( i1, i2, i3, i4, ipxx4 );
}
}
}
}
}
template< int de >
numbersGenerator<de>::numbersGenerator() :
m_total_numbers(0)
{
assert( denom_exp % 2 == 0 );
init();
}
template< int de >
int numbersGenerator<de>::getSde(int ipxx, int ipQxx) const
{
assert( isInRange(ipxx,ipQxx) );
return sdes[ipxx][ipQ_offset + ipQxx];
}
template< int de >
const typename numbersGenerator<de>::riArray& numbersGenerator<de>::numbers(int ipxx, int ipQxx) const
{
assert( isInRange(ipxx,ipQxx) );
return vals[ipxx][ipQ_offset + ipQxx];
}
template< int de >
const typename numbersGenerator<de>::riArray& numbersGenerator<de>::numbersWithPair(int ipxx, int ipQxx) const
{
static const riArray emp;
const auto& res = numbers( max_val2 - ipxx,-ipQxx );
if( ! (res.empty() ) )
return vals[ipxx][ipQxx];
else
return emp;
}
//////// template compilation requests
template class numbersGenerator<2>;
template class numbersGenerator<4>;
template class numbersGenerator<6>;
template class numbersGenerator<8>;
template class numbersGenerator<10>;
template class numbersGenerator<12>;
//////////////////////////////////////
template< int de >
void columnsCounter<de>::count_all_columns()
{
sde_stat.resize(bs::max_sde,0);
for( int ipxx = 0; ipxx < bs::max_val2 + 1; ++ipxx )
{
for( int j = 0; j < bs::ipQ_range; ++j )
{
int ipyy = bs::max_val2 - ipxx;
int ipQxx = j - bs::ipQ_offset;
int ipQyy = -ipQxx;
int k = bs::ipQ_offset + ipQyy;
int sde = bs::sdes[ipxx][j];
int sde2 = bs::sdes[ipyy][k];
auto ii_end = bs::vals[ipxx][j].end();
for( auto ii = bs::vals[ipxx][j].begin(); ii != ii_end; ++ii )
{
auto jj_end = bs::vals[ipyy][k].end();
for( auto jj = bs::vals[ipyy][k].begin(); jj != jj_end; ++jj )
{
int idx =std::min(sde2,sde);
sde_stat[idx] ++;
}
}
}
}
}
//////// template compilation requests
template class columnsCounter<2>;
template class columnsCounter<4>;
template class columnsCounter<6>;
template class columnsCounter<8>;
template class columnsCounter<10>;
template class columnsCounter<12>;
| [
"ajavadia@princeton.edu"
] | ajavadia@princeton.edu |
c6d0dbcd33dfb70803034a1de2cddf2642789f52 | 3f2dd509185bc85a44e5c22ea9e49e5076868c93 | /Prototype/src/client/sender.cpp | 58430d9aa2d44f341a05400cf25f89b3f0dfefec | [
"MIT"
] | permissive | tinoryj/FeatureSpy | 616b9abc1b3056ea75515fefe7db69fb39a825c0 | 161c4a185f6ab34a1df6a430d60cca459c4da394 | refs/heads/master | 2023-04-10T20:17:43.747635 | 2023-01-08T05:32:12 | 2023-01-08T05:32:12 | 514,726,660 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 23,094 | cpp | #include "sender.hpp"
#include <sys/time.h>
extern Configure config;
struct timeval timestartSender;
struct timeval timeendSender;
struct timeval timestartSenderRun;
struct timeval timeendSenderRun;
struct timeval timestartSenderRecipe;
struct timeval timeendSenderRecipe;
void PRINT_BYTE_ARRAY_SENDER(
FILE* file, void* mem, uint32_t len)
{
if (!mem || !len) {
fprintf(file, "\n( null )\n");
return;
}
uint8_t* array = (uint8_t*)mem;
fprintf(file, "%u bytes:\n{\n", len);
uint32_t i = 0;
for (i = 0; i < len - 1; i++) {
fprintf(file, "0x%x, ", array[i]);
if (i % 8 == 7)
fprintf(file, "\n");
}
fprintf(file, "0x%x ", array[i]);
fprintf(file, "\n}\n");
}
Sender::Sender()
{
inputMQ_ = new messageQueue<Data_t>;
dataSecurityChannel_ = new ssl(config.getStorageServerIP(), config.getStorageServerPort(), CLIENTSIDE);
powSecurityChannel_ = new ssl(config.getStorageServerIP(), config.getPOWServerPort(), CLIENTSIDE);
sslConnectionData_ = dataSecurityChannel_->sslConnect().second;
sslConnectionPow_ = powSecurityChannel_->sslConnect().second;
cryptoObj_ = new CryptoPrimitive();
clientID_ = config.getClientID();
}
Sender::~Sender()
{
delete dataSecurityChannel_;
delete powSecurityChannel_;
delete cryptoObj_;
inputMQ_->~messageQueue();
delete inputMQ_;
}
bool Sender::sendRecipe(Recipe_t request, RecipeList_t recipeList, int& status)
{
int totalRecipeNumber = recipeList.size();
// if (totalRecipeNumber != request.fileRecipeHead.totalChunkNumber) {
// cerr << "Sender : error, recipe entry size = " << totalRecipeNumber << ", recipe head require number = " << request.fileRecipeHead.totalChunkNumber << endl;
// }
sort(recipeList.begin(), recipeList.end(), [=](RecipeEntry_t& a, RecipeEntry_t& b) { return a.chunkID < b.chunkID; });
#if SYSTEM_DEBUG_FLAG == 1
ofstream localRecipeStream;
localRecipeStream.open("recipe.log", ios::out);
int currentID = 0;
for (int i = 0; i < recipeList.size(); i++) {
localRecipeStream << recipeList[i].chunkID << "\t" << recipeList[i].chunkSize << endl;
char chunkHashHexBuffer[SYSTEM_CIPHER_SIZE * 2 + 1];
for (int j = 0; j < SYSTEM_CIPHER_SIZE; j++) {
sprintf(chunkHashHexBuffer + 2 * j, "%02X", recipeList[i].chunkKeyMLE[j]);
}
localRecipeStream << chunkHashHexBuffer << endl;
for (int j = 0; j < SYSTEM_CIPHER_SIZE; j++) {
sprintf(chunkHashHexBuffer + 2 * j, "%02X", recipeList[i].chunkKeyFeature[j]);
}
localRecipeStream << chunkHashHexBuffer << endl;
if (currentID != recipeList[i].chunkID) {
cout << "Sender Chunk Sequence error, ID = " << recipeList[i].chunkID << ",\t current = " << currentID << endl;
}
currentID++;
}
localRecipeStream.close();
localRecipeStream.clear();
#endif
int totalRecipeSize = totalRecipeNumber * sizeof(RecipeEntry_t) + sizeof(Recipe_t);
u_char* recipeBuffer = (u_char*)malloc(sizeof(u_char) * totalRecipeNumber * sizeof(RecipeEntry_t));
for (int i = 0; i < totalRecipeNumber; i++) {
memcpy(recipeBuffer + i * sizeof(RecipeEntry_t), &recipeList[i], sizeof(RecipeEntry_t));
}
NetworkHeadStruct_t requestBody;
requestBody.clientID = clientID_;
requestBody.messageType = CLIENT_UPLOAD_ENCRYPTED_RECIPE;
int sendSize = sizeof(NetworkHeadStruct_t);
requestBody.dataSize = totalRecipeSize;
char* requestBufferFirst = (char*)malloc(sizeof(char) * sendSize);
memcpy(requestBufferFirst, &requestBody, sizeof(NetworkHeadStruct_t));
if (!dataSecurityChannel_->send(sslConnectionData_, requestBufferFirst, sendSize)) {
free(recipeBuffer);
free(requestBufferFirst);
cerr << "Sender : error sending file resipces size, peer may close" << endl;
return false;
} else {
free(requestBufferFirst);
sendSize = sizeof(NetworkHeadStruct_t) + totalRecipeSize;
requestBody.dataSize = totalRecipeSize;
char* requestBuffer = (char*)malloc(sizeof(char) * sendSize);
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t), &request, sizeof(Recipe_t));
cryptoObj_->encryptWithKey(recipeBuffer, totalRecipeNumber * sizeof(RecipeEntry_t), cryptoObj_->chunkKeyEncryptionKey_, (u_char*)requestBuffer + sizeof(NetworkHeadStruct_t) + sizeof(Recipe_t));
if (!dataSecurityChannel_->send(sslConnectionData_, requestBuffer, sendSize)) {
free(recipeBuffer);
free(requestBuffer);
cerr << "Sender : error sending file resipces, peer may close" << endl;
return false;
} else {
free(recipeBuffer);
free(requestBuffer);
return true;
}
}
}
bool Sender::getKeyServerSK(u_char* SK)
{
NetworkHeadStruct_t requestBody;
requestBody.clientID = clientID_;
requestBody.messageType = CLIENT_GET_KEY_SERVER_SK;
requestBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t);
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
char respondBuffer[sizeof(NetworkHeadStruct_t) + SYSTEM_CIPHER_SIZE];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
return false;
} else {
if (recvSize != sizeof(NetworkHeadStruct_t) + SYSTEM_CIPHER_SIZE) {
cerr << "Client : storage server reject connection beacuse keyexchange key not set not, try again later" << endl;
return false;
} else {
memcpy(SK, respondBuffer + sizeof(NetworkHeadStruct_t), SYSTEM_CIPHER_SIZE);
return true;
}
}
}
bool Sender::sendChunkList(char* requestBufferIn, int sendBufferSize, int sendChunkNumber, int& status)
{
NetworkHeadStruct_t requestBody;
requestBody.clientID = clientID_;
requestBody.messageType = CLIENT_UPLOAD_CHUNK;
int sendSize = sizeof(NetworkHeadStruct_t) + sizeof(int) + sendBufferSize;
memcpy(requestBufferIn + sizeof(NetworkHeadStruct_t), &sendChunkNumber, sizeof(int));
requestBody.dataSize = sendBufferSize + sizeof(int);
memcpy(requestBufferIn, &requestBody, sizeof(NetworkHeadStruct_t));
if (!dataSecurityChannel_->send(sslConnectionData_, requestBufferIn, sendSize)) {
cerr << "Sender : error sending chunk list, peer may close" << endl;
return false;
} else {
return true;
}
}
bool Sender::sendLogInMessage(int loginType)
{
NetworkHeadStruct_t requestBody;
requestBody.clientID = clientID_;
requestBody.messageType = loginType;
requestBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t);
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
char respondBuffer[sizeof(NetworkHeadStruct_t)];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
cerr << "Sender : peer closed, set log out error" << endl;
return false;
} else {
return true;
}
}
bool Sender::sendLogOutMessage()
{
NetworkHeadStruct_t requestBody;
requestBody.clientID = clientID_;
requestBody.messageType = CLIENT_SET_LOGOUT;
requestBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t);
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
char respondBuffer[sizeof(NetworkHeadStruct_t)];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
cerr << "Sender : peer closed, set log out error" << endl;
return false;
} else {
return true;
}
}
bool Sender::sendSGXmsg01(uint32_t& msg0, sgx_ra_msg1_t& msg1, sgx_ra_msg2_t*& msg2, int& status)
{
NetworkHeadStruct_t requestBody, respondBody;
requestBody.clientID = clientID_;
requestBody.messageType = SGX_RA_MSG01;
respondBody.clientID = 0;
respondBody.messageType = 0;
respondBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t) + sizeof(msg0) + sizeof(msg1);
requestBody.dataSize = sizeof(msg0) + sizeof(msg1);
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t), &msg0, sizeof(msg0));
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t) + sizeof(msg0), &msg1, sizeof(msg1));
char respondBuffer[SGX_MESSAGE_MAX_SIZE];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
cerr << "Sender : peer closed, send sgx msg 01 error" << endl;
return false;
}
memcpy(&respondBody, respondBuffer, sizeof(NetworkHeadStruct_t));
status = respondBody.messageType;
if (status == SUCCESS) {
msg2 = (sgx_ra_msg2_t*)malloc(recvSize - sizeof(NetworkHeadStruct_t));
memcpy(msg2, respondBuffer + sizeof(NetworkHeadStruct_t), recvSize - sizeof(NetworkHeadStruct_t));
return true;
}
return false;
}
bool Sender::sendSGXmsg3(sgx_ra_msg3_t* msg3, uint32_t size, ra_msg4_t*& msg4, int& status)
{
NetworkHeadStruct_t requestBody, respondBody;
requestBody.clientID = clientID_;
requestBody.messageType = SGX_RA_MSG3;
respondBody.clientID = 0;
respondBody.messageType = 0;
respondBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t) + size;
requestBody.dataSize = size;
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t), msg3, size);
char respondBuffer[SGX_MESSAGE_MAX_SIZE];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
cerr << "Sender : peer closed, send sgx msg 3 error" << endl;
return false;
}
memcpy(&respondBody, respondBuffer, sizeof(NetworkHeadStruct_t));
status = respondBody.messageType;
if (status == SUCCESS) {
msg4 = (ra_msg4_t*)malloc(sizeof(ra_msg4_t));
memcpy(msg4, respondBuffer + sizeof(NetworkHeadStruct_t), sizeof(ra_msg4_t));
return true;
}
return false;
}
bool Sender::sendEnclaveSignedHash(u_char* clientMac, u_char* hashList, int requestNumber, u_char* respond, int& status)
{
NetworkHeadStruct_t requestBody, respondBody;
requestBody.messageType = SGX_SIGNED_HASH;
requestBody.clientID = clientID_;
respondBody.messageType = 0;
respondBody.clientID = 0;
respondBody.dataSize = 0;
int sendSize = sizeof(NetworkHeadStruct_t) + sizeof(uint8_t) * 16 + requestNumber * SYSTEM_CIPHER_SIZE;
requestBody.dataSize = sizeof(uint8_t) * 16 + requestNumber * SYSTEM_CIPHER_SIZE;
char requestBuffer[sendSize];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t), clientMac, sizeof(uint8_t) * 16);
memcpy(requestBuffer + sizeof(NetworkHeadStruct_t) + sizeof(uint8_t) * 16, hashList, requestNumber * SYSTEM_CIPHER_SIZE);
char respondBuffer[sizeof(NetworkHeadStruct_t) + sizeof(bool) * requestNumber + sizeof(int)];
int recvSize = 0;
if (!this->sendDataPow(requestBuffer, sendSize, respondBuffer, recvSize)) {
cerr << "Sender : send enclave signed hash to server & get back required chunk list error" << endl;
return false;
}
memcpy(&respondBody, respondBuffer, sizeof(NetworkHeadStruct_t));
status = respondBody.messageType;
if (status == SUCCESS) {
memcpy(respond, respondBuffer + sizeof(NetworkHeadStruct_t), sizeof(int) + sizeof(bool) * requestNumber);
return true;
} else {
return false;
}
}
bool Sender::sendDataPow(char* request, int requestSize, char* respond, int& respondSize)
{
if (!powSecurityChannel_->send(sslConnectionPow_, request, requestSize)) {
cerr << "Sender : send data error peer closed" << endl;
return false;
}
if (!powSecurityChannel_->recv(sslConnectionPow_, respond, respondSize)) {
cerr << "Sender : recv data error peer closed" << endl;
return false;
}
return true;
}
bool Sender::sendEndFlag()
{
NetworkHeadStruct_t requestBody, responseBody;
requestBody.messageType = CLIENT_EXIT;
requestBody.clientID = clientID_;
int sendSize = sizeof(NetworkHeadStruct_t);
int recvSize;
requestBody.dataSize = 0;
char requestBuffer[sendSize];
char responseBuffer[sizeof(NetworkHeadStruct_t)];
memcpy(requestBuffer, &requestBody, sizeof(NetworkHeadStruct_t));
if (!powSecurityChannel_->send(sslConnectionPow_, requestBuffer, sendSize)) {
cerr << "Sender : send end flag to pow server error peer closed" << endl;
return false;
}
if (!powSecurityChannel_->recv(sslConnectionPow_, responseBuffer, recvSize)) {
cerr << "Sender : recv end flag from pow server error peer closed" << endl;
return false;
} else {
memcpy(&responseBody, responseBuffer, sizeof(NetworkHeadStruct_t));
if (responseBody.messageType == SERVER_JOB_DONE_EXIT_PERMIT) {
if (!dataSecurityChannel_->send(sslConnectionData_, requestBuffer, sendSize)) {
cerr << "Sender : send end flag to data server error peer closed" << endl;
return false;
}
if (!dataSecurityChannel_->recv(sslConnectionData_, responseBuffer, recvSize)) {
cerr << "Sender : recv end flag from data server error peer closed" << endl;
return false;
} else {
memcpy(&responseBody, responseBuffer, sizeof(NetworkHeadStruct_t));
if (responseBody.messageType == SERVER_JOB_DONE_EXIT_PERMIT) {
return true;
} else {
return false;
}
}
} else {
return false;
}
}
return true;
}
void Sender::run()
{
Data_t tempChunk;
RecipeList_t recipeList;
Recipe_t fileRecipe;
int sendBatchSize = config.getSendChunkBatchSize();
int status;
char* sendChunkBatchBuffer = (char*)malloc(sizeof(NetworkHeadStruct_t) + sizeof(int) + sizeof(char) * sendBatchSize * (SYSTEM_CIPHER_SIZE + MAX_CHUNK_SIZE + sizeof(int)));
bool jobDoneFlag = false;
int currentChunkNumber = 0;
int currentSendRecipeNumber = 0;
int currentSendChunkBatchBufferSize = sizeof(NetworkHeadStruct_t) + sizeof(int);
#if SYSTEM_BREAK_DOWN == 1
double totalSendChunkTime = 0;
double totalChunkAssembleTime = 0;
double totalSendRecipeTime = 0;
double totalRecipeAssembleTime = 0;
double totalReadMessageQueueTime = 0;
double totalSenderRunTime = 0;
long diff;
double second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSenderRun, NULL);
#endif
while (!jobDoneFlag) {
if (inputMQ_->done_ && inputMQ_->isEmpty()) {
jobDoneFlag = true;
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSender, NULL);
#endif
bool extractChunkStatus = extractMQ(tempChunk);
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalReadMessageQueueTime += second;
#endif
if (extractChunkStatus) {
if (tempChunk.dataType == DATA_TYPE_RECIPE) {
#if SYSTEM_DEBUG_FLAG == 1
cerr << "Sender : get file recipe head, file size = " << tempChunk.recipe.fileRecipeHead.fileSize << " file chunk number = " << tempChunk.recipe.fileRecipeHead.totalChunkNumber << endl;
PRINT_BYTE_ARRAY_SENDER(stderr, tempChunk.recipe.fileRecipeHead.fileNameHash, SYSTEM_CIPHER_SIZE);
#endif
memcpy(&fileRecipe, &tempChunk.recipe, sizeof(Recipe_t));
continue;
} else {
if (tempChunk.chunk.type == CHUNK_TYPE_NEED_UPLOAD) {
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSender, NULL);
#endif
memcpy(sendChunkBatchBuffer + currentSendChunkBatchBufferSize, tempChunk.chunk.chunkHash, SYSTEM_CIPHER_SIZE);
currentSendChunkBatchBufferSize += SYSTEM_CIPHER_SIZE;
memcpy(sendChunkBatchBuffer + currentSendChunkBatchBufferSize, &tempChunk.chunk.logicDataSize, sizeof(int));
currentSendChunkBatchBufferSize += sizeof(int);
memcpy(sendChunkBatchBuffer + currentSendChunkBatchBufferSize, tempChunk.chunk.logicData, tempChunk.chunk.logicDataSize);
currentSendChunkBatchBufferSize += tempChunk.chunk.logicDataSize;
currentChunkNumber++;
// cout << "Sender : Chunk ID = " << tempChunk.chunk.ID << " size = " << tempChunk.chunk.logicDataSize << endl;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalChunkAssembleTime += second;
#endif
// #if SYSTEM_DEBUG_FLAG == 1
// PRINT_BYTE_ARRAY_SENDER(stderr, tempChunk.chunk.chunkHash, SYSTEM_CIPHER_SIZE);
// PRINT_BYTE_ARRAY_SENDER(stderr, tempChunk.chunk.encryptKeyMLE, SYSTEM_CIPHER_SIZE);
// PRINT_BYTE_ARRAY_SENDER(stderr, tempChunk.chunk.logicData, tempChunk.chunk.logicDataSize);
// #endif
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSender, NULL);
#endif
// cout << "Sender : Chunk ID = " << tempChunk.chunk.ID << " size = " << tempChunk.chunk.logicDataSize << endl;
RecipeEntry_t newRecipeEntry;
newRecipeEntry.chunkID = tempChunk.chunk.ID;
newRecipeEntry.chunkSize = tempChunk.chunk.logicDataSize;
memcpy(newRecipeEntry.chunkHash, tempChunk.chunk.chunkHash, SYSTEM_CIPHER_SIZE);
memcpy(newRecipeEntry.chunkKeyMLE, tempChunk.chunk.encryptKeyMLE, SYSTEM_CIPHER_SIZE);
memcpy(newRecipeEntry.chunkKeyFeature, tempChunk.chunk.encryptKeyFeature, SYSTEM_CIPHER_SIZE);
recipeList.push_back(newRecipeEntry);
currentSendRecipeNumber++;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalRecipeAssembleTime += second;
#endif
}
}
if (currentChunkNumber == sendBatchSize || jobDoneFlag) {
// cout << "Sender : run -> start send " << fixed << currentChunkNumber << " chunks to server, size = " << fixed << currentSendChunkBatchBufferSize << endl;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSender, NULL);
#endif
if (this->sendChunkList(sendChunkBatchBuffer, currentSendChunkBatchBufferSize, currentChunkNumber, status)) {
// cout << "Sender : sent " << fixed << currentChunkNumber << " chunk" << endl;
currentSendChunkBatchBufferSize = sizeof(NetworkHeadStruct_t) + sizeof(int);
memset(sendChunkBatchBuffer, 0, sizeof(NetworkHeadStruct_t) + sizeof(int) + sizeof(char) * sendBatchSize * (SYSTEM_CIPHER_SIZE + MAX_CHUNK_SIZE + sizeof(int)));
currentChunkNumber = 0;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalSendChunkTime += second;
#endif
} else {
cerr << "Sender : send " << fixed << currentChunkNumber << " chunk error" << endl;
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalSendChunkTime += second;
#endif
break;
}
}
}
#if SYSTEM_BREAK_DOWN == 1
cout << "Sender : assemble chunk list time = " << totalChunkAssembleTime << " s" << endl;
cout << "Sender : chunk upload and storage service time = " << totalSendChunkTime << " s" << endl;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(×tartSender, NULL);
#endif
#if SYSTEM_DEBUG_FLAG == 1
cerr << "Sender : start send file recipes" << endl;
#endif
if (!this->sendRecipe(fileRecipe, recipeList, status)) {
cerr << "Sender : send recipe list error, upload fail " << endl;
free(sendChunkBatchBuffer);
bool serverJobDoneFlag = sendEndFlag();
if (serverJobDoneFlag) {
return;
} else {
cerr << "Sender : server job done flag error, server may shutdown, upload may faild" << endl;
return;
}
}
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSenderRun, NULL);
diff = 1000000 * (timeendSenderRun.tv_sec - timestartSenderRun.tv_sec) + timeendSenderRun.tv_usec - timestartSenderRun.tv_usec;
second = diff / 1000000.0;
totalSenderRunTime += second;
#endif
#if SYSTEM_BREAK_DOWN == 1
gettimeofday(&timeendSender, NULL);
diff = 1000000 * (timeendSender.tv_sec - timestartSender.tv_sec) + timeendSender.tv_usec - timestartSender.tv_usec;
second = diff / 1000000.0;
totalSendRecipeTime += second;
cout << "Sender : assemble recipe list time = " << totalRecipeAssembleTime << " s" << endl;
cout << "Sender : send recipe list time = " << totalSendRecipeTime << " s" << endl;
cout << "Sender : total sending work time = " << totalRecipeAssembleTime + totalSendRecipeTime + totalChunkAssembleTime + totalSendChunkTime << " s" << endl;
cout << "Sender : total thread work time = " << totalSenderRunTime - totalReadMessageQueueTime << " s" << endl;
#endif
free(sendChunkBatchBuffer);
bool serverJobDoneFlag = sendEndFlag();
if (serverJobDoneFlag) {
return;
} else {
cerr << "Sender : server job done flag error, server may shutdown, upload may faild" << endl;
return;
}
}
bool Sender::insertMQ(Data_t& newChunk)
{
return inputMQ_->push(newChunk);
}
bool Sender::extractMQ(Data_t& newChunk)
{
return inputMQ_->pop(newChunk);
}
bool Sender::editJobDoneFlag()
{
inputMQ_->done_ = true;
if (inputMQ_->done_) {
return true;
} else {
return false;
}
}
| [
"tinoryj@gmail.com"
] | tinoryj@gmail.com |
2b012f7e9e7d33dde9a24df3e560d5bb365971e2 | 51441b88f3ead35431a319e0503a32ebdab49a04 | /src/objects/hash-table-inl.h | 7ebaa5cc1c33ebc073f741849ee54e92669f0bf1 | [
"BSD-3-Clause",
"SunPro",
"bzip2-1.0.6"
] | permissive | laiyongqin/v8 | 1d7525a3633f0678125e3502aaa7a9abf4b45265 | 70aacc2e5f6c09211afed474825ea85945adb2ef | refs/heads/master | 2020-03-23T05:38:07.081198 | 2018-07-16T13:02:43 | 2018-07-16T14:35:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,738 | h | // Copyright 2017 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef V8_OBJECTS_HASH_TABLE_INL_H_
#define V8_OBJECTS_HASH_TABLE_INL_H_
#include "src/heap/heap.h"
#include "src/objects/hash-table.h"
namespace v8 {
namespace internal {
int HashTableBase::NumberOfElements() const {
return Smi::ToInt(get(kNumberOfElementsIndex));
}
int HashTableBase::NumberOfDeletedElements() const {
return Smi::ToInt(get(kNumberOfDeletedElementsIndex));
}
int HashTableBase::Capacity() const { return Smi::ToInt(get(kCapacityIndex)); }
void HashTableBase::ElementAdded() {
SetNumberOfElements(NumberOfElements() + 1);
}
void HashTableBase::ElementRemoved() {
SetNumberOfElements(NumberOfElements() - 1);
SetNumberOfDeletedElements(NumberOfDeletedElements() + 1);
}
void HashTableBase::ElementsRemoved(int n) {
SetNumberOfElements(NumberOfElements() - n);
SetNumberOfDeletedElements(NumberOfDeletedElements() + n);
}
// static
int HashTableBase::ComputeCapacity(int at_least_space_for) {
// Add 50% slack to make slot collisions sufficiently unlikely.
// See matching computation in HashTable::HasSufficientCapacityToAdd().
// Must be kept in sync with CodeStubAssembler::HashTableComputeCapacity().
int raw_cap = at_least_space_for + (at_least_space_for >> 1);
int capacity = base::bits::RoundUpToPowerOfTwo32(raw_cap);
return Max(capacity, kMinCapacity);
}
void HashTableBase::SetNumberOfElements(int nof) {
set(kNumberOfElementsIndex, Smi::FromInt(nof));
}
void HashTableBase::SetNumberOfDeletedElements(int nod) {
set(kNumberOfDeletedElementsIndex, Smi::FromInt(nod));
}
template <typename Key>
int BaseShape<Key>::GetMapRootIndex() {
return Heap::kHashTableMapRootIndex;
}
int EphemeronHashTableShape::GetMapRootIndex() {
return Heap::kEphemeronHashTableMapRootIndex;
}
template <typename Derived, typename Shape>
int HashTable<Derived, Shape>::FindEntry(Key key) {
return FindEntry(GetIsolate(), key);
}
template <typename Derived, typename Shape>
int HashTable<Derived, Shape>::FindEntry(Isolate* isolate, Key key) {
return FindEntry(ReadOnlyRoots(isolate), key, Shape::Hash(isolate, key));
}
// Find entry for key otherwise return kNotFound.
template <typename Derived, typename Shape>
int HashTable<Derived, Shape>::FindEntry(ReadOnlyRoots roots, Key key,
int32_t hash) {
uint32_t capacity = Capacity();
uint32_t entry = FirstProbe(hash, capacity);
uint32_t count = 1;
// EnsureCapacity will guarantee the hash table is never full.
Object* undefined = roots.undefined_value();
Object* the_hole = roots.the_hole_value();
USE(the_hole);
while (true) {
Object* element = KeyAt(entry);
// Empty entry. Uses raw unchecked accessors because it is called by the
// string table during bootstrapping.
if (element == undefined) break;
if (!(Shape::kNeedsHoleCheck && the_hole == element)) {
if (Shape::IsMatch(key, element)) return entry;
}
entry = NextProbe(entry, count++, capacity);
}
return kNotFound;
}
template <typename Derived, typename Shape>
bool HashTable<Derived, Shape>::IsKey(ReadOnlyRoots roots, Object* k) {
return Shape::IsKey(roots, k);
}
template <typename Derived, typename Shape>
bool HashTable<Derived, Shape>::ToKey(ReadOnlyRoots roots, int entry,
Object** out_k) {
Object* k = KeyAt(entry);
if (!IsKey(roots, k)) return false;
*out_k = Shape::Unwrap(k);
return true;
}
template <typename KeyT>
bool BaseShape<KeyT>::IsKey(ReadOnlyRoots roots, Object* key) {
return IsLive(roots, key);
}
template <typename KeyT>
bool BaseShape<KeyT>::IsLive(ReadOnlyRoots roots, Object* k) {
return k != roots.the_hole_value() && k != roots.undefined_value();
}
template <typename Derived, typename Shape>
HashTable<Derived, Shape>* HashTable<Derived, Shape>::cast(Object* obj) {
SLOW_DCHECK(obj->IsHashTable());
return reinterpret_cast<HashTable*>(obj);
}
template <typename Derived, typename Shape>
const HashTable<Derived, Shape>* HashTable<Derived, Shape>::cast(
const Object* obj) {
SLOW_DCHECK(obj->IsHashTable());
return reinterpret_cast<const HashTable*>(obj);
}
bool ObjectHashSet::Has(Isolate* isolate, Handle<Object> key, int32_t hash) {
return FindEntry(ReadOnlyRoots(isolate), key, hash) != kNotFound;
}
bool ObjectHashSet::Has(Isolate* isolate, Handle<Object> key) {
Object* hash = key->GetHash();
if (!hash->IsSmi()) return false;
return FindEntry(ReadOnlyRoots(isolate), key, Smi::ToInt(hash)) != kNotFound;
}
} // namespace internal
} // namespace v8
#endif // V8_OBJECTS_HASH_TABLE_INL_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
367da917e2597397a765a1293884a9c8616ea6e2 | 41d6b7e3b34b10cc02adb30c6dcf6078c82326a3 | /src/plugins/poshuku/plugins/webkitview/jsproxy.h | db046cad07d0b86a93f82f5e71b95103b6c594d4 | [
"BSL-1.0"
] | permissive | ForNeVeR/leechcraft | 1c84da3690303e539e70c1323e39d9f24268cb0b | 384d041d23b1cdb7cc3c758612ac8d68d3d3d88c | refs/heads/master | 2020-04-04T19:08:48.065750 | 2016-11-27T02:08:30 | 2016-11-27T02:08:30 | 2,294,915 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,987 | h | /**********************************************************************
* LeechCraft - modular cross-platform feature rich internet client.
* Copyright (C) 2006-2014 Georg Rudoy
*
* Boost Software License - Version 1.0 - August 17th, 2003
*
* Permission is hereby granted, free of charge, to any person or organization
* obtaining a copy of the software and accompanying documentation covered by
* this license (the "Software") to use, reproduce, display, distribute,
* execute, and transmit the Software, and to prepare derivative works of the
* Software, and to permit third-parties to whom the Software is furnished to
* do so, all subject to the following:
*
* The copyright notices in the Software and this entire statement, including
* the above license grant, this restriction and the following disclaimer,
* must be included in all copies of the Software, in whole or in part, and
* all derivative works of the Software, unless such copies or derivative
* works are solely in the form of machine-executable object code generated by
* a source language processor.
*
* 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
* SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
* FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
**********************************************************************/
#pragma once
#include <QObject>
#include <QVariant>
#include "customwebpage.h"
namespace LeechCraft
{
namespace Poshuku
{
namespace WebKitView
{
class JSProxy : public QObject
{
Q_OBJECT
public:
using QObject::QObject;
public slots:
void debug (const QString& str);
void warning (const QString& str);
};
}
}
}
| [
"0xd34df00d@gmail.com"
] | 0xd34df00d@gmail.com |
e3bc1f2e91163d18e46cde6ed2f20fb72b7b4fce | e4aa15885d471218adaf4ca6ec0233c1f2843497 | /include/raimd/md_dict.h | 46567824f2d5ee570fc02b6a3ee3c17ada5164c5 | [
"Apache-2.0"
] | permissive | raitechnology/raimd | a9f17717bcb384673def7f83cd03f48557b2dac6 | accffe44641e5691eeb4fe7a3093ba4b08e8d53b | refs/heads/master | 2023-08-16T13:14:52.173911 | 2023-06-13T21:32:52 | 2023-06-13T21:32:52 | 184,467,963 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 19,215 | h | #ifndef __rai_raimd__md_dict_h__
#define __rai_raimd__md_dict_h__
#include <raimd/md_types.h>
namespace rai {
namespace md {
/* The MDDict is a fid -> fname / type map, using 4 tables (+enums):
* * type table, uint32_t size,
* Each element indictes size and type of field,
* The lower 5 bits is the type, the upper 27 bits is the size
* el[ type_id ] = ( field_size << 27 ) | ( field_type )
* The number of elements in the table is ( 1 << type_shft )
* The type_id is encoded into the fid table to indicate the type
* This table enumerates all of the types used.. this is usually
* less than 64 types (56 in my dictionary).
* * fid table, bit array
* This is an array of bits indexed by fid - min_fid
* The string of bits used at this offset is tab_bits
* The bits are
* el[ fid bit offset ] = ( type_idx << N ) | field_offset
* Where N is ( fname_shft - fname_algn )
* * fname table, byte array
* This is an array of bytes for each field name prefixed by the
* length of the field name string length.
* The size of the table is ( 1 << fname_shft ), and each field
* is aligned on the ( 1 << fname_algn ) boundary.
* The index stored in the fid table is ( byte_index >> fname_algn )
* * fname hash, bit array
* This hashes the fnames to fids, it is a linear hash table where each
* slot is a bit string big enough (usually 14 bits) to fit ( fid -
* min_fid + 1 ) or zero when empty.
* The hash used is MDDict::dict_hash( fname, fnamelen )
* The size of the table is a power of 2 greater than
* 2 * entry count.
* Entry count is the count of fnames, it may be less than the number of
* fids if a fname maps to more than one fid (a common warning that occurs
* in many live systems).
* * enum tables, array of tables, one for each enum definition
* The tables are indexed by the type of the field. The field_size
* is a table number, so a enum type is encoded as:
* fid type = ( ( map num + 1 ) << 27 ) | MD_ENUM
* Each map table is a MDEnumMap structure, which is either an array
* of strings or a sorted array of enum values to strings when enum
* mappings are sparse. The enum strings are a fixed size.
* A dense map of a 3 char enum string would be
* [ " ", "ASE", "NYS", "BOS", etc ] where 0 = " ", 1 = "ASE"
* A sparse map
* [ 0, 4, 8, 12 ], [ " ", "AFA", "ALL", "DZD" ] where 4 = "AFA"
*/
struct MDDict {
/*
* [ type table (uint32 elem) ] = offset 0 (sizeof(MDDict))
* [ fid table (tab bits elem) ] = offset tab_off (+ntypes * uint32)
* [ fname table (string elem) ] = offset fname_off (+fid_bits * nfids)
* [ fname ht (tab bits ht) ] = offset ht_off (+fnamesz ht_off - fname_off)
* [ enum off (uint32_t off) ] = offset map_off (+fid_bits * ht_size)
*/
MDDict * next; /* list of multiple dictionaries (usually just 2, cfile&RDM )*/
char dict_type[ 8 ]; /* cfile or RDM(app_a) */
MDFid min_fid, /* minumum fid indexed */
max_fid; /* maximum fid indexed, inclusive */
uint32_t tab_off, /* offset of bit array table */
tab_size, /* size in bytes of bit array table */
ht_off, /* offset of fname hash */
ht_size, /* size in fids of ht */
entry_count, /* number of fids in the table */
fname_off, /* offset of fname start */
map_off, /* offset of enum map index */
map_count, /* count of enum maps */
dict_size; /* sizeof this + tables */
uint8_t type_shft, /* how many bits used for the type */
fname_shft, /* how many bits used for fname offset */
fname_algn, /* what byte alignment used for fname */
tab_bits, /* = type_shft + fname_shft - fname_algn*/
fid_bits, /* number of bits needed for a fid - min_fid + 1 */
pad[ 3 ]; /* pad to an int32 size */
/* used by get() below */
static uint32_t dict_hash( const void *key, size_t len,
uint32_t seed ) noexcept;
/* lookup fid, return {type, size, name/len} if found */
bool lookup( MDFid fid, MDType &ftype, uint32_t &fsize,
uint8_t &flags, uint8_t &fnamelen, const char *&fname ) const {
if ( fid < this->min_fid || fid > this->max_fid )
return false;
uint32_t bits = this->tab_bits, /* fname offset + type bits */
mask = ( 1U << bits ) - 1,
i = ( (uint32_t) fid - (uint32_t) this->min_fid ) * bits,
off = i / 8, /* byte offset for fid entry */
shft = i % 8, /* shift from byte offset */
fname_bits = ( this->fname_shft - this->fname_algn ),
fname_mask = ( 1U << fname_bits ) - 1,
type_idx,
fname_idx;
uint64_t val; /* bits at offset copied into val */
/* get the bits assoc with fid at bit index tab[ ( fid-min_fid ) * bits ] */
const uint8_t * tab = &((const uint8_t *) (void *) this)[ this->tab_off ];
val = tab[ off ] | ( tab[ off + 1 ] << 8 ) | ( tab[ off + 2 ] << 16 )
| ( tab[ off + 3 ] << 24 );
for ( off += 4; off * 8 < bits + shft; off++ )
val |= (uint64_t) tab[ off ] << ( off * 8 );
/* the type of the fid is first, then the fname index */
type_idx = ( val >> shft ) & mask;
if ( type_idx == 0 ) /* ftype is never zero (MD_NONE), zero is not found */
return false;
fname_idx = ( type_idx & fname_mask ) << this->fname_algn;
type_idx = type_idx >> fname_bits;
/* get the type/size using the type_idx from the type table */
const uint32_t * ttab = (const uint32_t *) (void *) &this[ 1 ];
ftype = (MDType) ( ttab[ type_idx ] & 0x1f );
flags = ( ttab[ type_idx ] >> 5 ) & 0x3;
fsize = ttab[ type_idx ] >> 7;
/* get the field name */
const uint8_t * fntab =
&((const uint8_t *) (void *) this)[ this->fname_off ];
fnamelen = fntab[ fname_idx ];
fname = (const char *) &fntab[ fname_idx + 1 ];
return true;
}
/* get a field by name, return {fid, type, size} if found */
bool get( const char *fname, uint8_t fnamelen, MDFid &fid, MDType &ftype,
uint32_t &fsize, uint8_t &flags ) const {
uint32_t h = dict_hash( fname, fnamelen, 0 ) & ( this->ht_size - 1 );
uint32_t bits = this->fid_bits, /* size in bits of each hash entry */
mask = ( 1U << bits ) - 1, /* mask for bits */
val;
/* the hash table */
const uint8_t * tab = &((const uint8_t *) (void *) this)[ this->ht_off ];
const char * fn; /* field name */
uint8_t len; /* field name length */
/* scan the linear hash table until found or zero (not found) */
for ( ; ; h = ( h + 1 ) & ( this->ht_size - 1 ) ) {
uint32_t i = h * bits,
off = i / 8,
shft = i % 8;
val = tab[ off ] | ( tab[ off + 1 ] << 8 ) | ( tab[ off + 2 ] << 16 )
| ( tab[ off + 3 ] << 24 );
val = ( val >> shft ) & mask;
if ( val == 0 ) /* if end of hash chain */
return false;
val = val + this->min_fid - 1;
/* val is the fid contained at this position */
if ( this->lookup( val, ftype, fsize, flags, len, fn ) ) {
if ( len == fnamelen && ::memcmp( fn, fname, len ) == 0 ) {
fid = val;
return true;
}
}
}
}
/* get display text using fid & value */
bool get_enum_text( MDFid fid, uint16_t val, const char *&disp,
size_t &disp_len ) noexcept;
/* get display text using map number & value */
bool get_enum_map_text( uint32_t map_num, uint16_t val, const char *&disp,
size_t &disp_len ) noexcept;
/* get value using fid & display text (reverse lookup) */
bool get_enum_val( MDFid fid, const char *disp, size_t disp_len,
uint16_t &val ) noexcept;
/* get value using map num & display text (reverse lookup) */
bool get_enum_map_val( uint32_t map_num, const char *disp, size_t disp_len,
uint16_t &val ) noexcept;
};
enum MDDictDebugFlags {
MD_DICT_NONE = 0,
MD_DICT_PRINT_FILES = 1
};
/* The following structures are used to build the MDDict, only used when
* building the index */
struct MDDictIdx;
struct MDDictEntry;
struct MDDictBuild {
MDDictIdx * idx;
int debug_flags;
MDDictBuild() : idx( 0 ), debug_flags( 0 ) {}
~MDDictBuild() noexcept;
MDDictIdx *get_dict_idx( void ) noexcept;
int add_entry( MDFid fid, uint32_t fsize, MDType ftype, uint8_t flags,
const char *fname, const char *name, const char *ripple,
const char *filename, uint32_t lineno,
MDDictEntry **eret = NULL ) noexcept;
int add_enum_map( uint32_t map_num, uint16_t max_value, uint32_t value_cnt,
uint16_t *value, uint16_t val_len, uint8_t *map ) noexcept;
int index_dict( const char *dtype, MDDict *&dict ) noexcept;
void clear_build( void ) noexcept;
};
template <class LIST>
struct MDQueue { /* list used for fields and files */
LIST * hd, * tl;
MDQueue() : hd( 0 ), tl( 0 ) {}
void init( void ) {
this->hd = this->tl = NULL;
}
bool is_empty( void ) const {
return this->hd == NULL;
}
void push_hd( LIST *p ) {
p->next = this->hd;
if ( this->hd == NULL )
this->tl = p;
this->hd = p;
}
void push_tl( LIST *p ) {
if ( this->tl == NULL )
this->hd = p;
else
this->tl->next = p;
this->tl = p;
}
LIST * pop( void ) {
LIST * p = this->hd;
if ( p != NULL ) {
if ( (this->hd = p->next) == NULL )
this->tl = NULL;
p->next = NULL;
}
return p;
}
};
struct MDEntryData { /* buffers for structures */
MDEntryData * next;
size_t off;
uint8_t data[ 320 * 1024 - 64 ]; /* should only need one of these */
void * operator new( size_t, void *ptr ) { return ptr; }
MDEntryData() : next( 0 ), off( 0 ) {}
void * alloc( size_t sz ) {
size_t len = ( sz + 7 ) & ~(size_t) 7,
i = this->off;
if ( this->off + len > sizeof( this->data ) )
return NULL;
this->off += len;
return (void *) &this->data[ i ];
}
};
static const size_t DICT_BUF_PAD = 4;
struct MDDictEntry {
MDDictEntry * next;
MDFid fid; /* fid of field */
uint32_t fsize, /* size of element */
fno, /* line and filename index of field definition */
hash; /* hash of field name (for dup fid checking) */
MDType ftype; /* type of field */
uint8_t fnamelen, /* len of fname (including nul char) */
namelen, /* len of name */
ripplelen, /* len of ripple */
enum_len, /* len of enum string */
mf_type, /* MF_TIME, MF_ALPHANUMERIC, .. */
rwf_type, /* RWF_REAL, RWF_ENUM, ... */
fld_flags; /* is_primitive, is_fixed */
uint16_t mf_len; /* size of field mf data (string length) */
uint32_t rwf_len; /* size of field rwf data (binary coded) */
char buf[ DICT_BUF_PAD ]; /* fname, name, ripple */
void * operator new( size_t, void *ptr ) { return ptr; }
MDDictEntry() : next( 0 ), fid( 0 ), fsize( 0 ), fno( 0 ), hash( 0 ),
ftype( MD_NODATA ), fnamelen( 0 ), namelen( 0 ),
ripplelen( 0 ), enum_len( 0 ), mf_type( 0 ), rwf_type( 0 ),
fld_flags( 0 ), mf_len( 0 ), rwf_len( 0 ) {}
const char *fname( void ) const {
return this->buf;
}
const char *name( void ) const {
return &(this->fname())[ this->fnamelen ];
}
const char *ripple( void ) const {
return &(this->name())[ this->namelen ];
}
};
struct MDDupHash {
uint8_t ht1[ 64 * 1024 / 8 ],
ht2[ 64 * 1024 / 8 ];
void * operator new( size_t, void *ptr ) { return ptr; }
void zero( void ) {
::memset( this->ht1, 0, sizeof( this->ht1 ) );
::memset( this->ht2, 0, sizeof( this->ht2 ) );
}
MDDupHash() { this->zero(); }
bool test_set( uint32_t h ) noexcept;
};
struct MDTypeHash {
uint32_t htshft, /* hash of types used by fields, tab size = 1 << htshft */
htsize, /* 1 << htshft */
htcnt, /* count of elements used */
ht[ 1 ]; /* each element is ( size << 5 ) | field type */
void * operator new( size_t, void *ptr ) { return ptr; }
MDTypeHash() : htshft( 0 ), htsize( 0 ), htcnt( 0 ) {}
static uint32_t alloc_size( uint32_t shft ) {
uint32_t htsz = ( 1U << shft );
return sizeof( MDTypeHash ) + ( ( htsz - 1 ) * sizeof( uint32_t ) );
}
void init( uint32_t shft ) {
uint32_t htsz = ( 1U << shft );
this->htshft = shft;
this->htsize = htsz;
::memset( this->ht, 0, sizeof( uint32_t ) * htsz ); /* zero is empty */
}
bool insert( uint32_t x ) noexcept; /* insert unique, if full, return false */
uint32_t find( uint32_t x ) noexcept; /* find element, return index of type */
bool insert( MDType ftype, uint32_t fsize, uint8_t flags ) {
return this->insert( ( fsize << 7 ) | ( (uint32_t) ( flags & 3 ) << 5 ) |
(uint32_t) ftype );
}
uint32_t find( MDType ftype, uint32_t fsize, uint8_t flags ) {
return this->find( ( fsize << 7 ) | ( (uint32_t) ( flags & 3 ) << 5 ) |
(uint32_t) ftype );
}
};
struct MDFilename {
MDFilename * next;
uint32_t id; /* filename + line number, location for dict errors */
char filename[ DICT_BUF_PAD ];
void * operator new( size_t, void *ptr ) { return ptr; }
MDFilename() : next( 0 ), id( 0 ) {}
};
struct MDEnumMap {
uint32_t map_num, /* map type number */
value_cnt; /* count of values, n -> max_value+1 */
uint16_t max_value, /* enum from 0 -> max_value, inclusive */
map_len; /* size of the enum value, same for each entry */
static size_t map_sz( size_t value_cnt, size_t max_value, size_t map_len ) {
size_t sz = ( map_len * value_cnt + 3U ) & ~3U;
if ( value_cnt == max_value + 1 )
return sz;
return sz + sizeof( uint16_t ) * ( ( value_cnt + 1U ) & ~1U );
}
size_t map_sz( void ) const {
return map_sz( this->value_cnt, this->max_value, this->map_len );
}
uint16_t *value( void ) {
if ( this->value_cnt == (uint32_t) this->max_value + 1 )
return NULL;
return (uint16_t *) (void *) &this[ 1 ];
}
uint8_t *map( void ) {
uint32_t off = ( ( this->value_cnt == (uint32_t) this->max_value + 1 ) ?
0 : ( ( this->value_cnt + 1U ) & ~1U ) );
uint16_t * value_cp = (uint16_t *) (void *) &this[ 1 ];
return (uint8_t *) (void *) &value_cp[ off ];
}
};
struct MDEnumList {
MDEnumList * next;
MDEnumMap map;
void * operator new( size_t, void *ptr ) { return ptr; }
MDEnumList() : next( 0 ) {}
};
struct MDDictIdx {
MDQueue< MDEntryData > data_q; /* data buffers */
MDQueue< MDDictEntry > entry_q; /* list of all fields */
MDQueue< MDEnumList > enum_q; /* list of all enum mappings */
MDQueue< MDFilename > file_q; /* list of all dict files */
MDDupHash * dup_hash; /* duplicate filter, doesn't store value, just hash */
MDTypeHash * type_hash; /* hash of all fid types */
MDFid min_fid, /* minimum fid seen, updated as fields are processed*/
max_fid; /* maximum fid seen */
size_t entry_count, /* cnt of field names, fids may map to same name */
map_cnt, /* count of enum maps */
map_size; /* size of all enum maps */
static const size_t ENUM_HTSZ = 1024;
MDDictEntry * enum_ht[ ENUM_HTSZ ];
void * operator new( size_t, void *ptr ) { return ptr; }
void operator delete( void *ptr ) { ::free( ptr ); }
MDDictIdx() : dup_hash( 0 ), type_hash( 0 ), min_fid( 0 ), max_fid( 0 ),
entry_count( 0 ), map_cnt( 0 ), map_size( 0 ) {
::memset( this->enum_ht, 0, sizeof( this->enum_ht ) );
}
~MDDictIdx() noexcept;
uint32_t file_lineno( const char *filename, uint32_t lineno ) noexcept;
uint32_t check_dup( const char *fname, uint8_t fnamelen,
bool &xdup ) noexcept;
size_t total_size( void ) noexcept;
size_t fname_size( uint8_t &shft, uint8_t &align ) noexcept;
template< class TYPE > TYPE * alloc( size_t sz ) noexcept;
};
struct DictParser {
DictParser * next; /* list of files pushed after included */
FILE * fp; /* fopen of file */
const char * str_input; /* when input from a string */
size_t str_size, /* size left of input string */
off, /* index into buf[] where reading */
len, /* length of buf[] filled */
tok_sz; /* length of tok_buf[] token */
int tok, /* token kind enumerated */
lineno, /* current line of input */
col, /* current column of input */
br_level; /* brace level == 0, none > 1 ( deep ) */
bool is_eof; /* consumed all of file */
char buf[ 1024 ], /* current input block */
tok_buf[ 1024 ], /* current token */
fname[ 1024 ]; /* current file name */
static const int EOF_CHAR = 256; /* int value signals end of file */
const int int_tok, /* int value of token */
ident_tok, /* token enum for identifier */
error_tok, /* token enum for error */
debug_flags;/* verbosity of parser debugging */
const char * dict_kind; /* what kind of dict this is */
DictParser( const char *p, int intk, int identk, int errk, int fl,
const char *k ) :
next( 0 ), fp( 0 ), str_input( 0 ), str_size( 0 ), off( 0 ), len( 0 ),
tok_sz( 0 ), col( 0 ), br_level( 0 ), is_eof( false ),
int_tok( intk ), ident_tok( identk ), error_tok( errk ),
debug_flags( fl ), dict_kind( k ) {
size_t len = 0;
if ( p != NULL ) {
len = ::strlen( p );
if ( len > sizeof( this->fname ) - 1 )
len = sizeof( this->fname ) - 1;
::memcpy( this->fname, p, len );
}
this->fname[ len ] = '\0';
this->tok = -1;
this->lineno = 1;
}
void open( void ) {
this->fp = fopen( this->fname, "r" );
}
void close( void ) {
this->is_eof = true;
if ( this->fp != NULL ) {
::fclose( this->fp );
this->fp = NULL;
}
}
bool fillbuf( void ) noexcept;
bool get_char( size_t i, int &c ) noexcept;
int eat_white( void ) noexcept;
void eat_comment( void ) noexcept;
bool match( const char *s, size_t sz ) noexcept;
int consume_tok( int k, size_t sz ) noexcept;
int consume_int_tok( void ) noexcept;
int consume_ident_tok( void ) noexcept;
int consume_string_tok( void ) noexcept;
static bool find_file( const char *path, const char *filename,
size_t file_sz, char *path_found ) noexcept;
};
}
}
#endif
| [
"chris@raitechnology.com"
] | chris@raitechnology.com |
6773a1c9ac9b4ad20bf7cd852217c072d2ea27e5 | ff4c8b2026d51917f92934e7762e32ffde4a6827 | /Template/Source/Math/pell.cpp | ea5cee833c6429dc5ddc4e51ebc6d7e877c2a2a5 | [] | no_license | smallling/SJTU_ACM_Platelet | db25b41c57b8b957a282e208260be3c21735c30a | 7f1fffd9a5b601c42ccf7b15630a275bfb3a9b30 | refs/heads/master | 2020-03-23T06:51:03.639087 | 2018-12-10T12:55:02 | 2018-12-10T12:55:02 | 141,233,137 | 6 | 2 | null | 2018-07-17T12:30:16 | 2018-07-17T04:55:45 | Vim script | UTF-8 | C++ | false | false | 536 | cpp | std::pair<int64_t, int64_t> pell(int64_t n) {
static int64_t p[N], q[N], g[N], h[N], a[N];
p[1] = q[0] = h[1] = 1;
p[0] = q[1] = g[1] = 0;
a[2] = std::sqrt(n) + 1e-7L;
for (int i = 2; true; i++) {
g[i] = -g[i - 1] + a[i] * h[i - 1];
h[i] = (n - g[i] * g[i]) / h[i - 1];
a[i + 1] = (g[i] + a[2]) / h[i];
p[i] = a[i] * p[i - 1] + p[i - 2];
q[i] = a[i] * q[i - 1] + q[i - 2];
if (p[i] * p[i] - n * q[i] * q[i] == 1)
return std::make_pair(p[i], q[i]);
}
}
| [
"wuqing157@gmail.com"
] | wuqing157@gmail.com |
d982ac090648280763539a29b2200e26048ff101 | 506dd031197e564045ec24acffe72d0c887d7e8a | /src/evo/deterministicmns.h | 8579b25658cd0b29dae3f7ab244220c814fe6d0e | [
"MIT"
] | permissive | cryptowithacause/cryptocause-coin | 031278de1382e56153fe0f52c8b52138d36fe3d3 | f68f3ed504094f8780db4d78d0aef2089a2198a9 | refs/heads/master | 2022-04-25T10:12:17.418805 | 2020-04-29T13:54:09 | 2020-04-29T13:54:09 | 259,937,823 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 16,468 | h | // Copyright (c) 2018 The Dash Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef CWAC_DETERMINISTICMNS_H
#define CWAC_DETERMINISTICMNS_H
#include "arith_uint256.h"
#include "bls/bls.h"
#include "dbwrapper.h"
#include "evodb.h"
#include "providertx.h"
#include "simplifiedmns.h"
#include "sync.h"
#include "immer/map.hpp"
#include "immer/map_transient.hpp"
#include <map>
class CBlock;
class CBlockIndex;
class CValidationState;
namespace llmq
{
class CFinalCommitment;
}
class CDeterministicMNState
{
public:
int nRegisteredHeight{-1};
int nLastPaidHeight{0};
int nPoSePenalty{0};
int nPoSeRevivedHeight{-1};
int nPoSeBanHeight{-1};
uint16_t nRevocationReason{CProUpRevTx::REASON_NOT_SPECIFIED};
// the block hash X blocks after registration, used in quorum calculations
uint256 confirmedHash;
// sha256(proTxHash, confirmedHash) to speed up quorum calculations
// please note that this is NOT a double-sha256 hash
uint256 confirmedHashWithProRegTxHash;
CKeyID keyIDOwner;
CBLSLazyPublicKey pubKeyOperator;
CKeyID keyIDVoting;
CService addr;
CScript scriptPayout;
CScript scriptOperatorPayout;
public:
CDeterministicMNState() {}
CDeterministicMNState(const CProRegTx& proTx)
{
keyIDOwner = proTx.keyIDOwner;
pubKeyOperator.Set(proTx.pubKeyOperator);
keyIDVoting = proTx.keyIDVoting;
addr = proTx.addr;
scriptPayout = proTx.scriptPayout;
}
template <typename Stream>
CDeterministicMNState(deserialize_type, Stream& s)
{
s >> *this;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(nRegisteredHeight);
READWRITE(nLastPaidHeight);
READWRITE(nPoSePenalty);
READWRITE(nPoSeRevivedHeight);
READWRITE(nPoSeBanHeight);
READWRITE(nRevocationReason);
READWRITE(confirmedHash);
READWRITE(confirmedHashWithProRegTxHash);
READWRITE(keyIDOwner);
READWRITE(pubKeyOperator);
READWRITE(keyIDVoting);
READWRITE(addr);
READWRITE(*(CScriptBase*)(&scriptPayout));
READWRITE(*(CScriptBase*)(&scriptOperatorPayout));
}
void ResetOperatorFields()
{
pubKeyOperator.Set(CBLSPublicKey());
addr = CService();
scriptOperatorPayout = CScript();
nRevocationReason = CProUpRevTx::REASON_NOT_SPECIFIED;
}
void BanIfNotBanned(int height)
{
if (nPoSeBanHeight == -1) {
nPoSeBanHeight = height;
}
}
void UpdateConfirmedHash(const uint256& _proTxHash, const uint256& _confirmedHash)
{
confirmedHash = _confirmedHash;
CSHA256 h;
h.Write(_proTxHash.begin(), _proTxHash.size());
h.Write(_confirmedHash.begin(), _confirmedHash.size());
h.Finalize(confirmedHashWithProRegTxHash.begin());
}
bool operator==(const CDeterministicMNState& rhs) const
{
return nRegisteredHeight == rhs.nRegisteredHeight &&
nLastPaidHeight == rhs.nLastPaidHeight &&
nPoSePenalty == rhs.nPoSePenalty &&
nPoSeRevivedHeight == rhs.nPoSeRevivedHeight &&
nPoSeBanHeight == rhs.nPoSeBanHeight &&
nRevocationReason == rhs.nRevocationReason &&
confirmedHash == rhs.confirmedHash &&
confirmedHashWithProRegTxHash == rhs.confirmedHashWithProRegTxHash &&
keyIDOwner == rhs.keyIDOwner &&
pubKeyOperator == rhs.pubKeyOperator &&
keyIDVoting == rhs.keyIDVoting &&
addr == rhs.addr &&
scriptPayout == rhs.scriptPayout &&
scriptOperatorPayout == rhs.scriptOperatorPayout;
}
bool operator!=(const CDeterministicMNState& rhs) const
{
return !(rhs == *this);
}
public:
std::string ToString() const;
void ToJson(UniValue& obj) const;
};
typedef std::shared_ptr<CDeterministicMNState> CDeterministicMNStatePtr;
typedef std::shared_ptr<const CDeterministicMNState> CDeterministicMNStateCPtr;
class CDeterministicMN
{
public:
CDeterministicMN() {}
template <typename Stream>
CDeterministicMN(deserialize_type, Stream& s)
{
s >> *this;
}
uint256 proTxHash;
COutPoint collateralOutpoint;
uint16_t nOperatorReward;
CDeterministicMNStateCPtr pdmnState;
public:
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(proTxHash);
READWRITE(collateralOutpoint);
READWRITE(nOperatorReward);
READWRITE(pdmnState);
}
public:
std::string ToString() const;
void ToJson(UniValue& obj) const;
};
typedef std::shared_ptr<CDeterministicMN> CDeterministicMNPtr;
typedef std::shared_ptr<const CDeterministicMN> CDeterministicMNCPtr;
class CDeterministicMNListDiff;
template <typename Stream, typename K, typename T, typename Hash, typename Equal>
void SerializeImmerMap(Stream& os, const immer::map<K, T, Hash, Equal>& m)
{
WriteCompactSize(os, m.size());
for (typename immer::map<K, T, Hash, Equal>::const_iterator mi = m.begin(); mi != m.end(); ++mi)
Serialize(os, (*mi));
}
template <typename Stream, typename K, typename T, typename Hash, typename Equal>
void UnserializeImmerMap(Stream& is, immer::map<K, T, Hash, Equal>& m)
{
m = immer::map<K, T, Hash, Equal>();
unsigned int nSize = ReadCompactSize(is);
for (unsigned int i = 0; i < nSize; i++) {
std::pair<K, T> item;
Unserialize(is, item);
m = m.set(item.first, item.second);
}
}
// For some reason the compiler is not able to choose the correct Serialize/Deserialize methods without a specialized
// version of SerReadWrite. It otherwise always chooses the version that calls a.Serialize()
template<typename Stream, typename K, typename T, typename Hash, typename Equal>
inline void SerReadWrite(Stream& s, const immer::map<K, T, Hash, Equal>& m, CSerActionSerialize ser_action)
{
::SerializeImmerMap(s, m);
}
template<typename Stream, typename K, typename T, typename Hash, typename Equal>
inline void SerReadWrite(Stream& s, immer::map<K, T, Hash, Equal>& obj, CSerActionUnserialize ser_action)
{
::UnserializeImmerMap(s, obj);
}
class CDeterministicMNList
{
public:
typedef immer::map<uint256, CDeterministicMNCPtr> MnMap;
typedef immer::map<uint256, std::pair<uint256, uint32_t> > MnUniquePropertyMap;
private:
uint256 blockHash;
int nHeight{-1};
MnMap mnMap;
// map of unique properties like address and keys
// we keep track of this as checking for duplicates would otherwise be painfully slow
// the entries in the map are ref counted as some properties might appear multiple times per MN (e.g. operator/owner keys)
MnUniquePropertyMap mnUniquePropertyMap;
public:
CDeterministicMNList() {}
explicit CDeterministicMNList(const uint256& _blockHash, int _height) :
blockHash(_blockHash),
nHeight(_height)
{
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(blockHash);
READWRITE(nHeight);
READWRITE(mnMap);
READWRITE(mnUniquePropertyMap);
}
public:
size_t GetAllMNsCount() const
{
return mnMap.size();
}
size_t GetValidMNsCount() const
{
size_t count = 0;
for (const auto& p : mnMap) {
if (IsMNValid(p.second)) {
count++;
}
}
return count;
}
template <typename Callback>
void ForEachMN(bool onlyValid, Callback&& cb) const
{
for (const auto& p : mnMap) {
if (!onlyValid || IsMNValid(p.second)) {
cb(p.second);
}
}
}
public:
const uint256& GetBlockHash() const
{
return blockHash;
}
void SetBlockHash(const uint256& _blockHash)
{
blockHash = _blockHash;
}
int GetHeight() const
{
return nHeight;
}
void SetHeight(int _height)
{
nHeight = _height;
}
bool IsMNValid(const uint256& proTxHash) const;
bool IsMNPoSeBanned(const uint256& proTxHash) const;
bool IsMNValid(const CDeterministicMNCPtr& dmn) const;
bool IsMNPoSeBanned(const CDeterministicMNCPtr& dmn) const;
bool HasMN(const uint256& proTxHash) const
{
return GetMN(proTxHash) != nullptr;
}
bool HasValidMN(const uint256& proTxHash) const
{
return GetValidMN(proTxHash) != nullptr;
}
bool HasMNByCollateral(const COutPoint& collateralOutpoint) const
{
return GetMNByCollateral(collateralOutpoint) != nullptr;
}
bool HasValidMNByCollateral(const COutPoint& collateralOutpoint) const
{
return GetValidMNByCollateral(collateralOutpoint) != nullptr;
}
CDeterministicMNCPtr GetMN(const uint256& proTxHash) const;
CDeterministicMNCPtr GetValidMN(const uint256& proTxHash) const;
CDeterministicMNCPtr GetMNByOperatorKey(const CBLSPublicKey& pubKey);
CDeterministicMNCPtr GetMNByCollateral(const COutPoint& collateralOutpoint) const;
CDeterministicMNCPtr GetValidMNByCollateral(const COutPoint& collateralOutpoint) const;
CDeterministicMNCPtr GetMNByService(const CService& service) const;
CDeterministicMNCPtr GetValidMNByService(const CService& service) const;
CDeterministicMNCPtr GetMNPayee() const;
/**
* Calculates the projected MN payees for the next *count* blocks. The result is not guaranteed to be correct
* as PoSe banning might occur later
* @param count
* @return
*/
std::vector<CDeterministicMNCPtr> GetProjectedMNPayees(int nCount) const;
/**
* Calculate a quorum based on the modifier. The resulting list is deterministically sorted by score
* @param maxSize
* @param modifier
* @return
*/
std::vector<CDeterministicMNCPtr> CalculateQuorum(size_t maxSize, const uint256& modifier) const;
std::vector<std::pair<arith_uint256, CDeterministicMNCPtr>> CalculateScores(const uint256& modifier) const;
/**
* Calculates the maximum penalty which is allowed at the height of this MN list. It is dynamic and might change
* for every block.
* @return
*/
int CalcMaxPoSePenalty() const;
/**
* Returns a the given percentage from the max penalty for this MN list. Always use this method to calculate the
* value later passed to PoSePunish. The percentage should be high enough to take per-block penalty decreasing for MNs
* into account. This means, if you want to accept 2 failures per payment cycle, you should choose a percentage that
* is higher then 50%, e.g. 66%.
* @param percent
* @return
*/
int CalcPenalty(int percent) const;
/**
* Punishes a MN for misbehavior. If the resulting penalty score of the MN reaches the max penalty, it is banned.
* Penalty scores are only increased when the MN is not already banned, which means that after banning the penalty
* might appear lower then the current max penalty, while the MN is still banned.
* @param proTxHash
* @param penalty
*/
void PoSePunish(const uint256& proTxHash, int penalty, bool debugLogs);
/**
* Decrease penalty score of MN by 1.
* Only allowed on non-banned MNs.
* @param proTxHash
*/
void PoSeDecrease(const uint256& proTxHash);
CDeterministicMNListDiff BuildDiff(const CDeterministicMNList& to) const;
CSimplifiedMNListDiff BuildSimplifiedDiff(const CDeterministicMNList& to) const;
CDeterministicMNList ApplyDiff(const CDeterministicMNListDiff& diff) const;
void AddMN(const CDeterministicMNCPtr& dmn);
void UpdateMN(const uint256& proTxHash, const CDeterministicMNStateCPtr& pdmnState);
void RemoveMN(const uint256& proTxHash);
template <typename T>
bool HasUniqueProperty(const T& v) const
{
return mnUniquePropertyMap.count(::SerializeHash(v)) != 0;
}
template <typename T>
CDeterministicMNCPtr GetUniquePropertyMN(const T& v) const
{
auto p = mnUniquePropertyMap.find(::SerializeHash(v));
if (!p) {
return nullptr;
}
return GetMN(p->first);
}
private:
template <typename T>
void AddUniqueProperty(const CDeterministicMNCPtr& dmn, const T& v)
{
static const T nullValue;
assert(v != nullValue);
auto hash = ::SerializeHash(v);
auto oldEntry = mnUniquePropertyMap.find(hash);
assert(!oldEntry || oldEntry->first == dmn->proTxHash);
std::pair<uint256, uint32_t> newEntry(dmn->proTxHash, 1);
if (oldEntry) {
newEntry.second = oldEntry->second + 1;
}
mnUniquePropertyMap = mnUniquePropertyMap.set(hash, newEntry);
}
template <typename T>
void DeleteUniqueProperty(const CDeterministicMNCPtr& dmn, const T& oldValue)
{
static const T nullValue;
assert(oldValue != nullValue);
auto oldHash = ::SerializeHash(oldValue);
auto p = mnUniquePropertyMap.find(oldHash);
assert(p && p->first == dmn->proTxHash);
if (p->second == 1) {
mnUniquePropertyMap = mnUniquePropertyMap.erase(oldHash);
} else {
mnUniquePropertyMap = mnUniquePropertyMap.set(oldHash, std::make_pair(dmn->proTxHash, p->second - 1));
}
}
template <typename T>
void UpdateUniqueProperty(const CDeterministicMNCPtr& dmn, const T& oldValue, const T& newValue)
{
if (oldValue == newValue) {
return;
}
static const T nullValue;
if (oldValue != nullValue) {
DeleteUniqueProperty(dmn, oldValue);
}
if (newValue != nullValue) {
AddUniqueProperty(dmn, newValue);
}
}
};
class CDeterministicMNListDiff
{
public:
uint256 prevBlockHash;
uint256 blockHash;
int nHeight{-1};
std::map<uint256, CDeterministicMNCPtr> addedMNs;
std::map<uint256, CDeterministicMNStateCPtr> updatedMNs;
std::set<uint256> removedMns;
public:
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action)
{
READWRITE(prevBlockHash);
READWRITE(blockHash);
READWRITE(nHeight);
READWRITE(addedMNs);
READWRITE(updatedMNs);
READWRITE(removedMns);
}
public:
bool HasChanges() const
{
return !addedMNs.empty() || !updatedMNs.empty() || !removedMns.empty();
}
};
class CDeterministicMNManager
{
static const int SNAPSHOT_LIST_PERIOD = 576; // once per day
static const int LISTS_CACHE_SIZE = 576;
public:
CCriticalSection cs;
private:
CEvoDB& evoDb;
std::map<uint256, CDeterministicMNList> mnListsCache;
int tipHeight{-1};
uint256 tipBlockHash;
public:
CDeterministicMNManager(CEvoDB& _evoDb);
bool ProcessBlock(const CBlock& block, const CBlockIndex* pindex, CValidationState& state, bool fJustCheck);
bool UndoBlock(const CBlock& block, const CBlockIndex* pindex);
void UpdatedBlockTip(const CBlockIndex* pindex);
// the returned list will not contain the correct block hash (we can't know it yet as the coinbase TX is not updated yet)
bool BuildNewListFromBlock(const CBlock& block, const CBlockIndex* pindexPrev, CValidationState& state, CDeterministicMNList& mnListRet, bool debugLogs);
void HandleQuorumCommitment(llmq::CFinalCommitment& qc, CDeterministicMNList& mnList, bool debugLogs);
void DecreasePoSePenalties(CDeterministicMNList& mnList);
CDeterministicMNList GetListForBlock(const uint256& blockHash);
CDeterministicMNList GetListAtChainTip();
// Test if given TX is a ProRegTx which also contains the collateral at index n
bool IsProTxWithCollateral(const CTransactionRef& tx, uint32_t n);
bool IsDIP3Enforced(int nHeight = -1);
private:
void CleanupCache(int nHeight);
};
extern CDeterministicMNManager* deterministicMNManager;
#endif //CWAC_DETERMINISTICMNS_H
| [
"64294729+cryptowithacause@users.noreply.github.com"
] | 64294729+cryptowithacause@users.noreply.github.com |
4dd8404bdf3d68888d3cfa3456ed8f57ffc57294 | cdb79e4ed5246ed423e31973150925b1eb6f6d29 | /src/potentials/sec_struct_restraint.cpp | f44c4b65af58149490450644cf6ed0de1b67c42c | [] | no_license | jmacdona/pd2_public | 6a0906e944878d954be29a245be718d3145c88e6 | 5b84579fd4a093e3095cd9bf15d2ca9d2b0b9b48 | refs/heads/master | 2020-03-08T09:27:34.373885 | 2019-03-25T15:38:21 | 2019-03-25T15:38:21 | 128,047,792 | 1 | 1 | null | 2018-04-11T09:42:33 | 2018-04-04T10:40:10 | C++ | UTF-8 | C++ | false | false | 2,248 | cpp | /*
* sec_struct_restraint.cpp
*
* Created on: 27 Jan 2011
* Author: jmacdona
*/
#include "sec_struct_restraint.h"
using namespace boost;
using namespace PRODART::UTILS;
using namespace PRODART;
using namespace PRODART::POSE;
using namespace PRODART::POSE::POTENTIALS;
using namespace PRODART::POSE::META;
using namespace PRODART::POSE_UTILS;
using namespace std;
namespace PRODART {
namespace POSE {
namespace POTENTIALS {
potential_shared_ptr new_sec_struct_restraint(){
potential_shared_ptr ptr(new sec_struct_restraint());
return ptr;
}
sec_struct_restraint::sec_struct_restraint() {
this->name_vector.clear();
this->name_vector.push_back(potentials_name("sec_struct_restraint"));
}
bool sec_struct_restraint::init(){
return true;
}
double sec_struct_restraint::get_energy(const PRODART::POSE::META::pose_meta_shared_ptr pose_meta_,
potentials_energies_map& energies_map) const{
const PRODART::POSE::four_state_sec_struct_vector& conf_class = pose_meta_->get_conf_class();
const PRODART::POSE::three_state_sec_struct_vector& sec_struct = pose_meta_->get_sec_struct();
const PRODART::POSE::four_state_sec_struct_vector& rsts = pose_meta_->get_sec_struct_restraint_list();
const double_vector& weights = pose_meta_->get_sec_struct_restraint_weight_list();
double total_energy = 0;
for (unsigned int i = 0; i < rsts.size(); i++){
const four_state_sec_struct ss_rst = rsts[i];
if (ss_rst != ss4_UNDEF){
const four_state_sec_struct cclass = conf_class[i];
const three_state_sec_struct secs = sec_struct[i];
const double weight = weights[i];
if (ss_rst == cclass){
total_energy += -0.5 * weight;
}
if (ss_rst == ss4_HELIX && secs == ss3_HELIX){
total_energy += -0.5 * weight;
}
else if (ss_rst == ss4_STRAND && secs == ss3_STRAND){
total_energy += -0.5 * weight;
}
else if (ss_rst == ss4_OTHER && secs == ss3_OTHER){
total_energy += -0.5 * weight;
}
}
}
return energies_map.add_energy_component(name_vector[0], total_energy);
}
double sec_struct_restraint::get_energy_with_gradient(const PRODART::POSE::META::pose_meta_shared_ptr pose_meta_,
potentials_energies_map& energies_map) const{
return this->get_energy(pose_meta_, energies_map);
}
}
}
}
| [
"jtmacdonald@gmail.com"
] | jtmacdonald@gmail.com |
313e54fbadc772357f6ce23acd40ebfd865df3a9 | 089e5b84a7b3fa2ae4af2a609b6648b64372b682 | /cpp/overload.cpp | 978e819627499e3a7bf708c10874f84da81c22e3 | [] | no_license | xusl/CodeDemo | c7c3ab96d843880b7497e337ec75c0a8ecc3b52a | 98bf47a9767bce8825cec67f02e423ea633f6867 | refs/heads/master | 2021-09-05T09:43:08.865635 | 2018-01-26T06:40:43 | 2018-01-26T06:40:43 | 103,500,065 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,381 | cpp | #include<iostream>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <sstream>
using namespace std;
#define MAX_LEN 256
#define FORMAT(x) "%"#x "s"
class base {
public:
base() {
cout << "base init" << endl;
};
~base() {
cout << "base destory" << endl;
};
//virtual void test_override(int num) = 0;
virtual void test_override(int num) {
cout << __LINE__ << "base :" << __func__ << ", " << num << endl;
}
virtual void test_overwrite(string text) {
cout << __LINE__ << "base :" << __func__ << ", " << text << endl;
}
};
class bar : public base{
public:
bar();
~bar();
void test_override(int num);
void test_overwrite(float f);
};
bar::bar() {
cout << "bar constructor" << endl;
}
bar::~bar() {
cout << "bar destroy" << endl;
}
void bar::test_override(int num) {
cout << __LINE__ << "bar :" << __func__ << ", " << num << endl;
}
void bar::test_overwrite(float f) {
cout << __LINE__ << "bar :" << __func__ << ", " << f << endl;
}
int main() {
bar bt;
base* b = &bt; //new bar();
b->test_override(3);
b->test_overwrite("hel");
bt.test_override(11);
bt.test_overwrite(0.000001);
//bt.test_overwrite("wooo");
return 0;
}
| [
"shenlong.xu.sz@tcl.com"
] | shenlong.xu.sz@tcl.com |
3a2eb4454f0a39da63e752f611b37297e19d335a | d9b573f026620973f27b5b68c16cb38d6bedd609 | /Double Pointer/No.633_Sum_of_Square_Numbers/633.cpp | 5f959799641c7c6cca35372baf71367c2d200462 | [] | no_license | mengxianghan123/leetcode | 9f35725b5037bff664dc22789654e137a5fc36ad | a4e0319e0dbd084630ee4d0778f00494e9702eac | refs/heads/master | 2023-05-09T02:03:36.530553 | 2021-06-01T04:44:56 | 2021-06-01T04:44:56 | 333,439,130 | 8 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 581 | cpp | // 双指针法(预存平方结果)
#include <cmath>
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
bool judgeSquareSum(int c) {
long long n = floor(sqrt(c));
vector<long long> num;
long long i = 0;
while (i <= n) {
num.push_back(i * i);
++i;
}
int l = 0, r = n;
while (l <= r) {
if (num[l] + num[r] == c) return true;
if (num[l] + num[r] < c)
++l;
else
--r;
}
return false;
}
};
int main() {
Solution sol;
cout << sol.judgeSquareSum(5) << endl;
} | [
"mengxianghan321@126.com"
] | mengxianghan321@126.com |
4aa80f164eb67ffb88499c4ddbaabc55f9399073 | abd51725ff8b57b131a7c1ce7e6cb5ef356aba85 | /examples/randomdots/src/randomdots.cpp | e3930fc087e7ecff9984d2b73e2efadec07a0edd | [
"Apache-2.0"
] | permissive | TheCoderRaman/pixel | 1489b092ce680b60fb38b8c400b0cd2842fd85d2 | c4411f67746fdd811aa5f8c102ac340e9eaf4ec5 | refs/heads/master | 2023-08-19T07:19:03.292627 | 2019-04-09T17:31:33 | 2019-04-09T17:31:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 878 | cpp | #include <pixel.hpp>
#include <thread>
#include <chrono>
using namespace std::literals::chrono_literals;
using namespace Pixel;
struct Point {
int x, y;
};
static const int npoint = 42;
static const int nstep = 50;
Point point[npoint];
void update_point_positions() {
for (int j = 0; j < npoint; ++j) {
point[j].x = rand() % 80;
point[j].y = rand() % 50;
}
}
int main() {
Window mainWindow(1920, 1080, "Hello world!");
Canvas canvas(80, 50);
for(int i=0; i<nstep; ++i) {
while (!mainWindow.shouldExit()) {
canvas.clear(Color::Blue);
update_point_positions();
for(int j=0; j < npoint; ++j)
{
canvas.plot(point[j].x, point[j].y, Color::Black);
}
mainWindow.show(canvas);
std::this_thread::sleep_for(400ms);
}
}
}
| [
"peter.bindels@tomtom.com"
] | peter.bindels@tomtom.com |
52404d382845a782ebb536322d84a3b96cb5432f | 7219fc9130c556742da08da7245d593ff2359a99 | /testobject.h | fe518ffcebfb88a1a85e0db3e6a61be53cd0d974 | [
"MIT"
] | permissive | saberhawk/hooksupport | 0be4b29b2c66b5844cb2738ea047c2a26948e362 | 5f88c4a6363bc130d3279d80adae5b16ea82bde2 | refs/heads/master | 2021-01-22T02:47:58.666540 | 2013-08-20T07:14:05 | 2013-08-20T07:27:01 | 12,236,937 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | h | #pragma once
// class hook rules:
// can't usually change base classes or order
// can't change size unless fully derived
// can't reorder instance variables
// can't reorder virtual methods
// can't add new virtual methods unless fully derived
// can add new instance fields in unused space
// can add/reorder static variables
// can add/reorder instance and static methods
class TestObject
{
public:
TestObject();
void Show();
void SetValue(int value) { Value = value; }
private:
bool CanShow();
short ShowCount; // 0
short TestCount; // 2 - new
int Value; // 4
}; // sizeof == 8
void RunObjectTests();
| [
"mark@derelictbase.com"
] | mark@derelictbase.com |
5e3e62434f448695ca04e284fe346af6c21e5c84 | ff244f7e6fa8f04294d48add511d0f0a1938310b | /base/task/task_scheduler/scheduler_worker.h | 37f4232d140a47deb89ea5216ae9ee09773a876b | [
"BSD-3-Clause"
] | permissive | javareact/chromium | 83c2a5faaefccaac692b58e1d52c20e94685d134 | 7657aa7a5001e0ae5dbbd3ce16622f4292364704 | refs/heads/master | 2023-01-13T10:10:09.853802 | 2019-04-10T08:01:55 | 2019-04-10T08:01:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,213 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef BASE_TASK_TASK_SCHEDULER_SCHEDULER_WORKER_H_
#define BASE_TASK_TASK_SCHEDULER_SCHEDULER_WORKER_H_
#include <memory>
#include "base/base_export.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/synchronization/atomic_flag.h"
#include "base/synchronization/waitable_event.h"
#include "base/task/task_scheduler/scheduler_lock.h"
#include "base/task/task_scheduler/scheduler_worker_params.h"
#include "base/task/task_scheduler/sequence.h"
#include "base/task/task_scheduler/tracked_ref.h"
#include "base/thread_annotations.h"
#include "base/threading/platform_thread.h"
#include "base/time/time.h"
#include "build/build_config.h"
#if defined(OS_WIN)
#include "base/win/com_init_check_hook.h"
#endif
namespace base {
class SchedulerWorkerObserver;
namespace internal {
class TaskTracker;
// A worker that manages a single thread to run Tasks from Sequences returned
// by a delegate.
//
// A SchedulerWorker starts out sleeping. It is woken up by a call to WakeUp().
// After a wake-up, a SchedulerWorker runs Tasks from Sequences returned by the
// GetWork() method of its delegate as long as it doesn't return nullptr. It
// also periodically checks with its TaskTracker whether shutdown has completed
// and exits when it has.
//
// This class is thread-safe.
class BASE_EXPORT SchedulerWorker
: public RefCountedThreadSafe<SchedulerWorker>,
public PlatformThread::Delegate {
public:
// Labels this SchedulerWorker's association. This doesn't affect any logic
// but will add a stack frame labeling this thread for ease of stack trace
// identification.
enum class ThreadLabel {
POOLED,
SHARED,
DEDICATED,
#if defined(OS_WIN)
SHARED_COM,
DEDICATED_COM,
#endif // defined(OS_WIN)
};
// Delegate interface for SchedulerWorker. All methods are called from the
// thread managed by the SchedulerWorker instance.
class BASE_EXPORT Delegate {
public:
virtual ~Delegate() = default;
// Returns the ThreadLabel the Delegate wants its SchedulerWorkers' stacks
// to be labeled with.
virtual ThreadLabel GetThreadLabel() const = 0;
// Called by |worker|'s thread when it enters its main function.
virtual void OnMainEntry(const SchedulerWorker* worker) = 0;
// Called by |worker|'s thread to get a Sequence from which to run a Task.
virtual scoped_refptr<Sequence> GetWork(SchedulerWorker* worker) = 0;
// Called by the SchedulerWorker after it ran a Task. If the Task's Sequence
// should be reenqueued, it is passed to |sequence|. Otherwise, |sequence|
// is nullptr.
virtual void DidRunTask(scoped_refptr<Sequence> sequence) = 0;
// Called to determine how long to sleep before the next call to GetWork().
// GetWork() may be called before this timeout expires if the worker's
// WakeUp() method is called.
virtual TimeDelta GetSleepTimeout() = 0;
// Called by the SchedulerWorker's thread to wait for work. Override this
// method if the thread in question needs special handling to go to sleep.
// |wake_up_event| is a manually resettable event and is signaled on
// SchedulerWorker::WakeUp()
virtual void WaitForWork(WaitableEvent* wake_up_event);
// Called by |worker|'s thread right before the main function exits. The
// Delegate is free to release any associated resources in this call. It is
// guaranteed that SchedulerWorker won't access the Delegate or the
// TaskTracker after calling OnMainExit() on the Delegate.
virtual void OnMainExit(SchedulerWorker* worker) {}
};
// Creates a SchedulerWorker that runs Tasks from Sequences returned by
// |delegate|. No actual thread will be created for this SchedulerWorker
// before Start() is called. |priority_hint| is the preferred thread priority;
// the actual thread priority depends on shutdown state and platform
// capabilities. |task_tracker| is used to handle shutdown behavior of Tasks.
// |predecessor_lock| is a lock that is allowed to be held when calling
// methods on this SchedulerWorker. |backward_compatibility| indicates
// whether backward compatibility is enabled. Either JoinForTesting() or
// Cleanup() must be called before releasing the last external reference.
SchedulerWorker(ThreadPriority priority_hint,
std::unique_ptr<Delegate> delegate,
TrackedRef<TaskTracker> task_tracker,
const SchedulerLock* predecessor_lock = nullptr,
SchedulerBackwardCompatibility backward_compatibility =
SchedulerBackwardCompatibility::DISABLED);
// Creates a thread to back the SchedulerWorker. The thread will be in a wait
// state pending a WakeUp() call. No thread will be created if Cleanup() was
// called. If specified, |scheduler_worker_observer| will be notified when the
// worker enters and exits its main function. It must not be destroyed before
// JoinForTesting() has returned (must never be destroyed in production).
// Returns true on success.
bool Start(SchedulerWorkerObserver* scheduler_worker_observer = nullptr);
// Wakes up this SchedulerWorker if it wasn't already awake. After this is
// called, this SchedulerWorker will run Tasks from Sequences returned by the
// GetWork() method of its delegate until it returns nullptr. No-op if Start()
// wasn't called. DCHECKs if called after Start() has failed or after
// Cleanup() has been called.
void WakeUp();
SchedulerWorker::Delegate* delegate() { return delegate_.get(); }
// Joins this SchedulerWorker. If a Task is already running, it will be
// allowed to complete its execution. This can only be called once.
//
// Note: A thread that detaches before JoinForTesting() is called may still be
// running after JoinForTesting() returns. However, it can't run tasks after
// JoinForTesting() returns.
void JoinForTesting();
// Returns true if the worker is alive.
bool ThreadAliveForTesting() const;
// Makes a request to cleanup the worker. This may be called from any thread.
// The caller is expected to release its reference to this object after
// calling Cleanup(). Further method calls after Cleanup() returns are
// undefined.
//
// Expected Usage:
// scoped_refptr<SchedulerWorker> worker_ = /* Existing Worker */
// worker_->Cleanup();
// worker_ = nullptr;
void Cleanup();
// Informs this SchedulerWorker about periods during which it is not being
// used. Thread-safe.
void BeginUnusedPeriod();
void EndUnusedPeriod();
// Returns the last time this SchedulerWorker was used. Returns a null time if
// this SchedulerWorker is currently in-use. Thread-safe.
TimeTicks GetLastUsedTime() const;
private:
friend class RefCountedThreadSafe<SchedulerWorker>;
class Thread;
~SchedulerWorker() override;
bool ShouldExit() const;
// Returns the thread priority to use based on the priority hint, current
// shutdown state, and platform capabilities.
ThreadPriority GetDesiredThreadPriority() const;
// Changes the thread priority to |desired_thread_priority|. Must be called on
// the thread managed by |this|.
void UpdateThreadPriority(ThreadPriority desired_thread_priority);
// PlatformThread::Delegate:
void ThreadMain() override;
// Dummy frames to act as "RunLabeledWorker()" (see RunMain() below). Their
// impl is aliased to prevent compiler/linker from optimizing them out.
void RunPooledWorker();
void RunBackgroundPooledWorker();
void RunSharedWorker();
void RunBackgroundSharedWorker();
void RunDedicatedWorker();
void RunBackgroundDedicatedWorker();
#if defined(OS_WIN)
void RunSharedCOMWorker();
void RunBackgroundSharedCOMWorker();
void RunDedicatedCOMWorker();
void RunBackgroundDedicatedCOMWorker();
#endif // defined(OS_WIN)
// The real main, invoked through :
// ThreadMain() -> RunLabeledWorker() -> RunWorker().
// "RunLabeledWorker()" is a dummy frame based on ThreadLabel+ThreadPriority
// and used to easily identify threads in stack traces.
void RunWorker();
// Self-reference to prevent destruction of |this| while the thread is alive.
// Set in Start() before creating the thread. Reset in ThreadMain() before the
// thread exits. No lock required because the first access occurs before the
// thread is created and the second access occurs on the thread.
scoped_refptr<SchedulerWorker> self_;
mutable SchedulerLock thread_lock_;
// Handle for the thread managed by |this|.
PlatformThreadHandle thread_handle_ GUARDED_BY(thread_lock_);
// The last time this worker was used by its owner (e.g. to process work or
// stand as a required idle thread).
TimeTicks last_used_time_ GUARDED_BY(thread_lock_);
// Event to wake up the thread managed by |this|.
WaitableEvent wake_up_event_{WaitableEvent::ResetPolicy::AUTOMATIC,
WaitableEvent::InitialState::NOT_SIGNALED};
// Whether the thread should exit. Set by Cleanup().
AtomicFlag should_exit_;
const std::unique_ptr<Delegate> delegate_;
const TrackedRef<TaskTracker> task_tracker_;
// Optional observer notified when a worker enters and exits its main
// function. Set in Start() and never modified afterwards.
SchedulerWorkerObserver* scheduler_worker_observer_ = nullptr;
// Desired thread priority.
const ThreadPriority priority_hint_;
// Actual thread priority. Can be different than |priority_hint_| depending on
// system capabilities and shutdown state. No lock required because all post-
// construction accesses occur on the thread.
ThreadPriority current_thread_priority_;
#if defined(OS_WIN) && !defined(COM_INIT_CHECK_HOOK_ENABLED)
const SchedulerBackwardCompatibility backward_compatibility_;
#endif
// Set once JoinForTesting() has been called.
AtomicFlag join_called_for_testing_;
DISALLOW_COPY_AND_ASSIGN(SchedulerWorker);
};
} // namespace internal
} // namespace base
#endif // BASE_TASK_TASK_SCHEDULER_SCHEDULER_WORKER_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b721f355aa53302cb9720951ddc78e4a102e0dbb | e1aef4e05f55c182832abe74006009129df04cb8 | /Vjezbe11-Narutofox/lista.h | 904da4d3709730fd4c8789c3a119bca4509a29d5 | [] | no_license | Narutofox/Algebra-SPA | b93e066e86fb708889ec818ebf1c0d985f1c9b94 | 21687cb5c46c7dbd8634a9b1a705f2e57b65086a | refs/heads/master | 2021-01-23T21:03:57.518470 | 2014-06-07T05:47:25 | 2014-06-07T05:47:25 | null | 0 | 0 | null | null | null | null | WINDOWS-1250 | C++ | false | false | 634 | h | #ifndef _LISTA_H_
#define _LISTA_H_
#include <string>
#include "student.h"
using namespace std;
typedef student ELTYPE; // Lista čuva studente.
struct cvor;
typedef cvor* POSITION;
struct cvor {
ELTYPE element;
POSITION previous;
POSITION next;
};
class lista {
private:
POSITION _head; // "Prvi ispred" početka liste.
POSITION _tail; // "Prvi iza" kraja liste.
public:
lista();
POSITION end();
POSITION first();
bool insert(ELTYPE element, POSITION pos);
bool read(POSITION pos, ELTYPE& element);
bool remove(POSITION pos);
POSITION empty();
POSITION next(POSITION pos);
POSITION prev(POSITION pos);
};
#endif | [
"cicekivan@gmail.com"
] | cicekivan@gmail.com |
49155991883efe26c8f07a4655f7778b1ec6d8dc | 42069212c627c54bf815e2a0ac64414e1b735c1b | /src/DirectedGraph.h | f48a5d300bb0a730e26d1c8f3830eb69bc01c315 | [] | no_license | vldmalov/HTMLParser | e8a1be18866147895560aafe6bc55510744653c8 | d8ec7d2f2456813635358a72e4db442c6af66b40 | refs/heads/master | 2020-02-26T16:07:30.980981 | 2017-09-18T21:41:29 | 2017-09-18T21:41:29 | 71,009,571 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 713 | h | #pragma once
#include <string>
#include <unordered_set>
#include <unordered_map>
struct GraphNode {
std::unordered_set<std::string> NodeIdsTo;
std::unordered_set<std::string> NodeIdsFrom;
};
typedef std::unordered_map<std::string, GraphNode> NodesMap;
class DirectedGraph {
public:
void addEdge(const std::string& nodeIdFrom, const std::string& nodeIdTo);
bool hasDirectEdge(const std::string& nodeIdFrom, const std::string& nodeIdTo) const;
bool hasLessThenTwoEdgeWay(const std::string& nodeIdFrom, const std::string& nodeIdTo) const;
void saveToFile(const std::string& fileName) const;
void loadFromFile(const std::string& fileName);
private:
NodesMap m_nodes;
};
| [
"vldmalov@gmail.com"
] | vldmalov@gmail.com |
d5f7cbf8cd86e5bf21d60de74f3bd7aec9114c58 | fc57402c4d8e200d2d2d297de92a302df464e834 | /UniversalLibs/Network/Packages/Streaming/iface/CNetNaturalSignalingIfaceGp.h | 747f8c3a71f60d628c224b6bce8b85d1cc58bde9 | [] | no_license | vladsopen/fragments | 07f5bb7e478c95db75e5091c86d3a9f8f7e180a8 | 41d59d0fc7ed3d0d3bd23c02136ab8f11c40df11 | refs/heads/master | 2022-01-11T23:29:21.562445 | 2019-07-03T21:23:34 | 2019-07-03T21:23:34 | 195,126,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,523 | h | // CNetNaturalSignalingIfaceGp.h
#pragma once
class CNetNaturalChannelTypeIfaceGp;
//
// CNetNaturalSignalingIfaceGp -
//
// Signal transfer for non-Uport devices.
//
//ASSUME_IMPL_FOR_IFACE(CNetNaturalSignalingIface, CNetNaturalSignalingIfaceGp)
//ASSUME_IMPL_FOR_IFACE(CNetNaturalSignalingImpl, CNetNaturalSignalingIface)
class CNetNaturalSignalingIfaceGp : public object
{
public:
CNetNaturalSignalingIfaceGp();
//~CNetNaturalSignalingIfaceGp();
//NEW_LOCAL(CNetNaturalSignalingImpl, CNetNaturalSignalingIfaceGp)
NEW_GP(Net, CNetNaturalSignalingImpl, CNetNaturalSignalingIfaceGp)
virtual void OnExposeContent(
ref<CExpose> rExpose);
// Constants
// Attributes
// parent
//ptr<> _x_p
// xauto(Get, Set);
// Operations
// One-time opener
//void InitNetNaturalSignaling();
// Cleanup
//void CloseNetNaturalSignaling();
// Read if ready, empty sbuf() means no data
bool IsReadingNaturalChannelSignal()
vhook;
sbuf ReadNaturalChannelSignal(
type<CNetNaturalChannelTypeIfaceGp> typeNetNaturalChannelType,
int nMinBytes,
int nMaxBytes,
out int& out_nErrorCount)
vhook;
// Queue for sending
bool IsSendingNaturalChannelSignal()
vhook;
void SendNaturalChannelSignal(
type<CNetNaturalChannelTypeIfaceGp> typeNetNaturalChannelType,
sbuf sbufSignal,
int nErrorCount)
vhook;
// UI
protected:
SEE_ALSO(CNetNaturalSignalingImpl) // F12-lookup
virtual bool OnIsReadingNaturalChannelSignal()
v1pure;
virtual sbuf OnReadNaturalChannelSignal(
type<CNetNaturalChannelTypeIfaceGp> typeNetNaturalChannelType,
int nMinBytes,
int nMaxBytes,
out int& out_nErrorCount)
v1pure;
virtual bool OnIsSendingNaturalChannelSignal()
v1pure;
virtual void OnSendNaturalChannelSignal(
type<CNetNaturalChannelTypeIfaceGp> typeNetNaturalChannelType,
sbuf sbufSignal,
int nErrorCount)
v1pure;
private:
//bool _m_bOneTimeInitNetNaturalSignalingIfaceGpOk = false;
//bool _m_bNetNaturalSignalingIfaceGpOpened = false;
void _init_AttachToNetNaturalSignalingIfaceGp();
//void cta_BeforeMethod(const DBeforeMethod& dataBeforeMethod);
//virtual void OnTestClass();
};
| [
"vladsprog@gmail.com"
] | vladsprog@gmail.com |
7d94f0e324b4a7f4e39899c23afbb723e50c355f | e214c23bbcae69fef20b2ba982f410789fdcf428 | /ネームバトラー/disp.cpp | 22f93236b9445558ba1994a9023d9e715ef23838 | [] | no_license | SakuraiNOOB2/MemeBattler | 1378fa4eed387b072ad17d11031d2eb1531f56c0 | d17216a4ff8ce35313e354be29d19e47ec0b8bfe | refs/heads/main | 2023-01-23T02:52:06.615209 | 2020-12-04T03:19:04 | 2020-12-04T03:19:04 | 318,389,255 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 6,163 | cpp | #include <stdio.h>
#include <string.h>
#include "disp.h"
//====================================================================================================//
//===================ここの関数は全部画像表示処理やBGMについての関数分割ファイルです==================//
//====================================================================================================//
//==========エフェクト音==========//
void effect(void) {
int check_effect;
char effect_path[100];
strcpy(effect_path, "big_oof.mp3");
check_effect = opensound(effect_path);
playsound(check_effect, 0);
closesound(check_effect);
}
//戦い始まったところに流すBGM
void effect2(void) {
int check_effect;
char effect_path[100];
strcpy(effect_path, "MLG_Horns.mp3");
check_effect = opensound(effect_path);
playsound(check_effect, 0);
closesound(check_effect);
}
//負けた時のBGM
void loseBGM(int onOff) {
int check_effect;
char effect_path[100];
strcpy(effect_path, "Mission_Failed.mp3");
check_effect = opensound(effect_path);
playsound(check_effect, 0);
if (onOff == 0) {
closesound(check_effect);
}
}
//勝った時のBGM
void winBGM(int onOff) {
int check_effect;
char effect_path[100];
strcpy(effect_path, "CRAB_RAVE.mp3");
check_effect = opensound(effect_path);
playsound(check_effect, 0);
if (onOff == 0) {
closesound(check_effect);
}
}
//======================画像表示処理================================//
//選択矢
void chooseArrow(int x, int y) {
gotoxy(x, y);
printf(" ●");
gotoxy(x, y+1);
printf("●●●");
gotoxy(x, y + 2);
printf(" ■");
gotoxy(x, y + 3);
printf(" ■");
}
//キャラクター読取の猫
void shock_cat(int x) {
gotoxy(x, 13);
printf(" /つ_∧");
gotoxy(x, 14);
printf(" /つ_,∧ 〈( ゚д゚)");
gotoxy(x, 15);
printf(" |( ゚д゚) ヽ ⊂ニ)");
gotoxy(x, 16);
printf(" ヽ__と/ ̄ ̄ ̄/ |");
gotoxy(x, 17);
printf(" ̄\/___/");
}
//殴る
void punch1(void) {
gotoxy(50, 15);
printf("∧_∧");
gotoxy(50, 16);
printf("・;'.、(・ω(:;(⊂=⊂≡ ");
gotoxy(50, 17);
printf("(っΣ⊂≡⊂=");
gotoxy(50, 18);
printf("/ ) ズバババ");
gotoxy(50, 19);
printf("( / ̄∪");
}
//キャラクター
void character1(int x,int y) {
gotoxy(10, y-5);
printf(" ∧");
gotoxy(10, y-4);
printf(" /´。 `ーァ");
gotoxy(10, y-3);
printf(" { 々 ゚l´");
gotoxy(10, y-2);
printf(" / っ /っ");
gotoxy(10, y-1);
printf("/ /");
gotoxy(10, y);
printf("∪^∪");
}
void character2(int x,int y) {
gotoxy(x, y-5);
printf(" m9 三 9m");
gotoxy(x, y-4);
printf(" 彡 ∧∧ ミ");
gotoxy(x, y-3);
printf("m9 (^Д^) 9m ");
gotoxy(x, y-2);
printf(" ヾヽ\ y ) 彡");
gotoxy(x, y-1);
printf(" m9/三 9m");
gotoxy(x, y);
printf(" ∪ ̄ ̄ ̄\)");
}
void character3(int x,int y) {
gotoxy(x, y-4);
printf(" ∧ ∧");
gotoxy(x, y-3);
printf(" /(*゚ー゚) /\");
gotoxy(x, y-2);
printf("/| ̄∪∪ ̄|\/");
gotoxy(x, y-1);
printf(" ヽ__と/ ̄ ̄ ̄/ |");
gotoxy(x, y);
printf(" | しぃ |/");
}
void character4(int x,int y) {
gotoxy(x, y-4);
printf(" ∧_∧");
gotoxy(x, y-3);
printf(" ( ^Д^)=9m≡9m");
gotoxy(x, y-2);
printf(" (m9 ≡m9=m9");
gotoxy(x, y-1);
printf(" / )");
gotoxy(x, y);
printf("( / ̄∪");
}
void character_choice(int x, int y, int choice) {
switch (choice) {
case 1:
character1(x, y);
break;
case 2:
character2(x, y);
break;
case 3:
character3(x, y);
break;
case 4:
character4(x, y);
break;
}
}
void winScreen(void) {
gotoxy(10, 15);
printf(" / ´ ̄ `(\ ");
gotoxy(10, 16);
printf(" / \-'、 「無敵の人は寂しいなぁ・・・」 ");
gotoxy(10, 17);
printf(" / ヽ ヽ");
gotoxy(10, 18);
printf(" _| | |");
gotoxy(10, 19);
printf(" ´! / 、/ ^ ──- 、_ ");
gotoxy(10, 20);
printf(" \.__ _ / //( _____/ `ヽ");
gotoxy(10, 21);
printf(" / ((( j─ ´ヽ// / \)ノノ ̄`\_ /^ヽ ");
gotoxy(10, 22);
printf(" (.  ̄ 人. i |____/ \| ̄ ̄ ノ");
gotoxy(10, 23);
printf(" ( ̄ ̄ ̄ ̄ / `ヽ、_ | ´_|__\ ` ─ 、_./ ");
gotoxy(10, 24);
printf("  ̄ ̄ ̄ ̄ ̄  ̄  ̄ ̄ (___ノ");
}
void loseScreen(void) {
gotoxy(10, 14);
printf(" /ヽ /ヽ");
gotoxy(10, 15);
printf(" / ヽ / ヽ");
gotoxy(10, 16);
printf(" ______ / ヽ__/ ヽ");
gotoxy(10, 17);
printf(" | ____ / :::::::::::::::\");
gotoxy(10, 18);
printf(" | | // \ :::::::::::::::|");
gotoxy(10, 19);
printf(" | | | ● ● ::::::::::::::| 弱い人こそ俺に負ける");
gotoxy(10, 20);
printf(" | | .| :::::::::::::|");
gotoxy(10, 21);
printf(" | | | (__人__丿 .....:::::::::::::::::::/");
gotoxy(10, 22);
printf(" | |____ ヽ .....:::::::::::::::::::::::<");
gotoxy(10, 23);
printf(" └___/ ̄ ̄ :::::::::::::::::::::::::|");
gotoxy(10, 24);
printf(" |\ | :::::::::::::::::::::::|");
gotoxy(10, 25);
printf(" \ \ \___ ::::::::::::::::::::::::|");
} | [
"52180510+SakuraiNOOB2@users.noreply.github.com"
] | 52180510+SakuraiNOOB2@users.noreply.github.com |
80d1e1560f28a3816f5c79c0ade83d0b707d89a7 | e3de0d8f74bb50fc755bff208a53a3ea07ac0d22 | /chapter 6/6-3/6-3-2.cpp | 8ec132b37d8ccdab12e5e2b666b4a2c575f70a34 | [] | no_license | Cobb-Yoo/c-programming-exercise | 39f8caa193c91f6e799f8ff53f167ad8254086c8 | 545bedab0a4793510143bc85dfe24271475e44ca | refs/heads/master | 2022-03-22T13:54:57.727888 | 2019-12-03T12:36:22 | 2019-12-03T12:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 301 | cpp | #include <iostream>
using namespace std;
int big(int a, int b, int c=100){
if(a > b)
if(a > c) return c;
else return a;
else
if(b > c) return c;
else return b;
}
int main(){
int x = big(3, 5);
int y = big(300, 60);
int z = big(30, 60, 50);
cout << x << ' ' << y << ' ' << z << endl;
}
| [
"yhj010597@naver.com"
] | yhj010597@naver.com |
ecd90a4f3fb9e7178b9b0bfe648d66bd8265645e | 6aaafe8033ca382931b613ce9d1f8c75dabf8fb4 | /TupleMakerObjects.h | aeeca620fed96f3c99e5b88e32dd89706ad2f1e5 | [] | no_license | JosephineWittkowski/analysis_SUSYTools_03_04_SusyNt_01_16_n0150 | c761b8de5766214e14718a8e0f64b6a87dc57527 | 08c979efd6b57a87a6f696184f3e547828883581 | refs/heads/master | 2021-01-20T07:02:09.267146 | 2014-06-27T07:27:24 | 2014-06-27T07:27:24 | 19,309,711 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | h | // emacs -*- C++ -*-
#ifndef SUSY_WH_TUPLEMAKEROBJECTS_H
#define SUSY_WH_TUPLEMAKEROBJECTS_H
#include "/data/etp3/jwittkow/analysis_SUSYTools_03_04/SusyNtuple/SusyNtuple/SusyNt.h"
#include <iostream>
#include <vector>
namespace susy
{
namespace wh
{
using Susy::Lepton;
using Susy::Jet;
using Susy::Met;
struct FourMom {
double px, py, pz, E;
bool isMu, isEl, isJet;
FourMom() : px(0), py(0), pz(0), E(0), isMu(false), isEl(false), isJet(false) {}
#ifndef __CINT__
// cint is not able to parse 'complex' code; see
// http://root.cern.ch/drupal/content/interacting-shared-libraries-rootcint
FourMom& set4mom(const Lepton &l) { px=l.Px(); py=l.Py(); pz=l.Pz(); E=l.E(); return *this; }
FourMom& set4mom(const Jet &j) { px=j.Px(); py=j.Py(); pz=j.Pz(); E=j.E(); return *this; }
FourMom& setMu(const Lepton &l) { isMu=true; isEl = isJet = false; return set4mom(l); }
FourMom& setEl(const Lepton &l) { isEl=true; isMu = isJet = false; return set4mom(l); }
FourMom& setJet(const Jet &j) { isJet=true; isMu = isEl = false; return set4mom(j); }
FourMom& setMet(const Met &m) { isJet=isMu=isEl=false; px=m.lv().Px(); py=m.lv().Py(); E=m.lv().E(); return *this; }
#endif
};
struct EventParameters {
double weight;
unsigned int eventNumber;
unsigned int runNumber;
EventParameters() : weight(0), eventNumber(0), runNumber(0) {}
#ifndef __CINT__
EventParameters& setWeight(const double &w) { weight=w; return *this; }
EventParameters& setEvent(const unsigned int &e) { eventNumber=e; return *this; }
EventParameters& setRun(const unsigned int &r) { runNumber=r; return *this; }
#endif
};
} // namespace wh
} // namespace susy
#endif // end include guard
| [
"Josephine.Wittkowski@yahoo.de"
] | Josephine.Wittkowski@yahoo.de |
bb66753d1787afba57c7e3387c69ee64f70ff438 | 3f3eb82035389ea0fd51a52a2be7edb0416164a4 | /src/service/shortcut_service.hpp | dbc1f34f0e382215d405af5f09bb85520c71a568 | [] | no_license | yydcnjjw/my-anything | 2e790c1f9266dde87e77f1e47db9c93015aef845 | e4bf1a67ed375c8118092626331856673f8c3d28 | refs/heads/main | 2023-07-15T12:04:01.484379 | 2021-08-24T14:18:28 | 2021-08-24T14:18:28 | 357,474,040 | 0 | 0 | null | 2021-06-22T04:08:43 | 2021-04-13T08:10:23 | C++ | UTF-8 | C++ | false | false | 6,603 | hpp | #pragma once
#include <QKeyEvent>
#include <service/command_service.hpp>
namespace my {
class KeyMap;
class KeyBind {
public:
SHARED_CLS(KeyBind)
using keymap_ptr_t = std::shared_ptr<const KeyMap>;
KeyBind(keymap_ptr_t const &keymap, QKeySequence const &keyseq,
Command::ptr_t const &cmd)
: _keymap(keymap), _keyseq(keyseq), _cmd(cmd) {}
~KeyBind() {
if (this->_cmd) {
this->cmd()->remove_keybind(this);
}
}
QKeySequence const &keyseq() const { return this->_keyseq; }
std::string keyseq_str() const {
return this->keyseq().toString().toStdString();
}
Command::ptr_t const &cmd() const { return this->_cmd; }
template <typename... Args> void exec(Args &&...args) {
if (this->_cmd) {
this->_cmd->exec(std::forward<Args>(args)...);
}
}
keymap_ptr_t const &keymap() { return this->_keymap; }
std::string str() const {
return (boost::format("KeyBind{%s, %s}") %
_keyseq.toString().toStdString() % (_cmd ? _cmd->name() : ""))
.str();
}
private:
std::shared_ptr<const KeyMap> _keymap;
QKeySequence _keyseq;
Command::ptr_t _cmd;
friend class Command;
void cmd(Command::ptr_t const &cmd) { this->_cmd = cmd; }
};
using keybind_container_t = std::unordered_map<std::string, KeyBind::ptr_t>;
class ShortcutService;
class KeyMap : public std::enable_shared_from_this<KeyMap> {
public:
SHARED_CLS(KeyMap)
KeyMap(ShortcutService &srv, std::string const &name)
: _srv(srv), _name(name) {}
std::string const &name() const { return this->_name; }
keybind_container_t const &map() const { return this->_keybinds; }
ptr_t add(std::string const &keyseq, std::string const &cmd);
ptr_t add(QKeySequence const &keyseq, std::string const &cmd);
ptr_t add(KeyBind::ptr_t const &keybind) {
for (auto &item : this->_keybinds) {
if (item.second->keyseq().matches(keybind->keyseq()) ==
QKeySequence::PartialMatch) {
throw std::runtime_error(
(boost::format("Key sequence %s starts with non-prefix key %s") %
keybind->keyseq_str() % item.second->keyseq_str())
.str());
}
}
this->_keybinds.insert_or_assign(keybind->keyseq_str(), keybind);
return this->shared_from_this();
}
std::string str() const {
std::stringstream ss;
ss << "KeyMap{name: " << this->_name << std::endl;
for (auto &kb : this->_keybinds) {
ss << kb.second->str() << std::endl;
}
ss << "}" << std::endl;
return ss.str();
}
private:
ShortcutService &_srv;
std::string _name; // unique id
keybind_container_t _keybinds;
};
class ShortcutService {
public:
SELF_T(ShortcutService)
using keymap_container_t = std::unordered_map<std::string, KeyMap::ptr_t>;
ShortcutService(CommandService &command_srv) : _command_srv(command_srv) {}
struct KeyBindCandidate {
std::optional<KeyBind::ptr_t> exact_match;
std::vector<KeyBind::ptr_t> partial_matches;
std::string str() const {
std::stringstream ss;
ss << "exact: " << (exact_match ? (*exact_match)->str() : "null");
for (auto kb : partial_matches) {
ss << kb->str() << std::endl;
}
return ss.str();
}
};
std::optional<KeyBind::ptr_t> exact_match(QKeySequence const &keyseq) const {
auto v = this->_keymaps | std::views::values |
std::views::filter([&keyseq](auto const &keymaps) {
return keymaps->map().count(keyseq.toString().toStdString());
}) |
std::views::transform([&keyseq](auto const &keymaps) {
return keymaps->map().at(keyseq.toString().toStdString());
}) |
std::views::take(1);
if (v.begin() != v.end()) {
return *v.begin();
} else {
return std::nullopt;
}
}
KeyBindCandidate partial_match(QKeySequence const &keyseq) const {
// return this->_keymaps | std::views::transform([](auto const &kv) {
// return kv.second->map() | std::views::values;
// }) |
// std::views::join |
// std::views::filter([&keyseq](auto const &keybind) {
// auto v = keybind->keyseq().matches(keyseq);
// return v == QKeySequence::ExactMatch ||
// v == QKeySequence::PartialMatch;
// return true;
// });
KeyBindCandidate candidate;
for (auto &keymap : this->_keymaps | std::views::values) {
for (auto &keybind : keymap->map() | std::views::values) {
auto v = keyseq.matches(keybind->keyseq());
if (v == QKeySequence::ExactMatch) {
candidate.exact_match = keybind;
} else if (v == QKeySequence::PartialMatch) {
candidate.partial_matches.push_back(keybind);
}
}
}
return candidate;
}
bool disptach(QKeyEvent *e) {
auto key{e->key()};
// filter unknown, modifiers key, extra key
switch (key) {
case Qt::Key_unknown:
case Qt::Key_Control:
case Qt::Key_Shift:
case Qt::Key_Alt:
case Qt::Key_Meta:
case Qt::Key_Super_L:
case Qt::Key_Super_R:
case Qt::Key_Hyper_L:
case Qt::Key_Hyper_R:
this->_cur_keyseq = {};
return false;
}
QKeySequence keyseq(e->modifiers() | e->key());
if (this->_cur_keyseq.isEmpty()) {
this->_cur_keyseq = keyseq;
} else {
this->_cur_keyseq =
QKeySequence::fromString((boost::format("%s, %s") %
this->_cur_keyseq.toString().toStdString() %
keyseq.toString().toStdString())
.str()
.c_str());
}
SPDLOG_DEBUG(this->_cur_keyseq.toString().toStdString());
auto candidate = this->partial_match(this->_cur_keyseq);
if (candidate.exact_match) {
(*candidate.exact_match)->exec();
this->_cur_keyseq = {};
} else if (candidate.partial_matches.empty()) {
this->_cur_keyseq = {};
}
return true;
}
template <typename... Args> auto make_keymap(Args &&...args) {
return KeyMap::make(*this, std::forward<Args>(args)...);
}
void map(KeyMap::ptr_t const &keymap) {
if (!this->_keymaps.emplace(keymap->name(), keymap).second) {
SPDLOG_WARN("keymap: {} has been mapped", keymap->name());
}
}
void unmap(std::string const &name) { this->_keymaps.erase(name); }
private:
CommandService &_command_srv;
friend class KeyMap;
keymap_container_t _keymaps;
QKeySequence _cur_keyseq;
};
} // namespace my
| [
"yydcnjjw@gmail.com"
] | yydcnjjw@gmail.com |
6621e2a3b88780968007e4aeba1c417100c8e115 | e016b0b04a6db80b0218a4f095e6aa4ea6fcd01c | /Classes/Native/System_Data_System_Data_SqlTypes_StorageState969348312.h | 04fd017dbd2ec0b0a4155ed44976d6799d3aa884 | [
"MIT"
] | permissive | rockarts/MountainTopo3D | 5a39905c66da87db42f1d94afa0ec20576ea68de | 2994b28dabb4e4f61189274a030b0710075306ea | refs/heads/master | 2021-01-13T06:03:01.054404 | 2017-06-22T01:12:52 | 2017-06-22T01:12:52 | 95,056,244 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 983 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include "mscorlib_System_Enum2459695545.h"
#include "System_Data_System_Data_SqlTypes_StorageState969348312.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Data.SqlTypes.StorageState
struct StorageState_t969348312
{
public:
// System.Int32 System.Data.SqlTypes.StorageState::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(StorageState_t969348312, ___value___1)); }
inline int32_t get_value___1() const { return ___value___1; }
inline int32_t* get_address_of_value___1() { return &___value___1; }
inline void set_value___1(int32_t value)
{
___value___1 = value;
}
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"stevenrockarts@gmail.com"
] | stevenrockarts@gmail.com |
3e020a0e862a35901e0017949dd6678a401283ff | 922c5f72dbc43869ffb26bef52fbc6a22a31be56 | /intento_andres/codigo_grupal_andres/Programs/header.h | 20a0c7118d70446d6c6d4bacee8d7f9f21c3cd26 | [] | no_license | jujimenezp/herrcomp_project01 | 3379d4eb70f4e5846879ad6b44d098b2910edfcc | 0aae0eb08647271100904d20804d8c9ddc80e4c6 | refs/heads/master | 2023-01-11T14:24:27.537352 | 2020-11-09T21:22:10 | 2020-11-09T21:22:10 | 304,541,735 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,124 | h | #pragma once
#include <cmath>
#include <iostream>
#include <fstream>
#include <vector>
#include <string>
#include <chrono>
#include <random>
struct CONFIG{
int nmolecules = 0;
int gridsize = 0;
int latticesize = 0;
int tmax = 0;
int seed = 0;
int resolution = 0;
int holeboolean = 0;
int holesize = 0;
int holeposition = 0;
void read(const std::string & fname); //read configuration
};
struct Particle{
int position[2] = {0,0};
void Move(const int &step, const int &direction, const CONFIG &config);
void Move_hole(const int &time, const int &step, const int &direction, const int &particle_id, const CONFIG &config, std::vector<int> &Cells, std::vector<Particle> &Particles);
int Getcell(const CONFIG &config);
};
typedef std::vector<Particle> Vec_p;
typedef std::vector<int> Vec_i;
typedef std::vector<double> Vec_d;
void start(const CONFIG &config, Vec_i &Cells, Vec_p &Particles);
void time_step(const int &time, const CONFIG &config, int random_particle, int step, int direction, Vec_i &Cells, Vec_p &Particles);
double entropy(const CONFIG &config,const Vec_i &Cells);
| [
"anvargasl@unal.edu.co"
] | anvargasl@unal.edu.co |
e9727853039091286cb02cd828b14803864737a8 | 319d6ad998711f39f706f0e2e6318cd476718489 | /first_period/week01/1W4/04_Sum/main.cpp | 5fa59047e8b6fad0a089882286b7156e91c40059 | [] | no_license | green-fox-academy/franzsi | 7361a708ab34527a756e39971c4c4c3226878e88 | 7e891b2a30ceb7b0cf2b60dafa19bc6bcfc5754d | refs/heads/master | 2020-04-02T17:34:02.636140 | 2019-02-11T04:25:44 | 2019-02-11T04:25:44 | 154,662,458 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 392 | cpp | #include <iostream>
#include <string>
int sum (int number){
int sum = 0;
for (int i=0; i <number; i++)
sum += i;
return sum;
}
int main(int argc, char* args[]) {
// - Write a function called `sum` that sum all the numbers
// until the given parameter and returns with an integer
int baseNum = 20;
std::cout << sum(baseNum) << std::endl;
return 0;
} | [
"franzsi@gmail.com"
] | franzsi@gmail.com |
ccc1939f48dfdc03839c89da52bf5ff30933bf88 | 1bf6927ad32481b95b271f4f1fbf5ec426edef32 | /src/main.cpp | baad855cd7614a0d9c5517226d3e582c675593d0 | [
"MIT"
] | permissive | dream8coin/dreamcoin | 288691f7d45dedefbe68c75800480eb434741294 | 100e73f65aa378c28304af8749df23ee739208ce | refs/heads/master | 2018-02-09T07:55:32.717927 | 2017-10-22T00:51:37 | 2017-10-22T00:51:37 | 70,240,498 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 130,279 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2012 The Bitcoin developers
// Copyright (c) 2011-2012 Litecoin Developers
// Copyright (c) 2015-2016 Dream8coin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "checkpoints.h"
#include "db.h"
#include "net.h"
#include "init.h"
#include "ui_interface.h"
#include <boost/algorithm/string/replace.hpp>
#include <boost/filesystem.hpp>
#include <boost/filesystem/fstream.hpp>
using namespace std;
using namespace boost;
//
// Global state
//
CCriticalSection cs_setpwalletRegistered;
set<CWallet*> setpwalletRegistered;
CCriticalSection cs_main;
CTxMemPool mempool;
unsigned int nTransactionsUpdated = 0;
map<uint256, CBlockIndex*> mapBlockIndex;
uint256 hashGenesisBlock("0x26164b28808f1ab880cb7dc2e44bae9fc7fca8e042627f51ea667db115843c28");
static CBigNum bnProofOfWorkLimit(~uint256(0) >> 20); // Dream8coin: starting difficulty is 1 / 2^12
CBlockIndex* pindexGenesisBlock = NULL;
int nBestHeight = -1;
CBigNum bnBestChainWork = 0;
CBigNum bnBestInvalidWork = 0;
uint256 hashBestChain = 0;
CBlockIndex* pindexBest = NULL;
int64 nTimeBestReceived = 0;
CMedianFilter<int> cPeerBlockCounts(5, 0); // Amount of blocks that other nodes claim to have
map<uint256, CBlock*> mapOrphanBlocks;
multimap<uint256, CBlock*> mapOrphanBlocksByPrev;
map<uint256, CDataStream*> mapOrphanTransactions;
map<uint256, map<uint256, CDataStream*> > mapOrphanTransactionsByPrev;
// Constant stuff for coinbase transactions we create:
CScript COINBASE_FLAGS;
const string strMessageMagic = "Dream8coin Signed Message:\n";
double dHashesPerSec;
int64 nHPSTimerStart;
// Settings
int64 nTransactionFee = 0;
int64 nMinimumInputValue = CENT / 100;
//////////////////////////////////////////////////////////////////////////////
//
// dispatching functions
//
// These functions dispatch to one or all registered wallets
void RegisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.insert(pwalletIn);
}
}
void UnregisterWallet(CWallet* pwalletIn)
{
{
LOCK(cs_setpwalletRegistered);
setpwalletRegistered.erase(pwalletIn);
}
}
// check whether the passed transaction is from us
bool static IsFromMe(CTransaction& tx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->IsFromMe(tx))
return true;
return false;
}
// get the wallet transaction with the given hash (if it exists)
bool static GetTransaction(const uint256& hashTx, CWalletTx& wtx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
if (pwallet->GetTransaction(hashTx,wtx))
return true;
return false;
}
// erases transaction with the given hash from all wallets
void static EraseFromWallets(uint256 hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->EraseFromWallet(hash);
}
// make sure all wallets know about the given transaction, in the given block
void SyncWithWallets(const CTransaction& tx, const CBlock* pblock, bool fUpdate)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->AddToWalletIfInvolvingMe(tx, pblock, fUpdate);
}
// notify wallets about a new best chain
void static SetBestChain(const CBlockLocator& loc)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->SetBestChain(loc);
}
// notify wallets about an updated transaction
void static UpdatedTransaction(const uint256& hashTx)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->UpdatedTransaction(hashTx);
}
// dump all wallets
void static PrintWallets(const CBlock& block)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->PrintWallet(block);
}
// notify wallets about an incoming inventory (for request counts)
void static Inventory(const uint256& hash)
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->Inventory(hash);
}
// ask wallets to resend their transactions
void static ResendWalletTransactions()
{
BOOST_FOREACH(CWallet* pwallet, setpwalletRegistered)
pwallet->ResendWalletTransactions();
}
//////////////////////////////////////////////////////////////////////////////
//
// mapOrphanTransactions
//
bool AddOrphanTx(const CDataStream& vMsg)
{
CTransaction tx;
CDataStream(vMsg) >> tx;
uint256 hash = tx.GetHash();
if (mapOrphanTransactions.count(hash))
return false;
CDataStream* pvMsg = new CDataStream(vMsg);
// Ignore big transactions, to avoid a
// send-big-orphans memory exhaustion attack. If a peer has a legitimate
// large transaction with a missing parent then we assume
// it will rebroadcast it later, after the parent transaction(s)
// have been mined or received.
// 10,000 orphans, each of which is at most 5,000 bytes big is
// at most 500 megabytes of orphans:
if (pvMsg->size() > 5000)
{
printf("ignoring large orphan tx (size: %u, hash: %s)\n", pvMsg->size(), hash.ToString().substr(0,10).c_str());
delete pvMsg;
return false;
}
mapOrphanTransactions[hash] = pvMsg;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapOrphanTransactionsByPrev[txin.prevout.hash].insert(make_pair(hash, pvMsg));
printf("stored orphan tx %s (mapsz %u)\n", hash.ToString().substr(0,10).c_str(),
mapOrphanTransactions.size());
return true;
}
void static EraseOrphanTx(uint256 hash)
{
if (!mapOrphanTransactions.count(hash))
return;
const CDataStream* pvMsg = mapOrphanTransactions[hash];
CTransaction tx;
CDataStream(*pvMsg) >> tx;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
mapOrphanTransactionsByPrev[txin.prevout.hash].erase(hash);
if (mapOrphanTransactionsByPrev[txin.prevout.hash].empty())
mapOrphanTransactionsByPrev.erase(txin.prevout.hash);
}
delete pvMsg;
mapOrphanTransactions.erase(hash);
}
unsigned int LimitOrphanTxSize(unsigned int nMaxOrphans)
{
unsigned int nEvicted = 0;
while (mapOrphanTransactions.size() > nMaxOrphans)
{
// Evict a random orphan:
uint256 randomhash = GetRandHash();
map<uint256, CDataStream*>::iterator it = mapOrphanTransactions.lower_bound(randomhash);
if (it == mapOrphanTransactions.end())
it = mapOrphanTransactions.begin();
EraseOrphanTx(it->first);
++nEvicted;
}
return nEvicted;
}
//////////////////////////////////////////////////////////////////////////////
//
// CTransaction and CTxIndex
//
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout, CTxIndex& txindexRet)
{
SetNull();
if (!txdb.ReadTxIndex(prevout.hash, txindexRet))
return false;
if (!ReadFromDisk(txindexRet.pos))
return false;
if (prevout.n >= vout.size())
{
SetNull();
return false;
}
return true;
}
bool CTransaction::ReadFromDisk(CTxDB& txdb, COutPoint prevout)
{
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::ReadFromDisk(COutPoint prevout)
{
CTxDB txdb("r");
CTxIndex txindex;
return ReadFromDisk(txdb, prevout, txindex);
}
bool CTransaction::IsStandard() const
{
if (nVersion > CTransaction::CURRENT_VERSION)
return false;
BOOST_FOREACH(const CTxIn& txin, vin)
{
// Biggest 'standard' txin is a 3-signature 3-of-3 CHECKMULTISIG
// pay-to-script-hash, which is 3 ~80-byte signatures, 3
// ~65-byte public keys, plus a few script ops.
if (txin.scriptSig.size() > 500)
return false;
if (!txin.scriptSig.IsPushOnly())
return false;
}
BOOST_FOREACH(const CTxOut& txout, vout)
if (!::IsStandard(txout.scriptPubKey))
return false;
return true;
}
//
// Check transaction inputs, and make sure any
// pay-to-script-hash transactions are evaluating IsStandard scripts
//
// Why bother? To avoid denial-of-service attacks; an attacker
// can submit a standard HASH... OP_EQUAL transaction,
// which will get accepted into blocks. The redemption
// script can be anything; an attacker could use a very
// expensive-to-check-upon-redemption script like:
// DUP CHECKSIG DROP ... repeated 100 times... OP_1
//
bool CTransaction::AreInputsStandard(const MapPrevTx& mapInputs) const
{
if (IsCoinBase())
return true; // Coinbases don't use vin normally
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prev = GetOutputFor(vin[i], mapInputs);
vector<vector<unsigned char> > vSolutions;
txnouttype whichType;
// get the scriptPubKey corresponding to this input:
const CScript& prevScript = prev.scriptPubKey;
if (!Solver(prevScript, whichType, vSolutions))
return false;
int nArgsExpected = ScriptSigArgsExpected(whichType, vSolutions);
if (nArgsExpected < 0)
return false;
// Transactions with extra stuff in their scriptSigs are
// non-standard. Note that this EvalScript() call will
// be quick, because if there are any operations
// beside "push data" in the scriptSig the
// IsStandard() call returns false
vector<vector<unsigned char> > stack;
if (!EvalScript(stack, vin[i].scriptSig, *this, i, 0))
return false;
if (whichType == TX_SCRIPTHASH)
{
if (stack.empty())
return false;
CScript subscript(stack.back().begin(), stack.back().end());
vector<vector<unsigned char> > vSolutions2;
txnouttype whichType2;
if (!Solver(subscript, whichType2, vSolutions2))
return false;
if (whichType2 == TX_SCRIPTHASH)
return false;
int tmpExpected;
tmpExpected = ScriptSigArgsExpected(whichType2, vSolutions2);
if (tmpExpected < 0)
return false;
nArgsExpected += tmpExpected;
}
if (stack.size() != (unsigned int)nArgsExpected)
return false;
}
return true;
}
unsigned int
CTransaction::GetLegacySigOpCount() const
{
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTxIn& txin, vin)
{
nSigOps += txin.scriptSig.GetSigOpCount(false);
}
BOOST_FOREACH(const CTxOut& txout, vout)
{
nSigOps += txout.scriptPubKey.GetSigOpCount(false);
}
return nSigOps;
}
int CMerkleTx::SetMerkleBranch(const CBlock* pblock)
{
if (fClient)
{
if (hashBlock == 0)
return 0;
}
else
{
CBlock blockTmp;
if (pblock == NULL)
{
// Load the block this tx is in
CTxIndex txindex;
if (!CTxDB("r").ReadTxIndex(GetHash(), txindex))
return 0;
if (!blockTmp.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos))
return 0;
pblock = &blockTmp;
}
// Update the tx's hashBlock
hashBlock = pblock->GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)pblock->vtx.size(); nIndex++)
if (pblock->vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)pblock->vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
printf("ERROR: SetMerkleBranch() : couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = pblock->GetMerkleBranch(nIndex);
}
// Is the tx in a block that's in the main chain
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return pindexBest->nHeight - pindex->nHeight + 1;
}
bool CTransaction::CheckTransaction() const
{
// Basic checks that don't depend on any context
if (vin.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vin empty"));
if (vout.empty())
return DoS(10, error("CTransaction::CheckTransaction() : vout empty"));
// Size limits
if (::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CTransaction::CheckTransaction() : size limits failed"));
// Check for negative or overflow output values
int64 nValueOut = 0;
BOOST_FOREACH(const CTxOut& txout, vout)
{
if (txout.nValue < 0)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue negative"));
if (txout.nValue > MAX_MONEY)
return DoS(100, error("CTransaction::CheckTransaction() : txout.nValue too high"));
nValueOut += txout.nValue;
if (!MoneyRange(nValueOut))
return DoS(100, error("CTransaction::CheckTransaction() : txout total out of range"));
}
// Check for duplicate inputs
set<COutPoint> vInOutPoints;
BOOST_FOREACH(const CTxIn& txin, vin)
{
if (vInOutPoints.count(txin.prevout))
return false;
vInOutPoints.insert(txin.prevout);
}
if (IsCoinBase())
{
if (vin[0].scriptSig.size() < 2 || vin[0].scriptSig.size() > 100)
return DoS(100, error("CTransaction::CheckTransaction() : coinbase script size"));
}
else
{
BOOST_FOREACH(const CTxIn& txin, vin)
if (txin.prevout.IsNull())
return DoS(10, error("CTransaction::CheckTransaction() : prevout is null"));
}
return true;
}
bool CTxMemPool::accept(CTxDB& txdb, CTransaction &tx, bool fCheckInputs,
bool* pfMissingInputs)
{
if (pfMissingInputs)
*pfMissingInputs = false;
if (!tx.CheckTransaction())
return error("CTxMemPool::accept() : CheckTransaction failed");
// Coinbase is only valid in a block, not as a loose transaction
if (tx.IsCoinBase())
return tx.DoS(100, error("CTxMemPool::accept() : coinbase as individual tx"));
// To help v0.1.5 clients who would see it as a negative number
if ((int64)tx.nLockTime > std::numeric_limits<int>::max())
return error("CTxMemPool::accept() : not accepting nLockTime beyond 2038 yet");
// Rather not work on nonstandard transactions (unless -testnet)
if (!fTestNet && !tx.IsStandard())
return error("CTxMemPool::accept() : nonstandard transaction type");
// Do we already have it?
uint256 hash = tx.GetHash();
{
LOCK(cs);
if (mapTx.count(hash))
return false;
}
if (fCheckInputs)
if (txdb.ContainsTx(hash))
return false;
// Check for conflicts with in-memory transactions
CTransaction* ptxOld = NULL;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (mapNextTx.count(outpoint))
{
// Disable replacement feature for now
return false;
// Allow replacing with a newer version of the same transaction
if (i != 0)
return false;
ptxOld = mapNextTx[outpoint].ptx;
if (ptxOld->IsFinal())
return false;
if (!tx.IsNewerThan(*ptxOld))
return false;
for (unsigned int i = 0; i < tx.vin.size(); i++)
{
COutPoint outpoint = tx.vin[i].prevout;
if (!mapNextTx.count(outpoint) || mapNextTx[outpoint].ptx != ptxOld)
return false;
}
break;
}
}
if (fCheckInputs)
{
MapPrevTx mapInputs;
map<uint256, CTxIndex> mapUnused;
bool fInvalid = false;
if (!tx.FetchInputs(txdb, mapUnused, false, false, mapInputs, fInvalid))
{
if (fInvalid)
return error("CTxMemPool::accept() : FetchInputs found invalid tx %s", hash.ToString().substr(0,10).c_str());
if (pfMissingInputs)
*pfMissingInputs = true;
return false;
}
// Check for non-standard pay-to-script-hash in inputs
if (!tx.AreInputsStandard(mapInputs) && !fTestNet)
return error("CTxMemPool::accept() : nonstandard transaction input");
// Note: if you modify this code to accept non-standard transactions, then
// you should add code here to check that the transaction does a
// reasonable number of ECDSA signature verifications.
int64 nFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
// Don't accept it if it can't get into a block
int64 txMinFee = tx.GetMinFee(1000, true, GMF_RELAY);
if (nFees < txMinFee)
return error("CTxMemPool::accept() : not enough fees %s, %"PRI64d" < %"PRI64d,
hash.ToString().c_str(),
nFees, txMinFee);
// Continuously rate-limit free transactions
// This mitigates 'penny-flooding' -- sending thousands of free transactions just to
// be annoying or make other's transactions take longer to confirm.
if (nFees < MIN_RELAY_TX_FEE)
{
static CCriticalSection cs;
static double dFreeCount;
static int64 nLastTime;
int64 nNow = GetTime();
{
LOCK(cs);
// Use an exponentially decaying ~10-minute window:
dFreeCount *= pow(1.0 - 1.0/600.0, (double)(nNow - nLastTime));
nLastTime = nNow;
// -limitfreerelay unit is thousand-bytes-per-minute
// At default rate it would take over a month to fill 1GB
if (dFreeCount > GetArg("-limitfreerelay", 15)*10*1000 && !IsFromMe(tx))
return error("CTxMemPool::accept() : free transaction rejected by rate limiter");
if (fDebug)
printf("Rate limit dFreeCount: %g => %g\n", dFreeCount, dFreeCount+nSize);
dFreeCount += nSize;
}
}
// Check against previous transactions
// This is done last to help prevent CPU exhaustion denial-of-service attacks.
if (!tx.ConnectInputs(mapInputs, mapUnused, CDiskTxPos(1,1,1), pindexBest, false, false))
{
return error("CTxMemPool::accept() : ConnectInputs failed %s", hash.ToString().substr(0,10).c_str());
}
}
// Store transaction in memory
{
LOCK(cs);
if (ptxOld)
{
printf("CTxMemPool::accept() : replacing tx %s with new version\n", ptxOld->GetHash().ToString().c_str());
remove(*ptxOld);
}
addUnchecked(hash, tx);
}
///// are we sure this is ok when loading transactions or restoring block txes
// If updated, erase old tx from wallet
if (ptxOld)
EraseFromWallets(ptxOld->GetHash());
printf("CTxMemPool::accept() : accepted %s (poolsz %u)\n",
hash.ToString().c_str(),
mapTx.size());
return true;
}
bool CTransaction::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs, bool* pfMissingInputs)
{
return mempool.accept(txdb, *this, fCheckInputs, pfMissingInputs);
}
bool CTxMemPool::addUnchecked(const uint256& hash, CTransaction &tx)
{
// Add to memory pool without checking anything. Don't call this directly,
// call CTxMemPool::accept to properly check the transaction first.
{
mapTx[hash] = tx;
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&mapTx[hash], i);
nTransactionsUpdated++;
}
return true;
}
bool CTxMemPool::remove(CTransaction &tx)
{
// Remove transaction from memory pool
{
LOCK(cs);
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
{
BOOST_FOREACH(const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
return true;
}
void CTxMemPool::queryHashes(std::vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTransaction>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
int CMerkleTx::GetDepthInMainChain(CBlockIndex* &pindexRet) const
{
if (hashBlock == 0 || nIndex == -1)
return 0;
// Find the block it claims to be in
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return pindexBest->nHeight - pindex->nHeight + 1;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return max(0, (COINBASE_MATURITY+20) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(CTxDB& txdb, bool fCheckInputs)
{
if (fClient)
{
if (!IsInMainChain() && !ClientConnectInputs())
return false;
return CTransaction::AcceptToMemoryPool(txdb, false);
}
else
{
return CTransaction::AcceptToMemoryPool(txdb, fCheckInputs);
}
}
bool CMerkleTx::AcceptToMemoryPool()
{
CTxDB txdb("r");
return AcceptToMemoryPool(txdb);
}
bool CWalletTx::AcceptWalletTransaction(CTxDB& txdb, bool fCheckInputs)
{
{
LOCK(mempool.cs);
// Add previous supporting transactions first
BOOST_FOREACH(CMerkleTx& tx, vtxPrev)
{
if (!tx.IsCoinBase())
{
uint256 hash = tx.GetHash();
if (!mempool.exists(hash) && !txdb.ContainsTx(hash))
tx.AcceptToMemoryPool(txdb, fCheckInputs);
}
}
return AcceptToMemoryPool(txdb, fCheckInputs);
}
return false;
}
bool CWalletTx::AcceptWalletTransaction()
{
CTxDB txdb("r");
return AcceptWalletTransaction(txdb);
}
int CTxIndex::GetDepthInMainChain() const
{
// Read block header
CBlock block;
if (!block.ReadFromDisk(pos.nFile, pos.nBlockPos, false))
return 0;
// Find the block in the index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(block.GetHash());
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !pindex->IsInMainChain())
return 0;
return 1 + nBestHeight - pindex->nHeight;
}
// Return transaction in tx, and if it was found inside a block, its hash is placed in hashBlock
bool GetTransaction(const uint256 &hash, CTransaction &tx, uint256 &hashBlock)
{
{
LOCK(cs_main);
{
LOCK(mempool.cs);
if (mempool.exists(hash))
{
tx = mempool.lookup(hash);
return true;
}
}
CTxDB txdb("r");
CTxIndex txindex;
if (tx.ReadFromDisk(txdb, COutPoint(hash, 0), txindex))
{
CBlock block;
if (block.ReadFromDisk(txindex.pos.nFile, txindex.pos.nBlockPos, false))
hashBlock = block.GetHash();
return true;
}
}
return false;
}
//////////////////////////////////////////////////////////////////////////////
//
// CBlock and CBlockIndex
//
bool CBlock::ReadFromDisk(const CBlockIndex* pindex, bool fReadTransactions)
{
if (!fReadTransactions)
{
*this = pindex->GetBlockHeader();
return true;
}
if (!ReadFromDisk(pindex->nFile, pindex->nBlockPos, fReadTransactions))
return false;
if (GetHash() != pindex->GetBlockHash())
return error("CBlock::ReadFromDisk() : GetHash() doesn't match index");
return true;
}
uint256 static GetOrphanRoot(const CBlock* pblock)
{
// Work back to the first block in the orphan chain
while (mapOrphanBlocks.count(pblock->hashPrevBlock))
pblock = mapOrphanBlocks[pblock->hashPrevBlock];
return pblock->GetHash();
}
int64 static GetBlockValue(int nHeight, int64 nFees)
{
int64 nSubsidy = 1 * COIN;
if (nHeight <= 300000) {
nSubsidy = 88 * COIN;
}
if (nHeight == 97825) {
nSubsidy = 20000000000 * COIN;
}
if (nHeight <= 40478) {
nSubsidy = 10000000 * COIN;
}
if (nHeight <= 40377) {
nSubsidy = 88 * COIN;
}
if (nHeight <= 36000) {
nSubsidy = 10 * COIN;
}
if (nHeight <= 80) { // PRM COIN
nSubsidy = 10000000 * COIN;
}
return nSubsidy + nFees;
}
static int64 nTargetTimespan = 1 * 24 * 60 * 60;
static int64 nTargetSpacing = 1 * 60; // Dream8coin: 1 minutes
static int64 nInterval = nTargetTimespan / nTargetSpacing;
//
// minimum amount of work that could possibly be required nTime after
// minimum work required was nBase
//
unsigned int ComputeMinWork(unsigned int nBase, int64 nTime)
{
// Testnet has min-difficulty blocks
// after nTargetSpacing*2 time between blocks:
if (fTestNet && nTime > nTargetSpacing*2)
return bnProofOfWorkLimit.GetCompact();
CBigNum bnResult;
bnResult.SetCompact(nBase);
while (nTime > 0 && bnResult < bnProofOfWorkLimit)
{
// Maximum 400% adjustment...
bnResult *= 4;
// ... in best-case exactly 4-times-normal target time
nTime -= nTargetTimespan*4;
}
if (bnResult > bnProofOfWorkLimit)
bnResult = bnProofOfWorkLimit;
return bnResult.GetCompact();
}
unsigned int static GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlock *pblock)
{
if ((pindexLast->nHeight+1) > 36065)
{
nTargetTimespan = 2 * 60;
nTargetSpacing = 2 * 60;
nInterval = nTargetTimespan / nTargetSpacing;
}
if ((pindexLast->nHeight+1) > 97820)
{
nTargetTimespan = 10 * 60;
nTargetSpacing = 10 * 60;
nInterval = nTargetTimespan / nTargetSpacing;
}
if ((pindexLast->nHeight+1) > 97838)
{
nTargetTimespan = 1 * 60;
nTargetSpacing = 1 * 60;
nInterval = nTargetTimespan / nTargetSpacing;
}
unsigned int nProofOfWorkLimit = bnProofOfWorkLimit.GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per interval
if ((pindexLast->nHeight+1) % nInterval != 0)
{
// Special difficulty rule for testnet:
if (fTestNet)
{
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->nTime > pindexLast->nTime + nTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % nInterval != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Dream8coin: This fixes an issue where a 51% attack can change difficulty at will.
// Go back the full period unless it's the first retarget after genesis. Code courtesy of Art Forz
int blockstogoback = nInterval-1;
if ((pindexLast->nHeight+1) != nInterval)
blockstogoback = nInterval;
// Go back by what we want to be 14 days worth of blocks
const CBlockIndex* pindexFirst = pindexLast;
for (int i = 0; pindexFirst && i < blockstogoback; i++)
pindexFirst = pindexFirst->pprev;
assert(pindexFirst);
// Limit adjustment step
int64 nActualTimespan = pindexLast->GetBlockTime() - pindexFirst->GetBlockTime();
printf(" nActualTimespan = %"PRI64d" before bounds\n", nActualTimespan);
if (nActualTimespan < nTargetTimespan/4)
nActualTimespan = nTargetTimespan/4;
if (nActualTimespan > nTargetTimespan*4)
nActualTimespan = nTargetTimespan*4;
// Retarget
CBigNum bnNew;
bnNew.SetCompact(pindexLast->nBits);
bnNew *= nActualTimespan;
bnNew /= nTargetTimespan;
if (bnNew > bnProofOfWorkLimit)
bnNew = bnProofOfWorkLimit;
/// debug print
printf("GetNextWorkRequired RETARGET\n");
printf("nTargetTimespan = %"PRI64d" nActualTimespan = %"PRI64d"\n", nTargetTimespan, nActualTimespan);
printf("Before: %08x %s\n", pindexLast->nBits, CBigNum().SetCompact(pindexLast->nBits).getuint256().ToString().c_str());
printf("After: %08x %s\n", bnNew.GetCompact(), bnNew.getuint256().ToString().c_str());
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits)
{
CBigNum bnTarget;
bnTarget.SetCompact(nBits);
// Check range
if (bnTarget <= 0 || bnTarget > bnProofOfWorkLimit)
return error("CheckProofOfWork() : nBits below minimum work");
// Check proof of work matches claimed amount
if (hash > bnTarget.getuint256())
return error("CheckProofOfWork() : hash doesn't match nBits");
return true;
}
// Return maximum amount of blocks that other nodes claim to have
int GetNumBlocksOfPeers()
{
return std::max(cPeerBlockCounts.median(), Checkpoints::GetTotalBlocksEstimate());
}
bool IsInitialBlockDownload()
{
if (pindexBest == NULL || nBestHeight < Checkpoints::GetTotalBlocksEstimate())
return true;
static int64 nLastUpdate;
static CBlockIndex* pindexLastBest;
if (pindexBest != pindexLastBest)
{
pindexLastBest = pindexBest;
nLastUpdate = GetTime();
}
return (GetTime() - nLastUpdate < 10 &&
pindexBest->GetBlockTime() < GetTime() - 24 * 60 * 60);
}
void static InvalidChainFound(CBlockIndex* pindexNew)
{
if (pindexNew->bnChainWork > bnBestInvalidWork)
{
bnBestInvalidWork = pindexNew->bnChainWork;
CTxDB().WriteBestInvalidWork(bnBestInvalidWork);
uiInterface.NotifyBlocksChanged();
}
printf("InvalidChainFound: invalid block=%s height=%d work=%s date=%s\n",
pindexNew->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->nHeight,
pindexNew->bnChainWork.ToString().c_str(), DateTimeStrFormat("%x %H:%M:%S",
pindexNew->GetBlockTime()).c_str());
printf("InvalidChainFound: current best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
printf("InvalidChainFound: WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.\n");
}
void CBlock::UpdateTime(const CBlockIndex* pindexPrev)
{
nTime = max(pindexPrev->GetMedianTimePast()+1, GetAdjustedTime());
// Updating time can change work required on testnet:
if (fTestNet)
nBits = GetNextWorkRequired(pindexPrev, this);
}
bool CTransaction::DisconnectInputs(CTxDB& txdb)
{
// Relinquish previous transactions' spent pointers
if (!IsCoinBase())
{
BOOST_FOREACH(const CTxIn& txin, vin)
{
COutPoint prevout = txin.prevout;
// Get prev txindex from disk
CTxIndex txindex;
if (!txdb.ReadTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : ReadTxIndex failed");
if (prevout.n >= txindex.vSpent.size())
return error("DisconnectInputs() : prevout.n out of range");
// Mark outpoint as not spent
txindex.vSpent[prevout.n].SetNull();
// Write back
if (!txdb.UpdateTxIndex(prevout.hash, txindex))
return error("DisconnectInputs() : UpdateTxIndex failed");
}
}
// Remove transaction from index
// This can fail if a duplicate of this transaction was in a chain that got
// reorganized away. This is only possible if this transaction was completely
// spent, so erasing it would be a no-op anway.
txdb.EraseTxIndex(*this);
return true;
}
bool CTransaction::FetchInputs(CTxDB& txdb, const map<uint256, CTxIndex>& mapTestPool,
bool fBlock, bool fMiner, MapPrevTx& inputsRet, bool& fInvalid)
{
// FetchInputs can return false either because we just haven't seen some inputs
// (in which case the transaction should be stored as an orphan)
// or because the transaction is malformed (in which case the transaction should
// be dropped). If tx is definitely invalid, fInvalid will be set to true.
fInvalid = false;
if (IsCoinBase())
return true; // Coinbase transactions have no inputs to fetch.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
if (inputsRet.count(prevout.hash))
continue; // Got it already
// Read txindex
CTxIndex& txindex = inputsRet[prevout.hash].first;
bool fFound = true;
if ((fBlock || fMiner) && mapTestPool.count(prevout.hash))
{
// Get txindex from current proposed changes
txindex = mapTestPool.find(prevout.hash)->second;
}
else
{
// Read txindex from txdb
fFound = txdb.ReadTxIndex(prevout.hash, txindex);
}
if (!fFound && (fBlock || fMiner))
return fMiner ? false : error("FetchInputs() : %s prev tx %s index entry not found", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
// Read txPrev
CTransaction& txPrev = inputsRet[prevout.hash].second;
if (!fFound || txindex.pos == CDiskTxPos(1,1,1))
{
// Get prev tx from single transactions in memory
{
LOCK(mempool.cs);
if (!mempool.exists(prevout.hash))
return error("FetchInputs() : %s mempool Tx prev not found %s", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
txPrev = mempool.lookup(prevout.hash);
}
if (!fFound)
txindex.vSpent.resize(txPrev.vout.size());
}
else
{
// Get prev tx from disk
if (!txPrev.ReadFromDisk(txindex.pos))
return error("FetchInputs() : %s ReadFromDisk prev tx %s failed", GetHash().ToString().substr(0,10).c_str(), prevout.hash.ToString().substr(0,10).c_str());
}
}
// Make sure all prevout.n's are valid:
for (unsigned int i = 0; i < vin.size(); i++)
{
const COutPoint prevout = vin[i].prevout;
assert(inputsRet.count(prevout.hash) != 0);
const CTxIndex& txindex = inputsRet[prevout.hash].first;
const CTransaction& txPrev = inputsRet[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
{
// Revisit this if/when transaction replacement is implemented and allows
// adding inputs:
fInvalid = true;
return DoS(100, error("FetchInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
}
}
return true;
}
const CTxOut& CTransaction::GetOutputFor(const CTxIn& input, const MapPrevTx& inputs) const
{
MapPrevTx::const_iterator mi = inputs.find(input.prevout.hash);
if (mi == inputs.end())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.hash not found");
const CTransaction& txPrev = (mi->second).second;
if (input.prevout.n >= txPrev.vout.size())
throw std::runtime_error("CTransaction::GetOutputFor() : prevout.n out of range");
return txPrev.vout[input.prevout.n];
}
int64 CTransaction::GetValueIn(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
int64 nResult = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
nResult += GetOutputFor(vin[i], inputs).nValue;
}
return nResult;
}
unsigned int CTransaction::GetP2SHSigOpCount(const MapPrevTx& inputs) const
{
if (IsCoinBase())
return 0;
unsigned int nSigOps = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
const CTxOut& prevout = GetOutputFor(vin[i], inputs);
if (prevout.scriptPubKey.IsPayToScriptHash())
nSigOps += prevout.scriptPubKey.GetSigOpCount(vin[i].scriptSig);
}
return nSigOps;
}
bool CTransaction::ConnectInputs(MapPrevTx inputs,
map<uint256, CTxIndex>& mapTestPool, const CDiskTxPos& posThisTx,
const CBlockIndex* pindexBlock, bool fBlock, bool fMiner, bool fStrictPayToScriptHash)
{
// Take over previous transactions' spent pointers
// fBlock is true when this is called from AcceptBlock when a new best-block is added to the blockchain
// fMiner is true when called from the internal dream8coin miner
// ... both are false when called from CTransaction::AcceptToMemoryPool
if (!IsCoinBase())
{
int64 nValueIn = 0;
int64 nFees = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
if (prevout.n >= txPrev.vout.size() || prevout.n >= txindex.vSpent.size())
return DoS(100, error("ConnectInputs() : %s prevout.n out of range %d %d %d prev tx %s\n%s", GetHash().ToString().substr(0,10).c_str(), prevout.n, txPrev.vout.size(), txindex.vSpent.size(), prevout.hash.ToString().substr(0,10).c_str(), txPrev.ToString().c_str()));
// If prev is coinbase, check that it's matured
if (txPrev.IsCoinBase())
for (const CBlockIndex* pindex = pindexBlock; pindex && pindexBlock->nHeight - pindex->nHeight < COINBASE_MATURITY; pindex = pindex->pprev)
if (pindex->nBlockPos == txindex.pos.nBlockPos && pindex->nFile == txindex.pos.nFile)
return error("ConnectInputs() : tried to spend coinbase at depth %d", pindexBlock->nHeight - pindex->nHeight);
// Check for negative or overflow input values
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return DoS(100, error("ConnectInputs() : txin values out of range"));
}
// The first loop above does all the inexpensive checks.
// Only if ALL inputs pass do we perform expensive ECDSA signature checks.
// Helps prevent CPU exhaustion attacks.
for (unsigned int i = 0; i < vin.size(); i++)
{
COutPoint prevout = vin[i].prevout;
assert(inputs.count(prevout.hash) > 0);
CTxIndex& txindex = inputs[prevout.hash].first;
CTransaction& txPrev = inputs[prevout.hash].second;
// Check for conflicts (double-spend)
// This doesn't trigger the DoS code on purpose; if it did, it would make it easier
// for an attacker to attempt to split the network.
if (!txindex.vSpent[prevout.n].IsNull())
return fMiner ? false : error("ConnectInputs() : %s prev tx already used at %s", GetHash().ToString().substr(0,10).c_str(), txindex.vSpent[prevout.n].ToString().c_str());
// Skip ECDSA signature verification when connecting blocks (fBlock=true)
// before the last blockchain checkpoint. This is safe because block merkle hashes are
// still computed and checked, and any change will be caught at the next checkpoint.
if (!(fBlock && (nBestHeight < Checkpoints::GetTotalBlocksEstimate())))
{
// Verify signature
if (!VerifySignature(txPrev, *this, i, fStrictPayToScriptHash, 0))
{
// only during transition phase for P2SH: do not invoke anti-DoS code for
// potentially old clients relaying bad P2SH transactions
if (fStrictPayToScriptHash && VerifySignature(txPrev, *this, i, false, 0))
return error("ConnectInputs() : %s P2SH VerifySignature failed", GetHash().ToString().substr(0,10).c_str());
return DoS(100,error("ConnectInputs() : %s VerifySignature failed", GetHash().ToString().substr(0,10).c_str()));
}
}
// Mark outpoints as spent
txindex.vSpent[prevout.n] = posThisTx;
// Write back
if (fBlock || fMiner)
{
mapTestPool[prevout.hash] = txindex;
}
}
if (nValueIn < GetValueOut())
return DoS(100, error("ConnectInputs() : %s value in < value out", GetHash().ToString().substr(0,10).c_str()));
// Tally transaction fees
int64 nTxFee = nValueIn - GetValueOut();
if (nTxFee < 0)
return DoS(100, error("ConnectInputs() : %s nTxFee < 0", GetHash().ToString().substr(0,10).c_str()));
nFees += nTxFee;
if (!MoneyRange(nFees))
return DoS(100, error("ConnectInputs() : nFees out of range"));
}
return true;
}
bool CTransaction::ClientConnectInputs()
{
if (IsCoinBase())
return false;
// Take over previous transactions' spent pointers
{
LOCK(mempool.cs);
int64 nValueIn = 0;
for (unsigned int i = 0; i < vin.size(); i++)
{
// Get prev tx from single transactions in memory
COutPoint prevout = vin[i].prevout;
if (!mempool.exists(prevout.hash))
return false;
CTransaction& txPrev = mempool.lookup(prevout.hash);
if (prevout.n >= txPrev.vout.size())
return false;
// Verify signature
if (!VerifySignature(txPrev, *this, i, true, 0))
return error("ConnectInputs() : VerifySignature failed");
///// this is redundant with the mempool.mapNextTx stuff,
///// not sure which I want to get rid of
///// this has to go away now that posNext is gone
// // Check for conflicts
// if (!txPrev.vout[prevout.n].posNext.IsNull())
// return error("ConnectInputs() : prev tx already used");
//
// // Flag outpoints as used
// txPrev.vout[prevout.n].posNext = posThisTx;
nValueIn += txPrev.vout[prevout.n].nValue;
if (!MoneyRange(txPrev.vout[prevout.n].nValue) || !MoneyRange(nValueIn))
return error("ClientConnectInputs() : txin values out of range");
}
if (GetValueOut() > nValueIn)
return false;
}
return true;
}
bool CBlock::DisconnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Disconnect in reverse order
for (int i = vtx.size()-1; i >= 0; i--)
if (!vtx[i].DisconnectInputs(txdb))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = 0;
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("DisconnectBlock() : WriteBlockIndex failed");
}
return true;
}
bool CBlock::ConnectBlock(CTxDB& txdb, CBlockIndex* pindex)
{
// Check it again in case a previous version let a bad block in
if (!CheckBlock())
return false;
// Do not allow blocks that contain transactions which 'overwrite' older transactions,
// unless those are already completely spent.
// If such overwrites are allowed, coinbases and transactions depending upon those
// can be duplicated to remove the ability to spend the first instance -- even after
// being sent to another address.
// See BIP30 and http://r6.ca/blog/20120206T005236Z.html for more information.
// This logic is not necessary for memory pool transactions, as AcceptToMemoryPool
// already refuses previously-known transaction id's entirely.
// This rule applies to all blocks whose timestamp is after October 1, 2012, 0:00 UTC.
int64 nBIP30SwitchTime = 1349049600;
bool fEnforceBIP30 = (pindex->nTime > nBIP30SwitchTime);
// BIP16 didn't become active until October 1 2012
int64 nBIP16SwitchTime = 1349049600;
bool fStrictPayToScriptHash = (pindex->nTime >= nBIP16SwitchTime);
//// issue here: it doesn't know the version
unsigned int nTxPos = pindex->nBlockPos + ::GetSerializeSize(CBlock(), SER_DISK, CLIENT_VERSION) - 1 + GetSizeOfCompactSize(vtx.size());
map<uint256, CTxIndex> mapQueuedChanges;
int64 nFees = 0;
unsigned int nSigOps = 0;
BOOST_FOREACH(CTransaction& tx, vtx)
{
uint256 hashTx = tx.GetHash();
if (fEnforceBIP30) {
CTxIndex txindexOld;
if (txdb.ReadTxIndex(hashTx, txindexOld)) {
BOOST_FOREACH(CDiskTxPos &pos, txindexOld.vSpent)
if (pos.IsNull())
return false;
}
}
nSigOps += tx.GetLegacySigOpCount();
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
CDiskTxPos posThisTx(pindex->nFile, pindex->nBlockPos, nTxPos);
nTxPos += ::GetSerializeSize(tx, SER_DISK, CLIENT_VERSION);
MapPrevTx mapInputs;
if (!tx.IsCoinBase())
{
bool fInvalid;
if (!tx.FetchInputs(txdb, mapQueuedChanges, true, false, mapInputs, fInvalid))
return false;
if (fStrictPayToScriptHash)
{
// Add in sigops done by pay-to-script-hash inputs;
// this is to prevent a "rogue miner" from creating
// an incredibly-expensive-to-validate block.
nSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("ConnectBlock() : too many sigops"));
}
nFees += tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (!tx.ConnectInputs(mapInputs, mapQueuedChanges, posThisTx, pindex, true, false, fStrictPayToScriptHash))
return false;
}
mapQueuedChanges[hashTx] = CTxIndex(posThisTx, tx.vout.size());
}
// Write queued txindex changes
for (map<uint256, CTxIndex>::iterator mi = mapQueuedChanges.begin(); mi != mapQueuedChanges.end(); ++mi)
{
if (!txdb.UpdateTxIndex((*mi).first, (*mi).second))
return error("ConnectBlock() : UpdateTxIndex failed");
}
if (vtx[0].GetValueOut() > GetBlockValue(pindex->nHeight, nFees))
return false;
// Update block index on disk without changing it in memory.
// The memory index structure will be changed after the db commits.
if (pindex->pprev)
{
CDiskBlockIndex blockindexPrev(pindex->pprev);
blockindexPrev.hashNext = pindex->GetBlockHash();
if (!txdb.WriteBlockIndex(blockindexPrev))
return error("ConnectBlock() : WriteBlockIndex failed");
}
// Watch for transactions paying to me
BOOST_FOREACH(CTransaction& tx, vtx)
SyncWithWallets(tx, this, true);
return true;
}
bool static Reorganize(CTxDB& txdb, CBlockIndex* pindexNew)
{
printf("REORGANIZE\n");
// Find the fork
CBlockIndex* pfork = pindexBest;
CBlockIndex* plonger = pindexNew;
while (pfork != plonger)
{
while (plonger->nHeight > pfork->nHeight)
if (!(plonger = plonger->pprev))
return error("Reorganize() : plonger->pprev is null");
if (pfork == plonger)
break;
if (!(pfork = pfork->pprev))
return error("Reorganize() : pfork->pprev is null");
}
// List of what to disconnect
vector<CBlockIndex*> vDisconnect;
for (CBlockIndex* pindex = pindexBest; pindex != pfork; pindex = pindex->pprev)
vDisconnect.push_back(pindex);
// List of what to connect
vector<CBlockIndex*> vConnect;
for (CBlockIndex* pindex = pindexNew; pindex != pfork; pindex = pindex->pprev)
vConnect.push_back(pindex);
reverse(vConnect.begin(), vConnect.end());
printf("REORGANIZE: Disconnect %i blocks; %s..%s\n", vDisconnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexBest->GetBlockHash().ToString().substr(0,20).c_str());
printf("REORGANIZE: Connect %i blocks; %s..%s\n", vConnect.size(), pfork->GetBlockHash().ToString().substr(0,20).c_str(), pindexNew->GetBlockHash().ToString().substr(0,20).c_str());
// Disconnect shorter branch
vector<CTransaction> vResurrect;
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for disconnect failed");
if (!block.DisconnectBlock(txdb, pindex))
return error("Reorganize() : DisconnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
// Queue memory transactions to resurrect
BOOST_FOREACH(const CTransaction& tx, block.vtx)
if (!tx.IsCoinBase())
vResurrect.push_back(tx);
}
// Connect longer branch
vector<CTransaction> vDelete;
for (unsigned int i = 0; i < vConnect.size(); i++)
{
CBlockIndex* pindex = vConnect[i];
CBlock block;
if (!block.ReadFromDisk(pindex))
return error("Reorganize() : ReadFromDisk for connect failed");
if (!block.ConnectBlock(txdb, pindex))
{
// Invalid block
return error("Reorganize() : ConnectBlock %s failed", pindex->GetBlockHash().ToString().substr(0,20).c_str());
}
// Queue memory transactions to delete
BOOST_FOREACH(const CTransaction& tx, block.vtx)
vDelete.push_back(tx);
}
if (!txdb.WriteHashBestChain(pindexNew->GetBlockHash()))
return error("Reorganize() : WriteHashBestChain failed");
// Make sure it's successfully written to disk before changing memory structure
if (!txdb.TxnCommit())
return error("Reorganize() : TxnCommit failed");
// Disconnect shorter branch
BOOST_FOREACH(CBlockIndex* pindex, vDisconnect)
if (pindex->pprev)
pindex->pprev->pnext = NULL;
// Connect longer branch
BOOST_FOREACH(CBlockIndex* pindex, vConnect)
if (pindex->pprev)
pindex->pprev->pnext = pindex;
// Resurrect memory transactions that were in the disconnected branch
BOOST_FOREACH(CTransaction& tx, vResurrect)
tx.AcceptToMemoryPool(txdb, false);
// Delete redundant memory transactions that are in the connected branch
BOOST_FOREACH(CTransaction& tx, vDelete)
mempool.remove(tx);
printf("REORGANIZE: done\n");
return true;
}
// Called from inside SetBestChain: attaches a block to the new best chain being built
bool CBlock::SetBestChainInner(CTxDB& txdb, CBlockIndex *pindexNew)
{
uint256 hash = GetHash();
// Adding to current best branch
if (!ConnectBlock(txdb, pindexNew) || !txdb.WriteHashBestChain(hash))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return false;
}
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
// Add to current best branch
pindexNew->pprev->pnext = pindexNew;
// Delete redundant memory transactions
BOOST_FOREACH(CTransaction& tx, vtx)
mempool.remove(tx);
return true;
}
bool CBlock::SetBestChain(CTxDB& txdb, CBlockIndex* pindexNew)
{
uint256 hash = GetHash();
if (!txdb.TxnBegin())
return error("SetBestChain() : TxnBegin failed");
if (pindexGenesisBlock == NULL && hash == hashGenesisBlock)
{
txdb.WriteHashBestChain(hash);
if (!txdb.TxnCommit())
return error("SetBestChain() : TxnCommit failed");
pindexGenesisBlock = pindexNew;
}
else if (hashPrevBlock == hashBestChain)
{
if (!SetBestChainInner(txdb, pindexNew))
return error("SetBestChain() : SetBestChainInner failed");
}
else
{
// the first block in the new chain that will cause it to become the new best chain
CBlockIndex *pindexIntermediate = pindexNew;
// list of blocks that need to be connected afterwards
std::vector<CBlockIndex*> vpindexSecondary;
// Reorganize is costly in terms of db load, as it works in a single db transaction.
// Try to limit how much needs to be done inside
while (pindexIntermediate->pprev && pindexIntermediate->pprev->bnChainWork > pindexBest->bnChainWork)
{
vpindexSecondary.push_back(pindexIntermediate);
pindexIntermediate = pindexIntermediate->pprev;
}
if (!vpindexSecondary.empty())
printf("Postponing %i reconnects\n", vpindexSecondary.size());
// Switch to new best branch
if (!Reorganize(txdb, pindexIntermediate))
{
txdb.TxnAbort();
InvalidChainFound(pindexNew);
return error("SetBestChain() : Reorganize failed");
}
// Connect futher blocks
BOOST_REVERSE_FOREACH(CBlockIndex *pindex, vpindexSecondary)
{
CBlock block;
if (!block.ReadFromDisk(pindex))
{
printf("SetBestChain() : ReadFromDisk failed\n");
break;
}
if (!txdb.TxnBegin()) {
printf("SetBestChain() : TxnBegin 2 failed\n");
break;
}
// errors now are not fatal, we still did a reorganisation to a new chain in a valid way
if (!block.SetBestChainInner(txdb, pindex))
break;
}
}
// Update best block in wallet (so we can detect restored wallets)
bool fIsInitialDownload = IsInitialBlockDownload();
if (!fIsInitialDownload)
{
const CBlockLocator locator(pindexNew);
::SetBestChain(locator);
}
// New best block
hashBestChain = hash;
pindexBest = pindexNew;
nBestHeight = pindexBest->nHeight;
bnBestChainWork = pindexNew->bnChainWork;
nTimeBestReceived = GetTime();
nTransactionsUpdated++;
printf("SetBestChain: new best=%s height=%d work=%s date=%s\n",
hashBestChain.ToString().substr(0,20).c_str(), nBestHeight, bnBestChainWork.ToString().c_str(),
DateTimeStrFormat("%x %H:%M:%S", pindexBest->GetBlockTime()).c_str());
// Check the version of the last 100 blocks to see if we need to upgrade:
if (!fIsInitialDownload)
{
int nUpgraded = 0;
const CBlockIndex* pindex = pindexBest;
for (int i = 0; i < 100 && pindex != NULL; i++)
{
if (pindex->nVersion > CBlock::CURRENT_VERSION)
++nUpgraded;
pindex = pindex->pprev;
}
if (nUpgraded > 0)
printf("SetBestChain: %d of last 100 blocks above version %d\n", nUpgraded, CBlock::CURRENT_VERSION);
// if (nUpgraded > 100/2)
// strMiscWarning is read by GetWarnings(), called by Qt and the JSON-RPC code to warn the user:
// strMiscWarning = _("Warning: this version is obsolete, upgrade required");
}
std::string strCmd = GetArg("-blocknotify", "");
if (!fIsInitialDownload && !strCmd.empty())
{
boost::replace_all(strCmd, "%s", hashBestChain.GetHex());
boost::thread t(runCommand, strCmd); // thread runs free
}
return true;
}
bool CBlock::AddToBlockIndex(unsigned int nFile, unsigned int nBlockPos)
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AddToBlockIndex() : %s already exists", hash.ToString().substr(0,20).c_str());
// Construct new block index object
CBlockIndex* pindexNew = new CBlockIndex(nFile, nBlockPos, *this);
if (!pindexNew)
return error("AddToBlockIndex() : new CBlockIndex failed");
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.insert(make_pair(hash, pindexNew)).first;
pindexNew->phashBlock = &((*mi).first);
map<uint256, CBlockIndex*>::iterator miPrev = mapBlockIndex.find(hashPrevBlock);
if (miPrev != mapBlockIndex.end())
{
pindexNew->pprev = (*miPrev).second;
pindexNew->nHeight = pindexNew->pprev->nHeight + 1;
}
pindexNew->bnChainWork = (pindexNew->pprev ? pindexNew->pprev->bnChainWork : 0) + pindexNew->GetBlockWork();
CTxDB txdb;
if (!txdb.TxnBegin())
return false;
txdb.WriteBlockIndex(CDiskBlockIndex(pindexNew));
if (!txdb.TxnCommit())
return false;
// New best
if (pindexNew->bnChainWork > bnBestChainWork)
if (!SetBestChain(txdb, pindexNew))
return false;
txdb.Close();
if (pindexNew == pindexBest)
{
// Notify UI to display prev block's coinbase if it was ours
static uint256 hashPrevBestCoinBase;
UpdatedTransaction(hashPrevBestCoinBase);
hashPrevBestCoinBase = vtx[0].GetHash();
}
uiInterface.NotifyBlocksChanged();
return true;
}
bool CBlock::CheckBlock() const
{
// These are checks that are independent of context
// that can be verified before saving an orphan block.
// Size limits
if (vtx.empty() || vtx.size() > MAX_BLOCK_SIZE || ::GetSerializeSize(*this, SER_NETWORK, PROTOCOL_VERSION) > MAX_BLOCK_SIZE)
return DoS(100, error("CheckBlock() : size limits failed"));
// Special short-term limits to avoid 10,000 BDB lock limit:
if (GetBlockTime() < 1376568000) // stop enforcing 15 August 2013 noon GMT
{
// Rule is: #unique txids referenced <= 4,500
// ... to prevent 10,000 BDB lock exhaustion on old clients
set<uint256> setTxIn;
for (size_t i = 0; i < vtx.size(); i++)
{
setTxIn.insert(vtx[i].GetHash());
if (i == 0) continue; // skip coinbase txin
BOOST_FOREACH(const CTxIn& txin, vtx[i].vin)
setTxIn.insert(txin.prevout.hash);
}
size_t nTxids = setTxIn.size();
if (nTxids > 4500)
return error("CheckBlock() : 15 Aug maxlocks violation");
}
// Check proof of work matches claimed amount
if (!CheckProofOfWork(GetPoWHash(), nBits))
return DoS(50, error("CheckBlock() : proof of work failed"));
// Check timestamp
if (GetBlockTime() > GetAdjustedTime() + 2 * 60 * 60)
return error("CheckBlock() : block timestamp too far in the future");
// First transaction must be coinbase, the rest must not be
if (vtx.empty() || !vtx[0].IsCoinBase())
return DoS(100, error("CheckBlock() : first tx is not coinbase"));
for (unsigned int i = 1; i < vtx.size(); i++)
if (vtx[i].IsCoinBase())
return DoS(100, error("CheckBlock() : more than one coinbase"));
// Check transactions
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.CheckTransaction())
return DoS(tx.nDoS, error("CheckBlock() : CheckTransaction failed"));
// Check for duplicate txids. This is caught by ConnectInputs(),
// but catching it earlier avoids a potential DoS attack:
set<uint256> uniqueTx;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
uniqueTx.insert(tx.GetHash());
}
if (uniqueTx.size() != vtx.size())
return DoS(100, error("CheckBlock() : duplicate transaction"));
unsigned int nSigOps = 0;
BOOST_FOREACH(const CTransaction& tx, vtx)
{
nSigOps += tx.GetLegacySigOpCount();
}
if (nSigOps > MAX_BLOCK_SIGOPS)
return DoS(100, error("CheckBlock() : out-of-bounds SigOpCount"));
// Check merkleroot
if (hashMerkleRoot != BuildMerkleTree())
return DoS(100, error("CheckBlock() : hashMerkleRoot mismatch"));
return true;
}
bool CBlock::AcceptBlock()
{
// Check for duplicate
uint256 hash = GetHash();
if (mapBlockIndex.count(hash))
return error("AcceptBlock() : block already in mapBlockIndex");
// Get prev block index
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashPrevBlock);
if (mi == mapBlockIndex.end())
return DoS(10, error("AcceptBlock() : prev block not found"));
CBlockIndex* pindexPrev = (*mi).second;
int nHeight = pindexPrev->nHeight+1;
// Check proof of work
if (nBits != GetNextWorkRequired(pindexPrev, this))
return DoS(100, error("AcceptBlock() : incorrect proof of work"));
// Check timestamp against prev
if (GetBlockTime() <= pindexPrev->GetMedianTimePast())
return error("AcceptBlock() : block's timestamp is too early");
// Check that all transactions are finalized
BOOST_FOREACH(const CTransaction& tx, vtx)
if (!tx.IsFinal(nHeight, GetBlockTime()))
return DoS(10, error("AcceptBlock() : contains a non-final transaction"));
// Check that the block chain matches the known block chain up to a checkpoint
if (!Checkpoints::CheckBlock(nHeight, hash))
return DoS(100, error("AcceptBlock() : rejected by checkpoint lockin at %d", nHeight));
// Write block to history file
if (!CheckDiskSpace(::GetSerializeSize(*this, SER_DISK, CLIENT_VERSION)))
return error("AcceptBlock() : out of disk space");
unsigned int nFile = -1;
unsigned int nBlockPos = 0;
if (!WriteToDisk(nFile, nBlockPos))
return error("AcceptBlock() : WriteToDisk failed");
if (!AddToBlockIndex(nFile, nBlockPos))
return error("AcceptBlock() : AddToBlockIndex failed");
// Relay inventory, but don't relay old inventory during initial block download
int nBlockEstimate = Checkpoints::GetTotalBlocksEstimate();
if (hashBestChain == hash)
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
if (nBestHeight > (pnode->nStartingHeight != -1 ? pnode->nStartingHeight - 2000 : nBlockEstimate))
pnode->PushInventory(CInv(MSG_BLOCK, hash));
}
return true;
}
bool ProcessBlock(CNode* pfrom, CBlock* pblock)
{
// Check for duplicate
uint256 hash = pblock->GetHash();
if (mapBlockIndex.count(hash))
return error("ProcessBlock() : already have block %d %s", mapBlockIndex[hash]->nHeight, hash.ToString().substr(0,20).c_str());
if (mapOrphanBlocks.count(hash))
return error("ProcessBlock() : already have block (orphan) %s", hash.ToString().substr(0,20).c_str());
// Preliminary checks
if (!pblock->CheckBlock())
return error("ProcessBlock() : CheckBlock FAILED");
CBlockIndex* pcheckpoint = Checkpoints::GetLastCheckpoint(mapBlockIndex);
if (pcheckpoint && pblock->hashPrevBlock != hashBestChain)
{
// Extra checks to prevent "fill up memory by spamming with bogus blocks"
int64 deltaTime = pblock->GetBlockTime() - pcheckpoint->nTime;
if (deltaTime < 0)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with timestamp before last checkpoint");
}
CBigNum bnNewBlock;
bnNewBlock.SetCompact(pblock->nBits);
CBigNum bnRequired;
bnRequired.SetCompact(ComputeMinWork(pcheckpoint->nBits, deltaTime));
if (bnNewBlock > bnRequired)
{
if (pfrom)
pfrom->Misbehaving(100);
return error("ProcessBlock() : block with too little proof-of-work");
}
}
// If don't already have its previous block, shunt it off to holding area until we get it
if (!mapBlockIndex.count(pblock->hashPrevBlock))
{
printf("ProcessBlock: ORPHAN BLOCK, prev=%s\n", pblock->hashPrevBlock.ToString().substr(0,20).c_str());
CBlock* pblock2 = new CBlock(*pblock);
mapOrphanBlocks.insert(make_pair(hash, pblock2));
mapOrphanBlocksByPrev.insert(make_pair(pblock2->hashPrevBlock, pblock2));
// Ask this guy to fill in what we're missing
if (pfrom)
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(pblock2));
return true;
}
// Store to disk
if (!pblock->AcceptBlock())
return error("ProcessBlock() : AcceptBlock FAILED");
// Recursively process any orphan blocks that depended on this one
vector<uint256> vWorkQueue;
vWorkQueue.push_back(hash);
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (multimap<uint256, CBlock*>::iterator mi = mapOrphanBlocksByPrev.lower_bound(hashPrev);
mi != mapOrphanBlocksByPrev.upper_bound(hashPrev);
++mi)
{
CBlock* pblockOrphan = (*mi).second;
if (pblockOrphan->AcceptBlock())
vWorkQueue.push_back(pblockOrphan->GetHash());
mapOrphanBlocks.erase(pblockOrphan->GetHash());
delete pblockOrphan;
}
mapOrphanBlocksByPrev.erase(hashPrev);
}
printf("ProcessBlock: ACCEPTED\n");
return true;
}
bool CheckDiskSpace(uint64 nAdditionalBytes)
{
uint64 nFreeBytesAvailable = filesystem::space(GetDataDir()).available;
// Check for nMinDiskSpace bytes (currently 50MB)
if (nFreeBytesAvailable < nMinDiskSpace + nAdditionalBytes)
{
fShutdown = true;
string strMessage = _("Warning: Disk space is low");
strMiscWarning = strMessage;
printf("*** %s\n", strMessage.c_str());
uiInterface.ThreadSafeMessageBox(strMessage, "Dream8coin", CClientUIInterface::OK | CClientUIInterface::ICON_EXCLAMATION | CClientUIInterface::MODAL);
StartShutdown();
return false;
}
return true;
}
FILE* OpenBlockFile(unsigned int nFile, unsigned int nBlockPos, const char* pszMode)
{
if ((nFile < 1) || (nFile == (unsigned int) -1))
return NULL;
FILE* file = fopen((GetDataDir() / strprintf("blk%04d.dat", nFile)).string().c_str(), pszMode);
if (!file)
return NULL;
if (nBlockPos != 0 && !strchr(pszMode, 'a') && !strchr(pszMode, 'w'))
{
if (fseek(file, nBlockPos, SEEK_SET) != 0)
{
fclose(file);
return NULL;
}
}
return file;
}
static unsigned int nCurrentBlockFile = 1;
FILE* AppendBlockFile(unsigned int& nFileRet)
{
nFileRet = 0;
loop
{
FILE* file = OpenBlockFile(nCurrentBlockFile, 0, "ab");
if (!file)
return NULL;
if (fseek(file, 0, SEEK_END) != 0)
return NULL;
// FAT32 filesize max 4GB, fseek and ftell max 2GB, so we must stay under 2GB
if (ftell(file) < 0x7F000000 - MAX_SIZE)
{
nFileRet = nCurrentBlockFile;
return file;
}
fclose(file);
nCurrentBlockFile++;
}
}
bool LoadBlockIndex(bool fAllowNew)
{
if (fTestNet)
{
pchMessageStart[0] = 0xfc;
pchMessageStart[1] = 0xc1;
pchMessageStart[2] = 0xb7;
pchMessageStart[3] = 0xdc;
hashGenesisBlock = uint256("0xd8c946602ff3ae919158f21a64db0d44fe042211f7e50e9224552876ada4ccc5");
}
//
// Load block index
//
CTxDB txdb("cr");
if (!txdb.LoadBlockIndex())
return false;
txdb.Close();
//
// Init with genesis block
//
if (mapBlockIndex.empty())
{
if (!fAllowNew)
return false;
// Genesis Block:
// CBlock(hash=12a765e31ffd4059bada, PoW=0000050c34a64b415b6b, ver=1, hashPrevBlock=00000000000000000000, hashMerkleRoot=97ddfbbae6, nTime=1317972665, nBits=1e0ffff0, nNonce=2084524493, vtx=1)
// CTransaction(hash=97ddfbbae6, ver=1, vin.size=1, vout.size=1, nLockTime=0)
// CTxIn(COutPoint(0000000000, -1), coinbase 04ffff001d0104404e592054696d65732030352f4f63742f32303131205374657665204a6f62732c204170706c65e280997320566973696f6e6172792c2044696573206174203536)
// CTxOut(nValue=50.00000000, scriptPubKey=040184710fa689ad5023690c80f3a4)
// vMerkleTree: 97ddfbbae6
// Genesis block
// RT
const char* pszTimestamp = "NY Times 10/2016 iPhone7, Apple’s Thanks";
CTransaction txNew;
txNew.vin.resize(1);
txNew.vout.resize(1);
txNew.vin[0].scriptSig = CScript() << 486604799 << CBigNum(4) << vector<unsigned char>((const unsigned char*)pszTimestamp, (const unsigned char*)pszTimestamp + strlen(pszTimestamp));
txNew.vout[0].nValue = 50 * COIN;
txNew.vout[0].scriptPubKey = CScript() << ParseHex("040184710fa689ad5023690c80f3a49c8f13f8d45b8c857fbcbc8bc4a8e4d3eb4b10f4d4604fa08dce601aaf0f470216fe1b51850b4acf21b179c45070ac7b03a9") << OP_CHECKSIG;
CBlock block;
block.vtx.push_back(txNew);
block.hashPrevBlock = 0;
block.hashMerkleRoot = block.BuildMerkleTree();
block.nVersion = 1;
block.nTime = 1475372052;
block.nBits = 0x1e0ffff0;
block.nNonce = 3073224493;
if (fTestNet)
{
block.nTime = 1475372009;
block.nNonce = 452170584;
}
//// debug print
printf("%s\n", block.GetHash().ToString().c_str());
printf("%s\n", hashGenesisBlock.ToString().c_str());
printf("%s\n", block.hashMerkleRoot.ToString().c_str());
assert(block.hashMerkleRoot == uint256("0xbb4fd26db604834f42cf72c7d8fd567aa247c64d97d1be418f9c6205aefd0062"));
// If genesis block hash does not match, then generate new genesis hash.
if (false && block.GetHash() != hashGenesisBlock)
{
printf("Searching for genesis block...\n");
// This will figure out a valid hash and Nonce if you're
// creating a different genesis block:
uint256 hashTarget = CBigNum().SetCompact(block.nBits).getuint256();
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(block.nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
break;
if ((block.nNonce & 0xFFF) == 0)
{
printf("nonce %08X: hash = %s (target = %s)\n", block.nNonce, thash.ToString().c_str(), hashTarget.ToString().c_str());
}
++block.nNonce;
if (block.nNonce == 0)
{
printf("NONCE WRAPPED, incrementing time\n");
++block.nTime;
}
}
printf("block.nTime = %u \n", block.nTime);
printf("block.nNonce = %u \n", block.nNonce);
printf("block.GetHash = %s\n", block.GetHash().ToString().c_str());
}
block.print();
assert(block.GetHash() == hashGenesisBlock);
// Start new block file
unsigned int nFile;
unsigned int nBlockPos;
if (!block.WriteToDisk(nFile, nBlockPos))
return error("LoadBlockIndex() : writing genesis block to disk failed");
if (!block.AddToBlockIndex(nFile, nBlockPos))
return error("LoadBlockIndex() : genesis block not accepted");
}
return true;
}
void PrintBlockTree()
{
// precompute tree structure
map<CBlockIndex*, vector<CBlockIndex*> > mapNext;
for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi)
{
CBlockIndex* pindex = (*mi).second;
mapNext[pindex->pprev].push_back(pindex);
// test
//while (rand() % 3 == 0)
// mapNext[pindex->pprev].push_back(pindex);
}
vector<pair<int, CBlockIndex*> > vStack;
vStack.push_back(make_pair(0, pindexGenesisBlock));
int nPrevCol = 0;
while (!vStack.empty())
{
int nCol = vStack.back().first;
CBlockIndex* pindex = vStack.back().second;
vStack.pop_back();
// print split or gap
if (nCol > nPrevCol)
{
for (int i = 0; i < nCol-1; i++)
printf("| ");
printf("|\\\n");
}
else if (nCol < nPrevCol)
{
for (int i = 0; i < nCol; i++)
printf("| ");
printf("|\n");
}
nPrevCol = nCol;
// print columns
for (int i = 0; i < nCol; i++)
printf("| ");
// print item
CBlock block;
block.ReadFromDisk(pindex);
printf("%d (%u,%u) %s %s tx %d",
pindex->nHeight,
pindex->nFile,
pindex->nBlockPos,
block.GetHash().ToString().substr(0,20).c_str(),
DateTimeStrFormat("%x %H:%M:%S", block.GetBlockTime()).c_str(),
block.vtx.size());
PrintWallets(block);
// put the main timechain first
vector<CBlockIndex*>& vNext = mapNext[pindex];
for (unsigned int i = 0; i < vNext.size(); i++)
{
if (vNext[i]->pnext)
{
swap(vNext[0], vNext[i]);
break;
}
}
// iterate children
for (unsigned int i = 0; i < vNext.size(); i++)
vStack.push_back(make_pair(nCol+i, vNext[i]));
}
}
bool LoadExternalBlockFile(FILE* fileIn)
{
int nLoaded = 0;
{
LOCK(cs_main);
try {
CAutoFile blkdat(fileIn, SER_DISK, CLIENT_VERSION);
unsigned int nPos = 0;
while (nPos != (unsigned int)-1 && blkdat.good() && !fRequestShutdown)
{
unsigned char pchData[65536];
do {
fseek(blkdat, nPos, SEEK_SET);
int nRead = fread(pchData, 1, sizeof(pchData), blkdat);
if (nRead <= 8)
{
nPos = (unsigned int)-1;
break;
}
void* nFind = memchr(pchData, pchMessageStart[0], nRead+1-sizeof(pchMessageStart));
if (nFind)
{
if (memcmp(nFind, pchMessageStart, sizeof(pchMessageStart))==0)
{
nPos += ((unsigned char*)nFind - pchData) + sizeof(pchMessageStart);
break;
}
nPos += ((unsigned char*)nFind - pchData) + 1;
}
else
nPos += sizeof(pchData) - sizeof(pchMessageStart) + 1;
} while(!fRequestShutdown);
if (nPos == (unsigned int)-1)
break;
fseek(blkdat, nPos, SEEK_SET);
unsigned int nSize;
blkdat >> nSize;
if (nSize > 0 && nSize <= MAX_BLOCK_SIZE)
{
CBlock block;
blkdat >> block;
if (ProcessBlock(NULL,&block))
{
nLoaded++;
nPos += 4 + nSize;
}
}
}
}
catch (std::exception &e) {
printf("%s() : Deserialize or I/O error caught during load\n",
__PRETTY_FUNCTION__);
}
}
printf("Loaded %i blocks from external file\n", nLoaded);
return nLoaded > 0;
}
//////////////////////////////////////////////////////////////////////////////
//
// CAlert
//
map<uint256, CAlert> mapAlerts;
CCriticalSection cs_mapAlerts;
string GetWarnings(string strFor)
{
int nPriority = 0;
string strStatusBar;
string strRPC;
if (GetBoolArg("-testsafemode"))
strRPC = "test";
// Misc warnings like out of disk space and clock is wrong
if (strMiscWarning != "")
{
nPriority = 1000;
strStatusBar = strMiscWarning;
}
// Longer invalid proof-of-work chain
if (pindexBest && bnBestInvalidWork > bnBestChainWork + pindexBest->GetBlockWork() * 6)
{
nPriority = 2000;
strStatusBar = strRPC = "WARNING: Displayed transactions may not be correct! You may need to upgrade, or other nodes may need to upgrade.";
}
// Alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.AppliesToMe() && alert.nPriority > nPriority)
{
nPriority = alert.nPriority;
strStatusBar = alert.strStatusBar;
}
}
}
if (strFor == "statusbar")
return strStatusBar;
else if (strFor == "rpc")
return strRPC;
assert(!"GetWarnings() : invalid parameter");
return "error";
}
CAlert CAlert::getAlertByHash(const uint256 &hash)
{
CAlert retval;
{
LOCK(cs_mapAlerts);
map<uint256, CAlert>::iterator mi = mapAlerts.find(hash);
if(mi != mapAlerts.end())
retval = mi->second;
}
return retval;
}
bool CAlert::ProcessAlert()
{
if (!CheckSignature())
return false;
if (!IsInEffect())
return false;
{
LOCK(cs_mapAlerts);
// Cancel previous alerts
for (map<uint256, CAlert>::iterator mi = mapAlerts.begin(); mi != mapAlerts.end();)
{
const CAlert& alert = (*mi).second;
if (Cancels(alert))
{
printf("cancelling alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else if (!alert.IsInEffect())
{
printf("expiring alert %d\n", alert.nID);
uiInterface.NotifyAlertChanged((*mi).first, CT_DELETED);
mapAlerts.erase(mi++);
}
else
mi++;
}
// Check if this alert has been cancelled
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
{
const CAlert& alert = item.second;
if (alert.Cancels(*this))
{
printf("alert already cancelled by %d\n", alert.nID);
return false;
}
}
// Add to mapAlerts
mapAlerts.insert(make_pair(GetHash(), *this));
// Notify UI if it applies to me
if(AppliesToMe())
uiInterface.NotifyAlertChanged(GetHash(), CT_NEW);
}
printf("accepted alert %d, AppliesToMe()=%d\n", nID, AppliesToMe());
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// Messages
//
bool static AlreadyHave(CTxDB& txdb, const CInv& inv)
{
switch (inv.type)
{
case MSG_TX:
{
bool txInMap = false;
{
LOCK(mempool.cs);
txInMap = (mempool.exists(inv.hash));
}
return txInMap ||
mapOrphanTransactions.count(inv.hash) ||
txdb.ContainsTx(inv.hash);
}
case MSG_BLOCK:
return mapBlockIndex.count(inv.hash) ||
mapOrphanBlocks.count(inv.hash);
}
// Don't know what it is, just say we already got one
return true;
}
// The message start string is designed to be unlikely to occur in normal data.
// The characters are rarely used upper ascii, not valid as UTF-8, and produce
// a large 4-byte int at any alignment.
unsigned char pchMessageStart[4] = { 0xfb, 0xc0, 0xb6, 0xdb }; // Dream8coin: increase each by adding 2 to bitcoin's value.
bool static ProcessMessage(CNode* pfrom, string strCommand, CDataStream& vRecv)
{
static map<CService, CPubKey> mapReuseKey;
RandAddSeedPerfmon();
if (fDebug)
printf("received: %s (%d bytes)\n", strCommand.c_str(), vRecv.size());
if (mapArgs.count("-dropmessagestest") && GetRand(atoi(mapArgs["-dropmessagestest"])) == 0)
{
printf("dropmessagestest DROPPING RECV MESSAGE\n");
return true;
}
if (strCommand == "version")
{
// Each connection can only send one version message
if (pfrom->nVersion != 0)
{
pfrom->Misbehaving(1);
return false;
}
int64 nTime;
CAddress addrMe;
CAddress addrFrom;
uint64 nNonce = 1;
vRecv >> pfrom->nVersion >> pfrom->nServices >> nTime >> addrMe;
if (pfrom->nVersion < MIN_PROTO_VERSION)
{
// Since February 20, 2012, the protocol is initiated at version 209,
// and earlier versions are no longer supported
printf("partner %s using obsolete version %i; disconnecting\n", pfrom->addr.ToString().c_str(), pfrom->nVersion);
pfrom->fDisconnect = true;
return false;
}
if (pfrom->nVersion == 10300)
pfrom->nVersion = 300;
if (!vRecv.empty())
vRecv >> addrFrom >> nNonce;
if (!vRecv.empty())
vRecv >> pfrom->strSubVer;
if (!vRecv.empty())
vRecv >> pfrom->nStartingHeight;
if (pfrom->fInbound && addrMe.IsRoutable())
{
pfrom->addrLocal = addrMe;
SeenLocal(addrMe);
}
// Disconnect if we connected to ourself
if (nNonce == nLocalHostNonce && nNonce > 1)
{
printf("connected to self at %s, disconnecting\n", pfrom->addr.ToString().c_str());
pfrom->fDisconnect = true;
return true;
}
// Be shy and don't send version until we hear
if (pfrom->fInbound)
pfrom->PushVersion();
pfrom->fClient = !(pfrom->nServices & NODE_NETWORK);
AddTimeData(pfrom->addr, nTime);
// Change version
pfrom->PushMessage("verack");
pfrom->vSend.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
if (!pfrom->fInbound)
{
// Advertise our address
if (!fNoListen && !IsInitialBlockDownload())
{
CAddress addr = GetLocalAddress(&pfrom->addr);
if (addr.IsRoutable())
pfrom->PushAddress(addr);
}
// Get recent addresses
if (pfrom->fOneShot || pfrom->nVersion >= CADDR_TIME_VERSION || addrman.size() < 1000)
{
pfrom->PushMessage("getaddr");
pfrom->fGetAddr = true;
}
addrman.Good(pfrom->addr);
} else {
if (((CNetAddr)pfrom->addr) == (CNetAddr)addrFrom)
{
addrman.Add(addrFrom, addrFrom);
addrman.Good(addrFrom);
}
}
// Ask the first connected node for block updates
static int nAskedForBlocks = 0;
if (!pfrom->fClient && !pfrom->fOneShot &&
(pfrom->nVersion < NOBLKS_VERSION_START ||
pfrom->nVersion >= NOBLKS_VERSION_END) &&
(nAskedForBlocks < 1 || vNodes.size() <= 1))
{
nAskedForBlocks++;
pfrom->PushGetBlocks(pindexBest, uint256(0));
}
// Relay alerts
{
LOCK(cs_mapAlerts);
BOOST_FOREACH(PAIRTYPE(const uint256, CAlert)& item, mapAlerts)
item.second.RelayTo(pfrom);
}
pfrom->fSuccessfullyConnected = true;
printf("receive version message: version %d, blocks=%d, us=%s, them=%s, peer=%s\n", pfrom->nVersion, pfrom->nStartingHeight, addrMe.ToString().c_str(), addrFrom.ToString().c_str(), pfrom->addr.ToString().c_str());
cPeerBlockCounts.input(pfrom->nStartingHeight);
}
else if (pfrom->nVersion == 0)
{
// Must have a version message before anything else
pfrom->Misbehaving(1);
return false;
}
else if (strCommand == "verack")
{
pfrom->vRecv.SetVersion(min(pfrom->nVersion, PROTOCOL_VERSION));
}
else if (strCommand == "addr")
{
vector<CAddress> vAddr;
vRecv >> vAddr;
// Don't want addr from older versions unless seeding
if (pfrom->nVersion < CADDR_TIME_VERSION && addrman.size() > 1000)
return true;
if (vAddr.size() > 1000)
{
pfrom->Misbehaving(20);
return error("message addr size() = %d", vAddr.size());
}
// Store the new addresses
vector<CAddress> vAddrOk;
int64 nNow = GetAdjustedTime();
int64 nSince = nNow - 10 * 60;
BOOST_FOREACH(CAddress& addr, vAddr)
{
if (fShutdown)
return true;
if (addr.nTime <= 100000000 || addr.nTime > nNow + 10 * 60)
addr.nTime = nNow - 5 * 24 * 60 * 60;
pfrom->AddAddressKnown(addr);
bool fReachable = IsReachable(addr);
if (addr.nTime > nSince && !pfrom->fGetAddr && vAddr.size() <= 10 && addr.IsRoutable())
{
// Relay to a limited number of other nodes
{
LOCK(cs_vNodes);
// Use deterministic randomness to send to the same nodes for 24 hours
// at a time so the setAddrKnowns of the chosen nodes prevent repeats
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint64 hashAddr = addr.GetHash();
uint256 hashRand = hashSalt ^ (hashAddr<<32) ^ ((GetTime()+hashAddr)/(24*60*60));
hashRand = Hash(BEGIN(hashRand), END(hashRand));
multimap<uint256, CNode*> mapMix;
BOOST_FOREACH(CNode* pnode, vNodes)
{
if (pnode->nVersion < CADDR_TIME_VERSION)
continue;
unsigned int nPointer;
memcpy(&nPointer, &pnode, sizeof(nPointer));
uint256 hashKey = hashRand ^ nPointer;
hashKey = Hash(BEGIN(hashKey), END(hashKey));
mapMix.insert(make_pair(hashKey, pnode));
}
int nRelayNodes = fReachable ? 2 : 1; // limited relaying of addresses outside our network(s)
for (multimap<uint256, CNode*>::iterator mi = mapMix.begin(); mi != mapMix.end() && nRelayNodes-- > 0; ++mi)
((*mi).second)->PushAddress(addr);
}
}
// Do not store addresses outside our network
if (fReachable)
vAddrOk.push_back(addr);
}
addrman.Add(vAddrOk, pfrom->addr, 2 * 60 * 60);
if (vAddr.size() < 1000)
pfrom->fGetAddr = false;
if (pfrom->fOneShot)
pfrom->fDisconnect = true;
}
else if (strCommand == "inv")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message inv size() = %d", vInv.size());
}
// find last block in inv vector
unsigned int nLastBlock = (unsigned int)(-1);
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++) {
if (vInv[vInv.size() - 1 - nInv].type == MSG_BLOCK) {
nLastBlock = vInv.size() - 1 - nInv;
break;
}
}
CTxDB txdb("r");
for (unsigned int nInv = 0; nInv < vInv.size(); nInv++)
{
const CInv &inv = vInv[nInv];
if (fShutdown)
return true;
pfrom->AddInventoryKnown(inv);
bool fAlreadyHave = AlreadyHave(txdb, inv);
if (fDebug)
printf(" got inventory: %s %s\n", inv.ToString().c_str(), fAlreadyHave ? "have" : "new");
if (!fAlreadyHave)
pfrom->AskFor(inv);
else if (inv.type == MSG_BLOCK && mapOrphanBlocks.count(inv.hash)) {
pfrom->PushGetBlocks(pindexBest, GetOrphanRoot(mapOrphanBlocks[inv.hash]));
} else if (nInv == nLastBlock) {
// In case we are on a very long side-chain, it is possible that we already have
// the last block in an inv bundle sent in response to getblocks. Try to detect
// this situation and push another getblocks to continue.
std::vector<CInv> vGetData(1,inv);
pfrom->PushGetBlocks(mapBlockIndex[inv.hash], uint256(0));
if (fDebug)
printf("force request: %s\n", inv.ToString().c_str());
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getdata")
{
vector<CInv> vInv;
vRecv >> vInv;
if (vInv.size() > 50000)
{
pfrom->Misbehaving(20);
return error("message getdata size() = %d", vInv.size());
}
if (fDebugNet || (vInv.size() != 1))
printf("received getdata (%d invsz)\n", vInv.size());
BOOST_FOREACH(const CInv& inv, vInv)
{
if (fShutdown)
return true;
if (fDebugNet || (vInv.size() == 1))
printf("received getdata for: %s\n", inv.ToString().c_str());
if (inv.type == MSG_BLOCK)
{
// Send block from disk
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(inv.hash);
if (mi != mapBlockIndex.end())
{
CBlock block;
block.ReadFromDisk((*mi).second);
pfrom->PushMessage("block", block);
// Trigger them to send a getblocks request for the next batch of inventory
if (inv.hash == pfrom->hashContinue)
{
// Bypass PushInventory, this must send even if redundant,
// and we want it right after the last block so they don't
// wait for other stuff first.
vector<CInv> vInv;
vInv.push_back(CInv(MSG_BLOCK, hashBestChain));
pfrom->PushMessage("inv", vInv);
pfrom->hashContinue = 0;
}
}
}
else if (inv.IsKnownType())
{
// Send stream from relay memory
{
LOCK(cs_mapRelay);
map<CInv, CDataStream>::iterator mi = mapRelay.find(inv);
if (mi != mapRelay.end())
pfrom->PushMessage(inv.GetCommand(), (*mi).second);
}
}
// Track requests for our stuff
Inventory(inv.hash);
}
}
else if (strCommand == "getblocks")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
// Find the last block the caller has in the main chain
CBlockIndex* pindex = locator.GetBlockIndex();
// Send the rest of the chain
if (pindex)
pindex = pindex->pnext;
int nLimit = 500;
printf("getblocks %d to %s limit %d\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str(), nLimit);
for (; pindex; pindex = pindex->pnext)
{
if (pindex->GetBlockHash() == hashStop)
{
printf(" getblocks stopping at %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
break;
}
pfrom->PushInventory(CInv(MSG_BLOCK, pindex->GetBlockHash()));
if (--nLimit <= 0)
{
// When this block is requested, we'll send an inv that'll make them
// getblocks the next batch of inventory.
printf(" getblocks stopping at limit %d %s\n", pindex->nHeight, pindex->GetBlockHash().ToString().substr(0,20).c_str());
pfrom->hashContinue = pindex->GetBlockHash();
break;
}
}
}
else if (strCommand == "getheaders")
{
CBlockLocator locator;
uint256 hashStop;
vRecv >> locator >> hashStop;
CBlockIndex* pindex = NULL;
if (locator.IsNull())
{
// If locator is null, return the hashStop block
map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.find(hashStop);
if (mi == mapBlockIndex.end())
return true;
pindex = (*mi).second;
}
else
{
// Find the last block the caller has in the main chain
pindex = locator.GetBlockIndex();
if (pindex)
pindex = pindex->pnext;
}
vector<CBlock> vHeaders;
int nLimit = 2000;
printf("getheaders %d to %s\n", (pindex ? pindex->nHeight : -1), hashStop.ToString().substr(0,20).c_str());
for (; pindex; pindex = pindex->pnext)
{
vHeaders.push_back(pindex->GetBlockHeader());
if (--nLimit <= 0 || pindex->GetBlockHash() == hashStop)
break;
}
pfrom->PushMessage("headers", vHeaders);
}
else if (strCommand == "tx")
{
vector<uint256> vWorkQueue;
vector<uint256> vEraseQueue;
CDataStream vMsg(vRecv);
CTxDB txdb("r");
CTransaction tx;
vRecv >> tx;
CInv inv(MSG_TX, tx.GetHash());
pfrom->AddInventoryKnown(inv);
// Truncate messages to the size of the tx in them
unsigned int nSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
unsigned int oldSize = vMsg.size();
if (nSize < oldSize) {
vMsg.resize(nSize);
printf("truncating oversized TX %s (%u -> %u)\n",
tx.GetHash().ToString().c_str(),
oldSize, nSize);
}
bool fMissingInputs = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs))
{
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
// Recursively process any orphan transactions that depended on this one
for (unsigned int i = 0; i < vWorkQueue.size(); i++)
{
uint256 hashPrev = vWorkQueue[i];
for (map<uint256, CDataStream*>::iterator mi = mapOrphanTransactionsByPrev[hashPrev].begin();
mi != mapOrphanTransactionsByPrev[hashPrev].end();
++mi)
{
const CDataStream& vMsg = *((*mi).second);
CTransaction tx;
CDataStream(vMsg) >> tx;
CInv inv(MSG_TX, tx.GetHash());
bool fMissingInputs2 = false;
if (tx.AcceptToMemoryPool(txdb, true, &fMissingInputs2))
{
printf(" accepted orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
SyncWithWallets(tx, NULL, true);
RelayMessage(inv, vMsg);
mapAlreadyAskedFor.erase(inv);
vWorkQueue.push_back(inv.hash);
vEraseQueue.push_back(inv.hash);
}
else if (!fMissingInputs2)
{
// invalid orphan
vEraseQueue.push_back(inv.hash);
printf(" removed invalid orphan tx %s\n", inv.hash.ToString().substr(0,10).c_str());
}
}
}
BOOST_FOREACH(uint256 hash, vEraseQueue)
EraseOrphanTx(hash);
}
else if (fMissingInputs)
{
AddOrphanTx(vMsg);
// DoS prevention: do not allow mapOrphanTransactions to grow unbounded
unsigned int nEvicted = LimitOrphanTxSize(MAX_ORPHAN_TRANSACTIONS);
if (nEvicted > 0)
printf("mapOrphan overflow, removed %u tx\n", nEvicted);
}
if (tx.nDoS) pfrom->Misbehaving(tx.nDoS);
}
else if (strCommand == "block")
{
CBlock block;
vRecv >> block;
printf("received block %s\n", block.GetHash().ToString().substr(0,20).c_str());
// block.print();
CInv inv(MSG_BLOCK, block.GetHash());
pfrom->AddInventoryKnown(inv);
if (ProcessBlock(pfrom, &block))
mapAlreadyAskedFor.erase(inv);
if (block.nDoS) pfrom->Misbehaving(block.nDoS);
}
else if (strCommand == "getaddr")
{
pfrom->vAddrToSend.clear();
vector<CAddress> vAddr = addrman.GetAddr();
BOOST_FOREACH(const CAddress &addr, vAddr)
pfrom->PushAddress(addr);
}
else if (strCommand == "checkorder")
{
uint256 hashReply;
vRecv >> hashReply;
if (!GetBoolArg("-allowreceivebyip"))
{
pfrom->PushMessage("reply", hashReply, (int)2, string(""));
return true;
}
CWalletTx order;
vRecv >> order;
/// we have a chance to check the order here
// Keep giving the same key to the same ip until they use it
if (!mapReuseKey.count(pfrom->addr))
pwalletMain->GetKeyFromPool(mapReuseKey[pfrom->addr], true);
// Send back approval of order and pubkey to use
CScript scriptPubKey;
scriptPubKey << mapReuseKey[pfrom->addr] << OP_CHECKSIG;
pfrom->PushMessage("reply", hashReply, (int)0, scriptPubKey);
}
else if (strCommand == "reply")
{
uint256 hashReply;
vRecv >> hashReply;
CRequestTracker tracker;
{
LOCK(pfrom->cs_mapRequests);
map<uint256, CRequestTracker>::iterator mi = pfrom->mapRequests.find(hashReply);
if (mi != pfrom->mapRequests.end())
{
tracker = (*mi).second;
pfrom->mapRequests.erase(mi);
}
}
if (!tracker.IsNull())
tracker.fn(tracker.param1, vRecv);
}
else if (strCommand == "ping")
{
if (pfrom->nVersion > BIP0031_VERSION)
{
uint64 nonce = 0;
vRecv >> nonce;
// Echo the message back with the nonce. This allows for two useful features:
//
// 1) A remote node can quickly check if the connection is operational
// 2) Remote nodes can measure the latency of the network thread. If this node
// is overloaded it won't respond to pings quickly and the remote node can
// avoid sending us more work, like chain download requests.
//
// The nonce stops the remote getting confused between different pings: without
// it, if the remote node sends a ping once per second and this node takes 5
// seconds to respond to each, the 5th ping the remote sends would appear to
// return very quickly.
pfrom->PushMessage("pong", nonce);
}
}
else if (strCommand == "alert")
{
CAlert alert;
vRecv >> alert;
if (alert.ProcessAlert())
{
// Relay
pfrom->setKnown.insert(alert.GetHash());
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
alert.RelayTo(pnode);
}
}
}
else
{
// Ignore unknown commands for extensibility
}
// Update the last seen time for this node's address
if (pfrom->fNetworkNode)
if (strCommand == "version" || strCommand == "addr" || strCommand == "inv" || strCommand == "getdata" || strCommand == "ping")
AddressCurrentlyConnected(pfrom->addr);
return true;
}
bool ProcessMessages(CNode* pfrom)
{
CDataStream& vRecv = pfrom->vRecv;
if (vRecv.empty())
return true;
//if (fDebug)
// printf("ProcessMessages(%u bytes)\n", vRecv.size());
//
// Message format
// (4) message start
// (12) command
// (4) size
// (4) checksum
// (x) data
//
loop
{
// Don't bother if send buffer is too full to respond anyway
if (pfrom->vSend.size() >= SendBufferSize())
break;
// Scan for message start
CDataStream::iterator pstart = search(vRecv.begin(), vRecv.end(), BEGIN(pchMessageStart), END(pchMessageStart));
int nHeaderSize = vRecv.GetSerializeSize(CMessageHeader());
if (vRecv.end() - pstart < nHeaderSize)
{
if ((int)vRecv.size() > nHeaderSize)
{
printf("\n\nPROCESSMESSAGE MESSAGESTART NOT FOUND\n\n");
vRecv.erase(vRecv.begin(), vRecv.end() - nHeaderSize);
}
break;
}
if (pstart - vRecv.begin() > 0)
printf("\n\nPROCESSMESSAGE SKIPPED %d BYTES\n\n", pstart - vRecv.begin());
vRecv.erase(vRecv.begin(), pstart);
// Read header
vector<char> vHeaderSave(vRecv.begin(), vRecv.begin() + nHeaderSize);
CMessageHeader hdr;
vRecv >> hdr;
if (!hdr.IsValid())
{
printf("\n\nPROCESSMESSAGE: ERRORS IN HEADER %s\n\n\n", hdr.GetCommand().c_str());
continue;
}
string strCommand = hdr.GetCommand();
// Message size
unsigned int nMessageSize = hdr.nMessageSize;
if (nMessageSize > MAX_SIZE)
{
printf("ProcessMessages(%s, %u bytes) : nMessageSize > MAX_SIZE\n", strCommand.c_str(), nMessageSize);
continue;
}
if (nMessageSize > vRecv.size())
{
// Rewind and wait for rest of message
vRecv.insert(vRecv.begin(), vHeaderSave.begin(), vHeaderSave.end());
break;
}
// Checksum
uint256 hash = Hash(vRecv.begin(), vRecv.begin() + nMessageSize);
unsigned int nChecksum = 0;
memcpy(&nChecksum, &hash, sizeof(nChecksum));
if (nChecksum != hdr.nChecksum)
{
printf("ProcessMessages(%s, %u bytes) : CHECKSUM ERROR nChecksum=%08x hdr.nChecksum=%08x\n",
strCommand.c_str(), nMessageSize, nChecksum, hdr.nChecksum);
continue;
}
// Copy message to its own buffer
CDataStream vMsg(vRecv.begin(), vRecv.begin() + nMessageSize, vRecv.nType, vRecv.nVersion);
vRecv.ignore(nMessageSize);
// Process message
bool fRet = false;
try
{
{
LOCK(cs_main);
fRet = ProcessMessage(pfrom, strCommand, vMsg);
}
if (fShutdown)
return true;
}
catch (std::ios_base::failure& e)
{
if (strstr(e.what(), "end of data"))
{
// Allow exceptions from underlength message on vRecv
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught, normally caused by a message being shorter than its stated length\n", strCommand.c_str(), nMessageSize, e.what());
}
else if (strstr(e.what(), "size too large"))
{
// Allow exceptions from overlong size
printf("ProcessMessages(%s, %u bytes) : Exception '%s' caught\n", strCommand.c_str(), nMessageSize, e.what());
}
else
{
PrintExceptionContinue(&e, "ProcessMessages()");
}
}
catch (std::exception& e) {
PrintExceptionContinue(&e, "ProcessMessages()");
} catch (...) {
PrintExceptionContinue(NULL, "ProcessMessages()");
}
if (!fRet)
printf("ProcessMessage(%s, %u bytes) FAILED\n", strCommand.c_str(), nMessageSize);
}
vRecv.Compact();
return true;
}
bool SendMessages(CNode* pto, bool fSendTrickle)
{
TRY_LOCK(cs_main, lockMain);
if (lockMain) {
// Don't send anything until we get their version message
if (pto->nVersion == 0)
return true;
// Keep-alive ping. We send a nonce of zero because we don't use it anywhere
// right now.
if (pto->nLastSend && GetTime() - pto->nLastSend > 30 * 60 && pto->vSend.empty()) {
uint64 nonce = 0;
if (pto->nVersion > BIP0031_VERSION)
pto->PushMessage("ping", nonce);
else
pto->PushMessage("ping");
}
// Resend wallet transactions that haven't gotten in a block yet
ResendWalletTransactions();
// Address refresh broadcast
static int64 nLastRebroadcast;
if (!IsInitialBlockDownload() && (GetTime() - nLastRebroadcast > 24 * 60 * 60))
{
{
LOCK(cs_vNodes);
BOOST_FOREACH(CNode* pnode, vNodes)
{
// Periodically clear setAddrKnown to allow refresh broadcasts
if (nLastRebroadcast)
pnode->setAddrKnown.clear();
// Rebroadcast our address
if (!fNoListen)
{
CAddress addr = GetLocalAddress(&pnode->addr);
if (addr.IsRoutable())
pnode->PushAddress(addr);
}
}
}
nLastRebroadcast = GetTime();
}
//
// Message: addr
//
if (fSendTrickle)
{
vector<CAddress> vAddr;
vAddr.reserve(pto->vAddrToSend.size());
BOOST_FOREACH(const CAddress& addr, pto->vAddrToSend)
{
// returns true if wasn't already contained in the set
if (pto->setAddrKnown.insert(addr).second)
{
vAddr.push_back(addr);
// receiver rejects addr messages larger than 1000
if (vAddr.size() >= 1000)
{
pto->PushMessage("addr", vAddr);
vAddr.clear();
}
}
}
pto->vAddrToSend.clear();
if (!vAddr.empty())
pto->PushMessage("addr", vAddr);
}
//
// Message: inventory
//
vector<CInv> vInv;
vector<CInv> vInvWait;
{
LOCK(pto->cs_inventory);
vInv.reserve(pto->vInventoryToSend.size());
vInvWait.reserve(pto->vInventoryToSend.size());
BOOST_FOREACH(const CInv& inv, pto->vInventoryToSend)
{
if (pto->setInventoryKnown.count(inv))
continue;
// trickle out tx inv to protect privacy
if (inv.type == MSG_TX && !fSendTrickle)
{
// 1/4 of tx invs blast to all immediately
static uint256 hashSalt;
if (hashSalt == 0)
hashSalt = GetRandHash();
uint256 hashRand = inv.hash ^ hashSalt;
hashRand = Hash(BEGIN(hashRand), END(hashRand));
bool fTrickleWait = ((hashRand & 3) != 0);
// always trickle our own transactions
if (!fTrickleWait)
{
CWalletTx wtx;
if (GetTransaction(inv.hash, wtx))
if (wtx.fFromMe)
fTrickleWait = true;
}
if (fTrickleWait)
{
vInvWait.push_back(inv);
continue;
}
}
// returns true if wasn't already contained in the set
if (pto->setInventoryKnown.insert(inv).second)
{
vInv.push_back(inv);
if (vInv.size() >= 1000)
{
pto->PushMessage("inv", vInv);
vInv.clear();
}
}
}
pto->vInventoryToSend = vInvWait;
}
if (!vInv.empty())
pto->PushMessage("inv", vInv);
//
// Message: getdata
//
vector<CInv> vGetData;
int64 nNow = GetTime() * 1000000;
CTxDB txdb("r");
while (!pto->mapAskFor.empty() && (*pto->mapAskFor.begin()).first <= nNow)
{
const CInv& inv = (*pto->mapAskFor.begin()).second;
if (!AlreadyHave(txdb, inv))
{
if (fDebugNet)
printf("sending getdata: %s\n", inv.ToString().c_str());
vGetData.push_back(inv);
if (vGetData.size() >= 1000)
{
pto->PushMessage("getdata", vGetData);
vGetData.clear();
}
mapAlreadyAskedFor[inv] = nNow;
}
pto->mapAskFor.erase(pto->mapAskFor.begin());
}
if (!vGetData.empty())
pto->PushMessage("getdata", vGetData);
}
return true;
}
//////////////////////////////////////////////////////////////////////////////
//
// BitcoinMiner
//
int static FormatHashBlocks(void* pbuffer, unsigned int len)
{
unsigned char* pdata = (unsigned char*)pbuffer;
unsigned int blocks = 1 + ((len + 8) / 64);
unsigned char* pend = pdata + 64 * blocks;
memset(pdata + len, 0, 64 * blocks - len);
pdata[len] = 0x80;
unsigned int bits = len * 8;
pend[-1] = (bits >> 0) & 0xff;
pend[-2] = (bits >> 8) & 0xff;
pend[-3] = (bits >> 16) & 0xff;
pend[-4] = (bits >> 24) & 0xff;
return blocks;
}
static const unsigned int pSHA256InitState[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
void SHA256Transform(void* pstate, void* pinput, const void* pinit)
{
SHA256_CTX ctx;
unsigned char data[64];
SHA256_Init(&ctx);
for (int i = 0; i < 16; i++)
((uint32_t*)data)[i] = ByteReverse(((uint32_t*)pinput)[i]);
for (int i = 0; i < 8; i++)
ctx.h[i] = ((uint32_t*)pinit)[i];
SHA256_Update(&ctx, data, sizeof(data));
for (int i = 0; i < 8; i++)
((uint32_t*)pstate)[i] = ctx.h[i];
}
//
// ScanHash scans nonces looking for a hash with at least some zero bits.
// It operates on big endian data. Caller does the byte reversing.
// All input buffers are 16-byte aligned. nNonce is usually preserved
// between calls, but periodically or if nNonce is 0xffff0000 or above,
// the block is rebuilt and nNonce starts over at zero.
//
unsigned int static ScanHash_CryptoPP(char* pmidstate, char* pdata, char* phash1, char* phash, unsigned int& nHashesDone)
{
unsigned int& nNonce = *(unsigned int*)(pdata + 12);
for (;;)
{
// Crypto++ SHA-256
// Hash pdata using pmidstate as the starting state into
// preformatted buffer phash1, then hash phash1 into phash
nNonce++;
SHA256Transform(phash1, pdata, pmidstate);
SHA256Transform(phash, phash1, pSHA256InitState);
// Return the nonce if the hash has at least some zero bits,
// caller will check if it has enough to reach the target
if (((unsigned short*)phash)[14] == 0)
return nNonce;
// If nothing found after trying for a while, return -1
if ((nNonce & 0xffff) == 0)
{
nHashesDone = 0xffff+1;
return (unsigned int) -1;
}
}
}
// Some explaining would be appreciated
class COrphan
{
public:
CTransaction* ptx;
set<uint256> setDependsOn;
double dPriority;
COrphan(CTransaction* ptxIn)
{
ptx = ptxIn;
dPriority = 0;
}
void print() const
{
printf("COrphan(hash=%s, dPriority=%.1f)\n", ptx->GetHash().ToString().substr(0,10).c_str(), dPriority);
BOOST_FOREACH(uint256 hash, setDependsOn)
printf(" setDependsOn %s\n", hash.ToString().substr(0,10).c_str());
}
};
uint64 nLastBlockTx = 0;
uint64 nLastBlockSize = 0;
CBlock* CreateNewBlock(CReserveKey& reservekey)
{
CBlockIndex* pindexPrev = pindexBest;
// Create new block
auto_ptr<CBlock> pblock(new CBlock());
if (!pblock.get())
return NULL;
// Create coinbase tx
CTransaction txNew;
txNew.vin.resize(1);
txNew.vin[0].prevout.SetNull();
txNew.vout.resize(1);
txNew.vout[0].scriptPubKey << reservekey.GetReservedKey() << OP_CHECKSIG;
// Add our coinbase tx as first transaction
pblock->vtx.push_back(txNew);
// Collect memory pool transactions into the block
int64 nFees = 0;
{
LOCK2(cs_main, mempool.cs);
CTxDB txdb("r");
// Priority order to process transactions
list<COrphan> vOrphan; // list memory doesn't move
map<uint256, vector<COrphan*> > mapDependers;
multimap<double, CTransaction*> mapPriority;
for (map<uint256, CTransaction>::iterator mi = mempool.mapTx.begin(); mi != mempool.mapTx.end(); ++mi)
{
CTransaction& tx = (*mi).second;
if (tx.IsCoinBase() || !tx.IsFinal())
continue;
COrphan* porphan = NULL;
double dPriority = 0;
BOOST_FOREACH(const CTxIn& txin, tx.vin)
{
// Read prev transaction
CTransaction txPrev;
CTxIndex txindex;
if (!txPrev.ReadFromDisk(txdb, txin.prevout, txindex))
{
// Has to wait for dependencies
if (!porphan)
{
// Use list for automatic deletion
vOrphan.push_back(COrphan(&tx));
porphan = &vOrphan.back();
}
mapDependers[txin.prevout.hash].push_back(porphan);
porphan->setDependsOn.insert(txin.prevout.hash);
continue;
}
int64 nValueIn = txPrev.vout[txin.prevout.n].nValue;
// Read block header
int nConf = txindex.GetDepthInMainChain();
dPriority += (double)nValueIn * nConf;
if (fDebug && GetBoolArg("-printpriority"))
printf("priority nValueIn=%-12"PRI64d" nConf=%-5d dPriority=%-20.1f\n", nValueIn, nConf, dPriority);
}
// Priority is sum(valuein * age) / txsize
dPriority /= ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (porphan)
porphan->dPriority = dPriority;
else
mapPriority.insert(make_pair(-dPriority, &(*mi).second));
if (fDebug && GetBoolArg("-printpriority"))
{
printf("priority %-20.1f %s\n%s", dPriority, tx.GetHash().ToString().substr(0,10).c_str(), tx.ToString().c_str());
if (porphan)
porphan->print();
printf("\n");
}
}
// Collect transactions into block
map<uint256, CTxIndex> mapTestPool;
uint64 nBlockSize = 1000;
uint64 nBlockTx = 0;
int nBlockSigOps = 100;
while (!mapPriority.empty())
{
// Take highest priority transaction off priority queue
double dPriority = -(*mapPriority.begin()).first;
CTransaction& tx = *(*mapPriority.begin()).second;
mapPriority.erase(mapPriority.begin());
// Size limits
unsigned int nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
if (nBlockSize + nTxSize >= MAX_BLOCK_SIZE_GEN)
continue;
// Legacy limits on sigOps:
unsigned int nTxSigOps = tx.GetLegacySigOpCount();
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
// Transaction fee required depends on block size
// Dream8coind: Reduce the exempted free transactions to 500 bytes (from Bitcoin's 3000 bytes)
bool fAllowFree = (nBlockSize + nTxSize < 1500 || CTransaction::AllowFree(dPriority));
int64 nMinFee = tx.GetMinFee(nBlockSize, fAllowFree, GMF_BLOCK);
// Connecting shouldn't fail due to dependency on other memory pool transactions
// because we're already processing them in order of dependency
map<uint256, CTxIndex> mapTestPoolTmp(mapTestPool);
MapPrevTx mapInputs;
bool fInvalid;
if (!tx.FetchInputs(txdb, mapTestPoolTmp, false, true, mapInputs, fInvalid))
continue;
int64 nTxFees = tx.GetValueIn(mapInputs)-tx.GetValueOut();
if (nTxFees < nMinFee)
continue;
nTxSigOps += tx.GetP2SHSigOpCount(mapInputs);
if (nBlockSigOps + nTxSigOps >= MAX_BLOCK_SIGOPS)
continue;
if (!tx.ConnectInputs(mapInputs, mapTestPoolTmp, CDiskTxPos(1,1,1), pindexPrev, false, true))
continue;
mapTestPoolTmp[tx.GetHash()] = CTxIndex(CDiskTxPos(1,1,1), tx.vout.size());
swap(mapTestPool, mapTestPoolTmp);
// Added
pblock->vtx.push_back(tx);
nBlockSize += nTxSize;
++nBlockTx;
nBlockSigOps += nTxSigOps;
nFees += nTxFees;
// Add transactions that depend on this one to the priority queue
uint256 hash = tx.GetHash();
if (mapDependers.count(hash))
{
BOOST_FOREACH(COrphan* porphan, mapDependers[hash])
{
if (!porphan->setDependsOn.empty())
{
porphan->setDependsOn.erase(hash);
if (porphan->setDependsOn.empty())
mapPriority.insert(make_pair(-porphan->dPriority, porphan->ptx));
}
}
}
}
nLastBlockTx = nBlockTx;
nLastBlockSize = nBlockSize;
printf("CreateNewBlock(): total size %lu\n", nBlockSize);
}
pblock->vtx[0].vout[0].nValue = GetBlockValue(pindexPrev->nHeight+1, nFees);
// Fill in header
pblock->hashPrevBlock = pindexPrev->GetBlockHash();
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
pblock->UpdateTime(pindexPrev);
pblock->nBits = GetNextWorkRequired(pindexPrev, pblock.get());
pblock->nNonce = 0;
return pblock.release();
}
void IncrementExtraNonce(CBlock* pblock, CBlockIndex* pindexPrev, unsigned int& nExtraNonce)
{
// Update nExtraNonce
static uint256 hashPrevBlock;
if (hashPrevBlock != pblock->hashPrevBlock)
{
nExtraNonce = 0;
hashPrevBlock = pblock->hashPrevBlock;
}
++nExtraNonce;
pblock->vtx[0].vin[0].scriptSig = (CScript() << pblock->nTime << CBigNum(nExtraNonce)) + COINBASE_FLAGS;
assert(pblock->vtx[0].vin[0].scriptSig.size() <= 100);
pblock->hashMerkleRoot = pblock->BuildMerkleTree();
}
void FormatHashBuffers(CBlock* pblock, char* pmidstate, char* pdata, char* phash1)
{
//
// Prebuild hash buffers
//
struct
{
struct unnamed2
{
int nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
unsigned int nTime;
unsigned int nBits;
unsigned int nNonce;
}
block;
unsigned char pchPadding0[64];
uint256 hash1;
unsigned char pchPadding1[64];
}
tmp;
memset(&tmp, 0, sizeof(tmp));
tmp.block.nVersion = pblock->nVersion;
tmp.block.hashPrevBlock = pblock->hashPrevBlock;
tmp.block.hashMerkleRoot = pblock->hashMerkleRoot;
tmp.block.nTime = pblock->nTime;
tmp.block.nBits = pblock->nBits;
tmp.block.nNonce = pblock->nNonce;
FormatHashBlocks(&tmp.block, sizeof(tmp.block));
FormatHashBlocks(&tmp.hash1, sizeof(tmp.hash1));
// Byte swap all the input buffer
for (unsigned int i = 0; i < sizeof(tmp)/4; i++)
((unsigned int*)&tmp)[i] = ByteReverse(((unsigned int*)&tmp)[i]);
// Precalc the first half of the first hash, which stays constant
SHA256Transform(pmidstate, &tmp.block, pSHA256InitState);
memcpy(pdata, &tmp.block, 128);
memcpy(phash1, &tmp.hash1, 64);
}
bool CheckWork(CBlock* pblock, CWallet& wallet, CReserveKey& reservekey)
{
uint256 hash = pblock->GetPoWHash();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
if (hash > hashTarget)
return false;
//// debug print
printf("BitcoinMiner:\n");
printf("proof-of-work found \n hash: %s \ntarget: %s\n", hash.GetHex().c_str(), hashTarget.GetHex().c_str());
pblock->print();
printf("generated %s\n", FormatMoney(pblock->vtx[0].vout[0].nValue).c_str());
// Found a solution
{
LOCK(cs_main);
if (pblock->hashPrevBlock != hashBestChain)
return error("BitcoinMiner : generated block is stale");
// Remove key from key pool
reservekey.KeepKey();
// Track how many getdata requests this block gets
{
LOCK(wallet.cs_wallet);
wallet.mapRequestCount[pblock->GetHash()] = 0;
}
// Process this block the same as if we had received it from another node
if (!ProcessBlock(NULL, pblock))
return error("BitcoinMiner : ProcessBlock, block not accepted");
}
return true;
}
void static ThreadBitcoinMiner(void* parg);
static bool fGenerateBitcoins = false;
static bool fLimitProcessors = false;
static int nLimitProcessors = -1;
void static BitcoinMiner(CWallet *pwallet)
{
printf("BitcoinMiner started\n");
SetThreadPriority(THREAD_PRIORITY_LOWEST);
// Make this thread recognisable as the mining thread
RenameThread("bitcoin-miner");
// Each thread has its own key and counter
CReserveKey reservekey(pwallet);
unsigned int nExtraNonce = 0;
while (fGenerateBitcoins)
{
if (fShutdown)
return;
while (vNodes.empty() || IsInitialBlockDownload())
{
Sleep(1000);
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
}
//
// Create new block
//
unsigned int nTransactionsUpdatedLast = nTransactionsUpdated;
CBlockIndex* pindexPrev = pindexBest;
auto_ptr<CBlock> pblock(CreateNewBlock(reservekey));
if (!pblock.get())
return;
IncrementExtraNonce(pblock.get(), pindexPrev, nExtraNonce);
printf("Running BitcoinMiner with %d transactions in block\n", pblock->vtx.size());
//
// Prebuild hash buffers
//
char pmidstatebuf[32+16]; char* pmidstate = alignup<16>(pmidstatebuf);
char pdatabuf[128+16]; char* pdata = alignup<16>(pdatabuf);
char phash1buf[64+16]; char* phash1 = alignup<16>(phash1buf);
FormatHashBuffers(pblock.get(), pmidstate, pdata, phash1);
unsigned int& nBlockTime = *(unsigned int*)(pdata + 64 + 4);
unsigned int& nBlockBits = *(unsigned int*)(pdata + 64 + 8);
//unsigned int& nBlockNonce = *(unsigned int*)(pdata + 64 + 12);
//
// Search
//
int64 nStart = GetTime();
uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
loop
{
unsigned int nHashesDone = 0;
//unsigned int nNonceFound;
uint256 thash;
char scratchpad[SCRYPT_SCRATCHPAD_SIZE];
loop
{
scrypt_1024_1_1_256_sp(BEGIN(pblock->nVersion), BEGIN(thash), scratchpad);
if (thash <= hashTarget)
{
// Found a solution
SetThreadPriority(THREAD_PRIORITY_NORMAL);
CheckWork(pblock.get(), *pwalletMain, reservekey);
SetThreadPriority(THREAD_PRIORITY_LOWEST);
break;
}
pblock->nNonce += 1;
nHashesDone += 1;
if ((pblock->nNonce & 0xFF) == 0)
break;
}
// Meter hashes/sec
static int64 nHashCounter;
if (nHPSTimerStart == 0)
{
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
}
else
nHashCounter += nHashesDone;
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
static CCriticalSection cs;
{
LOCK(cs);
if (GetTimeMillis() - nHPSTimerStart > 4000)
{
dHashesPerSec = 1000.0 * nHashCounter / (GetTimeMillis() - nHPSTimerStart);
nHPSTimerStart = GetTimeMillis();
nHashCounter = 0;
string strStatus = strprintf(" %.0f khash/s", dHashesPerSec/1000.0);
static int64 nLogTime;
if (GetTime() - nLogTime > 30 * 60)
{
nLogTime = GetTime();
printf("%s ", DateTimeStrFormat("%x %H:%M", GetTime()).c_str());
printf("hashmeter %3d CPUs %6.0f khash/s\n", vnThreadsRunning[THREAD_MINER], dHashesPerSec/1000.0);
}
}
}
}
// Check for stop or if block needs to be rebuilt
if (fShutdown)
return;
if (!fGenerateBitcoins)
return;
if (fLimitProcessors && vnThreadsRunning[THREAD_MINER] > nLimitProcessors)
return;
if (vNodes.empty())
break;
if (pblock->nNonce >= 0xffff0000)
break;
if (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)
break;
if (pindexPrev != pindexBest)
break;
// Update nTime every few seconds
pblock->UpdateTime(pindexPrev);
nBlockTime = ByteReverse(pblock->nTime);
if (fTestNet)
{
// Changing pblock->nTime can change work required on testnet:
nBlockBits = ByteReverse(pblock->nBits);
hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256();
}
}
}
}
void static ThreadBitcoinMiner(void* parg)
{
CWallet* pwallet = (CWallet*)parg;
try
{
vnThreadsRunning[THREAD_MINER]++;
BitcoinMiner(pwallet);
vnThreadsRunning[THREAD_MINER]--;
}
catch (std::exception& e) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(&e, "ThreadBitcoinMiner()");
} catch (...) {
vnThreadsRunning[THREAD_MINER]--;
PrintException(NULL, "ThreadBitcoinMiner()");
}
nHPSTimerStart = 0;
if (vnThreadsRunning[THREAD_MINER] == 0)
dHashesPerSec = 0;
printf("ThreadBitcoinMiner exiting, %d threads remaining\n", vnThreadsRunning[THREAD_MINER]);
}
void GenerateBitcoins(bool fGenerate, CWallet* pwallet)
{
fGenerateBitcoins = fGenerate;
nLimitProcessors = GetArg("-genproclimit", -1);
if (nLimitProcessors == 0)
fGenerateBitcoins = false;
fLimitProcessors = (nLimitProcessors != -1);
if (fGenerate)
{
int nProcessors = boost::thread::hardware_concurrency();
printf("%d processors\n", nProcessors);
if (nProcessors < 1)
nProcessors = 1;
if (fLimitProcessors && nProcessors > nLimitProcessors)
nProcessors = nLimitProcessors;
int nAddThreads = nProcessors - vnThreadsRunning[THREAD_MINER];
printf("Starting %d BitcoinMiner threads\n", nAddThreads);
for (int i = 0; i < nAddThreads; i++)
{
if (!CreateThread(ThreadBitcoinMiner, pwallet))
printf("Error: CreateThread(ThreadBitcoinMiner) failed\n");
Sleep(10);
}
}
}
| [
"yjpark1697@naver.com"
] | yjpark1697@naver.com |
741f4e7cc65e3dae4496209215639689b4adae69 | 84c02d4a42871140dd648362a9e80b4f3bae2f66 | /functionOverloading/functionOverloading.cpp | fd98ebde56b77d72c756716964df783de01905e8 | [] | no_license | YovyTheLurker/functionOverloading | 07f0ae2f4df2c7094ac784cf97fdf551de68b56d | 5208d6088d62213dc7668d3daa0b087df6316b7e | refs/heads/master | 2023-06-03T20:19:53.216823 | 2021-06-17T15:14:43 | 2021-06-17T15:14:43 | 377,873,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cpp | // functionOverloading.cpp : This file contains the 'main' function. Program execution begins and ends there.
//Function overload
#include <iostream>
using namespace std;
int sum(int a, int b);
double sum(double a, double b);
float sum(float a, float b, float c);
int main()
{
cout << sum(3, 4) << endl;
cout << sum(4.4, 3.3) << endl;
cout << sum(1.1, 2.2, 3.3) << endl;
system("pause>0");
}
int sum(int a, int b) {
return a+b;
}
double sum(double a, double b) {
return a + b;
}
float sum(float a, float b, float c) {
return a + b + c;
} | [
"yoerodri@yahoo.com"
] | yoerodri@yahoo.com |
ef3a8700531d14cdbcba257288a5efd7f9fb1f11 | 288e5f4f2ea19f9eea8e92db176218af6d64213a | /src/HookWininetDemo/DlgRequest.h | e81602da84a4d771e8c606c0b04cbbc05085d575 | [
"MIT"
] | permissive | xingyun86/HookWininetDemo | cd77c4cf2f0c0cace2b9b03a51d057e75dde8a02 | b77f61ce583eb56a1526f90e593c632633fd7693 | refs/heads/main | 2023-05-08T15:00:21.546894 | 2021-05-28T10:51:55 | 2021-05-28T10:51:55 | 370,026,605 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,373 | h | #pragma once
#include "afxwin.h"
#include "resource.h"
#include <WinInet.h>
#include <map>
// CDlgRequest dialog
typedef struct _tagInternetConnectInfo
{
CString strHost;
CString strPort;
} tagInternetConnectInfo, *LPInternetConnectInfo;
class CDlgRequest : public CDialog
{
DECLARE_DYNAMIC(CDlgRequest)
public:
CDlgRequest(CWnd* pParent = NULL); // standard constructor
virtual ~CDlgRequest();
void LogInternetConnect(HINTERNET hConnect, LPTSTR lpszHost, UINT uPort);
void LogRequest(HINTERNET hConnect, HINTERNET hRequest, LPCTSTR lpszObjName, LPCTSTR lpszMethod);
void LogHttpResponseHeader(HINTERNET hRequest);
void LogHttpResponseData(LPVOID lpBuffer, DWORD dwNumberOfBytesToRead);
void LogHttpResponseData(LPINTERNET_BUFFERSA lpBuffersOut);
void LogHttpResponseData(LPINTERNET_BUFFERSW lpBuffersOut);
// Dialog Data
enum { IDD = IDD_DIALOG_REQUEST };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
virtual BOOL OnInitDialog();
virtual void OnOK() { };
virtual void OnCancel() {};
DECLARE_MESSAGE_MAP()
afx_msg void OnLvnItemchangedListRequest(NMHDR *pNMHDR, LRESULT *pResult);
CListCtrl m_ctlRequest;
CString m_strHttpHeader;
CString m_strResponseHttpHeader;
CString m_strSessionID;
std::map< HINTERNET, tagInternetConnectInfo> m_mpConnection;
std::map< HINTERNET, INT> m_mpRequestItem;
};
| [
"xingyun_ppshuai@yeah.net"
] | xingyun_ppshuai@yeah.net |
599e9d6a01b2ab3090dd45a0150b2cfce4bc76b5 | dd5b5e5ee5476d1eeffc4987e1aeec94e047e6dd | /testCase/cavity/0.1075/currentcloudofpoints | ef3d3cabd8937a40c9b23ae7c2696986fdedf270 | [] | no_license | Cxb1993/IBM-3D | 5d4feca0321090d570089259a558585a67a512ec | 2fceceb2abf1fc9e80cb2c449cc14a8d54e41b89 | refs/heads/master | 2020-05-24T01:14:02.684839 | 2018-10-23T13:15:20 | 2018-10-23T13:15:20 | 186,721,487 | 1 | 0 | null | 2019-05-15T00:39:55 | 2019-05-15T00:39:55 | null | UTF-8 | C++ | false | false | 64,735 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: v1806 |
| \\ / A nd | Web: www.OpenFOAM.com |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class vectorField;
location "0.1075";
object currentcloudofpoints;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
2409
(
(1.0387 1.27181 1.08271)
(0.855358 1.01836 1.12492)
(1.46608 1.14179 1.00051)
(1.13357 1.29693 0.76473)
(1.20013 1.39761 1.26133)
(1.18238 1.2081 0.995689)
(1.17962 1.34441 1.02606)
(0.634031 1.27245 0.862332)
(1.66726 1.16264 0.995459)
(1.19588 1.04312 0.738968)
(1.28468 1.24501 1.37475)
(1.44986 1.16971 1.08424)
(1.44191 1.30192 1.11674)
(1.24477 1.31421 1.17925)
(1.43227 1.24284 1.11667)
(1.46065 1.15444 1.05104)
(1.43401 1.18424 1.0971)
(1.2274 1.47095 1.04178)
(1.44568 1.29874 1.10524)
(1.39387 1.26196 1.1517)
(0.877151 0.951081 1.34475)
(0.526142 1.32555 1.26591)
(0.964779 1.34164 1.18821)
(1.08485 1.22413 1.16593)
(0.968873 0.989274 1.12842)
(0.571031 1.09738 1.40941)
(0.709293 1.0667 1.35315)
(0.932832 1.53881 1.40114)
(1.06562 1.2317 1.32579)
(1.45276 1.17561 0.910517)
(1.42465 1.21391 0.903981)
(1.21838 1.45322 0.75052)
(1.24182 1.36218 0.758071)
(1.45908 1.1516 0.946846)
(1.4318 1.18954 0.911355)
(1.36965 1.38293 0.848618)
(1.20779 1.45128 0.758333)
(1.19592 1.44537 0.707176)
(0.899989 1.39859 0.62061)
(0.572876 0.950105 0.786862)
(0.762318 1.00391 0.705014)
(0.947418 0.960725 0.817281)
(1.0799 1.32186 0.805488)
(0.960786 1.2242 0.680117)
(0.633364 0.979458 0.729654)
(1.03273 0.940783 0.718032)
(0.848979 0.946371 1.00982)
(1.31496 1.42596 1.15272)
(1.23376 1.23651 1.11443)
(1.27779 1.20764 1.12911)
(1.15004 1.22446 1.01376)
(1.2251 1.39717 1.32455)
(1.34749 1.23305 1.15057)
(1.10837 1.34569 1.12588)
(1.44349 1.30561 0.983122)
(1.10388 1.23446 1.0954)
(1.21513 1.16312 0.865203)
(1.06845 1.53479 0.572182)
(1.10648 1.60449 0.709108)
(1.18963 1.28554 0.764282)
(1.01399 1.66108 1.00042)
(1.39843 1.32685 0.906563)
(1.09996 1.45421 0.797341)
(1.03585 1.37713 0.898558)
(1.1853 1.38366 0.792801)
(0.959202 1.03933 1.17337)
(0.932788 0.99373 1.13465)
(0.972974 1.31914 1.05487)
(1.10415 1.51393 1.03565)
(0.995336 1.01797 1.23707)
(0.95006 1.01968 1.14614)
(0.865446 0.984791 1.13189)
(0.981429 1.4503 1.00702)
(0.936322 1.54444 0.991169)
(1.18694 1.50708 0.946544)
(1.54732 1.40089 1.11885)
(1.55471 1.36934 1.09329)
(1.4924 1.18378 0.998189)
(1.13404 1.27158 1.03721)
(1.49715 1.44602 1.06542)
(1.56692 1.37181 1.09015)
(1.51821 1.39664 1.11735)
(1.49077 1.16245 0.997098)
(0.574032 1.13435 1.19554)
(0.474551 1.05834 1.15153)
(0.668792 1.17816 1.45882)
(1.07616 1.29466 1.4381)
(1.11795 1.1316 1.48946)
(1.11432 1.01637 1.49964)
(1.30705 1.31231 1.38923)
(0.629541 1.33675 1.05232)
(0.564881 1.10039 1.21645)
(0.551067 1.28117 1.40345)
(0.944623 1.36468 1.38211)
(1.14826 1.01191 1.48789)
(1.15685 0.965117 1.37163)
(1.11865 1.38324 1.37315)
(1.34282 1.24826 1.36581)
(1.24764 1.18306 1.36275)
(1.30653 1.07795 1.29296)
(1.38399 1.08524 1.29911)
(1.43612 1.11941 1.29351)
(1.48101 1.10449 1.2657)
(1.55816 1.11458 1.21855)
(1.64077 1.14865 1.13753)
(1.24656 1.26149 1.39711)
(1.26087 1.10202 1.2946)
(1.34553 1.07473 1.295)
(1.41434 1.1037 1.29339)
(1.45453 1.11475 1.28116)
(1.51296 1.10365 1.23998)
(1.59814 1.12791 1.18509)
(1.65917 1.15239 1.07043)
(0.633695 1.21111 0.768144)
(0.556675 1.03363 0.81821)
(0.753556 1.11507 0.856545)
(0.97832 1.16646 0.60691)
(1.12286 1.02055 0.739263)
(1.08464 1.04223 0.496042)
(1.07067 1.08822 0.548873)
(0.612082 1.0434 0.850717)
(0.692439 1.15381 0.657621)
(0.680345 1.09165 0.785688)
(0.904517 1.13059 0.613051)
(1.17563 1.04783 0.524596)
(1.08855 0.973328 0.609952)
(1.08995 1.0692 0.508103)
(1.20979 1.07779 0.74344)
(1.63699 1.15091 0.858264)
(1.56198 1.12038 0.773718)
(1.48473 1.1097 0.724326)
(1.43095 1.12578 0.694592)
(1.37874 1.11762 0.700452)
(1.31721 1.14063 0.716317)
(1.24364 1.15073 0.669419)
(1.65391 1.15371 0.922904)
(1.5988 1.13276 0.810254)
(1.51825 1.10987 0.750147)
(1.45506 1.11838 0.707662)
(1.40719 1.12228 0.696692)
(1.34887 1.12535 0.713453)
(1.27979 1.14968 0.701841)
(1.20961 1.12502 0.661588)
(1.20754 1.62611 1.17597)
(0.880584 1.58698 1.21608)
(0.848893 1.66327 1.29159)
(1.02044 1.63536 1.36139)
(1.03896 1.46638 1.44755)
(1.05352 1.29266 1.46314)
(1.37118 1.21402 1.32148)
(1.20825 1.70383 1.02196)
(0.95055 1.70399 1.21837)
(0.887594 1.53146 1.21265)
(0.878965 1.67021 1.30993)
(1.0454 1.55403 1.4169)
(1.04628 1.37814 1.50107)
(1.29955 1.13402 1.42713)
(1.34143 1.27212 1.27871)
(1.09583 1.75407 0.836339)
(0.930877 1.68767 0.780828)
(0.970988 1.59541 0.778957)
(1.04146 1.61984 0.596871)
(0.97722 1.48802 0.53219)
(1.06412 1.28392 0.476127)
(1.15641 1.19356 0.622758)
(1.15412 1.78836 0.879441)
(1.04144 1.70087 0.786101)
(0.949026 1.62831 0.783847)
(0.962101 1.58832 0.810399)
(1.03796 1.52749 0.53623)
(1.03287 1.40655 0.483189)
(1.1884 1.25838 0.573639)
(1.21877 1.09595 0.71922)
(0.643292 1.27326 0.878469)
(1.00793 1.6514 0.958619)
(0.980508 1.6197 1.05344)
(1.17532 1.5744 0.877734)
(1.15459 1.47264 1.07891)
(1.12587 1.62252 1.00907)
(1.10993 1.26202 0.993759)
(0.655498 1.3909 0.925542)
(0.826311 1.51577 0.923855)
(0.953159 1.60973 1.00514)
(1.07754 1.25081 0.903965)
(1.1769 1.46375 1.22233)
(1.13334 1.40479 1.0389)
(1.11025 1.26739 0.968423)
(1.10959 1.27214 1.01753)
(1.27585 1.48431 1.08738)
(1.40723 1.46577 1.06136)
(1.40122 1.48679 1.07885)
(1.5221 1.44316 1.09996)
(1.60206 1.43104 1.02933)
(1.65086 1.41041 1.00023)
(1.68678 1.30796 0.994979)
(1.30944 1.46078 1.03373)
(1.2673 1.41098 1.17712)
(1.42434 1.46775 1.03369)
(1.43822 1.49168 1.09266)
(1.58096 1.42794 1.05645)
(1.63342 1.42128 1.00758)
(1.67759 1.34889 0.994486)
(1.68543 1.23827 0.995356)
(1.3445 1.25818 0.820906)
(1.26416 1.08806 0.772269)
(1.1798 1.47358 0.710684)
(1.28611 1.24479 1.27199)
(1.27751 1.31871 1.19875)
(1.29117 1.18942 1.31322)
(0.623068 1.21289 0.86429)
(0.908447 1.09096 0.778537)
(0.652955 1.18057 0.7461)
(1.53128 1.11357 0.993894)
(1.50232 1.13279 0.997277)
(1.57993 1.10008 0.99328)
(1.24308 1.49156 1.28025)
(1.37044 1.63725 1.16353)
(1.30778 1.49486 1.36252)
(1.61608 1.37129 1.24838)
(1.20307 1.68678 1.18847)
(1.37947 1.15976 1.26337)
(1.64892 1.26583 1.21785)
(1.56629 1.33619 1.31531)
(1.17669 1.60835 1.27785)
(1.50641 1.68045 1.2378)
(1.53739 1.66076 1.16178)
(0.91409 1.56602 1.22057)
(1.51326 1.49615 1.27982)
(1.65681 1.36895 1.20786)
(1.36923 1.51731 1.10492)
(1.66656 1.37316 1.10572)
(1.4048 1.34292 1.30319)
(1.63468 1.40988 1.14694)
(1.06559 1.78576 1.20173)
(1.30185 1.16246 1.30259)
(0.962363 1.44271 1.11133)
(1.43681 1.45491 1.35294)
(1.51001 1.21566 1.31515)
(1.29589 1.64961 1.06038)
(0.95039 1.73453 1.22951)
(1.29384 1.43075 1.22791)
(1.45242 1.28088 1.30474)
(1.51671 1.3904 1.28266)
(1.09466 1.74293 1.06056)
(1.32342 1.1866 1.34884)
(1.68322 1.27829 1.09342)
(1.26483 1.49008 1.22788)
(1.06853 1.48903 1.22583)
(1.43579 1.35494 1.27572)
(1.41728 1.56358 1.26006)
(1.57896 1.42667 1.19667)
(1.27979 1.13118 1.28295)
(1.3569 1.11748 1.29286)
(1.32996 1.20319 1.34143)
(1.29881 1.18272 1.36335)
(1.26414 1.15423 1.30105)
(1.38873 1.15274 1.32128)
(1.40415 1.17931 1.32516)
(1.40093 1.27259 1.30444)
(1.41869 1.20717 1.31233)
(1.42769 1.23831 1.30617)
(1.4164 1.35039 1.29302)
(1.44086 1.21464 1.29763)
(1.4636 1.1746 1.2928)
(1.45376 1.32845 1.27936)
(1.49331 1.15325 1.28333)
(1.53545 1.14827 1.26232)
(1.46874 1.2423 1.31137)
(1.60075 1.17652 1.22995)
(1.64685 1.20582 1.17694)
(1.57605 1.22027 1.28488)
(1.66965 1.21141 1.11913)
(1.68249 1.21908 1.04555)
(1.6679 1.26732 1.1569)
(1.68661 1.29353 1.04573)
(1.25153 1.61671 1.15311)
(1.20269 1.68654 1.12092)
(1.08803 1.756 1.10317)
(1.22381 1.68535 1.07549)
(1.25685 1.67348 1.01485)
(1.25822 1.39702 1.22636)
(1.31033 1.64161 1.00494)
(1.24273 1.64067 1.24976)
(1.54499 1.59884 1.1352)
(1.43411 1.56297 1.25263)
(1.2476 1.40434 1.17874)
(1.59631 1.4205 1.12901)
(1.53661 1.43348 1.17081)
(1.5682 1.63931 1.22004)
(1.64298 1.40645 1.06997)
(1.62059 1.41866 1.09241)
(1.61936 1.40698 1.17315)
(1.67885 1.33559 1.05181)
(1.66095 1.38558 1.05196)
(1.65497 1.39046 1.12306)
(1.67817 1.3188 1.10187)
(1.17501 1.44194 1.25232)
(1.26728 1.63132 1.27133)
(1.31901 1.61209 1.19328)
(1.42166 1.65049 1.15109)
(1.38281 1.60521 1.1417)
(1.2686 1.65967 1.263)
(1.33972 1.64529 1.13897)
(1.40747 1.56864 1.06107)
(1.51907 1.67054 1.15799)
(1.29763 1.45468 1.15879)
(1.38556 1.32819 1.27487)
(1.36274 1.37017 1.29844)
(1.31934 1.16244 1.26581)
(1.38894 1.32167 1.29306)
(1.44596 1.4638 1.29591)
(1.42688 1.41569 1.26629)
(1.15851 1.42846 1.17571)
(1.10521 1.46155 1.33539)
(1.25878 1.55217 1.25571)
(1.03907 1.45165 1.18256)
(1.41137 1.58053 1.21159)
(1.61218 1.38586 1.22325)
(1.63801 1.37688 1.20451)
(1.59795 1.43987 1.25842)
(1.62149 1.52736 1.21937)
(1.55369 1.38382 1.29255)
(1.56325 1.40336 1.29242)
(1.5989 1.35193 1.28398)
(1.63907 1.36064 1.23094)
(1.62154 1.34309 1.27636)
(1.65246 1.38645 1.17488)
(1.56757 1.47486 1.28174)
(1.47456 1.51877 1.35186)
(1.14455 1.72979 1.23342)
(1.15986 1.75099 1.16128)
(1.19052 1.69401 1.25558)
(1.03418 1.75565 1.11533)
(1.04729 1.75609 1.15792)
(0.912258 1.68132 1.16776)
(1.12183 1.71788 1.10568)
(0.912791 1.59447 1.2522)
(0.892344 1.54373 1.25274)
(0.990251 1.75725 1.23608)
(0.866739 1.59211 1.18956)
(0.899273 1.67087 1.29658)
(0.894721 1.65145 1.17972)
(1.05775 1.56855 1.37581)
(1.03264 1.63653 1.28402)
(0.907642 1.67525 1.25976)
(1.0095 1.4049 1.35772)
(1.08353 1.36449 1.44901)
(1.03068 1.49458 1.27608)
(1.33149 1.15902 1.39026)
(1.34901 1.18512 1.31287)
(1.34827 1.20476 1.2966)
(1.31756 1.17402 1.31655)
(1.04405 1.39827 1.05618)
(1.10631 1.43007 1.24831)
(0.987699 1.64376 1.27608)
(1.30097 1.59943 1.03345)
(1.30916 1.61257 1.1167)
(1.13234 1.45693 1.15056)
(1.46555 1.63656 1.18724)
(1.66981 1.31173 1.16633)
(1.02845 1.45571 1.08304)
(1.03755 1.46009 1.17362)
(1.28464 1.52173 1.05612)
(1.28063 1.45833 1.14944)
(1.4838 1.61352 1.10252)
(1.65558 1.31674 1.22409)
(1.60658 1.29083 1.2854)
(1.53395 1.28288 1.31986)
(1.66602 1.36149 1.16397)
(1.53607 1.34982 1.29811)
(1.5256 1.45845 1.27435)
(1.49955 1.30643 1.29829)
(1.15206 1.63817 1.26029)
(1.42175 1.49829 1.37783)
(1.35363 1.57435 1.32828)
(1.46607 1.46111 1.33015)
(1.50023 1.48817 1.26417)
(1.47939 1.47606 1.24635)
(1.46708 1.40274 1.2593)
(1.49038 1.34778 1.26375)
(0.750723 1.54718 1.47833)
(0.69367 1.44389 1.39601)
(0.900948 1.17891 1.09686)
(0.549683 1.20938 1.27203)
(0.693572 1.5354 1.30304)
(0.871318 1.50984 1.47874)
(0.615216 1.08712 1.28142)
(0.848773 1.62328 1.2159)
(1.1876 1.21835 1.51722)
(0.952878 1.2484 1.10808)
(0.56664 1.26172 1.26347)
(0.852691 1.50914 1.24645)
(0.911301 1.61353 1.44387)
(0.945268 1.45882 1.41768)
(1.01172 1.48221 1.48563)
(0.840997 1.67074 1.23598)
(0.498419 1.04566 1.2009)
(1.06344 1.29603 1.45918)
(0.594166 1.15136 1.11312)
(0.796773 1.42479 1.12806)
(0.919789 1.48074 1.44189)
(0.839298 1.57393 1.27294)
(1.00971 1.45027 1.47999)
(0.818333 1.29213 1.25374)
(0.923649 1.35298 1.22327)
(0.84525 1.00737 1.32768)
(0.995442 1.23097 1.16505)
(0.660757 1.48223 1.42282)
(0.943723 1.46189 1.40617)
(0.77601 1.55558 1.42437)
(0.651382 1.37914 1.09881)
(0.6986 1.38406 1.11414)
(0.769107 1.16299 1.0646)
(1.29695 1.28903 1.40441)
(0.767071 1.5216 1.06013)
(1.2255 1.50963 1.20799)
(0.932164 1.30171 1.11359)
(0.662303 1.19184 1.16819)
(0.668847 1.14898 1.06981)
(0.52354 1.11576 1.24732)
(0.623501 1.191 1.19748)
(0.619919 1.09932 1.18116)
(0.4852 1.07714 1.21471)
(0.46797 1.04746 1.18665)
(0.614359 1.18865 1.19776)
(0.575098 0.987428 1.16032)
(0.603248 1.0548 1.20145)
(0.471959 1.0522 1.16898)
(1.08488 1.04861 1.52485)
(1.09472 1.36609 1.35216)
(1.14143 1.21673 1.52608)
(1.16035 1.09623 1.48072)
(0.995556 1.38353 1.44965)
(1.34589 1.30247 1.29378)
(1.32996 1.26134 1.26081)
(1.13365 1.29808 1.45514)
(0.740504 1.52205 1.23808)
(0.752698 1.48953 1.2721)
(0.683013 1.52801 1.27521)
(0.828942 1.54537 1.25333)
(0.737302 1.46587 1.25813)
(0.64729 1.42343 1.25291)
(0.681917 1.45142 1.26551)
(0.94269 1.66023 1.39218)
(0.892357 1.21982 1.28846)
(0.630808 1.41223 1.25546)
(0.881515 1.49414 1.28343)
(0.887963 1.18255 1.3037)
(0.534491 1.29918 1.22712)
(0.63071 1.15601 1.1074)
(0.603519 1.27696 1.09008)
(0.580829 1.30668 1.06318)
(0.964729 1.09997 1.28624)
(0.946199 1.03079 1.02839)
(0.691857 1.43699 1.08894)
(1.04002 1.62431 1.16194)
(0.870995 1.53614 1.26495)
(0.860575 1.57352 1.27285)
(0.965819 1.53981 1.33104)
(1.02091 1.6636 1.24671)
(0.808566 1.42191 1.40109)
(0.832379 1.57322 1.36116)
(1.23051 1.49412 1.23464)
(0.970481 1.50415 1.48545)
(1.0244 1.56414 1.43858)
(0.949616 1.48632 1.4869)
(0.892399 1.49002 1.49916)
(0.838285 1.55883 1.48912)
(0.811564 1.50769 1.49693)
(0.623145 1.37228 1.25181)
(1.13248 1.20219 1.52842)
(0.969546 1.4355 1.41683)
(0.952806 1.45808 1.43956)
(1.00425 1.36922 1.47378)
(0.851122 1.55103 1.41464)
(0.835643 1.55778 1.42765)
(0.880745 1.53247 1.42013)
(0.868355 1.54537 1.40787)
(0.82439 1.51941 1.40096)
(1.03976 1.54992 1.42964)
(0.999404 1.64627 1.37788)
(1.02158 1.4935 1.4569)
(1.02166 1.46942 1.45989)
(0.976869 1.50645 1.46367)
(0.936761 1.50611 1.46598)
(0.818845 1.65355 1.29387)
(0.8071 1.6155 1.22018)
(1.27058 1.16938 1.39233)
(1.05807 1.292 1.45933)
(0.995883 1.35235 1.48065)
(1.00488 1.3651 1.50068)
(1.32202 1.21534 1.40176)
(1.27146 1.22561 1.42327)
(1.1513 1.26781 1.5153)
(1.01977 1.32885 1.46617)
(1.01685 1.41318 1.4926)
(0.798197 1.0348 1.33202)
(0.572029 1.2463 1.26272)
(1.02184 1.17908 1.15227)
(0.833346 1.04904 1.3146)
(0.708592 1.31515 1.27734)
(1.02615 1.19915 1.08056)
(0.9739 1.23299 1.04971)
(0.526189 1.12622 1.28062)
(0.86051 1.59216 1.19967)
(1.06463 1.7299 1.22083)
(1.212 1.60856 1.21826)
(1.01544 1.32158 1.12453)
(0.905363 1.5182 1.27624)
(0.814888 1.55638 1.45594)
(0.741957 1.51943 1.4687)
(0.650801 1.47417 1.33336)
(1.02394 1.20558 1.14516)
(0.700647 1.51418 1.46014)
(0.871734 1.02743 1.21574)
(0.712412 1.50064 1.43987)
(0.67559 1.46895 1.01399)
(1.11769 1.61858 1.17164)
(1.18844 1.57715 1.16169)
(0.806521 1.50268 1.06462)
(0.73187 1.33146 1.2573)
(0.810632 1.33372 1.17468)
(0.908245 1.36828 1.32538)
(0.848927 1.31993 1.28079)
(1.0047 1.56284 1.0799)
(0.806543 1.43957 1.06797)
(0.948457 1.29999 1.08798)
(0.843959 1.36764 1.05107)
(0.827368 1.47515 1.03694)
(0.573224 1.30656 1.18887)
(0.931868 1.46494 1.39443)
(0.701466 1.10947 1.37808)
(0.592586 1.31169 1.22729)
(0.972565 1.38476 1.38639)
(0.891708 1.51841 1.40662)
(0.879028 1.52497 1.45545)
(0.586493 1.38427 1.25658)
(0.902147 1.23616 1.0648)
(0.890675 1.28066 1.04332)
(0.807765 1.35776 1.03728)
(0.957663 1.32453 1.21917)
(0.618829 1.44074 1.35439)
(0.619921 1.46126 1.23729)
(0.680174 1.42711 1.42042)
(0.732189 1.32626 1.29175)
(0.750976 1.28538 1.05129)
(0.765758 1.25115 1.31478)
(0.69218 1.29326 1.26609)
(0.680393 1.36879 1.12859)
(0.535443 1.25349 0.663771)
(0.877871 1.53552 0.743364)
(0.582562 1.13295 0.717578)
(0.484782 1.1953 0.688897)
(0.977671 1.43474 0.721237)
(0.753511 1.60656 0.660869)
(0.937788 1.64247 0.697377)
(0.842239 1.48254 0.615778)
(0.651113 1.22714 0.530572)
(0.793515 1.52326 0.778118)
(0.961089 1.29775 0.717834)
(0.925753 1.69859 0.651403)
(0.756766 1.63091 0.645868)
(0.591439 1.31962 0.756042)
(0.818605 1.22925 0.787102)
(0.864578 1.60129 0.7684)
(0.862089 1.564 0.606094)
(0.513794 0.975776 0.86286)
(1.19634 1.16132 0.570125)
(0.947908 1.21734 0.964413)
(1.07916 1.14918 0.776106)
(0.880193 1.32824 0.800833)
(1.04032 1.21139 0.865625)
(1.02891 1.12836 0.970587)
(0.938909 1.60333 0.770207)
(0.606015 1.51591 0.670184)
(0.805944 1.22489 0.747841)
(1.00673 1.15018 0.961133)
(0.938282 1.51398 0.542671)
(0.829066 1.43531 0.904678)
(0.866442 1.38928 0.612777)
(1.03468 1.25848 0.901954)
(1.09753 1.70775 0.857101)
(0.633882 1.5052 0.581053)
(0.914973 1.56866 0.554788)
(1.18493 1.28732 0.607555)
(0.531881 1.38297 0.761809)
(0.54889 1.3113 0.710506)
(0.571435 1.13507 0.681943)
(0.567134 1.12258 0.705227)
(0.601101 1.12473 0.688651)
(0.601499 1.51954 0.632058)
(0.705481 1.60538 0.762016)
(0.47947 1.10211 0.7054)
(0.526221 1.3567 0.651876)
(0.619644 1.41246 0.541433)
(0.829485 1.49634 0.624912)
(0.828331 1.56186 0.633168)
(0.959684 1.40241 0.518603)
(0.807053 1.60823 0.637779)
(0.861107 1.53588 0.619884)
(0.970164 1.38723 0.530737)
(0.779212 1.54279 0.633921)
(0.91596 1.32158 0.720667)
(0.70576 1.59172 0.671576)
(0.747858 1.62519 0.673176)
(0.816594 1.59875 0.611347)
(0.802114 1.40898 0.628507)
(1.15971 1.21573 0.623897)
(1.21746 1.14771 0.697154)
(1.12001 1.29915 0.590664)
(0.869828 1.62559 0.751095)
(0.870879 1.58723 0.694075)
(0.940745 1.59507 0.675477)
(0.912531 1.58897 0.793668)
(0.898227 1.61305 0.798499)
(1.10558 1.46688 0.797728)
(1.06906 1.4574 0.788192)
(0.944153 1.61635 0.781117)
(0.919859 1.62834 0.805583)
(1.02597 1.64875 0.710672)
(0.957121 1.67615 0.718629)
(1.19038 1.61913 0.806852)
(1.1103 1.24948 0.531254)
(1.0844 1.13722 0.58347)
(0.906252 1.46417 0.572287)
(0.933078 1.43333 0.513719)
(1.12001 1.26119 0.518068)
(0.612272 1.42351 0.619425)
(0.601212 1.5445 0.742934)
(0.589228 1.0857 0.60797)
(0.747845 1.042 0.936229)
(0.973007 1.19922 0.917174)
(1.10931 1.06327 0.531484)
(1.02206 1.24428 0.572281)
(1.16967 1.11167 0.595116)
(0.586011 1.35676 0.761201)
(0.68061 1.51045 0.804796)
(0.751224 1.50472 0.787358)
(0.614241 1.50067 0.803765)
(0.851248 1.58479 0.762208)
(0.856978 1.50739 0.669666)
(0.858878 1.51534 0.781249)
(0.772178 1.53859 0.76966)
(0.792246 1.48622 0.900948)
(0.632906 1.55305 0.708157)
(0.656736 1.5162 0.635047)
(0.778092 1.26585 0.814243)
(0.883798 1.24762 0.782869)
(0.852063 1.40106 0.615895)
(0.972037 1.36603 0.556233)
(0.930986 1.37857 0.590709)
(0.973272 1.26085 0.790261)
(0.875276 1.1612 0.618548)
(1.12811 1.13892 0.49603)
(0.98116 1.5757 0.79677)
(0.924378 1.58864 0.749179)
(0.969122 1.5673 0.757767)
(1.05817 1.60675 0.582414)
(0.986829 1.5888 0.757974)
(0.9672 1.58212 0.775416)
(1.00346 1.53984 0.5344)
(1.02311 1.52747 0.528383)
(0.988133 1.58967 0.559026)
(0.884684 1.66727 0.628236)
(0.920672 1.5363 0.548675)
(0.833624 1.63134 0.61483)
(0.764195 1.64223 0.735206)
(0.686059 1.59887 0.675768)
(0.896839 1.53422 0.577512)
(0.850861 1.57104 0.571032)
(0.82135 1.60151 0.593969)
(0.90737 1.51148 0.598521)
(0.940254 1.49727 0.567621)
(0.494819 1.1312 0.719788)
(0.500527 1.16833 0.732022)
(0.5753 1.17423 0.749825)
(0.494951 1.10536 0.61879)
(0.442934 1.11493 0.677226)
(0.940071 1.25416 0.976308)
(0.685265 1.15479 0.559404)
(0.943778 1.24208 0.969168)
(0.722129 1.02665 0.95531)
(0.916738 1.24521 0.768159)
(0.802788 1.24097 0.876557)
(0.588194 1.05453 0.616113)
(0.960151 1.11362 0.982023)
(0.534917 1.07007 0.61732)
(0.462331 1.01581 0.745847)
(1.07878 1.73055 0.854647)
(1.14044 1.77554 0.899411)
(0.628798 1.10854 0.82266)
(0.728218 1.17932 0.700333)
(0.684543 1.20217 0.689444)
(0.764163 1.18283 0.759141)
(1.10534 1.11532 0.738081)
(1.03312 1.46911 0.819902)
(1.04425 1.47212 0.824422)
(0.939122 1.09769 0.797338)
(0.906035 1.42661 0.870418)
(0.746246 1.33657 0.690454)
(0.962664 1.12019 0.731683)
(0.904143 1.46754 0.929524)
(0.891886 1.45338 0.833002)
(0.991678 1.25133 0.851037)
(0.999019 1.48858 0.934094)
(0.962502 1.56187 0.954582)
(0.768265 1.39911 0.841273)
(1.10133 1.55361 0.918195)
(0.83934 1.1988 0.934477)
(0.692754 1.17518 0.643492)
(0.918754 1.21723 0.966896)
(1.10134 1.11623 0.763858)
(1.05857 1.1721 0.854577)
(0.9003 1.23765 0.821273)
(1.41486 1.62242 0.781613)
(1.31795 1.67821 0.834911)
(1.63244 1.38909 0.764483)
(1.0328 1.41901 0.70975)
(1.18593 1.77372 0.79779)
(1.6407 1.26377 0.776564)
(1.32224 1.20725 0.699837)
(1.30178 1.32249 0.7438)
(1.3338 1.72264 0.851744)
(1.23178 1.59402 0.748271)
(0.915614 1.68191 0.826553)
(1.42677 1.53791 0.758488)
(1.47514 1.43648 0.715977)
(1.25629 1.30476 0.728187)
(1.45581 1.46556 0.63303)
(1.2813 1.21646 0.648061)
(1.53961 1.26112 0.68054)
(1.02599 1.40253 0.767221)
(1.22187 1.51661 0.940067)
(1.67455 1.36248 0.886271)
(1.61493 1.46807 0.898652)
(1.53866 1.38929 0.71424)
(1.36799 1.26862 0.682065)
(1.01022 1.71374 0.82561)
(1.28643 1.45973 0.89141)
(1.603 1.4652 0.737404)
(1.40271 1.28755 0.684842)
(1.44345 1.32373 0.797674)
(1.20336 1.77121 0.902955)
(1.68018 1.25617 0.89422)
(1.20892 1.21349 0.625651)
(1.56225 1.54814 0.771702)
(1.56406 1.46121 0.921526)
(1.44061 1.28616 0.668837)
(0.959997 1.64464 0.788644)
(1.17221 1.57287 0.786693)
(1.68601 1.27644 0.943473)
(1.67774 1.21006 0.946134)
(1.66368 1.20194 0.872544)
(1.39023 1.65071 0.83519)
(1.32519 1.68318 0.813232)
(1.37626 1.60418 0.830242)
(1.35478 1.56184 0.912364)
(1.34206 1.60256 0.733331)
(1.43343 1.5999 0.784325)
(1.44024 1.61386 0.855244)
(1.36801 1.50052 0.635599)
(1.45676 1.58704 0.691662)
(1.49053 1.60624 0.755068)
(1.52392 1.56632 0.772157)
(1.53792 1.55869 0.707162)
(1.24791 1.4631 0.917247)
(1.30798 1.48543 0.855152)
(1.24144 1.73221 0.951431)
(1.098 1.49006 0.992022)
(1.32761 1.67655 0.995736)
(1.33537 1.4832 0.829638)
(1.41041 1.49154 0.766463)
(1.24306 1.52052 0.939333)
(1.42236 1.50929 0.752179)
(1.5103 1.50889 0.794151)
(1.40944 1.50657 0.822595)
(1.58877 1.43555 0.979901)
(1.55482 1.43406 0.961706)
(1.54335 1.5193 0.826421)
(1.6115 1.44446 0.954302)
(1.64549 1.42177 0.936126)
(1.59629 1.4681 0.915545)
(1.67148 1.37645 0.94153)
(1.68348 1.31603 0.934665)
(1.65454 1.41081 0.880608)
(1.67908 1.29592 0.881898)
(1.18737 1.12627 0.657984)
(1.18617 1.17045 0.645159)
(1.2346 1.19124 0.635074)
(1.06024 1.71716 0.836267)
(1.11887 1.75853 0.817882)
(1.18136 1.78422 0.847481)
(1.14232 1.77745 0.838586)
(0.969826 1.70872 0.78536)
(1.08127 1.73697 0.783551)
(1.32117 1.71964 0.940589)
(1.24465 1.7659 0.89824)
(1.26309 1.76323 0.828964)
(1.21844 1.73801 0.768529)
(1.63312 1.32407 0.759956)
(1.58605 1.32341 0.708709)
(1.59193 1.25252 0.719219)
(1.55581 1.17379 0.725409)
(1.60133 1.1803 0.764544)
(1.66357 1.30714 0.822207)
(1.66295 1.25436 0.830801)
(1.65604 1.37001 0.818262)
(1.64291 1.2008 0.816215)
(0.949867 1.65882 0.819672)
(0.947302 1.59372 0.82276)
(0.965478 1.62059 0.77069)
(0.95331 1.69048 0.813337)
(1.13707 1.51844 0.570235)
(1.11616 1.62742 0.644243)
(0.982387 1.63238 0.756421)
(1.0826 1.38921 0.655433)
(1.12275 1.48086 0.586807)
(1.10354 1.56291 0.623998)
(1.20095 1.24464 0.616333)
(1.27105 1.22319 0.599615)
(1.30825 1.26144 0.694672)
(1.23788 1.21658 0.638127)
(1.4121 1.36221 0.760519)
(1.33285 1.52592 0.693563)
(1.19478 1.53171 0.719642)
(1.06715 1.41084 0.706622)
(1.28551 1.33793 0.724717)
(1.32078 1.45412 0.6919)
(0.990086 1.4207 0.906818)
(1.07597 1.53793 0.618521)
(1.15467 1.43443 0.952206)
(1.17875 1.48806 0.858498)
(1.2416 1.55864 0.795547)
(1.35469 1.51663 0.663126)
(1.02199 1.63896 0.672086)
(1.1862 1.62886 0.796752)
(1.17786 1.39928 0.961944)
(1.00918 1.68245 0.812132)
(1.33756 1.23532 0.741721)
(1.34582 1.25833 0.757341)
(1.35773 1.22442 0.692794)
(1.3238 1.28954 0.777712)
(1.28936 1.23495 0.708779)
(1.29091 1.21164 0.697172)
(1.28093 1.19225 0.662)
(1.32903 1.17026 0.694526)
(1.36181 1.16258 0.683085)
(1.28681 1.17961 0.673892)
(1.36519 1.31911 0.788419)
(1.48275 1.38253 0.78253)
(1.38116 1.29527 0.781066)
(1.38683 1.66165 0.930898)
(1.47818 1.44245 0.684692)
(0.966067 1.6728 0.805553)
(1.57788 1.50972 0.852403)
(1.5271 1.42448 0.693391)
(1.52797 1.42144 0.743916)
(1.5156 1.38233 0.768629)
(1.5586 1.41396 0.691671)
(1.54216 1.48047 0.670137)
(1.59003 1.50746 0.753188)
(1.49629 1.35055 0.719438)
(1.48014 1.26476 0.663543)
(1.52743 1.33926 0.69385)
(1.47078 1.18597 0.684754)
(1.50951 1.17212 0.701658)
(1.5725 1.3762 0.703768)
(1.4529 1.32125 0.751536)
(1.42222 1.29299 0.683104)
(1.42065 1.3032 0.766477)
(1.44102 1.21236 0.673669)
(1.42395 1.20478 0.675778)
(1.63735 1.43111 0.826493)
(1.61955 1.46113 0.817586)
(1.60291 1.4845 0.840791)
(1.61785 1.41621 0.750107)
(1.38453 1.28637 0.689425)
(1.38498 1.18204 0.67707)
(1.40455 1.19225 0.678079)
(0.974133 1.50907 1.34597)
(0.923813 0.970086 1.07015)
(1.00979 1.07825 1.32689)
(1.06958 1.27612 1.27353)
(1.14102 1.19747 1.30774)
(0.875096 1.07456 1.15299)
(0.800083 1.12058 1.34333)
(0.797213 1.02581 1.33795)
(0.82172 1.0345 1.1656)
(1.14914 1.32113 1.26252)
(1.02871 1.09331 1.40928)
(0.885742 1.10442 1.24995)
(1.35535 1.22136 1.12866)
(1.04896 1.11541 1.40479)
(1.13304 1.21401 1.04873)
(1.11241 1.25026 0.919469)
(1.11356 1.22315 0.986057)
(1.21304 1.23075 1.05313)
(1.42409 1.35468 1.10135)
(1.18372 1.16595 1.15091)
(0.543657 1.31686 1.31296)
(0.67669 1.21135 1.36143)
(0.579857 1.20292 1.40344)
(1.11574 1.08064 1.22169)
(0.659955 1.08605 1.3651)
(1.01505 1.06554 1.34153)
(1.0288 1.05015 1.36929)
(1.08076 1.1046 1.34489)
(1.04767 1.1368 1.40761)
(0.583054 1.29346 1.36708)
(0.523058 1.18051 1.37872)
(0.821658 1.11547 1.09708)
(1.0366 1.01178 1.10845)
(0.841423 0.979635 1.28709)
(0.986787 1.11459 1.3119)
(0.954035 1.22817 1.25127)
(0.936666 1.17931 1.26482)
(1.09443 1.06837 1.20553)
(0.955113 1.18613 1.14656)
(1.20771 1.15316 1.19587)
(1.29091 1.26128 1.32579)
(1.26998 1.19845 1.11019)
(1.09344 1.21802 1.04122)
(0.904163 1.07916 1.30516)
(1.06826 1.29468 1.15426)
(0.936118 1.18411 1.35916)
(1.16472 1.34406 1.23928)
(1.09581 1.2383 1.27715)
(0.93939 1.06385 1.36472)
(1.26962 1.28421 1.23334)
(1.28551 1.316 1.3156)
(0.881494 1.05183 1.20168)
(0.788651 1.18084 1.35179)
(0.842267 0.992461 1.32079)
(0.887775 1.02089 1.20172)
(1.04842 1.06671 1.20641)
(1.04551 1.06914 1.21181)
(1.0311 1.07493 1.22852)
(0.995615 1.07744 1.30886)
(0.97168 1.42248 1.18153)
(1.01535 1.16772 1.25035)
(0.968882 1.35986 1.17125)
(0.893239 1.13141 1.33731)
(0.964607 1.45097 1.1574)
(1.16786 1.29868 1.3159)
(1.12643 1.2205 1.30693)
(0.930146 1.37306 1.11696)
(0.967547 1.47148 1.15143)
(0.954215 1.023 1.35788)
(1.03168 1.00726 1.13309)
(0.983663 1.24419 1.22565)
(0.893511 1.10625 1.12793)
(1.3089 1.37331 1.00525)
(1.44882 1.43648 1.16558)
(1.49277 1.39898 1.16642)
(1.5462 1.56461 1.13479)
(1.50739 1.51456 1.15039)
(1.31682 1.39891 1.03502)
(1.44123 1.3803 1.20171)
(1.49013 1.376 1.1924)
(1.39895 1.36094 1.11942)
(1.49029 1.19438 1.051)
(1.53389 1.52579 1.16467)
(1.33725 1.38581 1.03339)
(1.3932 1.47967 1.34572)
(1.19853 1.28198 0.9996)
(1.32173 1.43539 1.12495)
(1.53366 1.35595 1.13649)
(1.51137 1.35556 1.14856)
(1.47668 1.36341 1.18844)
(1.56726 1.54991 1.18514)
(1.54949 1.48151 1.15406)
(1.4581 1.42725 1.19706)
(1.4679 1.54566 1.14883)
(1.45385 1.40354 1.20839)
(1.45241 1.43948 1.17235)
(1.46203 1.49719 1.18874)
(1.44152 1.4258 1.22506)
(1.53979 1.49026 1.15098)
(1.18306 1.26303 1.01469)
(1.18258 1.28701 1.02947)
(1.40474 1.39118 0.966777)
(1.31896 1.25043 0.962941)
(1.25285 1.27354 0.971419)
(1.4653 1.39179 1.14749)
(1.47543 1.20204 1.06795)
(1.5012 1.3191 1.04962)
(1.47927 1.18567 1.069)
(1.4902 1.16642 1.03371)
(1.33095 1.43077 1.05512)
(1.27964 1.47045 1.03515)
(1.22242 1.45036 1.29387)
(1.36456 1.44945 1.28976)
(1.51288 1.54564 1.19989)
(1.3213 1.42666 1.07779)
(1.29916 1.38842 1.12237)
(1.37017 1.43157 1.12466)
(1.31135 1.21891 1.1368)
(1.38848 1.40746 1.1368)
(1.33471 1.40865 1.16005)
(1.37269 1.44551 1.11442)
(1.3851 1.38867 1.03693)
(1.39017 1.2364 1.08725)
(1.39548 1.40742 1.08936)
(1.33137 1.47564 1.35599)
(1.49158 1.53555 1.19727)
(1.47206 1.53347 1.22125)
(1.2294 1.30241 0.990582)
(1.43171 1.3027 1.05845)
(1.26422 1.45122 1.01707)
(1.21415 1.38331 1.14533)
(1.3026 1.45074 1.00688)
(1.40081 1.46554 1.3505)
(1.3634 1.34649 1.05781)
(1.42034 1.44822 1.29697)
(1.49039 1.18378 1.02515)
(1.51538 1.38594 1.09501)
(1.5162 1.39283 1.1026)
(1.37309 1.47577 1.28045)
(1.53959 1.55098 1.12147)
(1.54918 1.36654 1.12808)
(1.5144 1.38505 1.17753)
(1.52798 1.57213 1.23078)
(1.51265 1.39437 1.1556)
(1.29335 1.37076 0.862391)
(1.51799 1.40775 1.01795)
(1.3591 1.46895 0.742201)
(1.3465 1.36404 0.977806)
(1.4836 1.43631 0.803835)
(1.55122 1.39193 1.04589)
(1.22326 1.22982 0.827167)
(1.54111 1.40316 0.905121)
(1.19635 1.23309 0.83393)
(1.21889 1.46709 0.905245)
(1.5012 1.23746 0.96763)
(1.20622 1.36149 0.780454)
(1.57649 1.34534 1.02742)
(1.18781 1.27623 0.937958)
(1.39014 1.28295 0.921237)
(0.970512 1.38623 0.949785)
(1.12262 1.24704 0.977404)
(1.2006 1.19913 0.873368)
(1.29828 1.25703 0.944978)
(1.23052 1.23307 0.834672)
(1.00484 1.4098 0.672674)
(1.0427 1.36848 0.962718)
(1.14484 1.19558 0.707837)
(1.19744 1.21727 0.777198)
(1.26054 1.39931 0.889642)
(1.24009 1.36881 0.835042)
(1.34124 1.40918 0.947701)
(1.5456 1.39054 0.896022)
(1.26254 1.54148 0.760211)
(1.2408 1.54077 0.76007)
(1.3113 1.5102 0.786576)
(1.19437 1.18651 0.781553)
(1.29788 1.34216 0.854206)
(1.09112 1.41558 0.910887)
(1.21277 1.32525 0.997052)
(1.17754 1.36168 0.910598)
(1.31155 1.34218 0.935449)
(1.45459 1.43991 0.762193)
(1.25203 1.34231 0.993594)
(1.19416 1.37037 0.777407)
(1.27357 1.37333 0.883384)
(1.29578 1.41897 0.968127)
(1.38527 1.4445 0.80137)
(1.36998 1.43774 0.761373)
(1.5564 1.39618 0.997669)
(1.15405 1.50724 0.925805)
(1.56866 1.36432 0.977794)
(1.37287 1.45037 0.844637)
(1.45792 1.46202 0.922498)
(1.46598 1.27961 0.921885)
(1.44837 1.46243 0.874428)
(1.19935 1.49103 0.901065)
(1.19365 1.41171 0.996106)
(1.521 1.42161 1.08893)
(1.52291 1.39514 1.02382)
(1.47255 1.18308 0.942559)
(1.45966 1.19344 0.929774)
(1.31937 1.44968 0.772516)
(1.56768 1.35822 1.06086)
(1.56851 1.38842 1.05513)
(1.5498 1.40601 0.922021)
(1.4495 1.4663 0.771182)
(1.49367 1.19469 0.975504)
(1.53023 1.39351 1.10364)
(1.54415 1.39019 1.09283)
(1.56781 1.36758 1.03616)
(1.48191 1.1667 0.961567)
(1.57712 1.36086 0.976552)
(1.04872 1.23544 0.662617)
(0.676922 1.33455 0.658655)
(0.953545 1.32006 0.805657)
(0.775584 1.41684 0.714797)
(1.01153 1.27756 0.726114)
(1.24268 1.22532 0.793419)
(0.521873 0.968967 0.731272)
(0.974164 1.1333 0.72907)
(0.798313 1.35351 0.867614)
(0.972833 1.18418 0.797491)
(1.164 1.28524 0.646386)
(0.934617 1.097 0.693663)
(1.06674 1.32719 0.841783)
(0.924869 1.16617 0.757409)
(1.04745 1.5053 0.545178)
(1.29056 1.3856 0.824744)
(1.1745 1.20383 0.680374)
(1.18775 1.15867 0.846879)
(1.08022 1.29356 0.895549)
(1.27653 1.22404 0.805843)
(1.07173 1.17617 0.691086)
(1.1814 1.2018 0.723365)
(0.929933 1.47143 0.626163)
(0.891106 0.972033 0.974667)
(1.0516 1.08124 0.814209)
(0.751168 1.31507 0.873288)
(0.917371 1.19401 0.871323)
(0.931994 1.17949 0.894614)
(0.838777 1.32291 0.690652)
(0.723127 1.34608 0.859513)
(0.820174 1.1156 0.619004)
(1.09287 1.11592 0.844081)
(0.970246 1.22168 0.771803)
(1.00747 1.20881 0.763896)
(0.912198 1.34556 0.694314)
(0.553619 1.01679 0.648721)
(0.522685 0.97296 0.731806)
(0.890063 1.18776 0.875938)
(0.878997 1.16193 0.926767)
(0.896458 1.0202 0.903696)
(1.00747 1.31662 0.803537)
(0.948791 1.31843 0.718127)
(0.923352 1.36239 0.81069)
(0.937881 1.36589 0.828879)
(1.09759 1.24762 0.784417)
(0.939118 0.957805 0.869101)
(1.00575 1.25077 1.00078)
(0.813803 1.29627 0.925341)
(1.05589 1.06923 0.734281)
(0.965584 1.48799 0.818734)
(0.953281 1.37557 0.765579)
(1.17721 1.22298 0.714295)
(1.11772 1.24469 0.662014)
(1.04305 1.13342 0.681908)
(0.813906 1.15298 0.62263)
(0.992125 1.15303 0.891602)
(1.04899 1.31249 0.795477)
(1.15188 1.14949 0.791584)
(1.19955 1.36568 0.706042)
(1.01695 1.37658 0.883181)
(0.920745 1.4012 0.86912)
(1.00423 1.33316 0.841795)
(1.17146 1.24618 0.730592)
(1.10355 1.63515 0.700696)
(1.0721 1.25273 0.839065)
(1.00798 1.29063 1.0103)
(1.04543 1.15884 1.00979)
(1.08171 1.05649 0.812726)
(1.15459 1.11642 0.742512)
(0.862232 1.3531 0.804828)
(1.1379 1.39887 0.761207)
(0.895211 1.15832 0.890688)
(0.574813 1.20123 0.774655)
(1.02774 1.40614 0.62044)
(1.14135 1.12895 0.559133)
(0.77198 1.30732 1.04178)
(1.23509 1.21654 0.740328)
(0.722071 1.11392 0.617483)
(1.05457 1.19685 0.552476)
(1.0827 1.24132 0.758207)
(1.10784 1.18848 0.915095)
(0.648273 0.997525 0.660367)
(0.635033 1.01412 0.642343)
(0.633997 1.14274 0.69065)
(0.557959 0.997741 0.696037)
(0.677217 1.05514 0.539157)
(0.723136 0.995681 0.976561)
(0.55708 1.05555 0.760863)
(0.469164 1.07147 0.77112)
(0.619424 1.00813 0.59601)
(0.61482 1.01138 0.879047)
(1.02576 1.1759 1.00333)
(0.914722 1.42688 0.574077)
(1.00939 1.44518 0.511661)
(0.974267 1.39709 0.599384)
(0.951334 1.38041 0.820494)
(0.952327 1.19763 0.715333)
(0.834961 1.14746 0.892131)
(1.00292 1.38659 0.53492)
(1.11144 1.11146 0.557844)
(1.07622 1.34598 0.53071)
(1.09812 1.37937 0.647391)
(0.811964 1.117 0.799941)
(0.882782 1.54563 1.02354)
(1.1363 1.03882 0.609299)
(1.06427 1.01918 0.667302)
(1.12807 0.988538 0.500803)
(1.0381 1.20798 0.582099)
(0.987656 1.38227 0.766865)
(1.09054 1.35056 0.8734)
(1.29684 1.22044 0.790099)
(1.22552 1.32566 0.741738)
(1.02395 1.37752 0.598799)
(1.12535 1.33565 0.609758)
(1.06073 1.08293 0.537587)
(1.05004 1.37874 0.575432)
(1.12649 1.04174 0.533073)
(1.03597 1.27411 0.888255)
(0.939427 1.35136 0.93098)
(0.851354 1.45092 0.998214)
(0.580703 1.12948 0.86669)
(0.706998 1.09579 0.793584)
(0.474298 1.16037 1.25352)
(0.961269 1.45923 1.1286)
(1.14447 1.10187 1.44159)
(1.31797 1.28265 1.24161)
(0.507863 1.06528 1.31525)
(0.498089 1.2472 1.36056)
(1.21227 1.15138 1.46466)
(0.711966 1.42945 1.07543)
(1.12829 1.29164 1.14276)
(0.587878 1.25724 1.42156)
(0.51889 1.32593 1.25849)
(0.674814 1.12648 1.46113)
(1.07286 0.963513 1.50385)
(1.16424 0.950827 1.43209)
(1.11134 1.10657 1.44392)
(1.23299 1.18283 1.46456)
(0.987988 1.39934 1.18784)
(1.00621 1.43489 1.41403)
(1.2628 1.42577 1.38159)
(1.26869 1.35539 1.39018)
(1.15107 1.39987 1.179)
(1.16948 1.25005 1.49242)
(0.994139 1.46413 1.28314)
(0.993189 1.50765 1.32764)
(1.13447 1.00467 1.40302)
(1.35651 1.25286 1.33703)
(1.31416 1.25588 1.225)
(0.521241 1.16287 1.39102)
(0.464042 1.21652 1.28449)
(0.541795 1.01344 1.09247)
(0.461053 1.07143 1.15722)
(0.644155 1.17901 1.48499)
(1.11675 1.30492 1.20017)
(1.04062 1.34755 1.16701)
(1.01124 1.51236 1.37299)
(0.997142 1.51678 1.33206)
(1.01903 1.47079 1.39502)
(1.26736 1.30993 1.22569)
(1.16193 1.23677 1.17654)
(0.544382 1.00635 1.28156)
(0.979549 1.05206 1.06379)
(0.661092 1.40376 1.05104)
(0.985741 0.973621 1.11708)
(0.522081 1.032 1.1507)
(0.478211 1.11004 1.30438)
(1.05515 1.18346 1.06793)
(1.03656 1.18488 1.09665)
(0.729882 1.51652 1.01767)
(0.664211 1.14668 1.06514)
(0.977106 1.14194 1.03043)
(1.30392 1.17612 1.17064)
(1.47412 1.20878 1.13491)
(1.28893 1.37912 1.26514)
(1.25363 1.08887 1.21605)
(1.51558 1.13062 1.1142)
(1.40055 1.15445 1.20327)
(1.45547 1.199 1.19)
(1.50296 1.1571 1.07627)
(1.3859 1.20885 1.12351)
(1.47555 1.2095 1.10942)
(1.45986 1.25877 1.11645)
(1.48183 1.17394 1.08306)
(1.48774 1.18173 1.11338)
(1.48962 1.14944 1.04034)
(1.39431 1.19767 1.12455)
(1.40848 1.20666 1.06719)
(1.29075 1.37736 1.24941)
(1.24057 1.44047 1.05701)
(1.30603 1.36095 1.21433)
(1.43949 1.22829 1.14915)
(1.36384 1.16786 1.1913)
(1.36752 1.24174 1.17301)
(1.41493 1.21957 1.12008)
(1.29697 1.18028 1.09073)
(1.25602 1.22237 1.38521)
(1.2262 1.13877 1.30204)
(1.19821 1.101 1.27523)
(1.24867 1.15534 1.21546)
(1.38997 1.10103 1.25325)
(1.34471 1.09277 1.25329)
(1.29637 1.11848 1.24535)
(1.29214 1.11771 1.1697)
(1.41878 1.12504 1.24558)
(1.44311 1.1518 1.23972)
(1.45762 1.13564 1.22701)
(1.43175 1.17589 1.22385)
(1.36449 1.36529 1.1924)
(1.47772 1.12289 1.20347)
(1.5233 1.11528 1.16098)
(1.55808 1.10665 1.12387)
(1.46499 1.21738 1.15282)
(1.48785 1.1331 1.17438)
(1.49088 1.16162 1.13383)
(1.56951 1.09884 1.063)
(1.53158 1.11802 1.06034)
(1.34005 1.39924 1.24311)
(1.51081 1.14569 1.09661)
(1.52044 1.12944 1.0392)
(1.2934 1.22862 1.20733)
(1.27104 1.16978 1.15497)
(1.46991 1.25204 0.866445)
(1.36626 1.16731 0.920267)
(1.28823 1.40574 0.753089)
(1.31016 1.08589 0.901298)
(1.50896 1.13521 0.876583)
(1.47415 1.21249 0.793596)
(1.42643 1.17887 0.810528)
(1.48803 1.15491 0.910253)
(1.27494 1.32837 0.791783)
(1.40976 1.38202 0.845938)
(1.35098 1.3964 0.78461)
(1.42774 1.24686 0.862014)
(1.45257 1.1819 0.750465)
(1.45637 1.15531 0.739888)
(1.40119 1.32161 0.863782)
(1.39876 1.35696 0.859862)
(1.40769 1.265 0.84878)
(1.42898 1.14287 0.733568)
(1.38116 1.33424 0.862108)
(1.39785 1.29148 0.857901)
(1.39126 1.27357 0.862162)
(1.26455 1.33486 0.784644)
(1.39056 1.14554 0.872818)
(1.33077 1.12991 0.925234)
(1.28734 1.14444 0.731025)
(1.34135 1.11566 0.758813)
(1.37572 1.28454 0.846722)
(1.36724 1.12543 0.744093)
(1.56824 1.10696 0.927487)
(1.4693 1.24157 0.840402)
(1.42562 1.37352 0.884052)
(1.48933 1.13023 0.782098)
(1.4968 1.14094 0.811373)
(1.47096 1.14095 0.755956)
(1.23466 1.04366 0.779632)
(1.48916 1.17938 0.851903)
(1.49688 1.15038 0.891734)
(1.48123 1.20922 0.873563)
(1.52685 1.1196 0.831221)
(1.5202 1.11898 0.929971)
(1.50698 1.12676 0.951196)
(1.55762 1.11341 0.871252)
(1.46363 1.27536 0.893224)
(1.47484 1.17803 0.900745)
(1.13033 1.44462 0.751434)
(1.37097 1.22935 0.846008)
(1.24258 1.1077 0.710028)
(1.26109 1.31507 0.784141)
(1.48004 1.14108 0.954283)
(1.40353 1.12599 0.736115)
(1.61013 1.24005 1.05657)
(1.29602 1.5027 0.998371)
(1.57981 1.61817 1.21432)
(1.14799 1.26411 1.30391)
(1.28348 1.2272 0.830111)
(1.24612 1.20244 1.11216)
(0.878903 1.37668 1.03565)
(1.09091 1.37701 0.921899)
(1.24582 1.47193 0.714946)
(1.1773 1.67717 1.17057)
(1.09433 1.26568 1.12793)
(1.31191 1.63475 1.08011)
(1.35505 1.25312 0.99881)
(1.29774 1.25486 0.85632)
(0.957312 1.16591 0.935732)
(1.04307 1.3233 1.13243)
(1.22605 1.35729 1.08463)
(0.90271 1.48501 0.651462)
(0.980773 1.48975 0.974972)
(0.883311 1.62497 1.38297)
(0.631975 0.988522 0.642296)
(1.38199 1.28923 1.18559)
(1.31563 1.36544 0.740319)
(1.01652 1.28374 1.13562)
(1.07027 1.44573 1.04347)
(0.957433 1.4213 0.595144)
(1.01603 1.24378 0.816823)
(1.17166 1.50653 0.9543)
(0.837157 1.3613 0.936122)
(1.0338 1.59251 0.897353)
(1.57733 1.36595 0.839395)
(1.41624 1.56086 0.739555)
(0.847116 1.26895 0.885413)
(0.7834 1.30219 0.89084)
(0.956577 1.20361 1.30704)
(1.55923 1.55062 1.11553)
(0.842829 1.32266 1.08043)
(1.08497 1.14641 1.17598)
(1.63102 1.34844 0.978611)
(1.26366 1.57511 0.949354)
(1.1138 1.11504 1.14344)
(0.974408 1.17425 1.14618)
(0.970067 1.0888 0.746779)
(1.03785 1.12393 1.34528)
(0.972218 1.31785 1.1092)
(0.981176 1.55181 0.945907)
(1.61517 1.22086 0.92078)
(1.61742 1.36727 0.895687)
(1.27107 1.22176 0.741085)
(1.24664 1.69807 0.810505)
(1.45065 1.3253 1.20537)
(0.921507 1.18229 1.19383)
(1.56372 1.44535 0.894972)
(1.52776 1.33024 0.888039)
(1.5143 1.51367 0.67855)
(1.60567 1.42696 0.811577)
(1.54074 1.49377 0.784613)
(1.53248 1.3199 0.929866)
(0.532341 1.13015 0.679355)
(0.512592 1.0295 0.780747)
(0.543266 1.14004 0.66872)
(0.841127 1.40282 0.726175)
(0.889504 1.03888 0.953453)
(0.556195 1.0363 0.892003)
(0.613926 1.1307 0.67693)
(0.617089 1.03681 0.631546)
(0.586489 0.987355 0.714754)
(0.921144 1.14101 0.797291)
(0.794487 0.991375 0.951354)
(1.54528 1.60228 1.15218)
(1.57715 1.38182 0.952856)
(1.58926 1.36787 1.03159)
(1.44389 1.51897 0.720355)
(1.58186 1.41366 0.950819)
(1.52346 1.4863 0.845377)
(1.60127 1.41075 0.997383)
(0.848252 1.19995 0.77667)
(0.62124 1.35453 0.576353)
(1.47595 1.5307 0.720725)
(1.39605 1.4647 0.710264)
(1.06449 1.13106 0.82361)
(0.881843 1.11951 0.976977)
(1.04692 1.12729 0.898292)
(1.00714 1.2518 0.826528)
(1.00683 1.11871 0.810814)
(1.64571 1.37798 0.914366)
(1.55735 1.27587 0.953475)
(1.59903 1.40183 1.04929)
(0.906044 1.13381 0.959501)
(0.554921 1.16997 0.662022)
(0.792476 1.28922 0.842153)
(0.938995 1.29219 0.794441)
(0.830037 1.61124 0.71276)
(1.38601 1.52399 0.842988)
(1.20589 1.47686 1.08939)
(1.24036 1.40845 1.04429)
(1.29261 1.45555 1.21645)
(1.39493 1.51301 1.1694)
(1.3278 1.53497 1.30427)
(1.23365 1.42485 1.01948)
(1.00529 1.1441 0.777509)
(0.566091 1.30311 0.712071)
(0.821081 1.52186 0.805985)
(0.602229 1.00298 0.751942)
(0.674685 1.09086 0.598587)
(0.64729 1.15476 0.563086)
(1.42497 1.53024 0.830084)
(1.44801 1.47069 0.778441)
(1.36751 1.50568 0.791791)
(1.34918 1.47952 1.17013)
(0.56261 1.28299 0.706332)
(0.998916 1.45713 0.906937)
(0.957467 1.32613 1.02722)
(0.868914 1.36944 0.659126)
(1.02693 1.1356 0.78521)
(0.922305 1.09307 0.748943)
(0.902191 1.111 0.783481)
(1.40991 1.58675 1.26494)
(1.40426 1.54232 0.818388)
(1.38929 1.56645 0.697288)
(1.36223 1.16858 1.31844)
(1.35217 1.17337 1.28779)
(1.30503 1.1818 1.25667)
(1.36664 1.19209 1.24528)
(1.21327 1.32181 1.29643)
(0.650019 1.52218 0.645946)
(0.949476 1.15382 0.958288)
(1.1313 1.12809 0.707385)
(1.08092 1.24374 0.905261)
(0.680492 1.22007 0.877259)
(1.6293 1.40164 0.868824)
(0.623804 1.16353 0.70012)
(0.472681 1.0584 1.21666)
(0.512965 1.13307 1.32793)
(0.545286 1.04883 1.33439)
(0.559285 1.19273 1.38721)
(0.531971 1.09175 1.37781)
(1.05186 1.11489 0.802836)
(0.839868 1.26937 0.871173)
(0.834183 1.40289 0.864138)
(1.07951 1.43904 0.754579)
(1.17315 1.29511 1.25315)
(1.14857 1.32056 1.19497)
(1.19437 1.40098 1.26273)
(1.158 1.27775 1.23892)
(1.23005 1.38794 1.35126)
(0.829219 0.963157 0.961174)
(0.896927 1.032 1.01445)
(1.09487 1.18111 0.90769)
(0.845522 1.36116 0.952374)
(0.643934 1.26204 0.863615)
(0.872062 1.22562 0.882436)
(0.74521 1.11367 1.00787)
(0.692064 1.02286 0.732352)
(0.997509 1.24959 1.00624)
(0.954922 1.0223 0.782747)
(0.841569 0.959927 1.02563)
(0.916957 1.50136 0.623833)
(0.94933 1.49282 0.606558)
(1.09238 1.31047 0.77693)
(0.976216 1.41164 0.850959)
(1.01033 1.40244 0.828599)
(0.802369 1.50005 0.756007)
(0.934435 1.17394 1.1595)
(0.827511 1.3262 1.24331)
(0.702472 1.31248 1.19352)
(0.940288 1.15305 1.25265)
(0.707152 1.26139 1.0622)
(0.733837 1.34157 1.20324)
(1.62535 1.35121 0.935612)
(0.993264 1.43046 0.702279)
(0.95627 1.2815 0.82111)
(0.871298 1.44325 0.896945)
(0.927215 1.02293 0.906526)
(1.29482 1.44359 1.29562)
(1.28808 1.62466 1.15989)
(1.31277 1.4761 1.10663)
(1.37802 1.5178 1.09165)
(0.686257 1.03295 0.672512)
(0.957825 1.20782 0.855794)
(1.03133 1.3734 0.51329)
(1.0747 1.33589 0.95929)
(1.39516 1.65035 0.870005)
(1.16817 1.35388 1.00858)
(1.018 1.20764 1.26886)
(1.3408 1.21938 1.19415)
(1.26974 1.27583 1.15912)
(0.556409 1.00986 0.681311)
(1.02422 1.37922 1.42511)
(1.28858 1.13683 1.3552)
(0.989316 1.24955 1.26591)
(0.528983 1.31253 1.25016)
(0.630364 1.18464 1.40308)
(0.876149 1.33446 1.18701)
(1.3083 1.41428 1.37205)
(0.83747 1.13343 1.0293)
(0.534218 1.02259 1.31028)
(0.633428 1.22077 1.04911)
(1.02723 1.17822 1.0364)
(1.05396 1.1211 1.3467)
(0.829932 1.30237 0.828897)
(0.894051 1.45858 0.610824)
(1.20543 1.26859 0.587255)
(0.915396 1.43474 0.60596)
(1.0479 1.38664 0.688174)
(1.05774 1.36825 0.873287)
(0.780489 1.41879 0.876534)
(0.927058 1.11101 0.730737)
(0.81643 1.55915 1.02581)
(0.770453 1.10387 1.09915)
(0.76505 1.43373 1.09308)
(0.835029 1.15035 1.12287)
(1.06207 1.23243 1.13099)
(1.4116 1.49671 1.2376)
(1.34846 1.42596 1.27947)
(1.52476 1.25852 1.1851)
(1.42816 1.48789 1.22662)
(1.403 1.42626 1.23268)
(0.887729 1.48935 0.883025)
(1.35753 1.49527 0.809218)
(1.5433 1.55066 1.1124)
(1.33796 1.70134 0.914014)
(1.38885 1.57659 0.896233)
(1.26376 1.61001 0.853751)
(1.13083 1.338 1.00921)
(1.14398 1.74156 0.813304)
(1.41759 1.58808 0.909597)
(1.10075 1.23117 0.574643)
(1.1248 1.37542 0.644868)
(1.15453 1.30752 0.596441)
(1.13534 1.15605 1.12812)
(0.973684 1.03829 1.03426)
(0.94192 1.02041 1.01447)
(1.21084 1.65598 1.24139)
(0.889729 1.46129 0.62391)
(0.833974 1.5353 0.643758)
(1.13169 1.27523 1.22119)
(1.00164 1.44381 1.2692)
(1.03044 1.55 1.35611)
(1.33125 1.67759 0.876712)
(1.26026 1.29008 1.28866)
(1.26144 1.26393 1.25921)
(0.852004 1.39129 1.2631)
(1.01433 1.08181 1.38667)
(1.03968 1.0919 1.21411)
(1.38816 1.43005 1.22564)
(1.48261 1.26362 1.11003)
(1.46192 1.32362 1.13509)
(1.53021 1.20359 1.08391)
(1.55442 1.2085 1.14824)
(1.53308 1.38329 1.2111)
(1.48032 1.29497 1.25586)
(1.55457 1.34672 1.20575)
(0.457466 0.999647 0.738134)
(0.65465 1.22201 0.858141)
(1.54598 1.19591 0.84356)
(1.61252 1.20961 0.822075)
(1.54274 1.16785 0.793183)
(1.54924 1.25673 0.818222)
(1.57406 1.26539 0.753417)
(1.61359 1.27471 0.888077)
(0.906864 1.00908 0.87175)
(1.05496 1.09303 1.13524)
(0.557053 1.01025 1.11788)
(0.656875 1.14912 1.10295)
(1.48362 1.3116 1.22821)
(1.44281 1.54144 1.24497)
(0.870257 1.62801 1.33955)
(1.25596 1.21458 1.06734)
(0.848667 1.62027 1.34435)
(0.923402 1.40295 1.36656)
(1.19717 1.32813 1.33828)
(1.01123 1.27296 1.12565)
(1.00962 1.08944 1.1775)
(0.769832 1.40595 1.40988)
(1.15099 1.10295 1.4526)
(0.597289 1.231 1.29361)
(1.01822 1.05092 1.38108)
(1.15831 1.57904 0.864176)
(0.768665 1.34745 1.12937)
(1.15723 1.57823 1.01314)
(0.94358 1.52249 0.996145)
(0.790669 1.35262 0.771482)
(1.32738 1.4157 1.11042)
(1.36652 1.33392 1.10188)
(0.584311 1.47386 0.627427)
(1.4724 1.19193 1.25673)
(1.54428 1.2705 1.24933)
(0.881122 1.02889 1.29001)
(0.591929 1.27895 1.35054)
(1.09605 1.12196 0.699811)
(0.636864 1.36745 1.05468)
(1.44968 1.37176 0.785053)
(1.10471 1.46249 0.977467)
(1.2766 1.31976 0.933694)
(1.52784 1.45228 1.22662)
(1.28784 1.28752 1.11374)
(1.52645 1.5602 1.1468)
(0.941237 1.57575 0.607141)
(0.985135 1.39481 0.895864)
(1.29411 1.36666 0.703059)
(1.44106 1.28138 1.23772)
(1.45088 1.2366 1.25768)
(1.29791 1.20766 1.26742)
(1.30999 1.20687 1.243)
(1.44341 1.41243 0.84823)
(1.49852 1.2701 0.905113)
(1.48685 1.37879 0.877118)
(1.18626 1.76156 0.829341)
(1.33486 1.58976 0.745376)
(1.06101 1.35104 1.25848)
(1.04602 1.22555 1.34567)
(1.32637 1.27541 1.23592)
(1.29126 1.21234 1.42158)
(1.2416 1.26373 1.13939)
(1.25451 1.30218 1.10434)
(1.02973 1.31321 0.560123)
(1.09519 1.27853 0.517338)
(1.60317 1.32167 1.09231)
(1.51117 1.2428 1.16954)
(0.96773 1.46059 0.837032)
(0.806728 1.28369 0.944923)
(1.51865 1.19993 0.745991)
(1.5554 1.30841 0.750949)
(1.13531 1.21833 1.1044)
(1.17988 1.40073 1.3396)
(0.957061 1.03017 1.32327)
(1.11848 1.46634 0.551253)
(0.947201 1.41213 0.911276)
(0.832512 1.59638 0.66352)
(1.31181 1.35151 1.13962)
(0.761583 1.55999 1.38326)
(1.13547 1.17339 1.22747)
(1.05712 1.58805 1.16122)
(0.945463 1.38287 1.14763)
(1.18393 1.31796 1.11326)
(1.0826 1.26628 1.2533)
(1.11027 1.35604 1.12851)
(1.08043 1.4112 1.23504)
(1.24455 1.16264 1.29048)
(1.49503 1.35332 0.871957)
(1.50155 1.36006 0.89439)
(1.53775 1.16434 1.1985)
(1.60971 1.2219 1.17673)
(1.56554 1.23493 1.23116)
(0.550615 1.02086 0.822549)
(0.590637 1.17547 0.75429)
(0.924565 0.996641 0.856087)
(1.02216 1.0958 1.14877)
(0.988565 1.10262 1.22905)
(1.03611 1.09197 1.15666)
(1.16313 1.37907 1.33778)
(0.792988 1.37515 1.2026)
(1.13109 1.17876 1.29681)
(1.45301 1.33967 1.15734)
(1.52337 1.259 1.0727)
(1.55832 1.28043 1.06141)
(1.58056 1.39928 1.12983)
(1.56265 1.62753 1.19458)
(1.30341 1.45557 1.05955)
(1.20359 1.50563 0.905272)
(0.762646 1.16156 0.733431)
(1.33592 1.20558 0.744377)
(1.23658 1.44612 0.718761)
(1.31687 1.18929 0.736874)
(1.39397 1.25625 0.769251)
(1.17284 1.4259 0.89774)
(1.16678 1.48155 0.760716)
(1.01995 1.5255 1.36924)
(1.50886 1.29918 0.720058)
(1.51378 1.25484 0.778718)
(1.60137 1.38914 0.865559)
(0.524752 1.1236 1.21992)
(0.523147 1.23128 1.20803)
(1.53238 1.17039 1.11181)
(1.6047 1.19389 1.11843)
(1.17044 1.59363 0.930347)
(1.10944 1.59454 0.923675)
(1.41113 1.58474 0.899725)
(1.32496 1.24806 0.85054)
(1.20291 1.18516 0.719798)
(1.04381 1.35035 0.920265)
(1.30476 1.21878 0.853089)
(1.21143 1.15674 0.83675)
(1.29989 1.38153 0.897586)
(1.29618 1.34858 0.909925)
(1.29725 1.46007 0.764513)
(1.52623 1.21997 0.912222)
(1.50193 1.33189 0.918209)
(0.644687 1.01063 0.630221)
(0.573104 1.14148 0.60936)
(1.55979 1.56953 1.26717)
(1.57874 1.15588 0.821668)
(1.58052 1.17501 0.877976)
(1.01578 1.12867 1.2712)
(0.721249 1.47434 1.03065)
(1.09404 1.11696 1.24961)
(1.12111 1.13772 1.51982)
(1.06243 1.35853 1.31539)
(1.44293 1.40921 0.809632)
(1.57999 1.42449 1.21646)
(1.43444 1.55037 1.10355)
(1.47632 1.66378 1.1595)
(1.59324 1.5601 1.27281)
(1.53354 1.27999 1.02684)
(1.57399 1.37821 1.11512)
(0.915689 1.53884 1.08139)
(0.770913 1.47862 1.41441)
(0.953375 1.25185 1.06182)
(0.766031 1.2318 1.12615)
(1.51346 1.18915 1.07463)
(1.57935 1.17717 1.09229)
(0.88985 1.45328 0.88203)
(0.930921 1.35318 0.86498)
(1.42367 1.29272 1.23422)
(1.51353 1.33947 1.22599)
(1.48056 1.34383 1.22144)
(1.56488 1.52872 1.25498)
(1.41546 1.54986 1.08937)
(1.55954 1.39182 1.2254)
(1.58675 1.4778 1.20243)
(1.26596 1.42581 1.17497)
(1.48976 1.18352 1.23209)
(0.941439 1.35195 1.21264)
(0.819766 0.942891 0.964978)
(1.2793 1.23131 1.37465)
(1.31578 1.2017 1.18686)
(0.803884 1.30007 1.28188)
(0.925313 1.29422 1.12843)
(0.757499 1.47572 1.07483)
(1.07061 1.07795 0.810515)
(1.06987 1.06871 1.14223)
(1.57487 1.29884 1.19712)
(1.06421 1.51514 1.22928)
(1.1211 1.54587 1.23097)
(1.59315 1.32933 0.784438)
(1.60457 1.46806 1.21181)
(1.4306 1.6405 1.13987)
(1.31138 1.55298 0.969234)
(1.48903 1.65875 1.24173)
(1.51967 1.33273 1.15909)
(1.32154 1.47938 1.27456)
(1.45562 1.5838 1.30349)
(1.64463 1.21815 1.11196)
(1.65712 1.23281 1.05044)
(1.65563 1.19931 1.01423)
(1.65263 1.21348 0.949933)
(1.61273 1.21984 0.999192)
(1.44977 1.33196 1.01668)
(1.37607 1.25422 0.96314)
(1.20611 1.25371 1.0436)
(0.975448 1.56246 1.0313)
(1.58215 1.15518 1.17645)
(0.846335 1.01368 1.30333)
(1.24373 1.33953 1.07379)
(1.43916 1.3392 1.17381)
(1.21459 1.65304 1.06502)
(0.937027 1.33198 1.12091)
(1.22155 1.65982 1.05458)
(1.25362 1.53227 0.95685)
(1.22562 1.35391 1.01955)
(0.967529 1.3921 1.15091)
(1.0491 1.32838 0.885531)
(1.05707 1.59058 0.944465)
(1.1433 1.15184 0.714843)
(1.07799 1.28806 0.881941)
(1.63793 1.34663 1.09482)
(1.62939 1.35877 1.15336)
(1.57747 1.40338 1.19753)
(1.60696 1.25755 0.795092)
(1.15979 1.72117 0.852626)
(1.117 1.45663 0.908508)
(1.0937 1.31739 0.978357)
(1.02452 1.16016 1.35852)
(1.27995 1.43567 0.702231)
(1.29821 1.34973 0.736545)
(0.66198 1.58985 0.729807)
(0.726259 1.55492 0.792909)
(1.09417 1.19766 0.894772)
(0.569801 1.04987 0.608451)
(1.13835 1.39421 0.960496)
(1.10718 1.18899 1.22713)
(1.02704 1.17075 1.35611)
(1.03407 1.16731 0.729242)
(1.00506 1.33775 0.852178)
(1.08956 1.59867 0.603262)
(0.991111 1.6247 0.811489)
(1.00921 1.41195 0.651757)
(1.05505 1.48244 0.626783)
(1.02121 1.5648 0.932139)
(0.784674 1.60375 0.717498)
(1.41225 1.38239 1.2223)
(1.37542 1.465 1.22521)
(1.24971 1.60603 1.10906)
(1.33365 1.48899 0.822982)
(1.32561 1.71912 0.918491)
(1.1784 1.76651 0.819441)
(1.25929 1.32347 0.879932)
(1.11338 1.44494 0.710794)
(0.994044 1.09053 1.33792)
(0.562226 1.01164 1.18504)
(1.00174 1.15408 1.02672)
(0.952482 1.24134 0.8328)
(1.29712 1.15591 0.750493)
(1.29504 1.22241 0.732998)
(1.23793 1.22699 0.647504)
(1.39322 1.18302 0.789403)
(1.32759 1.08811 0.803446)
(1.12864 1.48581 0.890851)
(1.02332 1.33838 0.87304)
(1.08332 1.57646 0.884899)
(1.39289 1.17228 0.732539)
(1.39357 1.29194 0.807962)
(1.334 1.50046 0.717669)
(1.15818 1.02968 1.40299)
(1.16042 1.171 1.46911)
(1.39417 1.30843 0.91438)
(1.25321 1.28385 0.932641)
(1.16155 1.23321 0.830883)
(0.953733 1.60024 1.04887)
(1.44357 1.52069 0.656369)
(1.58518 1.45362 0.771463)
(1.10544 1.43339 0.936049)
(1.15553 1.72578 0.848626)
(1.15632 1.25673 1.49006)
(1.47274 1.37138 0.905186)
(1.64026 1.36573 1.04543)
(1.61651 1.2852 1.0149)
(1.01306 1.22462 1.0851)
(0.750579 1.47944 1.06115)
(1.17388 1.30421 0.770316)
(1.21005 1.47904 0.706698)
(1.26029 1.35917 0.701599)
(1.11405 1.32924 0.812903)
(1.25915 1.26821 0.676888)
(1.23822 1.30151 0.710329)
(0.973023 1.62604 1.03097)
(1.0702 1.24463 0.931642)
(1.09457 1.5005 0.867827)
(1.14346 1.18875 1.19868)
(1.31913 1.26833 0.976461)
(1.26195 1.22505 1.05024)
(0.98145 1.5704 1.13239)
(1.04892 1.66986 1.10909)
(0.77114 1.54644 1.0584)
(0.81037 1.56398 1.05451)
(1.20268 1.30402 0.675253)
(1.1063 1.16066 0.722306)
(0.899015 1.39136 0.945039)
(1.2028 1.54326 1.03957)
(1.22516 1.55993 1.06008)
(1.19729 1.60879 1.02131)
(1.11244 1.7184 0.774408)
(1.20611 1.53428 0.982418)
(1.07106 1.24007 1.11935)
(1.20545 1.29902 1.0066)
(1.17134 1.29858 0.999202)
(1.17199 1.33053 1.22548)
(1.19002 1.29649 0.839609)
(1.11276 1.47503 0.711452)
(1.32768 1.4804 0.72403)
(1.11305 1.43219 0.936941)
(0.91757 1.59634 0.663369)
(1.11511 1.40389 0.965593)
(1.09554 1.51066 1.21658)
(1.03714 1.54935 1.03691)
(1.13082 1.62621 1.23452)
(0.824675 1.52924 1.20544)
(1.35576 1.47837 0.89278)
(0.91096 1.38119 0.656679)
(0.891852 1.45665 0.656589)
(0.820778 1.55609 0.679049)
(0.908931 1.3804 0.666589)
(0.770941 1.27711 0.916469)
(1.32595 1.4947 1.29448)
(0.607913 1.26131 1.46098)
(0.522825 1.07079 1.23353)
(1.23266 1.20273 0.689866)
(1.05829 1.47991 1.07629)
(1.16097 1.46695 1.16939)
(1.46384 1.40152 0.813326)
(1.38943 1.5395 0.712444)
(1.40127 1.44557 0.831927)
(1.28311 1.52894 0.756432)
(1.22437 1.27594 0.745156)
(1.05841 1.40799 0.919448)
(1.27893 1.4492 0.663709)
(1.09143 1.23786 0.583791)
(1.62136 1.25959 1.1558)
(1.59459 1.27235 1.18928)
(1.54908 1.2817 0.978036)
(1.24721 1.48323 1.10434)
(1.06532 1.08816 1.25051)
(1.52387 1.64682 1.21219)
(0.654891 1.169 1.42712)
(1.14947 1.25296 0.780278)
(1.12138 1.27823 0.813032)
(1.40426 1.38457 0.747664)
(1.31125 1.57121 0.854043)
(1.08585 1.44363 0.808103)
(1.54821 1.16945 0.999792)
(1.58456 1.15552 1.00102)
(0.908668 1.41646 0.655613)
(0.899512 1.38851 0.677745)
(1.26243 1.29889 0.8401)
(1.30358 1.44753 0.757265)
(1.62931 1.39283 0.85775)
(1.64225 1.29432 1.09868)
(1.64808 1.32194 1.03479)
(1.62971 1.3008 1.14232)
(1.0107 1.21798 1.02156)
(1.04307 1.11025 1.32126)
(1.38154 1.43704 0.833161)
(1.41903 1.42085 0.783072)
(1.64305 1.25322 1.11171)
(0.898847 1.49175 0.644703)
(1.00544 1.39085 0.947333)
(1.12501 1.3668 0.927775)
(1.32339 1.1547 1.34659)
(1.06477 1.35355 1.44565)
(1.54066 1.19514 1.03286)
(1.54028 1.19006 0.948256)
(1.61917 1.32062 1.16439)
(1.5778 1.39552 1.21351)
(1.60103 1.46271 1.22661)
(1.31313 1.15194 1.3057)
(1.07506 1.38415 1.11733)
(1.23944 1.27989 0.854352)
(0.457858 1.06388 0.642886)
(1.17133 1.40289 0.743954)
(1.29251 1.0589 0.820632)
(1.36474 1.27415 0.81199)
(1.3234 1.28409 0.801848)
(1.42157 1.58073 1.07759)
(1.23145 1.11133 0.707294)
(1.39811 1.22766 0.827328)
(0.561978 1.25309 1.19532)
(1.05243 1.05735 1.12337)
(0.993067 1.07112 1.35818)
(1.5228 1.17416 1.0399)
(1.12733 1.61339 1.11445)
(1.07886 1.2271 1.12782)
(1.22224 1.41882 1.05047)
(1.3766 1.57509 1.06481)
(1.20902 1.42797 1.06418)
(1.24819 1.60968 1.22272)
(1.27044 1.31737 1.05246)
(1.20632 1.44149 1.07123)
(1.2719 1.20948 0.873956)
(1.18698 1.73605 0.861082)
(1.07982 1.57762 1.00382)
(1.11204 1.58162 0.955053)
(1.2659 1.25608 0.918711)
(0.763846 1.52822 1.42054)
(0.744789 1.04826 1.32336)
(1.15712 1.64105 1.0036)
(0.783084 1.39155 1.09366)
(0.841757 1.6275 0.76244)
(1.13628 1.18175 0.780269)
(0.904079 1.41162 0.642732)
(1.25612 1.1874 1.34175)
(1.36048 1.14916 1.2479)
(0.988159 1.47445 1.27027)
(0.768683 1.52511 1.22691)
(0.886523 1.16609 1.27464)
(0.65164 1.14348 1.38818)
(1.31366 1.22518 1.19697)
(1.22949 1.31904 1.41965)
(1.24159 1.62381 0.98594)
(1.19054 1.59612 0.98351)
(0.826535 1.20133 0.798448)
(0.780416 1.43659 0.631196)
(0.982609 1.36387 1.15247)
(0.902423 1.6452 1.19582)
(1.0131 1.48519 1.16744)
(0.943151 1.61178 1.38443)
(0.945605 1.38249 1.07923)
(0.854774 1.34509 1.08759)
(1.03981 1.63372 1.14969)
(0.883083 1.14392 1.07598)
(1.31465 1.41787 0.769085)
(1.51812 1.31583 0.840013)
(1.53699 1.49993 0.747446)
(1.62223 1.13172 1.045)
(1.62129 1.18409 1.03582)
(1.60363 1.16622 0.94951)
(1.49785 1.21939 0.914712)
(1.4794 1.2522 0.907528)
(1.56493 1.41701 1.1423)
(0.910577 1.42581 0.660252)
(0.824219 1.40521 0.699909)
(0.975034 1.62197 0.976899)
(1.07358 1.65865 1.14806)
(1.15949 1.25767 0.690558)
(0.936439 1.15875 0.802227)
(1.10642 1.29188 0.680348)
(1.30035 1.24487 1.2663)
(1.01259 1.22738 0.777592)
(1.0265 1.21473 0.792479)
(1.30645 1.23826 1.12069)
(1.32564 1.54137 1.34561)
(1.2778 1.29527 1.33262)
(1.24212 1.34568 1.0824)
(1.09206 1.38921 1.08536)
(1.19711 1.48536 1.29785)
(1.27905 1.37134 1.04066)
(1.30853 1.63637 1.20594)
(1.33621 1.62657 1.16339)
(1.42724 1.29048 0.807518)
(1.27039 1.49855 0.747213)
(1.45234 1.25213 0.742916)
(1.47627 1.29789 0.778561)
(1.46266 1.27912 0.829474)
(0.966869 1.55709 0.652562)
(1.06618 1.53274 0.655427)
(1.22354 1.19322 1.19927)
(0.484313 1.20999 1.33818)
(1.22199 1.53786 1.04298)
(1.39475 1.454 0.995892)
(0.903156 1.35417 1.20941)
(0.920722 1.54448 1.38732)
(0.765561 1.54587 1.41234)
(0.695261 1.54981 1.27179)
(0.708687 1.55383 1.26083)
(0.790835 1.28303 1.1673)
(1.08408 1.23415 0.719735)
(0.432352 1.05258 0.723165)
(0.680556 1.54616 1.30417)
(0.808292 1.08754 1.32897)
(0.936394 1.48409 1.10093)
(0.790367 1.61748 1.31625)
(1.00127 1.72516 1.23329)
(1.13577 1.74492 1.16039)
(0.911837 1.67468 1.18952)
(0.9665 1.60575 1.35924)
(1.60684 1.13738 1.12205)
(0.811184 1.32336 0.678894)
(1.04939 1.10674 0.7391)
(0.989574 1.35511 1.10416)
(0.999933 1.51738 0.626737)
(1.27207 1.28394 0.816523)
(1.04171 1.45921 0.637593)
(1.11225 1.47447 0.941193)
(1.07665 1.50289 0.576601)
(1.06773 1.52879 0.603184)
(1.03513 1.19144 0.773858)
(1.05469 1.18526 0.687158)
(1.18086 1.13818 1.25306)
(0.960036 1.08556 1.32503)
(1.26109 1.32454 0.951725)
(1.55809 1.17367 0.900448)
(0.98625 1.47684 1.05129)
(1.64954 1.3269 0.877521)
(1.62453 1.34753 0.824009)
(0.995003 1.56855 1.15233)
(1.05216 1.12332 1.34677)
(0.745222 1.08742 1.29551)
(1.0635 1.11792 1.38324)
(0.855496 1.09913 1.33118)
(0.947842 1.20982 1.24648)
(0.905157 1.50055 0.647041)
(0.94308 1.68702 0.710241)
(1.0001 1.62154 0.657424)
(1.01824 1.42071 0.934478)
(1.30644 1.16878 1.40709)
(0.8997 1.55684 0.672639)
(1.0592 1.15825 1.27097)
(1.02064 1.53304 1.32645)
(1.37916 1.25754 1.06582)
(1.39616 1.27926 0.960408)
(1.35078 1.38189 1.00163)
(1.51174 1.49731 0.687946)
(1.55702 1.37154 0.798145)
(1.58819 1.40754 0.799266)
(0.948207 1.53855 0.741503)
(0.885929 1.34389 0.859068)
(0.942167 1.57042 0.791951)
(0.808398 1.58466 0.765646)
(1.50651 1.43123 0.779869)
(1.39784 1.52199 0.665308)
(0.819577 1.49579 0.632428)
(0.747687 1.10931 1.27847)
(1.60597 1.39246 0.806568)
(1.12514 1.24431 1.21571)
(1.05302 1.73132 1.2437)
(1.00796 1.37687 1.05176)
(1.059 1.53543 0.55184)
(0.889341 1.63532 0.617499)
(0.981697 1.03394 1.03822)
(1.65465 1.33768 0.966275)
(1.54054 1.45679 0.75103)
(1.25772 1.18487 0.687725)
(1.09241 1.18918 0.50021)
(0.997572 1.23255 0.785924)
(1.12852 1.28693 1.24273)
(1.23917 1.50925 0.696736)
(1.10266 1.43155 0.682075)
(0.878282 1.66842 0.669349)
(1.02676 1.26016 0.839391)
(0.848442 1.58149 0.812359)
(1.03344 1.27151 0.749497)
(0.965183 1.19061 0.730067)
(1.60287 1.46869 1.21776)
(1.16993 1.18865 1.21295)
(0.896086 1.38015 1.08248)
(0.984281 1.37451 1.04717)
(0.995939 1.60255 1.30217)
(0.973977 1.5037 1.10597)
(1.22986 1.57965 1.22127)
(1.22074 1.5679 1.00738)
(1.22203 1.59013 1.01193)
(1.13964 1.71448 1.11256)
(0.898121 1.36964 1.08054)
(1.20129 1.2326 1.12835)
(0.901038 1.3226 1.34164)
(0.744211 1.46336 1.42356)
(0.49424 1.20166 0.659637)
(1.18536 1.7057 1.19794)
(0.986071 1.3469 1.15483)
(0.839909 1.31182 0.8969)
(0.903661 1.35188 0.704602)
(1.02774 1.45546 1.39434)
(1.24382 1.4276 1.38986)
(1.26397 1.23547 1.11221)
(0.997229 1.58749 1.39584)
(1.63738 1.15419 0.991175)
(1.24743 1.54421 1.18802)
(1.21556 1.62849 1.14979)
(1.21997 1.75257 0.8938)
(1.09847 1.59127 0.950473)
(1.07857 1.20983 0.797899)
(0.893232 1.30541 1.1817)
(0.73337 1.3251 1.05092)
(0.834627 1.29478 1.23546)
(0.877248 1.30624 1.26966)
(1.45808 1.39434 0.827218)
(0.934779 1.47295 1.07815)
(0.908752 1.2295 1.26274)
(1.20555 1.60289 1.0735)
(1.13916 1.22476 0.721829)
(0.938675 1.35413 1.0892)
(1.1924 1.67416 1.20971)
(1.00331 1.47958 1.18424)
(1.62219 1.39615 1.05739)
(0.989595 1.11884 1.26571)
(0.975654 1.35083 1.14683)
(0.948602 1.48615 1.08758)
(0.863324 1.0129 1.1738)
(1.16782 1.44884 1.18765)
(1.26613 1.61158 1.08971)
(1.31508 1.31725 0.722222)
(1.22139 1.25947 0.594051)
(0.884945 1.51346 0.788041)
(0.721486 1.57966 1.27362)
(0.786183 1.3012 1.21534)
(0.874179 1.39264 1.32721)
(1.6392 1.23319 0.873209)
(1.62192 1.26874 0.954395)
(1.64466 1.2719 0.885589)
(1.61129 1.28132 0.803095)
(0.897411 1.54499 0.665398)
(0.921181 1.6307 0.664419)
(1.17925 1.723 0.815402)
(1.16976 1.7272 0.805593)
(1.16173 1.42837 1.08062)
(1.25597 1.52308 1.07153)
(1.465 1.57872 1.11965)
(1.47017 1.50403 1.28752)
(1.32331 1.35548 1.19825)
(1.37136 1.33153 1.26117)
(1.39709 1.15067 1.26031)
(1.32528 1.33098 1.07714)
(1.37825 1.34312 1.23267)
(1.34661 1.33344 1.20974)
(1.46647 1.26873 0.741224)
(1.49696 1.31209 0.756411)
(0.880975 1.59588 0.66722)
(0.902559 1.45091 1.08102)
(0.95472 1.68136 1.24183)
(0.861525 1.00146 1.18218)
(0.828762 1.15548 1.19253)
(0.897092 1.02383 1.00487)
(0.594775 1.04188 0.62153)
(0.957567 1.04219 0.976295)
(1.30104 1.49179 1.34688)
(0.978409 1.54031 1.33538)
(0.999066 1.22522 1.2464)
(0.645923 1.21966 0.801213)
(0.880104 1.3289 1.23811)
(0.91274 1.38133 1.14683)
(1.05198 1.17012 0.908986)
(0.959316 1.3531 1.12806)
(0.882344 1.16144 1.23734)
(0.834179 1.48564 1.26662)
(1.25476 1.28055 1.00074)
(0.882259 1.51842 0.78924)
(0.806359 1.57515 0.774305)
(1.03566 1.64358 1.0068)
(0.831746 1.24628 0.885847)
(1.03686 1.50182 0.650231)
(1.03013 1.62593 0.960188)
(0.931832 1.526 0.868876)
(1.08561 1.40904 0.552778)
(1.10869 1.30126 0.558557)
(0.951318 1.32341 1.09431)
(1.14658 1.33178 1.06597)
(1.0181 1.43894 0.907324)
(1.02527 1.34041 0.866432)
(1.08352 1.51096 0.662056)
(1.20025 1.31222 1.09432)
(1.45228 1.43823 1.2408)
(0.681427 1.42738 1.23836)
(0.876985 1.46178 1.37726)
(1.27964 1.13843 1.26506)
(1.0315 1.16402 0.873591)
(1.07757 1.12392 1.2964)
(1.62442 1.30555 0.822245)
(0.900327 1.15887 1.17386)
(1.01163 1.20184 1.36813)
(1.43701 1.32786 0.833153)
(1.51009 1.33415 0.807545)
(1.01938 1.42622 1.06264)
(0.980236 1.43656 1.06432)
(1.17456 1.66917 1.1733)
(1.04258 1.42784 0.600431)
(1.23137 1.72631 0.832916)
(1.22015 1.40293 1.02748)
(1.25623 1.21262 0.866605)
(1.15508 1.1945 0.819358)
(1.04563 1.14199 0.699245)
(0.880588 1.67489 0.760015)
(1.55634 1.32438 0.760002)
(1.55269 1.48852 1.17362)
(1.17445 1.57744 0.977596)
(1.21967 1.55777 1.01095)
(1.10306 1.2389 0.685651)
(1.23641 1.44176 1.1593)
(1.46093 1.48515 1.26243)
(0.790483 1.61601 1.25424)
(1.29955 1.62264 0.933878)
(0.959437 1.28423 0.794011)
(1.1548 1.23775 1.14144)
(1.21952 1.30274 1.02537)
(1.63398 1.38923 0.981616)
(1.20782 1.65985 1.07863)
(1.11728 1.25154 0.99845)
(0.712709 1.29697 1.26041)
(1.65128 1.27093 1.04244)
(1.33004 1.43222 1.34705)
(1.05375 1.43087 1.11697)
(0.745589 1.00528 0.566949)
(1.32942 1.67842 0.988117)
(1.01885 1.25705 1.16237)
(1.24825 1.23316 0.914714)
(1.19631 1.29358 0.95988)
(1.30693 1.33646 0.93729)
(1.17528 1.42825 1.12911)
(1.10193 1.04767 0.567517)
(1.01885 1.07742 1.22564)
(1.19471 1.69794 0.883011)
(0.852165 1.37467 1.05376)
(1.1708 1.15879 0.764358)
(0.999757 1.30625 1.17711)
(0.85658 1.51593 1.29261)
(1.40897 1.42391 1.25428)
(1.12534 1.0833 0.599805)
(1.04899 1.21041 1.08049)
(1.41478 1.26868 1.25427)
(1.39426 1.2871 1.20691)
(1.04474 1.35716 0.92916)
(1.14516 1.34563 1.04519)
(1.04803 1.475 1.04525)
(1.03929 1.29913 1.04058)
(1.11162 1.64574 0.941436)
(1.15242 1.35144 0.673813)
(1.15248 1.28573 0.665349)
(0.888241 1.33483 0.861279)
(1.28638 1.4163 1.04062)
(1.43813 1.50054 1.26335)
(1.29255 1.53856 1.27141)
(0.93 1.50618 0.965758)
(1.19444 1.61566 1.25212)
(1.40937 1.22731 1.2683)
(1.22946 1.43699 0.824493)
(0.832564 1.49037 0.663599)
(0.832474 1.53757 0.684722)
(1.33994 1.32254 0.879526)
(1.1257 1.2406 1.1132)
(1.03229 1.66628 1.03764)
(1.02593 1.67338 1.01105)
(1.08137 1.3097 0.908928)
(1.01495 1.66708 0.971995)
(0.911741 1.25906 0.798524)
(0.687366 1.5579 0.778863)
(1.32343 1.25416 1.10999)
(1.13002 1.39375 0.757036)
(0.979164 0.993073 0.947563)
(1.01014 1.06698 1.04547)
(1.31981 1.38161 1.07242)
(1.65319 1.29004 0.961193)
(0.930099 1.52834 1.07474)
(1.65096 1.24919 0.950329)
(1.24387 1.49243 0.850552)
(1.55613 1.50031 1.20257)
(0.831352 1.50144 1.2845)
(1.53197 1.24986 0.966629)
(1.00595 1.28062 0.811439)
(1.06162 1.66903 0.92947)
(0.753572 1.38774 0.845621)
(1.01356 1.56544 0.974745)
(1.59964 1.14478 0.872687)
(1.63767 1.19883 0.891577)
(0.94605 1.40196 0.763907)
(1.12012 1.68822 1.02851)
(0.95259 1.13737 0.907779)
(1.54803 1.15234 0.984278)
(1.42759 1.22832 0.714869)
(1.3644 1.36898 0.818431)
(1.16126 1.18778 1.31096)
(1.40767 1.20366 0.713767)
(1.23867 1.7571 0.90476)
(1.18508 1.64513 1.02967)
(0.974572 1.55655 1.08876)
(0.87112 1.45577 1.0442)
(0.960483 1.19631 0.784569)
(1.09026 1.29606 0.770923)
(1.46055 1.52698 1.21052)
(1.33995 1.14329 0.801104)
(1.32384 1.40931 0.782667)
(1.49783 1.20549 0.717775)
(1.50548 1.27741 0.769637)
(1.14147 1.2919 0.786085)
(0.886962 1.11878 0.725725)
(1.00661 1.29224 1.16974)
(0.999176 1.58591 0.63813)
(1.61563 1.13863 0.941039)
(0.672976 1.12689 1.25752)
(0.907238 1.07986 1.02739)
(1.53977 1.16178 0.948341)
(1.52459 1.27848 0.942995)
(1.50876 1.17416 0.94192)
(1.47127 1.23999 0.707819)
(1.24207 1.24739 0.662832)
(1.27054 1.24828 0.660771)
(1.28264 1.29149 0.650981)
(0.585623 1.22177 1.06961)
)
// ************************************************************************* //
| [
"you@example.com"
] | you@example.com | |
d96de8d75077fc7c0b65ce7606922caeb65b0c5e | 04537d80f663c9de8497f4038f74b7a7d307c687 | /arma.cpp | fb02416fa927f9cb239131898783f45946a30a8d | [] | no_license | jayantbit/UVA | 7a7c2c60f157e7c8021dc526d0614db2ecacac06 | 40ba2a6e4f720cb2f1470c1346befd9ac60b20ad | refs/heads/master | 2020-04-05T02:13:49.832851 | 2014-01-24T07:34:13 | 2014-01-24T07:34:13 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,112 | cpp | using namespace std;
#include<map>
#include<iostream>
#include<string>
#include<sstream>
#include<cstdio>
typedef long long int ull;
map <ull,int> m;
map <ull,int>::iterator it;
int main()
{
string str;
ull n;
int k=1,l,f;
while(getline(cin,str))
{l=0;
stringstream s(str);
while(s>>n){m[n]++;l++;}
getline(cin,str);
stringstream s2(str);
while(s2>>n){m[n]++;l++;if(m[n]==2)l-=2;}
printf("Judgement #%d: %d\n",k,l);
f=0;
for(it=m.begin();it!=m.end();it++)
if((*it).second==1)
{ if(f)cout<<" ";
cout<<(*it).first;
f++;
}
m.clear();
cout<<endl;
k++;
}
return 0;
}
| [
"jayantbit1@gmail.com"
] | jayantbit1@gmail.com |
c21cad9408212532421fc15c6fd11a2e304ab09b | 2cd6b3d7f85a2545c21c5896fa10c361f3a77436 | /Longest Palindromic Substring.cpp | 8167d6adc60297a7609287554cc315e51ca97c20 | [] | no_license | xmac1/leetcode-solution | d3043d2e0b99ee7e60a82026bf409f76bf49d334 | 481aa96809cafbc05e0e895ec3a8be2aacd4582d | refs/heads/master | 2020-03-30T22:24:22.777782 | 2018-12-12T05:03:18 | 2018-12-12T05:03:18 | 151,665,180 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,127 | cpp | // O(n2) 算法
// 遍历字符串,以每个字符为中心检测最长的回文字符串
// 注意到两个相同字符为中心的情况
// string::substr
class Solution {
public:
string longestPalindrome(string s) {
int size = s.size();
int left, right;
int maxLength = 1;
int maxLeft, maxRight;
maxLeft = maxRight = 0;
int single = 0;
int pair = 0;
for (int i = 0; i < size; i++) {
left = right = i;
while (left >= 0 && right < size && s.at(left) == s.at(right)) {
left--;
right++;
}
single = right - left - 1;
left = i;
right = i + 1 ;
while (left >= 0 && right < size && s.at(left) == s.at(right)) {
left--;
right++;
}
pair = right - left - 1;
maxLength = max(single, pair);
if (maxLength > maxRight - maxLeft) {
maxRight = i + maxLength / 2;
maxLeft = i - (maxLength - 1) / 2;
}
}
string s.substr(maxLeft, maxLength);
}
};
| [
"1743164928@qq.com"
] | 1743164928@qq.com |
a2015872ac6054d1a509f8439842360ffe55cf3f | e429ad2481bb272c9f6173474423522f5598aa94 | /include/caffe/layers/split_layer.hpp | ef4f6604032dc870696535a1d6b27bb262b80639 | [] | no_license | lewisgit/caffe-fixedpoint | 1b4681cd4bbe442234e0b4004f64162154aa146d | 0cfb006a18f31f7d44d6ae7bdffaa4483f85acbe | refs/heads/master | 2021-01-12T09:05:08.860277 | 2018-08-16T02:01:19 | 2018-08-16T02:01:19 | 76,762,918 | 6 | 4 | null | 2018-08-16T02:01:20 | 2016-12-18T04:39:39 | C++ | UTF-8 | C++ | false | false | 1,446 | hpp | #ifndef CAFFE_SPLIT_LAYER_HPP_
#define CAFFE_SPLIT_LAYER_HPP_
#include <vector>
#include "caffe/blob.hpp"
#include "caffe/layer.hpp"
#include "caffe/proto/caffe.pb.h"
namespace caffe {
/**
* @brief Creates a "split" path in the network by copying the bottom Blob
* into multiple top Blob%s to be used by multiple consuming layers.
*
* TODO(dox): thorough documentation for Forward, Backward, and proto params.
*/
template <typename Dtype>
class SplitLayer : public Layer<Dtype> {
public:
explicit SplitLayer(const LayerParameter& param)
: Layer<Dtype>(param) {}
virtual void Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual inline const char* type() const { return "Split"; }
virtual inline int ExactNumBottomBlobs() const { return 1; }
virtual inline int MinTopBlobs() const { return 1; }
protected:
virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
/* virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top);
virtual void Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
virtual void Backward_gpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom);
*/
int count_;
};
} // namespace caffe
#endif // CAFFE_SPLIT_LAYER_HPP_
| [
"lewisreg@126.com"
] | lewisreg@126.com |
ad31e301bd769550bbe8f4a4b5c463beddb271c5 | 69b3cc8e9896c3b8ac831767e5872f41d2de758c | /.history/mianshi按摩师_20200326164505.cpp | 4783fb07d022a4e465b256c9d6f0da5512d83455 | [] | no_license | enkilee/leetcode | c4d9c906dba590d32e13f8feca167da1b52b9372 | c523cab721d51931633da0a29b162319c8569017 | refs/heads/master | 2023-01-08T19:33:52.309972 | 2020-11-16T12:34:23 | 2020-11-16T12:34:23 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 904 | cpp | /*
* @Author: your name
* @Date: 2020-03-26 16:30:47
* @LastEditTime: 2020-03-26 16:43:56
* @LastEditors: Please set LastEditors
* @Description: In User Settings Edit
* @FilePath: \leecode\mianshi按摩师.cpp
*/
#include <iostream>
#include <cmath>
#include <vector>
#include <stack>
#include <map>
using namespace std;
int massage(vector<int>& nums)
{
int len=nums.size();
if(len==0)
{
return 0;
}
if(len==1)
{
return nums[0];
}
vector<int> dp(len,0);
dp[0]=0;
dp[1]=max(nums[0],nums[1]);
for(int i=2;i<len;i++)
{
dp[i]=max(dp[i-1],dp[i-2]+nums[i]);
}
return dp[len-1];
//遍历迄今为止的最大值,两种情况取较大:
//1:预约本次,则上一次不预约(dp[i-2] + nums[i])
//2:本次不预约,则值为预约到上一次的最大值
}
int main()
{
return 0;
} | [
"luhputu0815@gmail.com"
] | luhputu0815@gmail.com |
ec71ca38522328a384faf672102c3056e3b34cc7 | 3e2da6dcd07e7e520a35444b2f2a73cc8f9d93f0 | /src/Print.cpp | e7c7286bd9d45a08db3951bc86d3fc139696c297 | [] | no_license | HamzaHajeir/stm32_pio_issue | 11e026a5e5e5708a3e0c077a4539778b2a14ac5e | 910a5fae82ce0d0bea276744b868c6f9426b0c90 | refs/heads/master | 2023-02-21T07:36:42.353112 | 2021-01-19T19:58:30 | 2021-01-19T19:58:30 | 331,094,306 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,445 | cpp | /*
MIT License
Copyright (c) 2019 Phil Bowles <H48266@gmail.com>
github https://github.com/philbowles/H4
blog https://8266iot.blogspot.com
groups https://www.facebook.com/groups/esp8266questions/
https://www.facebook.com/H4-Esp8266-Firmware-Support-2338535503093896/
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.
Modified 23 November 2006 by David A. Mellis
Modified 03 August 2015 by Chuck Todd
Modified 30 November 2019 by Phil Bowles
(Lifted from Arduion and heavily modified for STM32, Ubuntu and Raspberry Pi to remove Arduino-specifics
*/
#include "H4.h"
#ifndef ARDUINO
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cmath>
#include <string>
#include "Print.h"
// Public Methods //////////////////////////////////////////////////////////////
size_t Print::write(const uint8_t *buffer, size_t size)
{
size_t n = 0;
while (size--) {
if (write(*buffer++)) n++;
else break;
}
return n;
}
size_t Print::print(std::string str)
{
return write(str.c_str());
}
size_t Print::print(const char str[])
{
return write(str);
}
size_t Print::print(char c)
{
return write(c);
}
size_t Print::print(unsigned char b, int base)
{
return print((unsigned int) b, base);
}
size_t Print::print(int n, int base)
{
return print((long) n, base);
}
size_t Print::print(unsigned int n, int base)
{
return print((unsigned long) n, base);
}
size_t Print::print(long n, int base)
{
if (base == 0) {
return write(n);
} else if (base == 10) {
if (n < 0) {
int t = print('-');
n = -n;
return printNumber(n, 10) + t;
}
return printNumber(n, 10);
} else {
return printNumber(n, base);
}
}
size_t Print::print(unsigned long n, int base)
{
if (base == 0) {
return write(n);
} else {
return printNumber(n, base);
}
}
size_t Print::print(double n, int digits)
{
return printFloat(n, digits);
}
size_t Print::println(void)
{
return write("\r\n");
}
size_t Print::println(std::string str)
{
size_t n = print(str);
n += println();
return n;
}
size_t Print::println(const char c[])
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(char c)
{
size_t n = print(c);
n += println();
return n;
}
size_t Print::println(unsigned char b, int base)
{
size_t n = print(b, base);
n += println();
return n;
}
size_t Print::println(int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned int num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(unsigned long num, int base)
{
size_t n = print(num, base);
n += println();
return n;
}
size_t Print::println(double num, int digits)
{
size_t n = print(num, digits);
n += println();
return n+println();
}
// Private Methods /////////////////////////////////////////////////////////////
size_t Print::printNumber(unsigned long n, uint8_t base)
{
char buf[8 * sizeof(long) + 1]; // Assumes 8-bit chars plus zero byte.
char *str = &buf[sizeof(buf) - 1];
*str = '\0';
// prevent crash if called with base == 1
if (base < 2) {
base = 10;
}
do {
unsigned long m = n;
n /= base;
char c = m - base * n;
*--str = c < 10 ? c + '0' : c + 'A' - 10;
} while (n);
return write(str);
}
size_t Print::printFloat(double number, uint8_t digits)
{
size_t n = 0;
if (std::isnan(number)) {
return print("nan");
}
if (std::isinf(number)) {
return print("inf");
}
if (number > 4294967040.0) {
return print("ovf"); // constant determined empirically
}
if (number < -4294967040.0) {
return print("ovf"); // constant determined empirically
}
// Handle negative numbers
if (number < 0.0) {
n += print('-');
number = -number;
}
// Round correctly so that print(1.999, 2) prints as "2.00"
double rounding = 0.5;
for (uint8_t i = 0; i < digits; ++i) {
rounding /= 10.0;
}
number += rounding;
// Extract the integer part of the number and print it
unsigned long int_part = (unsigned long)number;
double remainder = number - (double)int_part;
n += print(int_part);
// Print the decimal point, but only if there are digits beyond
if (digits > 0) {
n += print(".");
}
// Extract digits from the remainder one at a time
while (digits-- > 0) {
remainder *= 10.0;
int toPrint = int(remainder);
n += print(toPrint);
remainder -= toPrint;
}
return n;
}
#ifdef SUPPORT_LONGLONG
void Print::println(int64_t n, uint8_t base)
{
print(n, base);
println();
}
void Print::print(int64_t n, uint8_t base)
{
if (n < 0) {
print((char)'-');
n = -n;
}
if (base < 2) {
base = 2;
}
print((uint64_t)n, base);
}
void Print::println(uint64_t n, uint8_t base)
{
print(n, base);
println();
}
void Print::print(uint64_t n, uint8_t base)
{
if (base < 2) {
base = 2;
}
printLLNumber(n, base);
}
void Print::printLLNumber(uint64_t n, uint8_t base)
{
unsigned char buf[16 * sizeof(long)];
unsigned int i = 0;
if (n == 0) {
print((char)'0');
return;
}
while (n > 0) {
buf[i++] = n % base;
n /= base;
}
for (; i > 0; i--) {
print((char)(buf[i - 1] < 10 ? '0' + buf[i - 1] : 'A' + buf[i - 1] - 10));
}
}
#endif
#endif // define ARDUINO
| [
"hahajeir@gmail.com"
] | hahajeir@gmail.com |
893a5e8e6c87df4441a7e267ca04e569ca8152dc | 1b45e63a9242a14aa5f1d19e87050e7e46aa6579 | /test/unit/CheckCastAnalysisTest.cpp | 29a06074ef51784a139ec78003a5f0267c5f1490 | [
"MIT"
] | permissive | disconnect3d/redex | e2d35fc3287158b4114d52610409b97682c171cf | 86b7e12bc5a0eaeb6727dd3b348702f01c6306a5 | refs/heads/master | 2022-04-16T19:51:01.927997 | 2020-04-11T14:08:43 | 2020-04-11T14:10:19 | 255,344,205 | 0 | 0 | MIT | 2020-04-13T14:03:28 | 2020-04-13T14:03:27 | null | UTF-8 | C++ | false | false | 4,142 | cpp | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#include <gtest/gtest.h>
#include "CheckCastAnalysis.h"
#include "IRAssembler.h"
#include "RedexTest.h"
struct CheckCastAnalysisTest : public RedexTest {};
TEST_F(CheckCastAnalysisTest, simple_string) {
auto method = assembler::method_from_string(R"(
(method (public) "LFoo;.bar:()V"
(
(const-string "S1")
(move-result-pseudo-object v1)
(check-cast v1 "Ljava/lang/String;")
(move-result-pseudo-object v1)
)
)
)");
method->get_code()->build_cfg(true);
check_casts::impl::CheckCastAnalysis analysis(method);
auto replacements = analysis.collect_redundant_checks_replacement();
EXPECT_EQ(replacements.size(), 1);
auto it = replacements.begin();
auto insn = it->insn;
EXPECT_EQ(insn->opcode(), OPCODE_CHECK_CAST);
EXPECT_EQ(insn->get_type()->get_name()->str(), "Ljava/lang/String;");
EXPECT_EQ(it->replacement, boost::none);
method->get_code()->clear_cfg();
}
TEST_F(CheckCastAnalysisTest, new_instance) {
auto method = assembler::method_from_string(R"(
(method (public) "LFoo;.bar:()V"
(
(new-instance "LFoo;")
(move-result-pseudo-object v1)
(check-cast v1 "LFoo;")
(move-result-pseudo-object v1)
)
)
)");
method->get_code()->build_cfg(true);
check_casts::impl::CheckCastAnalysis analysis(method);
auto replacements = analysis.collect_redundant_checks_replacement();
EXPECT_EQ(replacements.size(), 1);
auto it = replacements.begin();
auto insn = it->insn;
EXPECT_EQ(insn->opcode(), OPCODE_CHECK_CAST);
EXPECT_EQ(insn->get_type()->get_name()->str(), "LFoo;");
EXPECT_EQ(it->replacement, boost::none);
method->get_code()->clear_cfg();
}
TEST_F(CheckCastAnalysisTest, parameter) {
auto method = assembler::method_from_string(R"(
(method (public) "LFoo;.bar:(LBar;)V"
(
(load-param-object v0)
(load-param-object v1)
(check-cast v1 "LBar;")
(move-result-pseudo-object v0)
)
)
)");
method->get_code()->build_cfg(true);
check_casts::impl::CheckCastAnalysis analysis(method);
auto replacements = analysis.collect_redundant_checks_replacement();
EXPECT_EQ(replacements.size(), 1);
auto it = replacements.begin();
auto insn = it->insn;
EXPECT_EQ(insn->opcode(), OPCODE_CHECK_CAST);
EXPECT_EQ(insn->get_type()->get_name()->str(), "LBar;");
EXPECT_NE(it->replacement, boost::none);
method->get_code()->clear_cfg();
}
TEST_F(CheckCastAnalysisTest, this_parameter) {
auto method = assembler::method_from_string(R"(
(method (public) "LFoo;.bar:(LBar;)V"
(
(load-param-object v0)
(load-param-object v1)
(check-cast v0 "LFoo;")
(move-result-pseudo-object v0)
)
)
)");
method->get_code()->build_cfg(true);
check_casts::impl::CheckCastAnalysis analysis(method);
auto replacements = analysis.collect_redundant_checks_replacement();
EXPECT_EQ(replacements.size(), 1);
auto it = replacements.begin();
auto insn = it->insn;
EXPECT_EQ(insn->opcode(), OPCODE_CHECK_CAST);
EXPECT_EQ(insn->get_type()->get_name()->str(), "LFoo;");
EXPECT_EQ(it->replacement, boost::none);
method->get_code()->clear_cfg();
}
TEST_F(CheckCastAnalysisTest, get_field) {
auto method = assembler::method_from_string(R"(
(method (public) "LFoo;.bar:()V"
(
(iget-object v0 "LFoo;.b:LBar;")
(move-result-pseudo-object v1)
(check-cast v1 "LBar;")
(move-result-pseudo-object v2)
)
)
)");
method->get_code()->build_cfg(true);
check_casts::impl::CheckCastAnalysis analysis(method);
auto replacements = analysis.collect_redundant_checks_replacement();
EXPECT_EQ(replacements.size(), 1);
auto it = replacements.begin();
auto insn = it->insn;
EXPECT_EQ(insn->opcode(), OPCODE_CHECK_CAST);
EXPECT_EQ(insn->get_type()->get_name()->str(), "LBar;");
EXPECT_NE(it->replacement, boost::none);
method->get_code()->clear_cfg();
}
| [
"facebook-github-bot@users.noreply.github.com"
] | facebook-github-bot@users.noreply.github.com |
f7f89c4e6c0cbbc6a46ab9a457d8538cbddcb017 | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/spirit/home/support/char_encoding/standard_wide.hpp | 770963f6e632f0402bdf4c6774649d44dce6241a | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,175 | hpp | /*=============================================================================
Copyright (c) 2001-2011 Hartmut Kaiser
Copyright (c) 2001-2011 Joel de Guzman
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#if !defined(BOOST_SPIRIT_STANDARD_WIDE_NOVEMBER_10_2006_0913AM)
#define BOOST_SPIRIT_STANDARD_WIDE_NOVEMBER_10_2006_0913AM
#if defined(_MSC_VER)
#pragma once
#endif
#include <cwctype>
#include <string>
#include <sstd/boost/cstdint.hpp>
#include <sstd/boost/spirit/home/support/assert_msg.hpp>
namespace boost { namespace spirit { namespace traits
{
template <std::size_t N>
struct wchar_t_size
{
BOOST_SPIRIT_ASSERT_MSG(N == 1 || N == 2 || N == 4,
not_supported_size_of_wchar_t, ());
};
template <> struct wchar_t_size<1> { enum { mask = 0xff }; };
template <> struct wchar_t_size<2> { enum { mask = 0xffff }; };
template <> struct wchar_t_size<4> { enum { mask = 0xffffffff }; };
}}}
namespace boost { namespace spirit { namespace char_encoding
{
///////////////////////////////////////////////////////////////////////////
// Test characters for specified conditions (using std wchar_t functions)
///////////////////////////////////////////////////////////////////////////
struct standard_wide
{
typedef wchar_t char_type;
template <typename Char>
static typename std::char_traits<Char>::int_type
to_int_type(Char ch)
{
return std::char_traits<Char>::to_int_type(ch);
}
template <typename Char>
static Char
to_char_type(typename std::char_traits<Char>::int_type ch)
{
return std::char_traits<Char>::to_char_type(ch);
}
static bool
ischar(int ch)
{
// we have to watch out for sign extensions (casting is there to
// silence certain compilers complaining about signed/unsigned
// mismatch)
return (
std::size_t(0) ==
std::size_t(ch & ~traits::wchar_t_size<sizeof(wchar_t)>::mask) ||
std::size_t(~0) ==
std::size_t(ch | traits::wchar_t_size<sizeof(wchar_t)>::mask)
) ? true : false; // any wchar_t, but no other bits set
}
static bool
isalnum(wchar_t ch)
{
using namespace std;
return iswalnum(to_int_type(ch)) ? true : false;
}
static bool
isalpha(wchar_t ch)
{
using namespace std;
return iswalpha(to_int_type(ch)) ? true : false;
}
static bool
iscntrl(wchar_t ch)
{
using namespace std;
return iswcntrl(to_int_type(ch)) ? true : false;
}
static bool
isdigit(wchar_t ch)
{
using namespace std;
return iswdigit(to_int_type(ch)) ? true : false;
}
static bool
isgraph(wchar_t ch)
{
using namespace std;
return iswgraph(to_int_type(ch)) ? true : false;
}
static bool
islower(wchar_t ch)
{
using namespace std;
return iswlower(to_int_type(ch)) ? true : false;
}
static bool
isprint(wchar_t ch)
{
using namespace std;
return iswprint(to_int_type(ch)) ? true : false;
}
static bool
ispunct(wchar_t ch)
{
using namespace std;
return iswpunct(to_int_type(ch)) ? true : false;
}
static bool
isspace(wchar_t ch)
{
using namespace std;
return iswspace(to_int_type(ch)) ? true : false;
}
static bool
isupper(wchar_t ch)
{
using namespace std;
return iswupper(to_int_type(ch)) ? true : false;
}
static bool
isxdigit(wchar_t ch)
{
using namespace std;
return iswxdigit(to_int_type(ch)) ? true : false;
}
static bool
isblank BOOST_PREVENT_MACRO_SUBSTITUTION (wchar_t ch)
{
return (ch == L' ' || ch == L'\t');
}
///////////////////////////////////////////////////////////////////////
// Simple character conversions
///////////////////////////////////////////////////////////////////////
static wchar_t
tolower(wchar_t ch)
{
using namespace std;
return isupper(ch) ?
to_char_type<wchar_t>(towlower(to_int_type(ch))) : ch;
}
static wchar_t
toupper(wchar_t ch)
{
using namespace std;
return islower(ch) ?
to_char_type<wchar_t>(towupper(to_int_type(ch))) : ch;
}
static ::boost::uint32_t
toucs4(int ch)
{
return ch;
}
};
}}}
#endif
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
97be6f3ad257e0da7c169a29040baa7e1ad34b84 | 6f57491fdcab5c9f0dedd5dd949dccad79f5783f | /Cpp_ex/C_ex/ch11/ch11 ex5.cpp | 9f03712724a63890a479a20671ea4a34116c1e93 | [] | no_license | frankylin1111/1081ML | 1e9f07de708d8c989fed1e7dd2f313c12b3c79fb | 1ee8c99516f28e07f5ecd2530800eba8104451a6 | refs/heads/master | 2022-01-31T09:00:11.816451 | 2022-01-24T02:01:24 | 2022-01-24T02:01:24 | 208,534,601 | 0 | 0 | null | null | null | null | BIG5 | C++ | false | false | 293 | cpp | #include <stdio.h>
#include <cstdlib>
#include <cstring>
/*
2018/07/21 心得
ch11 陣列 ------------------ example 5
陣列與指標
字元指標陣列
*/
int main()
{
int i;
char *p;
p = "C Language";
for (i=0;i<10;i+=2)
printf("%c",p[i]);
printf("\n");
}
| [
"poi861111@gmail.com"
] | poi861111@gmail.com |
2c2778bc32c5fd04dc88204f41f94cba8a3b169e | 1f5a2c45017d45a837daea81d314b8a60cbc55a8 | /C++基础/C++day02/Code/03 内联函数的引出-宏函数的缺陷/03_内联函数的引出-宏函数的缺陷.cpp | 7c3e479a74c1371c07e99efd9acd300639b17fb0 | [] | no_license | robotchaoX/CPP-learning-code | 92c815ea32b10517b85d213fe707d1e9488fa003 | a4f26f1f7c7ff2d2279cf1de13ad9677bd0ea139 | refs/heads/master | 2022-12-16T20:33:56.151910 | 2020-09-14T12:57:42 | 2020-09-14T12:57:42 | 211,495,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,265 | cpp | #define _CRT_SECURE_NO_WARNINGS
#include <iostream>
using namespace std;
//宏定义一个加法
#define MyAdd(x, y) x + y // 不加括号有问题((x) + (y))
void test01() {
int ret = MyAdd(10, 20) * 20; //预期结果 600 ((10)+(20))*20
cout << "#define MyAdd(x, y) : " << ret << endl;
}
//宏定义比较算法
#define defCompare(a, b) ((a) < (b)) ? (a) : (b)
// inline内联
inline void inliCompare(int a, int b) {
int ret = a < b ? a : b;
cout << "inline void inliCompare(int a, int b) :" << ret << endl;
}
void test02() {
int a = 10;
int b = 20;
int ret = defCompare(++a, b); // 预期结果 11 ((++a) < (b)) ? (++a):(b)
cout << "#define defCompare(++a, b) :" << ret << endl;
inliCompare(++a, b);
}
// 内联函数注意事项
// 1.类内实现的成员函数,默认内联,前面会自动加inline关键字
// 2.内联函数声明和实现前都必须加inline
inline void func(); //内联函数声明
inline void func() { //如果函数实现时候,没有加inline关键字,那么这个函数依然不算内联函数
;
};
// 宏函数没有作用域
int main() {
test01();
test02();
// system("pause");
return EXIT_SUCCESS;
} | [
"948037851@qq.com"
] | 948037851@qq.com |
b1f35ecbd42987a0b8fc0e02d0e35a8d3374ffef | 2576513184eb6a1f90e67693220701313915c6fc | /3304/italyantsev_yan/lab3/src/publisher.cpp | 11ce75da2aea97093cb81b4e8073b97fa98d11db | [] | no_license | anyfilatov/ROS-course | 31262710a4eead6f44e608cceb39d3f39f6db518 | 46bb70b942adf98ff20845fc48c1a53058fb1611 | refs/heads/master | 2020-04-10T16:55:20.723453 | 2018-12-28T11:36:11 | 2018-12-28T11:36:11 | 68,077,880 | 4 | 94 | null | 2019-01-29T10:57:35 | 2016-09-13T05:40:58 | CMake | UTF-8 | C++ | false | false | 3,200 | cpp | #include <ros/ros.h>
#include <geometry_msgs/Twist.h>
#include <tf/transform_listener.h>
#include <tf/transform_broadcaster.h>
#include <std_msgs/String.h>
#include <visualization_msgs/Marker.h>
#include <ros/console.h>
#include <string>
#include <cmath>
using namespace std;
static string LOBOT = "LOST";
class FBot {
public:
string name;
ros::NodeHandle &nh;
bool isFollow;
int id;
double x, y, z;
string nameSearcher;
ros::Publisher point_pub = nh.advertise<visualization_msgs::Marker>("visualization_marker", 10);
visualization_msgs::Marker point;
FBot(ros::NodeHandle &nh, string name) : nh(nh), name(name) {
isFollow = false;
id = 1;
x = y = z = 0;
}
string getName() {
return name;
}
void handlerVoice(const std_msgs::String& str) {
if (str.data != "stop") {
nameSearcher = str.data;
isFollow = true;
} else isFollow = false;
cout << "Lost robot voice (" << str.data << ")" << endl;
}
ros::Subscriber listen() {
return nh.subscribe("/voice", 100, &FBot::handlerVoice, this);
}
void walk() {
ros::Rate loop_rate(1);
while(ros::ok() && !isFollow) {
x += (rand() % 5 - 2);
y += (rand() % 5 - 2);
z = 0.0;
broadcastPosition();
repaint();
ros::spinOnce();
loop_rate.sleep();
}
follow();
}
void initVisualisation() {
point.header.frame_id = name;
point.header.stamp = ros::Time::now();
point.ns = name;
point.action = visualization_msgs::Marker::ADD;
point.id = id;
point.type = visualization_msgs::Marker::CYLINDER;
point.pose.orientation.w = 0.0;
point.pose.position.x = 0.0;
point.pose.position.y = 0.0;
point.pose.position.z = 0.0;
point.color.r = 0.4f;
point.color.g = 0.0f;
point.color.b = 0.6f;
point.color.a = 1.0;
point.scale.x = 1.0;
point.scale.y = 1.0;
point.scale.z = 1.0;
}
void repaint() {
point.pose.position.x = x;
point.pose.position.y = y;
point.pose.position.z = z;
point_pub.publish(point);
}
void follow() {
std::cout << "The LOBOT Move" << std::endl;
tf::TransformListener listener;
float thresholdX = 0.5f, thresholdY = 0.5f;
ros::Rate rate(1);
while (nh.ok() && isFollow) {
tf::StampedTransform transform;
try {
listener.lookupTransform(name, nameSearcher, ros::Time(0), transform);
}
catch (tf::TransformException &e) {
ROS_ERROR("%s", e.what());
broadcastPosition();
ros::Duration(1.0).sleep();
continue;
}
x += transform.getOrigin().x();
y += transform.getOrigin().y();
broadcastPosition();
repaint();
ros::spinOnce();
rate.sleep();
}
}
void broadcastPosition() {
static tf::TransformBroadcaster br;
tf::Transform transform;
cout << "LoBot (" << name <<") move out x:" << x << " y:" << y << endl;
transform.setOrigin(tf::Vector3(x, y, 0.0));
tf::Quaternion q;
q.setRPY(0, 0, z);
transform.setRotation(q);
br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "world", name));
}
};
int main(int argc, char **argv) {
ros::init(argc, argv, "lobot");
ros::NodeHandle nh;
FBot lost(nh, LOBOT);
lost.initVisualisation();
ros::Subscriber sub = lost.listen();
lost.walk();
return 0;
}
| [
"Bedrang12@yandex.ru"
] | Bedrang12@yandex.ru |
934690b3e58fb83ec43b7c3712c3f1ebd783411b | fa041d3904086a58e52a5c2ffd876ffa7679e5e0 | /libole/libstructstorage.cpp | b07d78e9d0517650c7a1a259be124776b0fd80f1 | [] | no_license | Lyarvo4ka/RecoveryProjects | b56fffe64f63b17943a37f6db68b5b5d57651b47 | 7bb9e68924d7397041dd2a3f15e63273e43e2b58 | refs/heads/master | 2021-06-25T15:49:14.350896 | 2021-02-17T13:28:48 | 2021-02-17T13:28:48 | 199,153,605 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,506 | cpp | // libstructstorage.cpp : Defines the exported functions for the DLL application.
//
#include "stdafx.h"
#include "ole/libstructstorage.h"
#include <boost/filesystem.hpp>
std::string getTimeFromFileTime(const FILETIME & file_time)
{
SYSTEMTIME st = { 0 };
std::string time_nane = "";
if (::FileTimeToSystemTime(&file_time, &st))
{
char time_buffer[255];
::GetTimeFormatA(LOCALE_USER_DEFAULT, 0, &st, "HH-mm-ss", time_buffer, 255);
time_nane = time_buffer;
}
return time_nane;
}
std::string getDateFromFileTime(const FILETIME & file_time)
{
SYSTEMTIME st = { 0 };
std::string date_name;
if (FileTimeToSystemTime(&file_time, &st))
{
char date_buffer[255];
GetDateFormatA(LOCALE_USER_DEFAULT, 0, &st, "yyyy-MM-dd", date_buffer, 255);
date_name = date_buffer;
}
return date_name;
}
std::string getDateTimeFromFileTime(const FILETIME & file_time)
{
return getDateFromFileTime(file_time) + "-" + getTimeFromFileTime(file_time);
}
std::string LIBSTRUCTSTORAGE_API toString(WORD nYear, const int size)
{
std::string sDate;
char *chDate = new char[size + 1];
if (sprintf_s(chDate, size + 1, "%.*i", size, nYear) == size)
sDate = chDate;
delete[] chDate;
return sDate;
}
std::string LIBSTRUCTSTORAGE_API toYearString(WORD nYear)
{
return toString(nYear, 4);
}
std::string LIBSTRUCTSTORAGE_API toStringDate(WORD nDateTime)
{
return toString(nDateTime, 2);
}
SummaryInformation::SummaryInformation() : Title_("")
, Subject_("")
, Author_("")
, Keywords_("")
, Comments_("")
, Template_("")
, LastSavedBy_("")
, RevisionNumber_("")
//, TotalEditTime_()
{
}
void SummaryInformation::setTitile(const std::string & title)
{
Title_ = title;
}
std::string SummaryInformation::title() const
{
return Title_;
}
void SummaryInformation::setSubject(const std::string & subject)
{
Subject_ = subject;
}
std::string SummaryInformation::subject() const
{
return Subject_;
}
void SummaryInformation::setAuthor(const std::string & author)
{
Author_ = author;
}
std::string SummaryInformation::author() const
{
return Author_;
}
void SummaryInformation::setKeywords(const std::string & keywords)
{
Keywords_ = keywords;
}
std::string SummaryInformation::keywords() const
{
return Keywords_;
}
void SummaryInformation::setComments(const std::string & comments)
{
Comments_ = comments;
}
std::string SummaryInformation::comments() const
{
return Comments_;
}
void SummaryInformation::setTemplate(const std::string & strTemplate)
{
Template_ = strTemplate;
}
std::string SummaryInformation::getTemplate() const
{
return Template_;
}
void SummaryInformation::setLastSavedBy(const std::string & LastSavedBy)
{
LastSavedBy_ = LastSavedBy;
}
std::string SummaryInformation::LastSavedBy() const
{
return LastSavedBy_;
}
void SummaryInformation::setRevisionNumber(const std::string & RevisionNumber)
{
RevisionNumber_ = RevisionNumber;
}
std::string SummaryInformation::RevisionNumber() const
{
return RevisionNumber_;
}
void SummaryInformation::setTotalEditingTime(const FILETIME & file_time)
{
TotalEditTime_.setFileTime(file_time);
}
FileDateTime SummaryInformation::totalEditTime() const
{
return TotalEditTime_;
}
void SummaryInformation::setLastPrintedTime(const FILETIME & file_time)
{
LastPrinted_.setFileTime(file_time);
}
FileDateTime SummaryInformation::lastPrintedTime() const
{
return LastPrinted_;
}
void SummaryInformation::setCreateTime(const FILETIME & file_time)
{
CreateTime_.setFileTime(file_time);
}
FileDateTime SummaryInformation::createTime() const
{
return CreateTime_;
}
void SummaryInformation::setLastSavedTime(const FILETIME & file_time)
{
LastSavedTime_.setFileTime( file_time );
}
FileDateTime SummaryInformation::lastSavedTime() const
{
return LastSavedTime_;
}
IPropertySetStorage * SSReader::toPropertySetStorage(IStorage * pStorage)
{
IPropertySetStorage * pPropSetStg = NULL;
HRESULT hr = S_OK;
if (FAILED(hr = pStorage->QueryInterface(IID_IPropertySetStorage, (void **)&pPropSetStg))) {
printf("QI for IPropertySetStorage failed w/error %08lx", hr);
pStorage->Release();
}
return pPropSetStg;
}
IStorage * SSReader::open_storage(const std::wstring & file)
{
// wprintf(L"%s",file.c_str());
HRESULT hr = S_OK;
IStorage *pStorage = NULL;
hr = ::StgOpenStorage(file.c_str(), NULL,
STGM_READ | STGM_SHARE_EXCLUSIVE, NULL, 0, &pStorage);
IPropertySetStorage *pPropSetStg;
if (FAILED(hr)) {
if (hr == STG_E_FILENOTFOUND)
printf("File not found.");
else if (hr == STG_E_FILEALREADYEXISTS)
printf("Not a compound file.");
else
{
printf("Other error (#%d)", hr);
}
return NULL;
}
return pStorage;
}
SSReader::SSReader()
{
}
SSReader::~SSReader()
{
}
bool SSReader::read_properties(const std::string & file_path, SummaryInformation & summary_information)
{
WCHAR buff[MAX_PATH];
MultiByteToWideChar(CP_ACP, 0, file_path.c_str(), -1, buff, MAX_PATH);
std::wstring file_name(buff);
IStorage * pStorage = this->open_storage(file_name);
if (!pStorage)
return false;
IPropertySetStorage * pPropSetStg = this->toPropertySetStorage(pStorage);
IPropertyStorage *pPropStg = NULL;
HRESULT hr = S_OK;
hr = pPropSetStg->Open(FMTID_SummaryInformation, STGM_READ | STGM_SHARE_EXCLUSIVE, &pPropStg);
if (FAILED(hr)) {
//printf("No Summary-Information.\n");
pStorage->Release();
pPropSetStg->Release();
return false;
}
struct pidsiStruct {
char *name;
long pidsi;
} pidsiArr[] = {
{ "Title", PIDSI_TITLE }, // VT_LPSTR
{ "Subject", PIDSI_SUBJECT }, // ...
{ "Author", PIDSI_AUTHOR },
{ "Keywords", PIDSI_KEYWORDS },
{ "Comments", PIDSI_COMMENTS },
{ "Template", PIDSI_TEMPLATE },
{ "LastAuthor", PIDSI_LASTAUTHOR },
{ "Revision Number", PIDSI_REVNUMBER },
{ "Edit Time", PIDSI_EDITTIME }, // VT_FILENAME (UTC)
{ "Last printed", PIDSI_LASTPRINTED }, // ...
{ "Created", PIDSI_CREATE_DTM },
{ "Last Saved", PIDSI_LASTSAVE_DTM },
{ "Page Count", PIDSI_PAGECOUNT }, // VT_I4
{ "Word Count", PIDSI_WORDCOUNT }, // ...
{ "Char Count", PIDSI_CHARCOUNT },
{ "Thumpnail", PIDSI_THUMBNAIL }, // VT_CF
{ "AppName", PIDSI_APPNAME }, // VT_LPSTR
{ "Doc Security", PIDSI_DOC_SECURITY }, // VT_I4
{ 0, 0 }
};
// Count elements in pidsiArr.
int nPidsi = 0;
for (nPidsi = 0; pidsiArr[nPidsi].name; nPidsi++);
// Initialize PROPSPEC for the properties you want.
PROPSPEC *pPropSpec = new PROPSPEC[nPidsi];
PROPVARIANT *pPropVar = new PROPVARIANT[nPidsi];
for (int i = 0; i < nPidsi; i++) {
ZeroMemory(&pPropSpec[i], sizeof(PROPSPEC));
pPropSpec[i].ulKind = PRSPEC_PROPID;
pPropSpec[i].propid = pidsiArr[i].pidsi;
}
// Read properties.
hr = pPropStg->ReadMultiple(nPidsi, pPropSpec, pPropVar);
if (FAILED(hr)) {
//printf("IPropertyStg::ReadMultiple() failed w/error %08lx\n", hr);
}
else {
setSummaryInformation(pPropSpec, pPropVar, nPidsi, summary_information);
}
delete[] pPropSpec;
delete[] pPropVar;
pPropSetStg->Release();
pStorage->Release();
return (SUCCEEDED(hr)) ? true : false;
}
void SSReader::setSummaryInformation(const PROPSPEC * pPropSpec, const PROPVARIANT * pPropVar, int nCount, SummaryInformation & summary_info)
{
for (int i = 0; i < nCount; ++i)
{
switch (pPropSpec[i].propid)
{
case PIDSI_TITLE:
if (pPropVar[i].pszVal != NULL)
summary_info.setTitile(pPropVar[i].pszVal);
break;
case PIDSI_SUBJECT:
if (pPropVar[i].pszVal != NULL)
summary_info.setSubject(pPropVar[i].pszVal);
case PIDSI_AUTHOR:
if (pPropVar[i].pszVal != NULL)
summary_info.setAuthor(pPropVar[i].pszVal);
break;
case PIDSI_KEYWORDS:
if (pPropVar[i].pszVal != NULL)
summary_info.setKeywords(pPropVar[i].pszVal);
case PIDSI_COMMENTS:
if (pPropVar[i].pszVal != NULL)
summary_info.setComments(pPropVar[i].pszVal);
break;
case PIDSI_TEMPLATE:
if (pPropVar[i].pszVal != NULL)
summary_info.setTemplate(pPropVar[i].pszVal);
case PIDSI_LASTAUTHOR:
if (pPropVar[i].pszVal != NULL)
summary_info.setLastSavedBy(pPropVar[i].pszVal);
case PIDSI_REVNUMBER:
if (pPropVar[i].pszVal != NULL)
summary_info.setRevisionNumber(pPropVar[i].pszVal);
case PIDSI_EDITTIME:
summary_info.setTotalEditingTime(pPropVar[i].filetime);
break;
case PIDSI_LASTPRINTED:
summary_info.setLastPrintedTime(pPropVar[i].filetime);
case PIDSI_CREATE_DTM:
summary_info.setCreateTime(pPropVar[i].filetime);
case PIDSI_LASTSAVE_DTM:
summary_info.setLastSavedTime(pPropVar[i].filetime);
break;
//default:
/*
????????
*/
};
}
}
| [
"Lyarvo4ka@gmail.com"
] | Lyarvo4ka@gmail.com |
cb3b95a312a60dd56b500ea6cf657838b110442b | ec5dfa5e311e54e424dd423395dc5061bb759248 | /CppNet/CppNet/CppNet/System/Random.cpp | 62d5ee529241ec8c508c1d3435ad8883b10ac1bb | [
"MIT"
] | permissive | kmc7468/CppNet | 348f7a7b2cda6d0f5d7fd4efb9ae2d5d02f7ee0b | c809bff2a41e3bc5320ce7c9883895d75b60eec9 | refs/heads/master | 2021-10-19T23:01:12.645005 | 2019-02-24T15:19:13 | 2019-02-24T15:19:13 | 67,591,680 | 12 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 4,002 | cpp | #include "Random.h"
namespace CppNet
{
namespace System
{
Random::Random(RandomType type)
{
this->type = type;
seed = std::random_device()();
}
Random::Random(RandomType type, UInt32 seed)
{
this->type = type;
this->seed = seed;
}
Random::Random(Random &&sNewRandom)
{
type = sNewRandom.type;
seed = sNewRandom.seed;
}
Random::Random(const Random &sNewRandom)
{
type = sNewRandom.type;
seed = sNewRandom.seed;
}
Random& Random::operator=(Random &&sNewRandom)
{
type = std::move(sNewRandom.type);
seed = std::move(sNewRandom.seed);
return *this;
}
Random& Random::operator=(const Random &sNewRandom)
{
type = sNewRandom.type;
seed = sNewRandom.seed;
return *this;
}
Int64 Random::Next() const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
return mt();
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
return mt();
}
default:
{
std::random_device rd;
return rd();
}
}
}
Int64 Random::Next(const Int64& max) const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_int_distribution<Int64> u(max);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_int_distribution<Int64> u(max);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_int_distribution<Int64> u(max);
return u(rd);
}
}
}
Int32 Random::Next(const Int32& max) const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_int_distribution<Int32> u(max);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_int_distribution<Int32> u(max);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_int_distribution<Int32> u(max);
return u(rd);
}
}
}
Int64 Random::Next(const Int64& min, const Int64& max) const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_int_distribution<Int64> u(min, max);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_int_distribution<Int64> u(min, max);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_int_distribution<Int64> u(min, max);
return u(rd);
}
}
}
Int32 Random::Next(const Int32& min, const Int32& max) const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_int_distribution<Int32> u(min, max);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_int_distribution<Int32> u(min, max);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_int_distribution<Int32> u(min, max);
return u(rd);
}
}
}
Double Random::NextDouble() const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(rd);
}
}
}
Double Random::Sample() const
{
switch (this->type)
{
case RandomType::MT19937:
{
std::mt19937 mt(seed);
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(mt);
}
case RandomType::MT19937_64:
{
std::mt19937_64 mt(seed);
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(mt);
}
default:
{
std::random_device rd;
std::uniform_real_distribution<Double> u(0.0, 1.0);
return u(rd);
}
}
}
}
} | [
"kmc7468@naver.com"
] | kmc7468@naver.com |
50ad6984eac4ac17132b8f0f405d887b047cb69a | 21794b65df26406be2ed6f26f0a3912b4e2bd1a4 | /Lab Teacher Worapan/fixed period in a video.cpp | 293c59a4155e5a69e0cbf0689bd50d9fdad5caae | [] | no_license | SunatP/ITCS381_Multimedia | d0f196caed36f083f082a441dda21a6fa9e5c6e4 | 3d1a894ced595d2ac3b0c43630f4dea528a7890e | refs/heads/master | 2023-05-11T15:21:21.167480 | 2021-01-06T06:10:00 | 2021-01-06T06:10:00 | 166,171,758 | 0 | 1 | null | 2023-05-01T20:15:33 | 2019-01-17T06:21:10 | Jupyter Notebook | UTF-8 | C++ | false | false | 1,187 | cpp | #include<stdio.h>
#include<opencv2/core/core.hpp>
#include"opencv2/opencv.hpp"
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/videoio/videoio.hpp>
#include<iostream>
using namespace std;
using namespace cv;
int main() {
time_t start, end;
VideoCapture cap("./20.avi");
if (!cap.isOpened()) {
cout << "Error opening video stream or file" << endl;
return -1;
}
int frame_width = cap.get(cv::CAP_PROP_FRAME_WIDTH);
int frame_height = cap.get(cv::CAP_PROP_FRAME_HEIGHT);
VideoWriter video("20out.avi", cv::CAP_PROP_FOURCC>>('M', 'J', 'P', 'G'), 30, Size(frame_width, frame_height), true);
time(&start);
for (;;) { // interval loop with time
Mat frame;
cap >> frame;
video.write(frame);
imshow("Frame", frame);
char c = (char)waitKey(33);
if (c == 27) break;
time(&end);
double dif = difftime(end, start);
printf("Elasped time is %.2lf seconds. \n", dif);
if (dif >= 18) // 18 second interval * 30 fps = 540 fps or 10 seconds output it's mean 5.4 frames per 1 second average should be 5.1 ~ 5.8 fps
{ // dif in second not millisecond
std::cout << "DONE" << dif << std::endl; // standard output when complete
break;
}
}
return 0;
} | [
"31818562+SunatP@users.noreply.github.com"
] | 31818562+SunatP@users.noreply.github.com |
34fcb4ca18f6b0a18cadd27cde3297177c0d3c23 | 1352c11eea6a4c7be56b8d35d2049d028811d3c0 | /ch2/ex2_2.cc | d489b9112df44d43517c26aa0a1ac3649d7f9470 | [] | no_license | jzhng/aoapc-ii | 65da7db4823671d9f1da911a357bf5972f45f64b | 36bbb94b56e2e6415ccf787852c6c6c5d56955de | refs/heads/master | 2022-07-03T01:29:27.437929 | 2022-06-16T06:17:17 | 2022-06-16T09:43:48 | 40,427,772 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 550 | cc | #include <stdio.h>
int main() {
int a, b, c;
int num = 0, count = -1;
FILE *fin, *fout;
fin = stdin;
fout = stdout;
while (fscanf(fin, "%d%d%d", &a, &b, &c) == 3) {
num = c;
count++;
while (num < 10) num += 7;
while (num <= 100) {
if ((num % 3 == a) && (num % 5 == b)) {
fprintf(fout, "Case %d: %d\n", count, num);
break;
}
num += 7;
}
if (num > 100) fprintf(fout, "Case %d: No answer\n", count);
}
fclose(fin);
fclose(fout);
return 0;
}
| [
"jz.zhangjin@gmail.com"
] | jz.zhangjin@gmail.com |
2dc3fa9b024861245c5630193b8fc9429c54762e | 3edd3da6213c96cf342dc842e8b43fe2358c960d | /abc/abc256/a/main.cpp | e6c27183359fb49d05f767629d90d150b3c7731e | [] | no_license | tic40/atcoder | 7c5d12cc147741d90a1f5f52ceddd708b103bace | 3c8ff68fe73e101baa2aff955bed077cae893e52 | refs/heads/main | 2023-08-30T20:10:32.191136 | 2023-08-30T00:58:07 | 2023-08-30T00:58:07 | 179,283,303 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 185 | cpp | #include <bits/stdc++.h>
using namespace std;
#define REP(i,n) for(int i=0;i<(n);i++)
int main() {
int n; cin >> n;
ll x = 1;
REP(i,n) x *= 2;
cout << x << endl;
return 0;
}
| [
"ccpzjoh@gmail.com"
] | ccpzjoh@gmail.com |
3e5dc7e887790ef720818b6ec8a01e7faef7d655 | 0dd5e1f1ecf11327b86e9595216d830d3ab405df | /BAK/node_vt.cpp | 8335dd11be8dcb49ae8c8b6a4cb229f385fafb68 | [] | no_license | qinyubo/mt_practice | e6e36f927f6a9371e65f1494e61f37b881b9f781 | 71a20cf4687a852e14dc2da57bec7989ffb315ca | refs/heads/master | 2021-08-29T19:42:05.873492 | 2017-12-14T20:09:35 | 2017-12-14T20:09:35 | 113,508,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,278 | cpp | #include <iostream>
#include "mpi.h"
#include <pthread.h>
#include <unistd.h> //sleep function in Linux
#include <cstdlib>
//#include <list.h>
#include <queue>
#include <errno.h>
using namespace std;
#define MAXTHRDS 3
#define TASK_NUM 4
#define TASK_BUDGET 10
pthread_t callThd[MAXTHRDS];
pthread_mutex_t mutex, mutex_debug;
queue <int> sending_queue;
queue <int> received_queue;
int task_budget = 10;
struct thread_status{
int status[MAXTHRDS];
int total_busy_thread;
int task_budget;
};
struct thread_status thrd_status;
int init_task_status(){
int i;
//thrd_status = malloc(sizeof(*thrd_status));
//memset(thrd_status, 0, sizeof(*thrd_status));
thrd_status.total_busy_thread = 0;
thrd_status.task_budget = TASK_BUDGET;
for(i=0; i<MAXTHRDS; i++){
thrd_status.status[i] = 0;
}
return 0;
}
int init_task_queue(){
//giving initial task id
received_queue.push(1);
sending_queue.push(2);
return 0;
}
int pick_receiver(){ //randomly pickup a rank as receiver
int receiver_rank;
int cur_size;
MPI_Comm_size(MPI_COMM_WORLD, &cur_size);
srand(time(NULL));
if (cur_size > 1){
receiver_rank = rand() % cur_size; //this generate a random number between 0 to cur_size
return receiver_rank;
}
else
return -1; //I am the only MPI process left
}
int pick_task(){ //pick a task for worker to execute
int task_id;
pthread_mutex_lock(&mutex_debug);
cout << "I am in pick_task()" <<endl;
pthread_mutex_unlock(&mutex_debug);
srand(time(NULL));
task_id = rand() % TASK_NUM;
return task_id;
}
void run_task(int task_id, int rank, int thrd_id){
pthread_mutex_lock(&mutex_debug);
cout << "NUM 5 I am rank " << rank << " worker thred #" << thrd_id <<endl;
pthread_mutex_unlock(&mutex_debug);
switch(task_id){
case 0:
cout << "Task 0: rank " << rank << " thrd_id " << thrd_id << " sleep 1 sec." <<endl;
sleep(1);
break;
case 1:
cout << "Task 1: rank " << rank << " thrd_id " << thrd_id << " sleep 2 sec." <<endl;
sleep(1);
break;
case 2:
cout << "Task 2: rank " << rank << " thrd_id " << thrd_id << " sleep 3 sec." <<endl;
sleep(1);
break;
case 3:
cout << "Task 3: rank " << rank << " thrd_id " << thrd_id << " sleep 4 sec." <<endl;
sleep(1);
break;
default :
cout << "Unknown task, break!" <<endl;
break;
}
return;
}
void Finalize_my_task(){ //move all task in sending queue to received queue,
//doing all taks myself till run out of task budget
pthread_mutex_lock(&mutex_debug);
cout << "Debug: I am in finalize my task"<<endl;
//cout << "Debug: sending_queue empty=" << sending_queue.empty() << " received_queue empty=" << received_queue.empty() <<endl;
pthread_mutex_unlock(&mutex_debug);
pthread_mutex_lock(&mutex);
while (!sending_queue.empty()){
received_queue.push(sending_queue.front());
sending_queue.pop();
}
pthread_mutex_unlock(&mutex);
return;
}
void *master_thrd(void *arg){
int i, myrank, receiver_rank, sender_rank;
long mythrd;
int* wr_get[100];
int* wr_send[100];
MPI_Status mpi_status;
int err=0;
int task_id;
int err_lock=0;
mythrd = (long)arg;
MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
//Init buffer
for(int i=0; i<100; i++){
wr_get[i] = 0;
wr_send[i] = 0;
}
//MPI_Barrier(MPI_COMM_WORLD);
pthread_mutex_lock(&mutex_debug);
cout << "PIN1 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
while(task_budget > 0){
pthread_mutex_lock(&mutex_debug);
cout << "PIN9 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
// Sending MPI message
err_lock = pthread_mutex_trylock(&mutex);
if(err_lock == EBUSY){
cout << "#1 Mutex lock busy rank " << myrank << " master thred #" << mythrd <<endl;
}
else if(!sending_queue.empty()){
task_id = sending_queue.front();
sending_queue.pop();
//wr_send[0] = task_id;
receiver_rank = pick_receiver();
pthread_mutex_lock(&mutex_debug);
cout << "PIN2 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
if (receiver_rank >= 0){
//pthread_mutex_lock(&mutex);
received_queue.push(task_id);
pthread_mutex_lock(&mutex_debug);
cout << "PIN3 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
}
else{
Finalize_my_task();
pthread_mutex_lock(&mutex_debug);
cout << "PIN4 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
}
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex_debug);
cout << "PIN7 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
if(myrank == 0){
sender_rank = 1;
}
else
sender_rank = 0;
// Listen and receive MPI message
/*
err = MPI_Recv(&task_id, 256, MPI_INT, MPI_ANY_SOURCE, MPI_ANY_TAG, MPI_COMM_WORLD, &mpi_status);
pthread_mutex_lock(&mutex_debug);
cout << "PIN5 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
if (err == MPI_SUCCESS){
pthread_mutex_lock(&mutex);
//task_id = wr_get[0];
received_queue.push(task_id);
//wr_get[0] = 0;
pthread_mutex_unlock(&mutex);
pthread_mutex_lock(&mutex_debug);
cout << "PIN6 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
}
pthread_mutex_lock(&mutex_debug);
cout << "PIN7 I am rank " << myrank << " master thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
*/
}
pthread_mutex_lock(&mutex_debug);
cout << "PIN8 I am rank " << myrank << " master thred #" << mythrd <<"DONE!"<<endl;
pthread_mutex_unlock(&mutex_debug);
}
void *worker_thrd(void *arg){
int i, myrank;
long mythrd;
int wr_get; //work_request, local thread fetch from task queue
int wr_send; //thread generate new task and put into sending queue
int task_id;
int err_lock=0;
//int receiver_rank;
mythrd = (long)arg;
MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
pthread_mutex_lock(&mutex_debug);
cout << "I am rank " << myrank << " worker thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
while(task_budget > 0){//keep looping
/*
pthread_mutex_lock(&mutex_debug);
cout << "NUM 1 I am rank " << myrank << " worker thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
*/
//fetch work request from received pending queue
if(!received_queue.empty()){
pthread_mutex_lock(&mutex_debug);
cout << "NUM 2 I am rank " << myrank << " worker thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
pthread_mutex_lock(&mutex);
//fetch work request from received queue, temporarily just task id
wr_get = received_queue.front();
received_queue.pop();
task_budget -= 1;
pthread_mutex_unlock(&mutex);
task_id = wr_get;
//execute task
run_task(task_id, myrank, mythrd);
//task_id for next work request
wr_send = pick_task();
pthread_mutex_lock(&mutex_debug);
cout << "NUM 3 I am rank " << myrank << " worker thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
//put work request into sending queue
err_lock = pthread_mutex_trylock(&mutex);
if(err_lock == EBUSY){
cout << "#2 Mutex lock busy rank " << myrank << " worker thred #" << mythrd <<endl;
}
else{
//list_add(&wr_send->wr_entry, &tk_queue->sending_queue);
sending_queue.push(wr_send);
pthread_mutex_unlock(&mutex);
}
pthread_mutex_lock(&mutex_debug);
cout << "NUM 4 I am rank " << myrank << " worker thred #" << mythrd <<endl;
pthread_mutex_unlock(&mutex_debug);
//update
}//end of if
}//end of while
pthread_mutex_lock(&mutex_debug);
cout << "NUM 6 I am rank " << myrank << " worker thred #" << mythrd <<"DONE!"<<endl;
pthread_mutex_unlock(&mutex_debug);
//return; //back to multithreading
}
/*for debugging */
void* master_test(void *arg){
int i, myrank;
long mythrd;
mythrd = (long)arg;
MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
for(i=0; i<10;i++){
//pthread_mutex_lock(&mutex);
cout <<"Master say hi from rank " << myrank << "thread " << mythrd <<endl;
sleep(0.5);
//pthread_mutex_unlock(&mutex);
}
pthread_exit((void*)0);
}
void* worker_test(void *arg){
int i, myrank;
long mythrd;
mythrd = (long)arg;
MPI_Comm_rank (MPI_COMM_WORLD, &myrank);
for(i=0; i<10; i++){
//pthread_mutex_lock(&mutex);
cout <<"Worker say hi from rank " << myrank << "thread " << mythrd <<endl;
sleep(0.5);
//pthread_mutex_unlock(&mutex);
}
pthread_exit((void*)0);
}
int multithreading(){
/* 1. create threads
2. assign master and worker
*/
pthread_attr_t attr;
int numthrds;
int i;
long j;
void *status;
/*Create thread attribute to specify that the main thread needs
to join with the threads it create.
*/
//pthread_attr_init(&attr);
//pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
/*Create mutex*/
pthread_mutex_init(&mutex, NULL);
pthread_mutex_init(&mutex_debug, NULL);
//init task status
//init_task_status();
task_budget = 10;
init_task_queue();
/*Create threads*/
numthrds = MAXTHRDS;
for(j=0; j<numthrds; j++){
if(j==0){ //master thread
pthread_create(&callThd[j], NULL, master_thrd, (void *)j);
pthread_mutex_lock(&mutex_debug);
cout << "Debug: create master thread"<<endl;
//cout << "Debug: sending_queue empty=" << sending_queue.empty() << " received_queue empty=" << received_queue.empty() <<endl;
pthread_mutex_unlock(&mutex_debug);
}
else{
pthread_create(&callThd[j], NULL, worker_thrd, (void *)j);
pthread_mutex_lock(&mutex_debug);
cout << "Debug: create worker thread"<<endl;
//cout << "Debug: sending_queue empty=" << sending_queue.empty() << " received_queue empty=" << received_queue.empty() <<endl;
pthread_mutex_unlock(&mutex_debug);
}
}
/*Release the thread attribute handle*/
//pthread_attr_destroy(&attr);
/*Wait for the other threads within this node*/
for(i=0; i<numthrds; i++){
pthread_join(callThd[i], &status);
pthread_mutex_lock(&mutex_debug);
cout << "Debug: I am at multithreading() pthread_join"<<endl;
//cout << "Debug: sending_queue empty=" << sending_queue.empty() << " received_queue empty=" << received_queue.empty() <<endl;
pthread_mutex_unlock(&mutex_debug);
}
/*Release mutex*/
pthread_mutex_lock(&mutex_debug);
cout << "Debug: before destroy mutex"<<endl;
//cout << "Debug: sending_queue empty=" << sending_queue.empty() << " received_queue empty=" << received_queue.empty() <<endl;
pthread_mutex_unlock(&mutex_debug);
pthread_mutex_destroy(&mutex);
pthread_mutex_destroy(&mutex_debug);
cout << "Debug: after destroy mutex"<<endl;
return 0;
}
int main(int argc, char** argv){
int world_rank, world_size;
int provided;
//MPI_Init(&argc, &argv);
MPI_Init_thread(&argc,&argv,MPI_THREAD_MULTIPLE, &provided);
if(provided != MPI_THREAD_MULTIPLE)
{
cout << "MPI do not Support Multiple thread" << endl;
exit(0);
}
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
multithreading();
cout << "Rank" << world_rank << "finish job!" << endl;
MPI_Finalize();
return 0;
}
| [
"qybo123@gmail.com"
] | qybo123@gmail.com |
aa8d6581888ce2fa3a74d6827a958e9a0051eb8f | 1c2aeace325d44225843b186dd438aa2a6bde266 | /EQ_partition.cpp | 1cbcb592d6c1f3fe13034179a101977ffc2d306e | [] | no_license | chhf129/EQSP | d57ef030ec492b73b6c2ca813d9f599015d691e6 | 4137692d26756c09646d0e3d71c7f1b5e8af3da5 | refs/heads/master | 2020-03-07T08:37:46.749027 | 2018-04-04T11:57:53 | 2018-04-04T11:57:53 | 127,384,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,850 | cpp | #include "EQSP.h"
Mat EQSP::eq_point_set_polar(int dim, int n){
return eq_point_set_polar(dim,n,false, 0);
}
Mat EQSP::eq_point_set_polar(int dim, int n, bool use_offset, double offset){
if (dim<1 || dim>3 || n < 1){
cout << "1<=dim<=3,n>=1" << endl;
}
Mat points_s;
if (n == 1){
points_s = Mat::zeros(dim, 1, matType);
return points_s;
}
pair<Mat, Mat> result = eq_caps(dim, n);
Mat a_cap = result.first;
Mat n_regions = result.second;
if (dim == 1){
points_s = a_cap - pi / n;
return points_s;
}
int n_collars = n_regions.cols - 2;
points_s = Mat::zeros(dim, n, matType);
Mat r;
if (use_offset && dim == 3){
r = Mat::eye(3, 3, matType);
}
if (dim == 2){
offset = 0;
}
// int cache_size = floor(n_collars / 2.0);
int cache_size = n_collars;
bool use_cache = dim >= 2;
//use_cache = false;
vector<Mat> cache;
Mat points_1;
int point_n = 2;
for (int collar_n = 1; collar_n <= n_collars; collar_n++){
double a_top = a_cap.at<double>(0, collar_n-1);
double a_bot = a_cap.at<double>(0, collar_n);
double n_in_collar = n_regions.at<double>(0, collar_n);
cache.assign(cache_size, Mat(0, 0, matType));
if (use_cache && !cache.empty()){
int twin_collar_n = n_collars - collar_n+1;
if (twin_collar_n <= cache_size &&
cache[twin_collar_n-1].cols == n_in_collar){
points_1 = cache[twin_collar_n-1];
}
else{
points_1 = eq_point_set_polar(dim - 1, n_in_collar, use_offset, offset);
cache.insert(cache.begin() + collar_n - 1, points_1);
cache.erase(cache.begin() + cache.size()-1);//
}
}
else{
points_1 = eq_point_set_polar(dim - 1, n_in_collar, use_offset, offset);
}
if (use_offset && dim == 3 && collar_n > 1){
r = s2_offset(points_1)*r;
//TODO
}
double a_point = (a_top + a_bot) / 2;
int point_1_n = points_1.cols;
int k = 0;
for (int i = 1; i <= dim - 1; i++){
for (int j = point_n; j <= point_1_n + point_n - 1; j++){
if (dim == 2){
points_s.at<double>(i - 1, j - 1) = fmod(points_1.at<double>(i - 1, j - point_n) + 2 * pi*offset, pi * 2);
}
else{
points_s.at<double>(i - 1, j - 1) = points_1.at<double>(i - 1, j - point_n);
}
points_s.at<double>(dim - 1, j-1) = a_point;
}
}
offset += circle_offset(n_in_collar, n_regions.at<double>(0, 1 + collar_n), use_offset);
offset -= floor(offset);
point_n += points_1.cols;
}
points_s.col(point_n - 1) = 0;
points_s.at<double>(dim - 1, point_n - 1) = pi;
return points_s;
}
pair<Mat, vector<Mat>> EQSP::eq_regions(int dim, int n, bool use_offset, double offset){
return eq_regions(dim, n, false, 0);
}
pair<Mat, vector<Mat>> EQSP::eq_regions(int dim, int n, bool use_offset, double offset){
if (dim<1 || dim>3 || n < 1){
cout << "1<=dim<=3,n>=1" << endl;
}
vector<Mat> dim_1_rot(n);
Mat regions;
if (n == 1){
}
}
| [
"hxc334@case.edu"
] | hxc334@case.edu |
4e1a88f3a79466e055c78b4af6c8e604c5596865 | c15e07ae1816be18935951d2c60a65fb6e4d1f5c | /Lap3/Bai3_Lab3/Bai3_Lab3/BALL.cpp | ef8b27b5ac56db76f88bb39e431cf22582615a28 | [] | no_license | TuocThieu/dhmt | 756e6b28d0af6533f6362978f041f316c302d33a | f33569e581e8ff59adb7aad935b5bfff23944120 | refs/heads/master | 2022-01-07T14:19:20.392595 | 2019-06-20T15:31:36 | 2019-06-20T15:31:36 | 192,944,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 417 | cpp | #include "stdafx.h"
#include "BALL.h"
void ballInit(BALL * ball, int x, int y)
{
ball->x = x;
ball->y = y;
ball->vx = velocity(); /* phát sinh ngẫu nhiên vector chuyển động */
ball->vy = velocity();
}
void ballDraw(BALL * ball)
{
rectDraw(ball->x, ball->y, BALL_SIZE, BALL_SIZE, CR_WHITE);
}
void ballUpdate(BALL * ball)
{
ball->x += BALL_SPEED * ball->vx;
ball->y += BALL_SPEED * ball->vy;
} | [
"phamthanhmai0809@gmail.com"
] | phamthanhmai0809@gmail.com |
9e5e5aaac9362e289b193eb475b29e2791dfd270 | 85cce50c27d7bbd6d098ec0af7b5ec712ad6abd8 | /CodeChef/C++/CodeChef_BestBats.cpp | 08fa744cfc032fd41ea5abc5dbc1937cf773d300 | [] | no_license | saikiran03/competitive | 69648adcf783183a6767caf6db2f63aa5be4aa25 | c65e583c46cf14e232fdb5126db1492f958ba267 | refs/heads/master | 2020-04-06T07:04:06.577311 | 2016-10-05T08:28:19 | 2016-10-05T08:28:19 | 53,259,126 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 717 | cpp | #include <iostream>
#include <string>
#include <algorithm>
#include <vector>
using namespace std;
long long int ncr(int n, int r)
{
long long int res = 1;
int a, b;
if(r>n-r){ a = n-r; b = r; }
else{ a = r; b = n-r; }
for(int i=n; i>b; i--) res*=i;
for(int i=a; i>0; i--) res/=i;
return res;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int test,length;
cin >> test;
while(test--)
{
int count,end,mid,scores[11];
for(int i=0; i<11; i++) cin >> scores[i];
cin >> length;
sort(scores,scores+11);
mid = 11-length-1;
count = 0;
for(int i=0; i<11; i++) if(scores[i]==scores[mid]){ end = i; count++; }
cout << ncr(count,end-mid) << endl;
}
} | [
"kiransai3284462@gmail.com"
] | kiransai3284462@gmail.com |
4a979c44b48134d9b01a65dab49f7d7209a31d19 | 055023b1ff9fde2ec4894b4022e545a0a411f8a0 | /Lec-5 Greedy/CoinChange.cpp | 5e095829887806c09875e2b8c78b2036e07c3bac | [] | no_license | saniyat-hydra007/Data-Structure-Algorithm-II-Lab-Codes | 6fda7b256af99039198f35701d0531a6fc9232fb | 0a77f223abdfe0cd06a337dcade72299acb02d8e | refs/heads/main | 2023-06-01T18:51:27.742112 | 2021-06-19T09:31:38 | 2021-06-19T09:31:38 | 343,026,285 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,733 | cpp | /**
* @Author: Saniyat Mushrat Lamim
* @Date: 28-Mar-2021
* @Email: robertarmstrong096@gmail.com
* @Filename: CoinChange.cpp
* @Last modified by: Saniyat Mushrat Lamim
* @Last modified time: 04-Apr-2021
*/
#include "bits/stdc++.h"
using namespace std;
#define el "\n"
#define F first
#define S second
#define PI 3.14159265358979323846 /* pi */
#define FOR(i,a,b) for(int i = a; i <= b; ++i)
#define FORD(i,a,b) for(int i = a; i >= b; --i)
#define RI(i,n) FOR(i,1,n)
#define REP(i,n) FOR(i,0,(n)-1)
#define SQR(x) (x)*(x)
#define all(v) ((v).begin()),((v).end())
#define degreesToRadians(angleDegrees) (angleDegrees * PI / 180.0) // Converts degrees to radians.
#define radiansToDegrees(angleRadians) (angleRadians * 180.0 / PI) // Converts radians to degrees.
typedef long long ll;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef long double ld;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pii> vpii;
typedef vector<pll> vpll;
const double EPS = 1e-9;
const int N = 1e3+2, M = 3e5+5, OO = 0x3f3f3f3f;
int cmpfunc (const void * a, const void * b) {
return ( *(int*)b - *(int*)a );
}
int main () {
int coins[] = { 1, 5, 10, 25, 100 };
qsort(coins, 5, sizeof(int), cmpfunc);
int m;
std::cout << "Enter The Ammount: ";
std::cin >> m;
std::cout << endl;
int i = 0;
while(m>0) {
int c = coins[i];
int req_num_coin = m/c;
if (req_num_coin >0) {
std::cout << "Take coin " << coins[i] << " for " << req_num_coin << " times" << '\n';
}
i++;
m = m%c;
}
return 0;
}
| [
"70531660+saniyat-hydra007@users.noreply.github.com"
] | 70531660+saniyat-hydra007@users.noreply.github.com |
ae95d5e0440062d13ca656f978a5483f6642b84a | dd6d8d3a66a8a9901b533bc9f4ed97194a9830e7 | /Shooter.cpp | 31ff01ed848a986455cae27276c393103761ea82 | [] | no_license | Techbrick/Test_Tank_Drive | 8cc3f1497b5bafe65eb15c70fa971d6a22384127 | 80b10cde60b1cd35de9ea199d7ee1ff7d3de35f9 | refs/heads/master | 2016-08-12T11:27:52.393681 | 2016-02-04T00:25:23 | 2016-02-04T00:25:23 | 49,994,668 | 0 | 3 | null | 2016-01-20T01:56:02 | 2016-01-20T01:09:26 | C++ | UTF-8 | C++ | false | false | 201 | cpp | #include "Shooter.h"
Shooter::Shooter(uint32_t leftTalon, uint32_t rightTalon) :
left(leftTalon),
right(rightTalon) {}
void Shooter::setSpeed(float speed)
{
left.Set(speed);
right.Set(speed);
} | [
"Numeri@users.noreply.github.com"
] | Numeri@users.noreply.github.com |
2c928b562c33a745baf05a3f5db4883050978ea4 | 1a086a86102434f2f7b437043fe64b6c1012962c | /lex_parse/FLOPPY_parser.h | fcd6180f717d8b9d1ed0ce7b96843465dd2091c8 | [] | no_license | apraturu/468 | b2f04b57f349d24313a532bee5a92d3f6471b87a | 3ab6f87c9381720f723fcbd9b6da659c8e09b68c | refs/heads/master | 2021-01-18T21:12:48.341269 | 2016-06-08T18:13:50 | 2016-06-08T18:13:50 | 55,921,068 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 5,120 | h | /* A Bison parser, made by GNU Bison 3.0.4. */
/* Bison interface for Yacc-like parsers in C
Copyright (C) 1984, 1989-1990, 2000-2015 Free Software Foundation, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
/* As a special exception, you may create a larger work that contains
part or all of the Bison parser skeleton and distribute that work
under terms of your choice, so long as that work isn't itself a
parser generator using the skeleton or a modified version thereof
as a parser skeleton. Alternatively, if you modify or redistribute
the parser skeleton itself, you may (at your option) remove this
special exception, which will cause the skeleton and the resulting
Bison output files to be licensed under the GNU General Public
License without this special exception.
This special exception was added by the Free Software Foundation in
version 2.2 of Bison. */
#ifndef YY_YY_FLOPPY_PARSER_H_INCLUDED
# define YY_YY_FLOPPY_PARSER_H_INCLUDED
/* Debug traces. */
#ifndef YYDEBUG
# define YYDEBUG 0
#endif
#if YYDEBUG
extern int yydebug;
#endif
/* "%code requires" blocks. */
#line 24 "FLOPPY_parser.y" /* yacc.c:1915 */
#include "../FLOPPY_statements/statements.h"
#include "../FLOPPYOutput.h"
#ifndef YYtypeDEF_YY_SCANNER_T
#define YYtypeDEF_YY_SCANNER_T
typedef void* yyscan_t;
#endif
#line 53 "FLOPPY_parser.h" /* yacc.c:1915 */
/* Token type. */
#ifndef YYTOKENTYPE
# define YYTOKENTYPE
enum yytokentype
{
FLOPPY_INTVAL = 258,
FLOPPY_FLOATVAL = 259,
FLOPPY_ID = 260,
FLOPPY_STRING = 261,
FLOPPY_CREATE = 262,
FLOPPY_TABLE = 263,
FLOPPY_VOLATILE = 264,
FLOPPY_PRIMARY = 265,
FLOPPY_FOREIGN = 266,
FLOPPY_KEY = 267,
FLOPPY_REFERENCES = 268,
FLOPPY_INDEX = 269,
FLOPPY_ONLY = 270,
FLOPPY_SPLIT = 271,
FLOPPY_DROP = 272,
FLOPPY_ON = 273,
FLOPPY_INTO = 274,
FLOPPY_VALUES = 275,
FLOPPY_DELETE = 276,
FLOPPY_INSERT = 277,
FLOPPY_SELECT = 278,
FLOPPY_FROM = 279,
FLOPPY_WHERE = 280,
FLOPPY_UPDATE = 281,
FLOPPY_SET = 282,
FLOPPY_GROUP = 283,
FLOPPY_BY = 284,
FLOPPY_HAVING = 285,
FLOPPY_ORDER = 286,
FLOPPY_LIMIT = 287,
FLOPPY_DISTINCT = 288,
FLOPPY_COUNT = 289,
FLOPPY_AVERAGE = 290,
FLOPPY_MAX = 291,
FLOPPY_MIN = 292,
FLOPPY_SUM = 293,
FLOPPY_NULL = 294,
FLOPPY_AS = 295,
FLOPPY_NOT = 296,
FLOPPY_MOD = 297,
FLOPPY_LE = 298,
FLOPPY_GE = 299,
FLOPPY_NE = 300,
FLOPPY_TRUE = 301,
FLOPPY_FALSE = 302,
FLOPPY_AND = 303,
FLOPPY_INT = 304,
FLOPPY_FLOAT = 305,
FLOPPY_BOOLEAN = 306,
FLOPPY_DATETIME = 307,
FLOPPY_VARCHAR = 308
};
#endif
/* Value type. */
#if ! defined YYSTYPE && ! defined YYSTYPE_IS_DECLARED
union YYSTYPE
{
#line 44 "FLOPPY_parser.y" /* yacc.c:1915 */
int64_t ival;
float fval;
bool bval;
char *sval;
FLOPPYStatement *statement;
FLOPPYCreateTableStatement *create_table_statement;
FLOPPYDropTableStatement *drop_table_statement;
FLOPPYCreateIndexStatement *create_index_statement;
FLOPPYDropIndexStatement *drop_index_statement;
FLOPPYInsertStatement *insert_statement;
FLOPPYDeleteStatement *delete_statement;
FLOPPYUpdateStatement *update_statement;
FLOPPYSelectStatement *select_statement;
FLOPPYForeignKey *foreign_key;
FLOPPYSelectItem *select_item;
FLOPPYTableSpec *table_spec;
FLOPPYGroupBy *group_by;
FLOPPYTableAttribute *table_attribute;
std::vector<char *> *str_vec;
std::vector<FLOPPYCreateColumn *> *create_column_vec;
std::vector<FLOPPYForeignKey *> *foreign_key_vec;
std::vector<FLOPPYValue *> *value_vec;
std::vector<FLOPPYSelectItem *> *select_item_vec;
std::vector<FLOPPYTableSpec *> *table_spec_vec;
std::vector<FLOPPYTableAttribute *> *table_attr_vec;
CreateTableAdditionalFunctionality *flags;
FLOPPYCreateColumn *create_column;
FLOPPYPrimaryKey *primary_key;
FLOPPYValue *value;
FLOPPYNode *node;
#line 156 "FLOPPY_parser.h" /* yacc.c:1915 */
};
typedef union YYSTYPE YYSTYPE;
# define YYSTYPE_IS_TRIVIAL 1
# define YYSTYPE_IS_DECLARED 1
#endif
/* Location type. */
#if ! defined YYLTYPE && ! defined YYLTYPE_IS_DECLARED
typedef struct YYLTYPE YYLTYPE;
struct YYLTYPE
{
int first_line;
int first_column;
int last_line;
int last_column;
};
# define YYLTYPE_IS_DECLARED 1
# define YYLTYPE_IS_TRIVIAL 1
#endif
int yyparse (FLOPPYOutput** result, yyscan_t scanner);
#endif /* !YY_YY_FLOPPY_PARSER_H_INCLUDED */
| [
"jthomasarchives@gmail.com"
] | jthomasarchives@gmail.com |
d0221aedcfd30764c0511ffdd7146e13fddfae62 | 1f78176b62c0dfa065d139820aa00bdba6ac1cae | /engine_template/SceneObject.hpp | 147e242d14454c8a062f14051a4311ca3b0c8d9c | [
"MIT"
] | permissive | grant-h/gfx | faf4b44a05f14f6c9281fbe61c6362cbf6d76988 | 1ae200350f019fec23dfd7c17fdae74a2e587a57 | refs/heads/master | 2021-06-28T01:33:30.112817 | 2020-09-29T08:12:27 | 2020-09-29T08:12:27 | 150,923,093 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,750 | hpp | #ifndef _SCENE_OBJECT_HPP
#define _SCENE_OBJECT_HPP
#include <glm/glm.hpp>
#include <memory>
#include <string>
#include <vector>
class CameraObject;
class SceneRenderer;
class SceneObject: public std::enable_shared_from_this<SceneObject> {
public:
SceneObject(const char * name);
virtual ~SceneObject();
virtual bool init() = 0;
virtual void tick() = 0;
virtual void draw(SceneRenderer *) = 0;
virtual void position(glm::vec3 & pos);
virtual void position(float x, float y, float z);
virtual glm::vec3 position();
virtual void set_scale(float scale) { scale_ = glm::vec3(scale); }
virtual void set_scale(float x, float y, float z) { scale_ = glm::vec3(x, y, z); }
virtual void set_scale(glm::vec3 scale) { scale_ = scale; }
virtual glm::vec3 get_scale() { return scale_; }
virtual void set_rotation(glm::vec3 & rotation) { rotation_ = rotation; }
virtual glm::vec3 get_rotation() { return rotation_; }
glm::mat4 get_model_matrix();
glm::mat4 get_normal_matrix();
std::vector<std::shared_ptr<SceneObject> >::const_iterator iter_children() {
return child_objects_.begin();
}
std::vector<std::shared_ptr<SceneObject> >::const_iterator iter_children_end() {
return child_objects_.end();
}
void add_child_object(std::shared_ptr<SceneObject> child);
std::string to_string();
std::string get_name() { return object_name_; }
protected:
std::weak_ptr<SceneObject> parent_object_;
private:
std::string object_name_;
std::vector<std::shared_ptr<SceneObject> > child_objects_;
// transforms / rotations
glm::vec3 position_;
glm::vec3 rotation_; // in radians
glm::vec3 scale_;
};
#endif // _SCENE_OBJECT_HPP
| [
"grant.h.hernandez@gmail.com"
] | grant.h.hernandez@gmail.com |
70c85a2b828e30cc6b7a81e3509a8051a1ac4964 | dd6c70ba403c80610f5a78a3492f367388102505 | /src/long/aug16/chefrrun.cpp | 99494b349b50f670be59ec0c836f7582b4eb362f | [
"MIT"
] | permissive | paramsingh/cp | 80e13abe4dddb2ea1517a6423a7426c452a59be2 | 126ac919e7ccef78c4571cfc104be21da4a1e954 | refs/heads/master | 2023-04-11T05:20:47.473163 | 2023-03-23T20:20:58 | 2023-03-23T20:21:05 | 27,965,608 | 16 | 6 | null | 2017-03-21T03:10:03 | 2014-12-13T16:01:19 | C++ | UTF-8 | C++ | false | false | 788 | cpp | #include <bits/stdc++.h>
using namespace std;
int done[100100];
int depth[100100];
int a[100100];
int n;
int cmp;
int ans;
void dfs(int u, int d) {
done[u] = cmp;
depth[u] = d;
int nxt = (u + a[u] + 1) % n;
if (done[nxt] == 0)
dfs(nxt, d + 1);
else if (done[nxt] != cmp)
return;
else
ans += d - depth[nxt] + 1;
}
int main(void) {
int t;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", a+i);
done[i] = 0;
}
ans = 0;
cmp = 0;
for (int i = 0; i < n; i++) {
if (done[i] == 0) {
cmp++;
dfs(i, 0);
}
}
printf("%d\n", ans);
}
return 0;
}
| [
"paramsingh258@gmail.com"
] | paramsingh258@gmail.com |
19f766c38d6b182c4fe2f6ed70328f1da788a677 | 24968782d8ef049c146999ed55ed9e5e3d8e1803 | /Laba_6(2)_OP.cpp | af001d4743ced0521e77ef8392f236d5a0fff2d0 | [] | no_license | jprorokova/Laba_6-2- | 5f8ec1610469a15baaee29972cf218a1944258a8 | 26d4224625f92c03e2969b6a17e002f109eaa50e | refs/heads/master | 2022-10-09T12:52:50.709055 | 2020-06-08T20:41:46 | 2020-06-08T20:41:46 | 269,790,621 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 164 | cpp | #include <cstdio>
#include <cstdlib>
#include <ctime>
#include <random>
#include <iostream>
int main()
{
srand(time(0));
std::cout << "Hello World!\n";
}
| [
"j.prorokova@gmail.com"
] | j.prorokova@gmail.com |
37ca49693f8e74e3b9f82ef5dacc07ae1a9b848d | d0fb46aecc3b69983e7f6244331a81dff42d9595 | /live/include/alibabacloud/live/model/InitializeAutoShowListTaskRequest.h | 17011b9d09f282c4f5319549303d1ed0954d8f25 | [
"Apache-2.0"
] | permissive | aliyun/aliyun-openapi-cpp-sdk | 3d8d051d44ad00753a429817dd03957614c0c66a | e862bd03c844bcb7ccaa90571bceaa2802c7f135 | refs/heads/master | 2023-08-29T11:54:00.525102 | 2023-08-29T03:32:48 | 2023-08-29T03:32:48 | 115,379,460 | 104 | 82 | NOASSERTION | 2023-09-14T06:13:33 | 2017-12-26T02:53:27 | C++ | UTF-8 | C++ | false | false | 2,048 | h | /*
* Copyright 2009-2017 Alibaba Cloud All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef ALIBABACLOUD_LIVE_MODEL_INITIALIZEAUTOSHOWLISTTASKREQUEST_H_
#define ALIBABACLOUD_LIVE_MODEL_INITIALIZEAUTOSHOWLISTTASKREQUEST_H_
#include <alibabacloud/live/LiveExport.h>
#include <alibabacloud/core/RpcServiceRequest.h>
#include <string>
#include <vector>
#include <map>
namespace AlibabaCloud {
namespace Live {
namespace Model {
class ALIBABACLOUD_LIVE_EXPORT InitializeAutoShowListTaskRequest : public RpcServiceRequest {
public:
InitializeAutoShowListTaskRequest();
~InitializeAutoShowListTaskRequest();
long getStartTime() const;
void setStartTime(long startTime);
std::string getCasterConfig() const;
void setCasterConfig(const std::string &casterConfig);
std::string getDomainName() const;
void setDomainName(const std::string &domainName);
long getEndTime() const;
void setEndTime(long endTime);
long getOwnerId() const;
void setOwnerId(long ownerId);
std::string getCallBackUrl() const;
void setCallBackUrl(const std::string &callBackUrl);
std::string getResourceIds() const;
void setResourceIds(const std::string &resourceIds);
private:
long startTime_;
std::string casterConfig_;
std::string domainName_;
long endTime_;
long ownerId_;
std::string callBackUrl_;
std::string resourceIds_;
};
} // namespace Model
} // namespace Live
} // namespace AlibabaCloud
#endif // !ALIBABACLOUD_LIVE_MODEL_INITIALIZEAUTOSHOWLISTTASKREQUEST_H_
| [
"sdk-team@alibabacloud.com"
] | sdk-team@alibabacloud.com |
345891fbe4936088a36cfd1ac285cb2d7f8f957d | 51b2be0a9a2eb58dd1940bc148caaf041948dedb | /ScreenGif/src/ScreenGif/WellcomPage.h | 9e5fe1820d2c38db55c940f71e86a0b8ee5538cd | [
"MIT"
] | permissive | wenii/ScreenGif | 3f49d42e1bf72bfde2a1fa9c803f211fea1f961e | 3c8b62b93e59fcf1d17879055c0e1eabf335acf3 | refs/heads/master | 2021-01-21T12:59:50.336326 | 2018-01-27T09:36:48 | 2018-01-27T09:36:48 | 55,071,507 | 2 | 2 | null | null | null | null | GB18030 | C++ | false | false | 498 | h | #pragma once
#include "afxcmn.h"
// CWellcomPage 对话框
class CWellcomPage : public CDialog
{
DECLARE_DYNAMIC(CWellcomPage)
public:
CWellcomPage(CWnd* pParent = NULL); // 标准构造函数
virtual ~CWellcomPage();
// 对话框数据
enum { IDD = IDD_DIALOG_WELLCOM };
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnPaint();
virtual BOOL OnInitDialog();
afx_msg void OnTimer(UINT_PTR nIDEvent);
};
| [
"727420175@qq.com"
] | 727420175@qq.com |
c31327e12cb4449610e48a0320430e1b221343f2 | 0a7c429c78853d865ff19f2a75f26690b8e61b9c | /Experimental/Showtime/ShowtimeDelegate/Viewer.cpp | ca983e56c6f7056dff1aa2394a2e0d99e3e059b5 | [] | no_license | perryiv/cadkit | 2a896c569b1b66ea995000773f3e392c0936c5c0 | 723db8ac4802dd8d83ca23f058b3e8ba9e603f1a | refs/heads/master | 2020-04-06T07:43:30.169164 | 2018-11-13T03:58:57 | 2018-11-13T03:58:57 | 157,283,008 | 2 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 22,106 | cpp |
///////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2008, Perry L Miller IV
// All rights reserved.
// BSD License: http://www.opensource.org/licenses/bsd-license.html
//
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
//
// Qt viewer class.
//
///////////////////////////////////////////////////////////////////////////////
#include "Showtime/ShowtimeDelegate/Viewer.h"
#include "Display/Events/Events.h"
#include "OsgTools/Render/Defaults.h"
#include "Usul/Adaptors/MemberFunction.h"
#include "Usul/Adaptors/Bind.h"
#include "Usul/Documents/Manager.h"
#include "Usul/Exceptions/Exception.h"
#include "Usul/Functions/SafeCall.h"
#include "Usul/Interfaces/ICanClose.h"
#include "Usul/Interfaces/IRead.h"
#include "Usul/Jobs/Manager.h"
#include "Usul/Scope/Caller.h"
#include "Usul/Strings/Format.h"
#include "Usul/Threads/Named.h"
#include "Usul/Threads/ThreadId.h"
#include "Usul/Trace/Trace.h"
#include "QtCore/QUrl"
#include "QtGui/QResizeEvent"
#include "boost/bind.hpp"
#include <limits>
using namespace Showtime;
///////////////////////////////////////////////////////////////////////////////
//
// Constructor.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::Viewer ( IUnknown::RefPtr doc, const QGLFormat& format, QWidget* parent, IUnknown* caller ) :
BaseClass ( format, parent ),
_viewer ( new Display::View::Viewer ( doc ) ),
_caller ( caller ),
_document ( doc ),
_refCount ( 0 ),
_threadId ( Usul::Threads::currentThreadId() ),
_mutex ( new Viewer::Mutex ),
_keysDown()
{
USUL_TRACE_SCOPE;
// Initialize openGL.
this->initializeGL();
// For convienence;
Usul::Interfaces::IUnknown::QueryPtr me ( this );
// Set the focus policy.
this->setFocusPolicy ( Qt::ClickFocus );
// Delete on close.
this->setAttribute ( Qt::WA_DeleteOnClose );
// Initalize the placement and size.
this->_initPlacement();
// Add us to the document.
IDocument::QueryPtr document ( _document );
if ( true == document.valid() )
document->addWindow ( this );
// Add ourselves as a modified listener.
Usul::Interfaces::IModifiedSubject::QueryPtr subject ( doc );
if ( true == subject.valid() )
{
subject->addModifiedObserver ( this );
}
// Enable drag 'n drop.
this->setAcceptDrops ( true );
}
///////////////////////////////////////////////////////////////////////////////
//
// Destructor.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::~Viewer()
{
USUL_TRACE_SCOPE;
Usul::Functions::safeCall ( Usul::Adaptors::memberFunction ( this, &Viewer::_destroy ), "1668467860" );
}
///////////////////////////////////////////////////////////////////////////////
//
// Destroy this object.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::_destroy()
{
USUL_TRACE_SCOPE;
// Clear members.
_viewer = 0x0;
_caller = Usul::Interfaces::IUnknown::RefPtr ( 0x0 );
_document = 0x0;
_keysDown.clear();
// Now delete the mutex.
delete _mutex; _mutex = 0x0;
// Better be zero
USUL_ASSERT ( 0 == _refCount );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the document.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::IUnknown::RefPtr Viewer::document()
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _document;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the document.
//
///////////////////////////////////////////////////////////////////////////////
const Viewer::IUnknown::RefPtr Viewer::document() const
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _document;
}
///////////////////////////////////////////////////////////////////////////////
//
// Query for the interface.
//
///////////////////////////////////////////////////////////////////////////////
Usul::Interfaces::IUnknown * Viewer::queryInterface ( unsigned long iid )
{
USUL_TRACE_SCOPE;
switch ( iid )
{
case Usul::Interfaces::IUnknown::IID:
case Usul::Interfaces::IOpenGLContext::IID:
return static_cast < Usul::Interfaces::IOpenGLContext * > ( this );
case Usul::Interfaces::IWindow::IID:
return static_cast < Usul::Interfaces::IWindow * > ( this );
case Usul::Interfaces::IModifiedObserver::IID:
return static_cast < Usul::Interfaces::IModifiedObserver * > ( this );
default:
return 0x0;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Helper function to get the mouse state.
//
///////////////////////////////////////////////////////////////////////////////
namespace Helper
{
template < class EventType > inline Viewer::ButtonsDown buttonsDown ( EventType *event )
{
USUL_TRACE_SCOPE;
Viewer::ButtonsDown mouse;
if ( 0x0 != event )
{
if ( true == event->buttons().testFlag ( Qt::LeftButton ) )
mouse.insert ( 0 );
if ( true == event->buttons().testFlag ( Qt::MidButton ) )
mouse.insert ( 1 );
if ( true == event->buttons().testFlag ( Qt::RightButton ) )
mouse.insert ( 2 );
}
return mouse;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Draw.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::paintGL()
{
USUL_TRACE_SCOPE;
ViewerPtr viewer ( this->viewer() );
if ( true == viewer.valid() )
viewer->render();
}
///////////////////////////////////////////////////////////////////////////////
//
// Resize.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::resizeGL ( int width, int height )
{
USUL_TRACE_SCOPE;
BaseClass::resizeGL ( width, height );
ViewerPtr viewer ( this->viewer() );
if ( ( true == viewer.valid() ) && ( width > 0 ) && ( height > 0 ) )
{
viewer->resize ( static_cast < unsigned int > ( width ), static_cast < unsigned int > ( height ) );
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Window now has focus.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::focusInEvent ( QFocusEvent *event )
{
USUL_TRACE_SCOPE;
// Call the base class first.
BaseClass::focusInEvent ( event );
// Make our view current.
Usul::Documents::Manager::instance().activeView ( this->viewer() );
}
///////////////////////////////////////////////////////////////////////////////
//
// Window has lost the focus.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::focusOutEvent ( QFocusEvent *event )
{
USUL_TRACE_SCOPE;
// Call the base class first.
BaseClass::focusInEvent ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// Is the current thread the thread we were created in.
//
///////////////////////////////////////////////////////////////////////////////
bool Viewer::isContextThread() const
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return ( Usul::Threads::currentThreadId() == _threadId );
}
///////////////////////////////////////////////////////////////////////////////
//
// Make current.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::makeCurrent()
{
USUL_TRACE_SCOPE;
BaseClass::makeCurrent();
}
///////////////////////////////////////////////////////////////////////////////
//
// Swap buffers.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::swapBuffers()
{
USUL_TRACE_SCOPE;
BaseClass::swapBuffers();
}
///////////////////////////////////////////////////////////////////////////////
//
// Initialize the placement. This gives the nice cascading behavior.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::_initPlacement()
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
Guard guard ( this );
if ( QWidget* parent = dynamic_cast < QWidget* > ( this->parent() ) )
{
// Shortcuts.
const double percent ( 0.8 );
const int width ( parent->width() );
const int height ( parent->height() );
const int w ( static_cast <int> ( percent * width ) );
const int h ( static_cast <int> ( percent * height ) );
// Declare the placement static.
static int x ( 0 );
static int y ( 0 );
// Set the placement.
this->move ( x, y );
this->resize ( w, h );
// Increment.
x += 20;
y += 20;
// If we are too far then start over.
if ( ( x + w ) > width || ( y + h ) > height )
{
x = 0;
y = 0;
}
this->adjustSize();
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Preferred size. Needed for cascading.
//
///////////////////////////////////////////////////////////////////////////////
QSize Viewer::sizeHint() const
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return QSize ( -1, -1 ) );
Guard guard ( this );
if ( QWidget* parent = dynamic_cast < QWidget* > ( this->parent() ) )
{
// Shortcuts.
const double percent ( 0.8 );
const int width ( parent->width() );
const int height ( parent->height() );
const int w ( static_cast <int> ( percent * width ) );
const int h ( static_cast <int> ( percent * height ) );
return QSize ( w, h );
}
return QSize ( -1, -1 );
}
///////////////////////////////////////////////////////////////////////////////
//
// The mouse has moved.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::mouseMoveEvent ( QMouseEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
Display::Events::MouseMove event ( e->x(), e->y(), this->keysDown(), Helper::buttonsDown ( e ) );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// A mouse button has been pressed.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::mousePressEvent ( QMouseEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
Display::Events::MousePress event ( e->button(), this->keysDown(), Helper::buttonsDown ( e ) );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// A mouse button has been released.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::mouseReleaseEvent ( QMouseEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
Display::Events::MouseRelease event ( e->button(), this->keysDown(), Helper::buttonsDown ( e ) );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// A mouse button has been double-clicked.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::mouseDoubleClickEvent ( QMouseEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
Display::Events::MouseDoubleClick event ( e->button(), this->keysDown(), Helper::buttonsDown ( e ) );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// The mouse wheel has been moved.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::wheelEvent ( QWheelEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
Display::Events::MouseWheel event ( e->delta(), this->keysDown(), Helper::buttonsDown ( e ) );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// Key pressed.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::keyPressEvent ( QKeyEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
{
Guard guard ( this );
_keysDown.insert ( e->key() );
}
Display::Events::KeyPress event ( e->key(), this->keysDown(), Viewer::ButtonsDown() );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// Key released.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::keyReleaseEvent ( QKeyEvent *e )
{
USUL_TRACE_SCOPE;
if ( 0x0 == e )
return;
{
Guard guard ( this );
_keysDown.erase ( e->key() );
}
Display::Events::KeyRelease event ( e->key(), this->keysDown(), Viewer::ButtonsDown() );
this->_notify ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// Make this window the active window.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::setFocus()
{
USUL_TRACE_SCOPE;
BaseClass::setFocus();
}
///////////////////////////////////////////////////////////////////////////////
//
// Update the title.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::setTitle ( const std::string& title )
{
USUL_TRACE_SCOPE;
this->setWindowTitle ( title.c_str() );
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the mutex.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::Mutex &Viewer::mutex() const
{
return *_mutex;
}
///////////////////////////////////////////////////////////////////////////////
//
// Dragging has entering window.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::dragEnterEvent ( QDragEnterEvent *event )
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
IDocument::QueryPtr document ( this->document() );
if ( false == document.valid() || 0x0 == event )
return;
typedef QList < QUrl > Urls;
typedef Urls::const_iterator ConstIterator;
Urls urls ( event->mimeData()->urls() );
for ( ConstIterator i = urls.begin(); i != urls.end(); ++ i )
{
std::string file ( i->toLocalFile().toStdString() );
if ( document->canInsert ( file ) )
{
event->acceptProposedAction();
return;
}
}
event->accept();
}
///////////////////////////////////////////////////////////////////////////////
//
// Files have been dropped.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::dropEvent ( QDropEvent *event )
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
Usul::Interfaces::IRead::QueryPtr document ( this->document() );
if ( false == document.valid() || 0x0 == event )
return;
typedef QList < QUrl > Urls;
typedef Urls::const_iterator ConstIterator;
Urls urls ( event->mimeData()->urls() );
Usul::Interfaces::IUnknown::QueryPtr me ( this );
for ( ConstIterator i = urls.begin(); i != urls.end(); ++ i )
{
std::string file ( i->toLocalFile().toStdString() );
document->read ( file, me.get() );
}
event->acceptProposedAction();
}
///////////////////////////////////////////////////////////////////////////////
//
// Close event.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::closeEvent ( QCloseEvent *event )
{
USUL_TRACE_SCOPE;
Usul::Functions::safeCallV1 ( Usul::Adaptors::memberFunction ( this, &Viewer::_closeEvent ), event, "1483190776" );
}
///////////////////////////////////////////////////////////////////////////////
//
// Make sure we can close.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::_closeEvent ( QCloseEvent *event )
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
Guard guard ( this );
// Get the document.
Usul::Interfaces::ICanClose::QueryPtr doc ( this->document() );
// Ask the document if we can close.
if ( true == doc.valid() && false == doc->canClose ( this, Usul::Interfaces::IUnknown::QueryPtr ( this ) ) )
{
event->ignore();
return;
}
// Close. Removing this from the document's windows.
Usul::Functions::safeCall ( Usul::Adaptors::memberFunction ( this, &Viewer::_close ), "1638161623" );
// Pass along to the base class.
BaseClass::closeEvent ( event );
}
///////////////////////////////////////////////////////////////////////////////
//
// Tell the document that we are closing.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::_close()
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
// Clean up the viewer first.
{
Guard guard ( this );
// Save viewer's state and clear.
if ( _viewer.valid() )
{
_viewer->stateSave();
_viewer->clear();
}
_viewer = 0x0;
}
// Get the document.
IDocument::QueryPtr document ( this->document() );
// Remove ourselves as a modified listener.
Usul::Interfaces::IModifiedSubject::QueryPtr subject ( document );
if ( true == subject.valid() )
{
subject->removeModifiedObserver ( this );
}
// If the document is valid...
if ( true == document.valid() )
{
// Remove this window from the document's sets.
document->removeWindow ( this );
// Tell the document this is closing.
// Make sure removeWindow is called called first.
// Ask document if it has a job to close it.
Usul::Jobs::Job::RefPtr job ( document->closeJob() );
if ( true == job.valid() )
{
Usul::Jobs::Manager::instance().addJob ( job );
}
// No job, just close here.
else
{
document->closing ( this );
}
}
// Clear the document.
{
Guard guard ( this );
_document = 0x0;
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the caller.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::IUnknown::RefPtr Viewer::caller()
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _caller;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the caller.
//
///////////////////////////////////////////////////////////////////////////////
const Viewer::IUnknown::RefPtr Viewer::caller() const
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _caller;
}
///////////////////////////////////////////////////////////////////////////////
//
// Force the window closed. Will not prompt.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::forceClose()
{
USUL_TRACE_SCOPE;
USUL_THREADS_ENSURE_GUI_THREAD ( return );
Guard guard ( this );
// Close. Removing this from the document's windows.
Usul::Functions::safeCall ( Usul::Adaptors::memberFunction ( this, &Viewer::_close ), "3614568329" );
this->close();
}
///////////////////////////////////////////////////////////////////////////////
//
// Increment the reference count.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::ref()
{
USUL_TRACE_SCOPE;
Guard guard ( this );
++_refCount;
}
///////////////////////////////////////////////////////////////////////////////
//
// Decrement the reference count.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::unref ( bool )
{
USUL_TRACE_SCOPE;
Guard guard ( this );
if ( 0 == _refCount )
{
USUL_ASSERT ( 0 );
throw Usul::Exceptions::Exception ( "Error 1957966139: Reference count is already 0" );
}
--_refCount;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the internal viewer.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::ViewerPtr Viewer::viewer()
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _viewer;
}
///////////////////////////////////////////////////////////////////////////////
//
// Get the internal viewer.
//
///////////////////////////////////////////////////////////////////////////////
const Viewer::ViewerPtr Viewer::viewer() const
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _viewer;
}
///////////////////////////////////////////////////////////////////////////////
//
// Called when the document is modified (Usul::Interfaces::IModifiedObserver).
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::subjectModified ( Usul::Interfaces::IUnknown * )
{
USUL_TRACE_SCOPE;
// Queue a repaint. Do not change this behavior unless you also change the
// fact that IDocument's requestRedraw() uses the modified-observers to
// implement the request, which results in this function being called.
this->update();
}
///////////////////////////////////////////////////////////////////////////////
//
// Load the saved state.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::stateLoad()
{
USUL_TRACE_SCOPE;
ViewerPtr viewer ( this->viewer() );
if ( true == viewer.valid() )
{
viewer->stateLoad();
}
}
///////////////////////////////////////////////////////////////////////////////
//
// Return the set of keys that are currenty pressed.
//
///////////////////////////////////////////////////////////////////////////////
Viewer::KeysDown Viewer::keysDown() const
{
USUL_TRACE_SCOPE;
Guard guard ( this );
return _keysDown;
}
///////////////////////////////////////////////////////////////////////////////
//
// Send the event to the internal viewer.
//
///////////////////////////////////////////////////////////////////////////////
void Viewer::_notify ( Display::Events::Event &e )
{
USUL_TRACE_SCOPE;
ViewerPtr viewer ( this->viewer() );
if ( false == viewer.valid() )
return;
viewer->notify ( e );
}
| [
"pep4@73d323f7-f32a-0410-a0ec-c7cf9bc3a937"
] | pep4@73d323f7-f32a-0410-a0ec-c7cf9bc3a937 |
be5b20226af3664185cedb43e44f205e7dea3393 | 73315286bb22c860bd920c435ecce3df8736f4d2 | /Source/VaRest/Private/VaRest.cpp | 793b49868e1cbd2368992914978c2522051a2dbe | [
"MIT"
] | permissive | Phrensoua/VaRest | 1560fb386af8eb13d6af92bb0f9d1783302ef135 | 12ac4e35476017edce581493bea7f044b0f293f9 | refs/heads/develop | 2020-07-27T10:34:08.666678 | 2020-04-06T18:08:22 | 2020-04-06T18:08:22 | 209,060,744 | 0 | 0 | MIT | 2020-04-06T18:08:23 | 2019-09-17T13:24:44 | null | UTF-8 | C++ | false | false | 1,347 | cpp | // Copyright 2014-2019 Vladimir Alyamkin. All Rights Reserved.
#include "VaRest.h"
#include "VaRestDefines.h"
#include "VaRestSettings.h"
#include "Developer/Settings/Public/ISettingsModule.h"
#define LOCTEXT_NAMESPACE "FVaRestModule"
void FVaRestModule::StartupModule()
{
ModuleSettings = NewObject<UVaRestSettings>(GetTransientPackage(), "VaRestSettings", RF_Standalone);
ModuleSettings->AddToRoot();
// Register settings
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->RegisterSettings("Project", "Plugins", "VaRest",
LOCTEXT("RuntimeSettingsName", "VaRest"),
LOCTEXT("RuntimeSettingsDescription", "Configure VaRest plugin settings"),
ModuleSettings);
}
UE_LOG(LogVaRest, Log, TEXT("%s: VaRest module started"), *VA_FUNC_LINE);
}
void FVaRestModule::ShutdownModule()
{
if (ISettingsModule* SettingsModule = FModuleManager::GetModulePtr<ISettingsModule>("Settings"))
{
SettingsModule->UnregisterSettings("Project", "Plugins", "VaRest");
}
if (!GExitPurge)
{
ModuleSettings->RemoveFromRoot();
}
else
{
ModuleSettings = nullptr;
}
}
UVaRestSettings* FVaRestModule::GetSettings() const
{
check(ModuleSettings);
return ModuleSettings;
}
IMPLEMENT_MODULE(FVaRestModule, VaRest)
DEFINE_LOG_CATEGORY(LogVaRest);
#undef LOCTEXT_NAMESPACE
| [
"ufna@ufna.ru"
] | ufna@ufna.ru |
aaa2f4f597710de32cc59a06b7e162851a2b83b8 | 42ac42236f68e1c4c736ea5a42ca7e9b7f7e37c8 | /XGame/XSrc/XPatcher/XGamePatcher/GeneratedFiles/qrc_xgamepatcher.cpp | ed461388daca0eb0c0910b4bc662526c741e28b6 | [] | no_license | FireLeaf/XGame | c711718dae5a57c7ff17ddf0291c0c7f05c7fb72 | 863f441b93d8fa13fb679df4e3bbe1382f5361e0 | refs/heads/master | 2021-04-09T16:48:50.214417 | 2016-02-03T07:54:46 | 2016-02-03T07:54:46 | 20,708,715 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | /****************************************************************************
** Resource object code
**
** Created by: The Resource Compiler for Qt version 4.8.6
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
QT_BEGIN_NAMESPACE
QT_END_NAMESPACE
int QT_MANGLE_NAMESPACE(qInitResources_xgamepatcher)()
{
return 1;
}
Q_CONSTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qInitResources_xgamepatcher))
int QT_MANGLE_NAMESPACE(qCleanupResources_xgamepatcher)()
{
return 1;
}
Q_DESTRUCTOR_FUNCTION(QT_MANGLE_NAMESPACE(qCleanupResources_xgamepatcher))
| [
"ycqfsly@163.com"
] | ycqfsly@163.com |
abd26980f30df6a38e4008157d1a0490546fa7ff | aa88744f1d8723da6d34472d6dbe941c730aae26 | /Plugins/Wwise/ThirdParty/include/AK/SoundEngine/Common/AkDynamicSequence.h | 28a3952c1602d1c854f42765c6fb9882f15def3a | [
"Apache-2.0"
] | permissive | Volvary/ChessGame | 65771ef554e93c7762dde3f4d0c85108f7aa05da | 5a20d0ef03518f7d17a4f04290c5bf1d5f95cb4f | refs/heads/master | 2020-04-30T03:20:30.040654 | 2019-05-20T17:45:13 | 2019-05-20T17:45:13 | 176,584,057 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,168 | h | /*******************************************************************************
The content of this file includes portions of the AUDIOKINETIC Wwise Technology
released in source code form as part of the SDK installer package.
Commercial License Usage
Licensees holding valid commercial licenses to the AUDIOKINETIC Wwise Technology
may use this file in accordance with the end user license agreement provided
with the software or, alternatively, in accordance with the terms contained in a
written agreement between you and Audiokinetic Inc.
Apache License Usage
Alternatively, this file may be used under the Apache License, Version 2.0 (the
"Apache License"); you may not use this file except in compliance with the
Apache License. You may obtain a copy of the Apache License at
http://www.apache.org/licenses/LICENSE-2.0.
Unless required by applicable law or agreed to in writing, software distributed
under the Apache License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
OR CONDITIONS OF ANY KIND, either express or implied. See the Apache License for
the specific language governing permissions and limitations under the License.
Version: v2018.1.6 Build: 6858
Copyright (c) 2006-2019 Audiokinetic Inc.
*******************************************************************************/
#ifndef _AK_SOUNDENGINE_AKDYNAMICSEQUENCE_H
#define _AK_SOUNDENGINE_AKDYNAMICSEQUENCE_H
#include <AK/SoundEngine/Common/AkSoundEngine.h>
#include <AK/Tools/Common/AkArray.h>
class AkExternalSourceArray;
namespace AK
{
namespace SoundEngine
{
/// Dynamic Sequence namespace
/// \remarks The functions in this namespace are thread-safe, unless stated otherwise.
namespace DynamicSequence
{
/// Playlist Item for Dynamic Sequence Playlist.
/// \sa
/// - AK::SoundEngine::DynamicSequence::Playlist
/// - AK::SoundEngine::PostEvent
/// - \ref integrating_external_sources
class PlaylistItem
{
public:
PlaylistItem();
PlaylistItem(const PlaylistItem& in_rCopy);
~PlaylistItem();
PlaylistItem& operator=(const PlaylistItem& in_rCopy);
bool operator==(const PlaylistItem& in_rCopy)
{
AKASSERT(pExternalSrcs == NULL);
return audioNodeID == in_rCopy.audioNodeID &&
msDelay == in_rCopy.msDelay &&
pCustomInfo == in_rCopy.pCustomInfo;
};
/// Sets the external sources used by this item.
/// \sa
/// \ref integrating_external_sources
AKRESULT SetExternalSources(AkUInt32 in_nExternalSrc, AkExternalSourceInfo* in_pExternalSrc);
/// Get the external source array. Internal use only.
AkExternalSourceArray* GetExternalSources(){return pExternalSrcs;}
AkUniqueID audioNodeID; ///< Unique ID of Audio Node
AkTimeMs msDelay; ///< Delay before playing this item, in milliseconds
void * pCustomInfo; ///< Optional user data
private:
AkExternalSourceArray *pExternalSrcs;
};
/// List of items to play in a Dynamic Sequence.
/// \sa
/// - AK::SoundEngine::DynamicSequence::LockPlaylist
/// - AK::SoundEngine::DynamicSequence::UnlockPlaylist
class Playlist
: public AkArray<PlaylistItem, const PlaylistItem&, ArrayPoolDefault, 4>
{
public:
/// Enqueue an Audio Node.
/// \return AK_Success if successful, AK_Fail otherwise
AkForceInline AKRESULT Enqueue(
AkUniqueID in_audioNodeID, ///< Unique ID of Audio Node
AkTimeMs in_msDelay = 0, ///< Delay before playing this item, in milliseconds
void * in_pCustomInfo = NULL, ///< Optional user data
AkUInt32 in_cExternals = 0, ///< Optional count of external source structures
AkExternalSourceInfo *in_pExternalSources = NULL///< Optional array of external source resolution information
)
{
PlaylistItem * pItem = AddLast();
if ( !pItem )
return AK_Fail;
pItem->audioNodeID = in_audioNodeID;
pItem->msDelay = in_msDelay;
pItem->pCustomInfo = in_pCustomInfo;
return pItem->SetExternalSources(in_cExternals, in_pExternalSources);
}
};
/// The DynamicSequenceType is specified when creating a new dynamic sequence.\n
/// \n
/// The default option is DynamicSequenceType_SampleAccurate. \n
/// \n
/// In sample accurate mode, when a dynamic sequence item finishes playing and there is another item\n
/// pending in its playlist, the next sound will be stitched to the end of the ending sound. In this \n
/// mode, if there are one or more pending items in the playlist while the dynamic sequence is playing,\n
/// or if something is added to the playlist during the playback, the dynamic sequence\n
/// can remove the next item to be played from the playlist and prepare it for sample accurate playback before\n
/// the first sound is finished playing. This mechanism helps keep sounds sample accurate, but then\n
/// you might not be able to remove that next item from the playlist if required.\n
/// \n
/// If your game requires the capability of removing the next to be played item from the\n
/// playlist at any time, then you should use the DynamicSequenceType_NormalTransition option instead.\n
/// In this mode, you cannot ensure sample accuracy between sounds.\n
/// \n
/// Note that a Stop or a Break will always prevent the next to be played sound from actually being played.
///
/// \sa
/// - AK::SoundEngine::DynamicSequence::Open
enum DynamicSequenceType
{
DynamicSequenceType_SampleAccurate, ///< Sample accurate mode
DynamicSequenceType_NormalTransition ///< Normal transition mode, allows the entire playlist to be edited at all times.
};
/// Open a new Dynamic Sequence.
/// \return Playing ID of the dynamic sequence, or AK_INVALID_PLAYING_ID in failure case
///
/// \sa
/// - AK::SoundEngine::DynamicSequence::DynamicSequenceType
AK_EXTERNAPIFUNC( AkPlayingID, Open )(
AkGameObjectID in_gameObjectID, ///< Associated game object ID
AkUInt32 in_uFlags = 0, ///< Bitmask: see \ref AkCallbackType
AkCallbackFunc in_pfnCallback = NULL, ///< Callback function
void* in_pCookie = NULL, ///< Callback cookie that will be sent to the callback function along with additional information;
DynamicSequenceType in_eDynamicSequenceType = DynamicSequenceType_SampleAccurate ///< See : \ref AK::SoundEngine::DynamicSequence::DynamicSequenceType
);
/// Close specified Dynamic Sequence. The Dynamic Sequence will play until finished and then
/// deallocate itself.
AK_EXTERNAPIFUNC( AKRESULT, Close )(
AkPlayingID in_playingID ///< AkPlayingID returned by DynamicSequence::Open
);
/// Play specified Dynamic Sequence.
AK_EXTERNAPIFUNC( AKRESULT, Play )(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkTimeMs in_uTransitionDuration = 0, ///< Fade duration
AkCurveInterpolation in_eFadeCurve = AkCurveInterpolation_Linear ///< Curve type to be used for the transition
);
/// Pause specified Dynamic Sequence.
/// To restart the sequence, call Resume. The item paused will resume its playback, followed by the rest of the sequence.
AK_EXTERNAPIFUNC( AKRESULT, Pause )(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkTimeMs in_uTransitionDuration = 0, ///< Fade duration
AkCurveInterpolation in_eFadeCurve = AkCurveInterpolation_Linear ///< Curve type to be used for the transition
);
/// Resume specified Dynamic Sequence.
AK_EXTERNAPIFUNC( AKRESULT, Resume )(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkTimeMs in_uTransitionDuration = 0, ///< Fade duration
AkCurveInterpolation in_eFadeCurve = AkCurveInterpolation_Linear ///< Curve type to be used for the transition
);
/// Stop specified Dynamic Sequence immediately.
/// To restart the sequence, call Play. The sequence will restart with the item that was in the
/// playlist after the item that was stopped.
AK_EXTERNAPIFUNC( AKRESULT, Stop )(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkTimeMs in_uTransitionDuration = 0, ///< Fade duration
AkCurveInterpolation in_eFadeCurve = AkCurveInterpolation_Linear ///< Curve type to be used for the transition
);
/// Break specified Dynamic Sequence. The sequence will stop after the current item.
AK_EXTERNAPIFUNC( AKRESULT, Break )(
AkPlayingID in_playingID ///< AkPlayingID returned by DynamicSequence::Open
);
/// Get pause times.
AK_EXTERNAPIFUNC(AKRESULT, GetPauseTimes)(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkUInt32 &out_uTime, ///< If sequence is currently paused, returns time when pause started, else 0.
AkUInt32 &out_uDuration ///< Returns total pause duration since last call to GetPauseTimes, excluding the time elapsed in the current pause.
);
/// Get currently playing item. Note that this may be different from the currently heard item
/// when sequence is in sample-accurate mode.
AK_EXTERNAPIFUNC(AKRESULT, GetPlayingItem)(
AkPlayingID in_playingID, ///< AkPlayingID returned by DynamicSequence::Open
AkUniqueID & out_audioNodeID, ///< Returned audio node ID of playing item.
void *& out_pCustomInfo ///< Returned user data of playing item.
);
/// Lock the Playlist for editing. Needs a corresponding UnlockPlaylist call.
/// \return Pointer to locked Playlist if successful, NULL otherwise
/// \sa
/// - AK::SoundEngine::DynamicSequence::UnlockPlaylist
AK_EXTERNAPIFUNC( Playlist *, LockPlaylist )(
AkPlayingID in_playingID ///< AkPlayingID returned by DynamicSequence::Open
);
/// Unlock the playlist.
/// \sa
/// - AK::SoundEngine::DynamicSequence::LockPlaylist
AK_EXTERNAPIFUNC( AKRESULT, UnlockPlaylist )(
AkPlayingID in_playingID ///< AkPlayingID returned by DynamicSequence::Open
);
}
}
}
#endif // _AK_SOUNDENGINE_AKDYNAMICSEQUENCE_H
| [
"percivalaugust@gmail.com"
] | percivalaugust@gmail.com |
7b828c6182bc0936656fcadc6428efef0cf9211d | a406fc3652519a92b135fdaf5d461a87200f9705 | /TouchGFX/target/generated/TouchGFXGeneratedHAL.cpp | cbab19fe32478554dfd5378b347f6f1fcd559f62 | [] | no_license | ThanhTrungqn/level | 9edb5f9e93c13dc6469be648dd26720b63e6dd57 | 2dfe54faffbc52355a0b59ca394dcdd3842e0156 | refs/heads/master | 2021-01-03T06:37:26.156383 | 2020-03-05T14:45:24 | 2020-03-05T14:45:24 | 239,963,293 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,666 | cpp | /**
******************************************************************************
* File Name : TouchGFXGeneratedHAL.cpp
******************************************************************************
* @attention
*
* <h2><center>© Copyright (c) 2020 STMicroelectronics.
* All rights reserved.</center></h2>
*
* This software component is licensed by ST under Ultimate Liberty license
* SLA0044, the "License"; You may not use this file except in compliance with
* the License. You may obtain a copy of the License at:
* www.st.com/SLA0044
*
******************************************************************************
*/
#include <TouchGFXGeneratedHAL.hpp>
#include <touchgfx/hal/GPIO.hpp>
#include <touchgfx/hal/OSWrappers.hpp>
#include <gui/common/FrontendHeap.hpp>
#include "stm32f4xx.h"
#include "stm32f4xx_hal_ltdc.h"
namespace {
// Use the section "TouchGFX_Framebuffer" in the linker to specify the placement of the buffer
LOCATION_PRAGMA("TouchGFX_Framebuffer")
uint32_t frameBuf[(240 * 320 * 2 + 3) / 4] LOCATION_ATTRIBUTE("TouchGFX_Framebuffer");
static uint16_t lcd_int_active_line;
static uint16_t lcd_int_porch_line;
}
void TouchGFXGeneratedHAL::initialize()
{
HAL::initialize();
registerEventListener(*(touchgfx::Application::getInstance()));
registerTaskDelayFunction(&OSWrappers::taskDelay);
setFrameRefreshStrategy(HAL::REFRESH_STRATEGY_OPTIM_SINGLE_BUFFER_TFT_CTRL);
setFrameBufferStartAddresses((void*)frameBuf, (void*)0, (void*)0);
/*
* Set whether the DMA transfers are locked to the TFT update cycle. If
* locked, DMA transfer will not begin until the TFT controller has finished
* updating the display. If not locked, DMA transfers will begin as soon as
* possible. Default is true (DMA is locked with TFT).
*/
lockDMAToFrontPorch(true);
}
void TouchGFXGeneratedHAL::configureInterrupts()
{
NVIC_SetPriority(DMA2D_IRQn, 9);
NVIC_SetPriority(LTDC_IRQn, 9);
}
void TouchGFXGeneratedHAL::enableInterrupts()
{
NVIC_EnableIRQ(DMA2D_IRQn);
NVIC_EnableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::disableInterrupts()
{
NVIC_DisableIRQ(DMA2D_IRQn);
NVIC_DisableIRQ(LTDC_IRQn);
}
void TouchGFXGeneratedHAL::enableLCDControllerInterrupt()
{
lcd_int_active_line = (LTDC->BPCR & 0x7FF) - 1;
lcd_int_porch_line = (LTDC->AWCR & 0x7FF) - 1;
/* Sets the Line Interrupt position */
LTDC->LIPCR = lcd_int_active_line;
/* Line Interrupt Enable */
LTDC->IER |= LTDC_IER_LIE;
}
uint16_t* TouchGFXGeneratedHAL::getTFTFrameBuffer() const
{
return (uint16_t*)LTDC_Layer1->CFBAR;
}
void TouchGFXGeneratedHAL::setTFTFrameBuffer(uint16_t* adr)
{
LTDC_Layer1->CFBAR = (uint32_t)adr;
/* Reload immediate */
LTDC->SRCR = (uint32_t)LTDC_SRCR_IMR;
}
void TouchGFXGeneratedHAL::flushFrameBuffer(const touchgfx::Rect& rect)
{
HAL::flushFrameBuffer(rect);
}
uint16_t TouchGFXGeneratedHAL::getTFTCurrentLine()
{
// This function only requires an implementation if single buffering
// on LTDC display is being used (REFRESH_STRATEGY_OPTIM_SINGLE_BUFFER_TFT_CTRL).
// The CPSR register (bits 15:0) specify current line of TFT controller.
uint16_t curr = (uint16_t)(LTDC->CPSR & 0xffff);
uint16_t backPorchY = (uint16_t)(LTDC->BPCR & 0x7FF) + 1;
// The semantics of the getTFTCurrentLine() function is to return a value
// in the range of 0-totalheight. If we are still in back porch area, return 0.
if (curr < backPorchY)
{
return 0;
}
else
{
return curr - backPorchY;
}
}
extern "C"
{
void HAL_LTDC_LineEventCallback(LTDC_HandleTypeDef *hltdc)
{
if (LTDC->LIPCR == lcd_int_active_line)
{
//entering active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_porch_line);
HAL::getInstance()->vSync();
OSWrappers::signalVSync();
// Swap frame buffers immediately instead of waiting for the task to be scheduled in.
// Note: task will also swap when it wakes up, but that operation is guarded and will not have
// any effect if already swapped.
HAL::getInstance()->swapFrameBuffers();
GPIO::set(GPIO::VSYNC_FREQ);
}
else
{
//exiting active area
HAL_LTDC_ProgramLineEvent(hltdc, lcd_int_active_line);
GPIO::clear(GPIO::VSYNC_FREQ);
HAL::getInstance()->frontPorchEntered();
}
}
}
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| [
"thanhtrungqn93@gmail.com"
] | thanhtrungqn93@gmail.com |
ac0efcdff0bddc9150f24e9c898ca1e241a237e3 | 45ac6a3e22f3258b051b9519aaedede0d955b1ff | /AmongUs/source/player.cpp | 25bbe266c07ea2f88cb6d532b4efe7e124caea51 | [] | no_license | meghna-mishra/AmongUs | 44571d8a2290eb9a45b2d98f0ca18afcd295225f | cfff8f25295637044f4fc6b76175c5095e085cf0 | refs/heads/main | 2023-05-08T13:45:33.135516 | 2021-05-27T06:30:43 | 2021-05-27T06:30:43 | 371,266,229 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,923 | cpp | #include "player.h"
#include "main.h"
Player::Player(float x, float y, color_t color) {
this->position = glm::vec3(x, y, 0);
this->rotation = 0;
speed = 1;
static const GLfloat vertex_buffer_data[5][18] = {
{0.15, -0.15, 0,
0.35, -0.15, 0,
0.35, -0.35, 0,
0.15, -0.15, 0,
0.15, -0.35, 0,
0.35, -0.35, 0},
{0.22, -0.35, 0,
0.18, -0.35, 0,
0.22, -0.38, 0,
0.22, -0.38, 0,
0.18, -0.35, 0,
0.18, -0.38, 0},
{0.28, -0.35, 0,
0.32, -0.35, 0,
0.28, -0.38, 0,
0.28, -0.38, 0,
0.32, -0.35, 0,
0.32, -0.38, 0},
{0.20, -0.12, 0,
0.30, -0.12, 0,
0.20, -0.18, 0,
0.30, -0.12, 0,
0.20, -0.18, 0,
0.30, -0.18, 0}
};
color_t colarr[] = {COLOR_GREEN, COLOR_GREEN, COLOR_GREEN, COLOR_BLACK};
for(int i = 0; i < 4; i++){
//std::cout << i << "\n";
this->object[i] = create3DObject(GL_TRIANGLES, 2*3, vertex_buffer_data[i], colarr[i], GL_FILL);
}
}
void Player::draw(glm::mat4 VP) {
Matrices.model = glm::mat4(1.0f);
glm::mat4 translate = glm::translate (this->position); // glTranslatef
glm::mat4 rotate = glm::rotate((float) (this->rotation * M_PI / 180.0f), glm::vec3(1, 0, 0));
// No need as coords centered at 0, 0, 0 of cube arouund which we waant to rotate
// rotate = rotate * glm::translate(glm::vec3(0, -0.6, 0));
Matrices.model *= (translate * rotate);
glm::mat4 MVP = VP * Matrices.model;
glUniformMatrix4fv(Matrices.MatrixID, 1, GL_FALSE, &MVP[0][0]);
for(int i=0; i<4; i++){
draw3DObject(this->object[i]);
}
}
void Player::set_position(float x, float y) {
this->position = glm::vec3(x, y, 0);
}
void Player::tick() {
this->rotation += speed;
// this->position.x -= speed;
// this->position.y -= speed;
}
| [
"meghna.mishra@research.iiit.ac.in"
] | meghna.mishra@research.iiit.ac.in |
4b3e5d4b9279af0d739fee89bdb7a7a112aded36 | 5bfcd0c40509ed4f4251e5d286aa010e0a04243f | /3rdParty/Raknet/include/EmailSender.cpp | 50ade1343b92e56266fd4196967b763305c2fb86 | [] | no_license | CedricGuillemet/theRush | 28b912d8c90f8c7b67c7c0c3e55512ab9bb7df0c | bf1a85200f236d8eff672fb701b213a4ea24424c | refs/heads/master | 2021-09-06T09:07:56.188895 | 2018-02-04T19:06:26 | 2018-02-04T19:06:26 | 120,213,513 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 10,924 | cpp | #include "NativeFeatureIncludes.h"
#if _RAKNET_SUPPORT_EmailSender==1
// Useful sites
// http://www.faqs.org\rfcs\rfc2821.html
// http://www2.rad.com\networks/1995/mime/examples.htm
#include "EmailSender.h"
#include "TCPInterface.h"
#include "GetTime.h"
#include "Rand.h"
#include "FileList.h"
#include "BitStream.h"
#include <stdio.h>
#if defined(_XBOX) || defined(X360)
#endif
#include "RakSleep.h"
using namespace RakNet;
STATIC_FACTORY_DEFINITIONS(EmailSender,EmailSender);
const char *EmailSender::Send(const char *hostAddress, unsigned short hostPort, const char *sender, const char *recipient, const char *senderName, const char *recipientName, const char *subject, const char *body, FileList *attachedFiles, bool doPrintf, const char *password)
{
RakNet::Packet *packet;
char query[1024];
TCPInterface tcpInterface;
SystemAddress emailServer;
if (tcpInterface.Start(0, 0)==false)
return "Unknown error starting TCP";
emailServer=tcpInterface.Connect(hostAddress, hostPort,true);
if (emailServer==UNASSIGNED_SYSTEM_ADDRESS)
return "Failed to connect to host";
#if OPEN_SSL_CLIENT_SUPPORT==1
tcpInterface.StartSSLClient(emailServer);
#endif
RakNet::TimeMS timeoutTime = RakNet::GetTimeMS()+3000;
packet=0;
while (RakNet::GetTimeMS() < timeoutTime)
{
packet = tcpInterface.Receive();
if (packet)
{
if (doPrintf)
RAKNET_DEBUG_PRINTF("%s", packet->data);
break;
}
RakSleep(250);
}
if (packet==0)
return "Timeout while waiting for initial data from server.";
tcpInterface.Send("EHLO\r\n", 6, emailServer,false);
const char *response;
bool authenticate=false;
#ifdef _MSC_VER
#pragma warning(disable:4127) // conditional expression is constant
#endif
while (1)
{
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0 && strcmp(response, "AUTHENTICATE")==0)
{
authenticate=true;
break;
}
// Something other than continue?
if (response!=0 && strcmp(response, "CONTINUE")!=0)
return response;
// Success?
if (response==0)
break;
}
if (authenticate)
{
sprintf(query, "EHLO %s\r\n", sender);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
if (password==0)
return "Password needed";
char *outputData = RakNet::OP_NEW_ARRAY<char >((const int) (strlen(sender)+strlen(password)+2)*3, _FILE_AND_LINE_ );
RakNet::BitStream bs;
char zero=0;
bs.Write(&zero,1);
bs.Write(sender,(const unsigned int)strlen(sender));
//bs.Write("jms1@jms1.net",(const unsigned int)strlen("jms1@jms1.net"));
bs.Write(&zero,1);
bs.Write(password,(const unsigned int)strlen(password));
bs.Write(&zero,1);
//bs.Write("not.my.real.password",(const unsigned int)strlen("not.my.real.password"));
TCPInterface::Base64Encoding((const char*)bs.GetData(), bs.GetNumberOfBytesUsed(), outputData);
sprintf(query, "AUTH PLAIN %s", outputData);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
}
if (sender)
sprintf(query, "MAIL From: <%s>\r\n", sender);
else
sprintf(query, "MAIL From: <>\r\n");
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
if (recipient)
sprintf(query, "RCPT TO: <%s>\r\n", recipient);
else
sprintf(query, "RCPT TO: <>\r\n");
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
tcpInterface.Send("DATA\r\n", (unsigned int)strlen("DATA\r\n"), emailServer,false);
// Wait for 354...
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
if (subject)
{
sprintf(query, "Subject: %s\r\n", subject);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
}
if (senderName)
{
sprintf(query, "From: %s\r\n", senderName);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
}
if (recipientName)
{
sprintf(query, "To: %s\r\n", recipientName);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
}
const int boundarySize=60;
char boundary[boundarySize+1];
int i,j;
if (attachedFiles && attachedFiles->fileList.Size())
{
rakNetRandom.SeedMT((unsigned int) RakNet::GetTimeMS());
// Random multipart message boundary
for (i=0; i < boundarySize; i++)
boundary[i]=TCPInterface::Base64Map()[rakNetRandom.RandomMT()%64];
boundary[boundarySize]=0;
}
sprintf(query, "MIME-version: 1.0\r\n");
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
if (attachedFiles && attachedFiles->fileList.Size())
{
sprintf(query, "Content-type: multipart/mixed; BOUNDARY=\"%s\"\r\n\r\n", boundary);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
sprintf(query, "This is a multi-part message in MIME format.\r\n\r\n--%s\r\n", boundary);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
}
sprintf(query, "Content-Type: text/plain; charset=\"US-ASCII\"\r\n\r\n");
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
// Write the body of the email, doing some lame shitty shit where I have to make periods at the start of a newline have a second period.
char *newBody;
int bodyLength;
bodyLength=(int)strlen(body);
newBody = (char*) rakMalloc_Ex( bodyLength*3, _FILE_AND_LINE_ );
if (bodyLength>0)
newBody[0]=body[0];
for (i=1, j=1; i < bodyLength; i++)
{
// Transform \n . \r \n into \n . . \r \n
if (i < bodyLength-2 &&
body[i-1]=='\n' &&
body[i+0]=='.' &&
body[i+1]=='\r' &&
body[i+2]=='\n')
{
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='\r';
newBody[j++]='\n';
i+=2;
}
// Transform \n . . \r \n into \n . . . \r \n
// Having to process .. is a bug in the mail server - the spec says ONLY \r\n.\r\n should be transformed
else if (i <= bodyLength-3 &&
body[i-1]=='\n' &&
body[i+0]=='.' &&
body[i+1]=='.' &&
body[i+2]=='\r' &&
body[i+3]=='\n')
{
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='\r';
newBody[j++]='\n';
i+=3;
}
// Transform \n . \n into \n . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does)
else if (i < bodyLength-1 &&
body[i-1]=='\n' &&
body[i+0]=='.' &&
body[i+1]=='\n')
{
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='\r';
newBody[j++]='\n';
i+=1;
}
// Transform \n . . \n into \n . . . \r \n (this is a bug in the mail server - the spec says do not count \n alone but it does)
// In fact having to process .. is a bug too - because the spec says ONLY \r\n.\r\n should be transformed
else if (i <= bodyLength-2 &&
body[i-1]=='\n' &&
body[i+0]=='.' &&
body[i+1]=='.' &&
body[i+2]=='\n')
{
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='.';
newBody[j++]='\r';
newBody[j++]='\n';
i+=2;
}
else
newBody[j++]=body[i];
}
newBody[j++]='\r';
newBody[j++]='\n';
tcpInterface.Send(newBody, j, emailServer,false);
rakFree_Ex(newBody, _FILE_AND_LINE_ );
int outputOffset;
// What a pain in the rear. I have to map the binary to printable characters using 6 bits per character.
if (attachedFiles && attachedFiles->fileList.Size())
{
for (i=0; i < (int) attachedFiles->fileList.Size(); i++)
{
// Write boundary
sprintf(query, "\r\n--%s\r\n", boundary);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
sprintf(query, "Content-Type: APPLICATION/Octet-Stream; SizeOnDisk=%i; name=\"%s\"\r\nContent-Transfer-Encoding: BASE64\r\nContent-Description: %s\r\n\r\n", attachedFiles->fileList[i].dataLengthBytes, attachedFiles->fileList[i].filename.C_String(), attachedFiles->fileList[i].filename.C_String());
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
newBody = (char*) rakMalloc_Ex( (size_t) (attachedFiles->fileList[i].dataLengthBytes*3)/2, _FILE_AND_LINE_ );
outputOffset=TCPInterface::Base64Encoding(attachedFiles->fileList[i].data, (int) attachedFiles->fileList[i].dataLengthBytes, newBody);
// Send the base64 mapped file.
tcpInterface.Send(newBody, outputOffset, emailServer,false);
rakFree_Ex(newBody, _FILE_AND_LINE_ );
}
// Write last boundary
sprintf(query, "\r\n--%s--\r\n", boundary);
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
}
sprintf(query, "\r\n.\r\n");
tcpInterface.Send(query, (unsigned int)strlen(query), emailServer,false);
response=GetResponse(&tcpInterface, emailServer, doPrintf);
if (response!=0)
return response;
tcpInterface.Send("QUIT\r\n", (unsigned int)strlen("QUIT\r\n"), emailServer,false);
RakSleep(30);
if (doPrintf)
{
packet = tcpInterface.Receive();
while (packet)
{
RAKNET_DEBUG_PRINTF("%s", packet->data);
packet = tcpInterface.Receive();
}
}
tcpInterface.Stop();
return 0; // Success
}
const char *EmailSender::GetResponse(TCPInterface *tcpInterface, const SystemAddress &emailServer, bool doPrintf)
{
RakNet::Packet *packet;
RakNet::TimeMS timeout;
timeout=RakNet::GetTimeMS()+5000;
#ifdef _MSC_VER
#pragma warning( disable : 4127 ) // warning C4127: conditional expression is constant
#endif
while (1)
{
if (tcpInterface->HasLostConnection()==emailServer)
return "Connection to server lost.";
packet = tcpInterface->Receive();
if (packet)
{
if (doPrintf)
{
RAKNET_DEBUG_PRINTF("%s", packet->data);
}
#if OPEN_SSL_CLIENT_SUPPORT==1
if (strstr((const char*)packet->data, "220"))
{
tcpInterface->StartSSLClient(packet->systemAddress);
return "AUTHENTICATE"; // OK
}
// if (strstr((const char*)packet->data, "250-AUTH LOGIN PLAIN"))
// {
// tcpInterface->StartSSLClient(packet->systemAddress);
// return "AUTHENTICATE"; // OK
// }
#endif
if (strstr((const char*)packet->data, "235"))
return 0; // Authentication accepted
if (strstr((const char*)packet->data, "354"))
return 0; // Go ahead
#if OPEN_SSL_CLIENT_SUPPORT==1
if (strstr((const char*)packet->data, "250-STARTTLS"))
{
tcpInterface->Send("STARTTLS\r\n", (unsigned int) strlen("STARTTLS\r\n"), packet->systemAddress, false);
return "CONTINUE";
}
#endif
if (strstr((const char*)packet->data, "250"))
return 0; // OK
if (strstr((const char*)packet->data, "550"))
return "Failed on error code 550";
if (strstr((const char*)packet->data, "553"))
return "Failed on error code 553";
}
if (RakNet::GetTimeMS() > timeout)
return "Timed out";
RakSleep(100);
}
}
#endif // _RAKNET_SUPPORT_*
| [
"cedric.guillemet@gmail.com"
] | cedric.guillemet@gmail.com |
d6c05c5570e54c7a1ef28c50b5f1d1ce16352d51 | e991bcfb47226ecb9e843137b366dbeec367ae50 | /chrome/browser/chromeos/crosapi/test_mojo_connection_manager_unittest.cc | a346ba42701ab321d702324dcca205530e363056 | [
"BSD-3-Clause"
] | permissive | hdwdsj/chromium-1 | 61d4756c7eb0d82a7eac454c549eb5703fcd42c7 | 67e55c4d99283c8ce4f626ac450007f6ecdc4128 | refs/heads/master | 2023-01-03T22:13:22.189772 | 2020-10-27T02:59:16 | 2020-10-27T02:59:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,513 | cc | // Copyright 2020 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/crosapi/test_mojo_connection_manager.h"
#include <fcntl.h>
#include "base/bind.h"
#include "base/command_line.h"
#include "base/files/file_path.h"
#include "base/files/file_path_watcher.h"
#include "base/files/scoped_file.h"
#include "base/files/scoped_temp_dir.h"
#include "base/process/launch.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/thread_pool.h"
#include "base/test/bind_test_util.h"
#include "base/test/multiprocess_test.h"
#include "base/test/task_environment.h"
#include "base/test/test_timeouts.h"
#include "chrome/test/base/scoped_testing_local_state.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chromeos/crosapi/mojom/crosapi.mojom.h"
#include "mojo/public/cpp/platform/named_platform_channel.h"
#include "mojo/public/cpp/platform/platform_channel.h"
#include "mojo/public/cpp/platform/socket_utils_posix.h"
#include "mojo/public/cpp/system/invitation.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/multiprocess_func_list.h"
namespace crosapi {
class TestLacrosChromeService : public crosapi::mojom::LacrosChromeService {
public:
TestLacrosChromeService(
mojo::PendingReceiver<mojom::LacrosChromeService> receiver,
base::RunLoop& run_loop)
: receiver_(this, std::move(receiver)), run_loop_(run_loop) {}
~TestLacrosChromeService() override = default;
void Init(crosapi::mojom::LacrosInitParamsPtr params) override {
init_is_called_ = true;
}
void RequestAshChromeServiceReceiver(
RequestAshChromeServiceReceiverCallback callback) override {
EXPECT_TRUE(init_is_called_);
std::move(callback).Run(ash_chrome_service_.BindNewPipeAndPassReceiver());
request_ash_chrome_service_is_called_ = true;
run_loop_.Quit();
}
void NewWindow(NewWindowCallback callback) override {}
void GetFeedbackData(GetFeedbackDataCallback callback) override {}
bool init_is_called() { return init_is_called_; }
bool request_ash_chrome_service_is_called() {
return request_ash_chrome_service_is_called_;
}
private:
mojo::Receiver<mojom::LacrosChromeService> receiver_;
bool init_is_called_ = false;
bool request_ash_chrome_service_is_called_ = false;
base::RunLoop& run_loop_;
mojo::Remote<crosapi::mojom::AshChromeService> ash_chrome_service_;
};
using TestMojoConnectionManagerTest = testing::Test;
TEST_F(TestMojoConnectionManagerTest, ConnectWithLacrosChrome) {
// Constructing LacrosInitParams requires local state prefs.
ScopedTestingLocalState local_state(TestingBrowserProcess::GetGlobal());
// Create temp dir before task environment, just in case lingering tasks need
// to access it.
base::ScopedTempDir temp_dir;
ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
// Use IO type to support the FileDescriptorWatcher API on POSIX.
base::test::TaskEnvironment task_environment{
base::test::TaskEnvironment::MainThreadType::IO};
// Ash-chrome queues an invitation, drop a socket and wait for connection.
std::string socket_path =
temp_dir.GetPath().MaybeAsASCII() + "/lacros.socket";
// Sets up watcher to Wait for the socket to be created by
// |TestMojoConnectionManager| before attempting to connect. There is no
// garanteen that |OnTestingSocketCreated| has run after the run loop is done,
// so this test should NOT depend on the assumption.
base::FilePathWatcher watcher;
base::RunLoop run_loop1;
watcher.Watch(base::FilePath(socket_path), false,
base::BindRepeating(base::BindLambdaForTesting(
[&run_loop1](const base::FilePath& path, bool error) {
EXPECT_FALSE(error);
run_loop1.Quit();
})));
TestMojoConnectionManager test_mojo_connection_manager{
base::FilePath(socket_path)};
run_loop1.Run();
// Test connects with ash-chrome via the socket.
auto channel = mojo::NamedPlatformChannel::ConnectToServer(socket_path);
ASSERT_TRUE(channel.is_valid());
base::ScopedFD socket_fd = channel.TakePlatformHandle().TakeFD();
uint8_t buf[32];
std::vector<base::ScopedFD> descriptors;
ssize_t size;
base::RunLoop run_loop2;
base::ThreadPool::PostTaskAndReply(
FROM_HERE, {base::MayBlock()},
base::BindOnce(base::BindLambdaForTesting([&]() {
// Mark the channel as blocking.
int flags = fcntl(socket_fd.get(), F_GETFL);
PCHECK(flags != -1);
fcntl(socket_fd.get(), F_SETFL, flags & ~O_NONBLOCK);
size = mojo::SocketRecvmsg(socket_fd.get(), buf, sizeof(buf),
&descriptors, true /*block*/);
})),
run_loop2.QuitClosure());
run_loop2.Run();
EXPECT_EQ(1, size);
EXPECT_EQ(0u, buf[0]);
ASSERT_EQ(1u, descriptors.size());
// Test launches lacros-chrome as child process.
base::LaunchOptions options;
options.fds_to_remap.emplace_back(descriptors[0].get(), descriptors[0].get());
base::CommandLine lacros_cmd(base::GetMultiProcessTestChildBaseCommandLine());
lacros_cmd.AppendSwitchASCII(mojo::PlatformChannel::kHandleSwitch,
base::NumberToString(descriptors[0].release()));
base::Process lacros_process =
base::SpawnMultiProcessTestChild("LacrosMain", lacros_cmd, options);
// lacros-chrome accepts the invitation to establish mojo connection with
// ash-chrome.
int rv = -1;
ASSERT_TRUE(base::WaitForMultiprocessTestChildExit(
lacros_process, TestTimeouts::action_timeout(), &rv));
lacros_process.Close();
EXPECT_EQ(0, rv);
}
// Another process that emulates the behavior of lacros-chrome.
MULTIPROCESS_TEST_MAIN(LacrosMain) {
base::test::SingleThreadTaskEnvironment task_environment;
mojo::IncomingInvitation invitation = mojo::IncomingInvitation::Accept(
mojo::PlatformChannel::RecoverPassedEndpointFromCommandLine(
*base::CommandLine::ForCurrentProcess()));
base::RunLoop run_loop;
TestLacrosChromeService test_lacros_chrome_service(
mojo::PendingReceiver<crosapi::mojom::LacrosChromeService>(
invitation.ExtractMessagePipe(0)),
run_loop);
run_loop.Run();
DCHECK(test_lacros_chrome_service.init_is_called());
DCHECK(test_lacros_chrome_service.request_ash_chrome_service_is_called());
return 0;
}
} // namespace crosapi
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
b2307f29e7f4adf388b126146179dc12418a9a2c | 8567438779e6af0754620a25d379c348e4cd5a5d | /gpu/command_buffer/tests/gl_unittest.cc | cd9373e2ce00666ee6f1c3b5d7320f9998c45df5 | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 5,136 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <GLES2/gl2.h>
#include <GLES2/gl2ext.h>
#include <stdint.h>
#include <memory>
#include "gpu/command_buffer/service/feature_info.h"
#include "gpu/command_buffer/tests/gl_manager.h"
#include "gpu/command_buffer/tests/gl_test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace gpu {
class GLTest : public testing::Test {
protected:
void SetUp() override { gl_.Initialize(GLManager::Options()); }
void TearDown() override { gl_.Destroy(); }
GLManager gl_;
};
// Test that GL is at least minimally working.
TEST_F(GLTest, Basic) {
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
uint8_t expected[] = {
0, 255, 0, 255,
};
EXPECT_TRUE(GLTestHelper::CheckPixels(0, 0, 1, 1, 0, expected, nullptr));
GLTestHelper::CheckGLError("no errors", __LINE__);
}
TEST_F(GLTest, BasicFBO) {
GLuint tex = 0;
glGenTextures(1, &tex);
GLuint fbo = 0;
glGenFramebuffers(1, &fbo);
glBindTexture(GL_TEXTURE_2D, tex);
std::unique_ptr<uint8_t[]> pixels(new uint8_t[16 * 16 * 4]);
memset(pixels.get(), 0, 16*16*4);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 16, 16, 0, GL_RGBA, GL_UNSIGNED_BYTE,
pixels.get());
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D,
tex, 0);
EXPECT_EQ(static_cast<GLenum>(GL_FRAMEBUFFER_COMPLETE),
glCheckFramebufferStatus(GL_FRAMEBUFFER));
glClearColor(0.0f, 1.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);
uint8_t expected[] = {
0, 255, 0, 255,
};
EXPECT_TRUE(GLTestHelper::CheckPixels(0, 0, 16, 16, 0, expected, nullptr));
glDeleteFramebuffers(1, &fbo);
glDeleteTextures(1, &tex);
GLTestHelper::CheckGLError("no errors", __LINE__);
}
TEST_F(GLTest, SimpleShader) {
static const char* v_shader_str =
"attribute vec4 a_Position;\n"
"void main()\n"
"{\n"
" gl_Position = a_Position;\n"
"}\n";
static const char* f_shader_str =
"precision mediump float;\n"
"void main()\n"
"{\n"
" gl_FragColor = vec4(0.0, 1.0, 0.0, 1.0);\n"
"}\n";
GLuint program = GLTestHelper::LoadProgram(v_shader_str, f_shader_str);
glUseProgram(program);
GLuint position_loc = glGetAttribLocation(program, "a_Position");
GLTestHelper::SetupUnitQuad(position_loc);
uint8_t expected_clear[] = {
127, 0, 255, 0,
};
glClearColor(0.5f, 0.0f, 1.0f, 0.0f);
glClear(GL_COLOR_BUFFER_BIT);
EXPECT_TRUE(
GLTestHelper::CheckPixels(0, 0, 1, 1, 1, expected_clear, nullptr));
uint8_t expected_draw[] = {
0, 255, 0, 255,
};
glDrawArrays(GL_TRIANGLES, 0, 6);
EXPECT_TRUE(GLTestHelper::CheckPixels(0, 0, 1, 1, 0, expected_draw, nullptr));
}
TEST_F(GLTest, FeatureFlagsMatchCapabilities) {
scoped_refptr<gles2::FeatureInfo> features =
new gles2::FeatureInfo(gl_.workarounds());
EXPECT_TRUE(features->InitializeForTesting());
const auto& caps = gl_.GetCapabilities();
const auto& flags = features->feature_flags();
EXPECT_EQ(caps.egl_image_external, flags.oes_egl_image_external);
EXPECT_EQ(caps.texture_format_bgra8888, flags.ext_texture_format_bgra8888);
EXPECT_EQ(caps.texture_format_etc1, flags.oes_compressed_etc1_rgb8_texture);
EXPECT_EQ(caps.texture_rectangle, flags.arb_texture_rectangle);
EXPECT_EQ(caps.texture_usage, flags.angle_texture_usage);
EXPECT_EQ(caps.texture_storage, flags.ext_texture_storage);
EXPECT_EQ(caps.discard_framebuffer, flags.ext_discard_framebuffer);
EXPECT_EQ(caps.sync_query, flags.chromium_sync_query);
EXPECT_EQ(caps.blend_equation_advanced, flags.blend_equation_advanced);
EXPECT_EQ(caps.blend_equation_advanced_coherent,
flags.blend_equation_advanced_coherent);
EXPECT_EQ(caps.texture_rg, flags.ext_texture_rg);
EXPECT_EQ(caps.image_ycbcr_422, flags.chromium_image_ycbcr_422);
EXPECT_EQ(caps.image_ycbcr_420v, flags.chromium_image_ycbcr_420v);
EXPECT_EQ(caps.render_buffer_format_bgra8888,
flags.ext_render_buffer_format_bgra8888);
EXPECT_EQ(caps.occlusion_query_boolean, flags.occlusion_query_boolean);
}
TEST_F(GLTest, GetString) {
EXPECT_STREQ(
"OpenGL ES 2.0 Chromium",
reinterpret_cast<const char*>(glGetString(GL_VERSION)));
EXPECT_STREQ(
"OpenGL ES GLSL ES 1.0 Chromium",
reinterpret_cast<const char*>(glGetString(GL_SHADING_LANGUAGE_VERSION)));
EXPECT_STREQ(
"Chromium",
reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
EXPECT_STREQ(
"Chromium",
reinterpret_cast<const char*>(glGetString(GL_VENDOR)));
}
} // namespace gpu
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
980414866d02beae6dc9f3b04e7cf86b3e0da376 | 87d6f902fedf4437d73606094815d4738295a700 | /L1-Ejercicios/Ejercicio20-Switch/switch.cpp | 0c1e13f7f00a542ccfae00f8ac1990823f7fb845 | [
"MIT"
] | permissive | thaniay/cpp | 8269e8aeb22f1f245e22e34bc7a4b78d33241d52 | 6fda71364d68340884be12ba6d8b5d746e206acb | refs/heads/master | 2022-12-23T00:51:19.605110 | 2020-10-05T03:04:32 | 2020-10-05T03:04:32 | 276,259,289 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 543 | cpp | #include <iostream>
using namespace std;
int main(int argc, char const *argv[])
{
int opcion;
cout << "Ingrese una opcion:";
cin>> opcion;
switch (opcion)
{
case 1:
{
cout <<"Escogistes 1" << endl;
cout <<"Segunda linea opcion 1" << endl;
break;
}
case 2:
cout <<"Escogistes 2" << endl;
break;
case 3:
cout <<"Escogistes 3" << endl;
break;
default:
cout <<"Ingrese una opcion entre 1 y 3" << endl;
break;
}
return 0;
}
| [
"yorelyyanezguevara@gmail.com"
] | yorelyyanezguevara@gmail.com |
a2a26d4422d6c08f5d8052900d7b738afee780fa | 8567438779e6af0754620a25d379c348e4cd5a5d | /components/sessions/core/session_service_commands.cc | d066372deaa837d96429fe52a5c52c4d523599aa | [
"BSD-3-Clause"
] | permissive | thngkaiyuan/chromium | c389ac4b50ccba28ee077cbf6115c41b547955ae | dab56a4a71f87f64ecc0044e97b4a8f247787a68 | refs/heads/master | 2022-11-10T02:50:29.326119 | 2017-04-08T12:28:57 | 2017-04-08T12:28:57 | 84,073,924 | 0 | 1 | BSD-3-Clause | 2022-10-25T19:47:15 | 2017-03-06T13:04:15 | null | UTF-8 | C++ | false | false | 33,548 | cc | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/sessions/core/session_service_commands.h"
#include <stdint.h>
#include <string.h>
#include <utility>
#include <vector>
#include "base/memory/ptr_util.h"
#include "base/pickle.h"
#include "components/sessions/core/base_session_service_commands.h"
#include "components/sessions/core/base_session_service_delegate.h"
#include "components/sessions/core/session_command.h"
#include "components/sessions/core/session_types.h"
namespace sessions {
// Identifier for commands written to file.
static const SessionCommand::id_type kCommandSetTabWindow = 0;
// OBSOLETE Superseded by kCommandSetWindowBounds3.
// static const SessionCommand::id_type kCommandSetWindowBounds = 1;
static const SessionCommand::id_type kCommandSetTabIndexInWindow = 2;
static const SessionCommand::id_type
kCommandTabNavigationPathPrunedFromBack = 5;
static const SessionCommand::id_type kCommandUpdateTabNavigation = 6;
static const SessionCommand::id_type kCommandSetSelectedNavigationIndex = 7;
static const SessionCommand::id_type kCommandSetSelectedTabInIndex = 8;
static const SessionCommand::id_type kCommandSetWindowType = 9;
// OBSOLETE Superseded by kCommandSetWindowBounds3. Except for data migration.
// static const SessionCommand::id_type kCommandSetWindowBounds2 = 10;
static const SessionCommand::id_type
kCommandTabNavigationPathPrunedFromFront = 11;
static const SessionCommand::id_type kCommandSetPinnedState = 12;
static const SessionCommand::id_type kCommandSetExtensionAppID = 13;
static const SessionCommand::id_type kCommandSetWindowBounds3 = 14;
static const SessionCommand::id_type kCommandSetWindowAppName = 15;
static const SessionCommand::id_type kCommandTabClosed = 16;
static const SessionCommand::id_type kCommandWindowClosed = 17;
static const SessionCommand::id_type kCommandSetTabUserAgentOverride = 18;
static const SessionCommand::id_type kCommandSessionStorageAssociated = 19;
static const SessionCommand::id_type kCommandSetActiveWindow = 20;
static const SessionCommand::id_type kCommandLastActiveTime = 21;
// OBSOLETE Superseded by kCommandSetWindowWorkspace2.
// static const SessionCommand::id_type kCommandSetWindowWorkspace = 22;
static const SessionCommand::id_type kCommandSetWindowWorkspace2 = 23;
namespace {
// Various payload structures.
struct ClosedPayload {
SessionID::id_type id;
int64_t close_time;
};
struct WindowBoundsPayload2 {
SessionID::id_type window_id;
int32_t x;
int32_t y;
int32_t w;
int32_t h;
bool is_maximized;
};
struct WindowBoundsPayload3 {
SessionID::id_type window_id;
int32_t x;
int32_t y;
int32_t w;
int32_t h;
int32_t show_state;
};
using ActiveWindowPayload = SessionID::id_type;
struct IDAndIndexPayload {
SessionID::id_type id;
int32_t index;
};
using TabIndexInWindowPayload = IDAndIndexPayload;
using TabNavigationPathPrunedFromBackPayload = IDAndIndexPayload;
using SelectedNavigationIndexPayload = IDAndIndexPayload;
using SelectedTabInIndexPayload = IDAndIndexPayload;
using WindowTypePayload = IDAndIndexPayload;
using TabNavigationPathPrunedFromFrontPayload = IDAndIndexPayload;
struct PinnedStatePayload {
SessionID::id_type tab_id;
bool pinned_state;
};
struct LastActiveTimePayload {
SessionID::id_type tab_id;
int64_t last_active_time;
};
// Persisted versions of ui::WindowShowState that are written to disk and can
// never change.
enum PersistedWindowShowState {
// SHOW_STATE_DEFAULT (0) never persisted.
PERSISTED_SHOW_STATE_NORMAL = 1,
PERSISTED_SHOW_STATE_MINIMIZED = 2,
PERSISTED_SHOW_STATE_MAXIMIZED = 3,
// SHOW_STATE_INACTIVE (4) never persisted.
PERSISTED_SHOW_STATE_FULLSCREEN = 5,
PERSISTED_SHOW_STATE_DETACHED_DEPRECATED = 6,
PERSISTED_SHOW_STATE_DOCKED_DEPRECATED = 7,
PERSISTED_SHOW_STATE_END = 7
};
using IdToSessionTab =
std::map<SessionID::id_type, std::unique_ptr<SessionTab>>;
using IdToSessionWindow =
std::map<SessionID::id_type, std::unique_ptr<SessionWindow>>;
// Assert to ensure PersistedWindowShowState is updated if ui::WindowShowState
// is changed.
static_assert(ui::SHOW_STATE_END ==
static_cast<ui::WindowShowState>(PERSISTED_SHOW_STATE_END),
"SHOW_STATE_END must equal PERSISTED_SHOW_STATE_END");
// Returns the show state to store to disk based |state|.
PersistedWindowShowState ShowStateToPersistedShowState(
ui::WindowShowState state) {
switch (state) {
case ui::SHOW_STATE_NORMAL:
return PERSISTED_SHOW_STATE_NORMAL;
case ui::SHOW_STATE_MINIMIZED:
return PERSISTED_SHOW_STATE_MINIMIZED;
case ui::SHOW_STATE_MAXIMIZED:
return PERSISTED_SHOW_STATE_MAXIMIZED;
case ui::SHOW_STATE_FULLSCREEN:
return PERSISTED_SHOW_STATE_FULLSCREEN;
// TODO(afakhry): Remove Docked Windows in M58.
case ui::SHOW_STATE_DOCKED:
return PERSISTED_SHOW_STATE_DOCKED_DEPRECATED;
case ui::SHOW_STATE_DEFAULT:
case ui::SHOW_STATE_INACTIVE:
return PERSISTED_SHOW_STATE_NORMAL;
case ui::SHOW_STATE_END:
break;
}
NOTREACHED();
return PERSISTED_SHOW_STATE_NORMAL;
}
// Lints show state values when read back from persited disk.
ui::WindowShowState PersistedShowStateToShowState(int state) {
switch (state) {
case PERSISTED_SHOW_STATE_NORMAL:
return ui::SHOW_STATE_NORMAL;
case PERSISTED_SHOW_STATE_MINIMIZED:
return ui::SHOW_STATE_MINIMIZED;
case PERSISTED_SHOW_STATE_MAXIMIZED:
return ui::SHOW_STATE_MAXIMIZED;
case PERSISTED_SHOW_STATE_FULLSCREEN:
return ui::SHOW_STATE_FULLSCREEN;
case PERSISTED_SHOW_STATE_DOCKED_DEPRECATED:
return ui::SHOW_STATE_DOCKED;
case PERSISTED_SHOW_STATE_DETACHED_DEPRECATED:
return ui::SHOW_STATE_NORMAL;
}
NOTREACHED();
return ui::SHOW_STATE_NORMAL;
}
// Iterates through the vector updating the selected_tab_index of each
// SessionWindow based on the actual tabs that were restored.
void UpdateSelectedTabIndex(
std::vector<std::unique_ptr<SessionWindow>>* windows) {
for (auto& window : *windows) {
// See note in SessionWindow as to why we do this.
int new_index = 0;
for (auto j = window->tabs.begin(); j != window->tabs.end(); ++j) {
if ((*j)->tab_visual_index == window->selected_tab_index) {
new_index = static_cast<int>(j - window->tabs.begin());
break;
}
}
window->selected_tab_index = new_index;
}
}
// Returns the window in windows with the specified id. If a window does
// not exist, one is created.
SessionWindow* GetWindow(SessionID::id_type window_id,
IdToSessionWindow* windows) {
auto i = windows->find(window_id);
if (i == windows->end()) {
SessionWindow* window = new SessionWindow();
window->window_id.set_id(window_id);
(*windows)[window_id] = base::WrapUnique(window);
return window;
}
return i->second.get();
}
// Returns the tab with the specified id in tabs. If a tab does not exist,
// it is created.
SessionTab* GetTab(SessionID::id_type tab_id, IdToSessionTab* tabs) {
DCHECK(tabs);
auto i = tabs->find(tab_id);
if (i == tabs->end()) {
SessionTab* tab = new SessionTab();
tab->tab_id.set_id(tab_id);
(*tabs)[tab_id] = base::WrapUnique(tab);
return tab;
}
return i->second.get();
}
// Returns an iterator into navigations pointing to the navigation whose
// index matches |index|. If no navigation index matches |index|, the first
// navigation with an index > |index| is returned.
//
// This assumes the navigations are ordered by index in ascending order.
std::vector<sessions::SerializedNavigationEntry>::iterator
FindClosestNavigationWithIndex(
std::vector<sessions::SerializedNavigationEntry>* navigations,
int index) {
DCHECK(navigations);
for (auto i = navigations->begin(); i != navigations->end(); ++i) {
if (i->index() >= index)
return i;
}
return navigations->end();
}
// Function used in sorting windows. Sorting is done based on window id. As
// window ids increment for each new window, this effectively sorts by creation
// time.
static bool WindowOrderSortFunction(const std::unique_ptr<SessionWindow>& w1,
const std::unique_ptr<SessionWindow>& w2) {
return w1->window_id.id() < w2->window_id.id();
}
// Compares the two tabs based on visual index.
static bool TabVisualIndexSortFunction(const std::unique_ptr<SessionTab>& t1,
const std::unique_ptr<SessionTab>& t2) {
const int delta = t1->tab_visual_index - t2->tab_visual_index;
return delta == 0 ? (t1->tab_id.id() < t2->tab_id.id()) : (delta < 0);
}
// Does the following:
// . Deletes and removes any windows with no tabs. NOTE: constrained windows
// that have been dragged out are of type browser. As such, this preserves any
// dragged out constrained windows (aka popups that have been dragged out).
// . Sorts the tabs in windows with valid tabs based on the tabs;
// visual order, and adds the valid windows to |valid_windows|.
void SortTabsBasedOnVisualOrderAndClear(
IdToSessionWindow* windows,
std::vector<std::unique_ptr<SessionWindow>>* valid_windows) {
for (auto& window_pair : *windows) {
std::unique_ptr<SessionWindow> window = std::move(window_pair.second);
if (window->tabs.empty() || window->is_constrained) {
continue;
} else {
// Valid window; sort the tabs and add it to the list of valid windows.
std::sort(window->tabs.begin(), window->tabs.end(),
&TabVisualIndexSortFunction);
// Add the window such that older windows appear first.
if (valid_windows->empty()) {
valid_windows->push_back(std::move(window));
} else {
valid_windows->insert(
std::upper_bound(valid_windows->begin(), valid_windows->end(),
window, &WindowOrderSortFunction),
std::move(window));
}
}
}
// There are no more pointers left in |window|, just empty husks from the
// move, so clear it out.
windows->clear();
}
// Adds tabs to their parent window based on the tab's window_id. This
// ignores tabs with no navigations.
void AddTabsToWindows(IdToSessionTab* tabs, IdToSessionWindow* windows) {
DVLOG(1) << "AddTabsToWindows";
DVLOG(1) << "Tabs " << tabs->size() << ", windows " << windows->size();
for (auto& tab_pair : *tabs) {
std::unique_ptr<SessionTab> tab = std::move(tab_pair.second);
if (!tab->window_id.id() || tab->navigations.empty())
continue;
SessionTab* tab_ptr = tab.get();
SessionWindow* window = GetWindow(tab_ptr->window_id.id(), windows);
window->tabs.push_back(std::move(tab));
// See note in SessionTab as to why we do this.
auto j = FindClosestNavigationWithIndex(&tab_ptr->navigations,
tab_ptr->current_navigation_index);
if (j == tab_ptr->navigations.end()) {
tab_ptr->current_navigation_index =
static_cast<int>(tab_ptr->navigations.size() - 1);
} else {
tab_ptr->current_navigation_index =
static_cast<int>(j - tab_ptr->navigations.begin());
}
}
// There are no more pointers left in |tabs|, just empty husks from the
// move, so clear it out.
tabs->clear();
}
// Creates tabs and windows from the commands specified in |data|. The created
// tabs and windows are added to |tabs| and |windows| respectively, with the
// id of the active window set in |active_window_id|. It is up to the caller
// to delete the tabs and windows added to |tabs| and |windows|.
//
// This does NOT add any created SessionTabs to SessionWindow.tabs, that is
// done by AddTabsToWindows.
bool CreateTabsAndWindows(
const std::vector<std::unique_ptr<SessionCommand>>& data,
IdToSessionTab* tabs,
IdToSessionWindow* windows,
SessionID::id_type* active_window_id) {
// If the file is corrupt (command with wrong size, or unknown command), we
// still return true and attempt to restore what we we can.
DVLOG(1) << "CreateTabsAndWindows";
for (const auto& command_ptr : data) {
const SessionCommand::id_type kCommandSetWindowBounds2 = 10;
const SessionCommand* command = command_ptr.get();
DVLOG(1) << "Read command " << (int) command->id();
switch (command->id()) {
case kCommandSetTabWindow: {
SessionID::id_type payload[2];
if (!command->GetPayload(payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetTab(payload[1], tabs)->window_id.set_id(payload[0]);
break;
}
// This is here for forward migration only. New data is saved with
// |kCommandSetWindowBounds3|.
case kCommandSetWindowBounds2: {
WindowBoundsPayload2 payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
GetWindow(payload.window_id, windows)->show_state =
payload.is_maximized ?
ui::SHOW_STATE_MAXIMIZED : ui::SHOW_STATE_NORMAL;
break;
}
case kCommandSetWindowBounds3: {
WindowBoundsPayload3 payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetWindow(payload.window_id, windows)->bounds.SetRect(payload.x,
payload.y,
payload.w,
payload.h);
GetWindow(payload.window_id, windows)->show_state =
PersistedShowStateToShowState(payload.show_state);
break;
}
case kCommandSetTabIndexInWindow: {
TabIndexInWindowPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetTab(payload.id, tabs)->tab_visual_index = payload.index;
break;
}
case kCommandTabClosed:
case kCommandWindowClosed: {
ClosedPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
if (command->id() == kCommandTabClosed)
tabs->erase(payload.id);
else
windows->erase(payload.id);
break;
}
case kCommandTabNavigationPathPrunedFromBack: {
TabNavigationPathPrunedFromBackPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
SessionTab* tab = GetTab(payload.id, tabs);
tab->navigations.erase(
FindClosestNavigationWithIndex(&(tab->navigations), payload.index),
tab->navigations.end());
break;
}
case kCommandTabNavigationPathPrunedFromFront: {
TabNavigationPathPrunedFromFrontPayload payload;
if (!command->GetPayload(&payload, sizeof(payload)) ||
payload.index <= 0) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
SessionTab* tab = GetTab(payload.id, tabs);
// Update the selected navigation index.
tab->current_navigation_index =
std::max(-1, tab->current_navigation_index - payload.index);
// And update the index of existing navigations.
for (auto i = tab->navigations.begin(); i != tab->navigations.end();) {
i->set_index(i->index() - payload.index);
if (i->index() < 0)
i = tab->navigations.erase(i);
else
++i;
}
break;
}
case kCommandUpdateTabNavigation: {
sessions::SerializedNavigationEntry navigation;
SessionID::id_type tab_id;
if (!RestoreUpdateTabNavigationCommand(*command,
&navigation,
&tab_id)) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
SessionTab* tab = GetTab(tab_id, tabs);
auto i = FindClosestNavigationWithIndex(&(tab->navigations),
navigation.index());
if (i != tab->navigations.end() && i->index() == navigation.index())
*i = navigation;
else
tab->navigations.insert(i, navigation);
break;
}
case kCommandSetSelectedNavigationIndex: {
SelectedNavigationIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetTab(payload.id, tabs)->current_navigation_index = payload.index;
break;
}
case kCommandSetSelectedTabInIndex: {
SelectedTabInIndexPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetWindow(payload.id, windows)->selected_tab_index = payload.index;
break;
}
case kCommandSetWindowType: {
WindowTypePayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetWindow(payload.id, windows)->is_constrained = false;
GetWindow(payload.id, windows)->type =
static_cast<SessionWindow::WindowType>(payload.index);
break;
}
case kCommandSetPinnedState: {
PinnedStatePayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetTab(payload.tab_id, tabs)->pinned = payload.pinned_state;
break;
}
case kCommandSetWindowAppName: {
SessionID::id_type window_id;
std::string app_name;
if (!RestoreSetWindowAppNameCommand(*command, &window_id, &app_name))
return true;
GetWindow(window_id, windows)->app_name.swap(app_name);
break;
}
case kCommandSetExtensionAppID: {
SessionID::id_type tab_id;
std::string extension_app_id;
if (!RestoreSetTabExtensionAppIDCommand(*command,
&tab_id,
&extension_app_id)) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetTab(tab_id, tabs)->extension_app_id.swap(extension_app_id);
break;
}
case kCommandSetTabUserAgentOverride: {
SessionID::id_type tab_id;
std::string user_agent_override;
if (!RestoreSetTabUserAgentOverrideCommand(
*command,
&tab_id,
&user_agent_override)) {
return true;
}
GetTab(tab_id, tabs)->user_agent_override.swap(user_agent_override);
break;
}
case kCommandSessionStorageAssociated: {
std::unique_ptr<base::Pickle> command_pickle(
command->PayloadAsPickle());
SessionID::id_type command_tab_id;
std::string session_storage_persistent_id;
base::PickleIterator iter(*command_pickle.get());
if (!iter.ReadInt(&command_tab_id) ||
!iter.ReadString(&session_storage_persistent_id))
return true;
// Associate the session storage back.
GetTab(command_tab_id, tabs)->session_storage_persistent_id =
session_storage_persistent_id;
break;
}
case kCommandSetActiveWindow: {
ActiveWindowPayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
*active_window_id = payload;
break;
}
case kCommandLastActiveTime: {
LastActiveTimePayload payload;
if (!command->GetPayload(&payload, sizeof(payload))) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
SessionTab* tab = GetTab(payload.tab_id, tabs);
tab->last_active_time =
base::TimeTicks::FromInternalValue(payload.last_active_time);
break;
}
case kCommandSetWindowWorkspace2: {
std::unique_ptr<base::Pickle> pickle(command->PayloadAsPickle());
base::PickleIterator it(*pickle);
SessionID::id_type window_id;
std::string workspace;
if (!it.ReadInt(&window_id) || !it.ReadString(&workspace)) {
DVLOG(1) << "Failed reading command " << command->id();
return true;
}
GetWindow(window_id, windows)->workspace = workspace;
break;
}
default:
// TODO(skuhne): This might call back into a callback handler to extend
// the command set for specific implementations.
DVLOG(1) << "Failed reading an unknown command " << command->id();
return true;
}
}
return true;
}
} // namespace
std::unique_ptr<SessionCommand> CreateSetSelectedTabInWindowCommand(
const SessionID& window_id,
int index) {
SelectedTabInIndexPayload payload = { 0 };
payload.id = window_id.id();
payload.index = index;
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandSetSelectedTabInIndex, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetTabWindowCommand(
const SessionID& window_id,
const SessionID& tab_id) {
SessionID::id_type payload[] = { window_id.id(), tab_id.id() };
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandSetTabWindow, sizeof(payload));
memcpy(command->contents(), payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetWindowBoundsCommand(
const SessionID& window_id,
const gfx::Rect& bounds,
ui::WindowShowState show_state) {
WindowBoundsPayload3 payload = { 0 };
payload.window_id = window_id.id();
payload.x = bounds.x();
payload.y = bounds.y();
payload.w = bounds.width();
payload.h = bounds.height();
payload.show_state = ShowStateToPersistedShowState(show_state);
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandSetWindowBounds3, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetTabIndexInWindowCommand(
const SessionID& tab_id,
int new_index) {
TabIndexInWindowPayload payload = { 0 };
payload.id = tab_id.id();
payload.index = new_index;
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandSetTabIndexInWindow, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateTabClosedCommand(
const SessionID::id_type tab_id) {
ClosedPayload payload;
// Because of what appears to be a compiler bug setting payload to {0} doesn't
// set the padding to 0, resulting in Purify reporting an UMR when we write
// the structure to disk. To avoid this we explicitly memset the struct.
memset(&payload, 0, sizeof(payload));
payload.id = tab_id;
payload.close_time = base::Time::Now().ToInternalValue();
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandTabClosed, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateWindowClosedCommand(
const SessionID::id_type window_id) {
ClosedPayload payload;
// See comment in CreateTabClosedCommand as to why we do this.
memset(&payload, 0, sizeof(payload));
payload.id = window_id;
payload.close_time = base::Time::Now().ToInternalValue();
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandWindowClosed, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetSelectedNavigationIndexCommand(
const SessionID& tab_id,
int index) {
SelectedNavigationIndexPayload payload = { 0 };
payload.id = tab_id.id();
payload.index = index;
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandSetSelectedNavigationIndex, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetWindowTypeCommand(
const SessionID& window_id,
SessionWindow::WindowType type) {
WindowTypePayload payload = { 0 };
payload.id = window_id.id();
payload.index = static_cast<int32_t>(type);
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandSetWindowType, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreatePinnedStateCommand(
const SessionID& tab_id,
bool is_pinned) {
PinnedStatePayload payload = { 0 };
payload.tab_id = tab_id.id();
payload.pinned_state = is_pinned;
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandSetPinnedState, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSessionStorageAssociatedCommand(
const SessionID& tab_id,
const std::string& session_storage_persistent_id) {
base::Pickle pickle;
pickle.WriteInt(tab_id.id());
pickle.WriteString(session_storage_persistent_id);
return std::unique_ptr<SessionCommand>(base::MakeUnique<SessionCommand>(
kCommandSessionStorageAssociated, pickle));
}
std::unique_ptr<SessionCommand> CreateSetActiveWindowCommand(
const SessionID& window_id) {
ActiveWindowPayload payload = 0;
payload = window_id.id();
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandSetActiveWindow, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateLastActiveTimeCommand(
const SessionID& tab_id,
base::TimeTicks last_active_time) {
LastActiveTimePayload payload = {0};
payload.tab_id = tab_id.id();
payload.last_active_time = last_active_time.ToInternalValue();
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandLastActiveTime, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateSetWindowWorkspaceCommand(
const SessionID& window_id,
const std::string& workspace) {
base::Pickle pickle;
pickle.WriteInt(window_id.id());
pickle.WriteString(workspace);
std::unique_ptr<SessionCommand> command =
base::MakeUnique<SessionCommand>(kCommandSetWindowWorkspace2, pickle);
return command;
}
std::unique_ptr<SessionCommand> CreateTabNavigationPathPrunedFromBackCommand(
const SessionID& tab_id,
int count) {
TabNavigationPathPrunedFromBackPayload payload = { 0 };
payload.id = tab_id.id();
payload.index = count;
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandTabNavigationPathPrunedFromBack, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateTabNavigationPathPrunedFromFrontCommand(
const SessionID& tab_id,
int count) {
TabNavigationPathPrunedFromFrontPayload payload = { 0 };
payload.id = tab_id.id();
payload.index = count;
std::unique_ptr<SessionCommand> command = base::MakeUnique<SessionCommand>(
kCommandTabNavigationPathPrunedFromFront, sizeof(payload));
memcpy(command->contents(), &payload, sizeof(payload));
return command;
}
std::unique_ptr<SessionCommand> CreateUpdateTabNavigationCommand(
const SessionID& tab_id,
const sessions::SerializedNavigationEntry& navigation) {
return CreateUpdateTabNavigationCommand(kCommandUpdateTabNavigation,
tab_id.id(),
navigation);
}
std::unique_ptr<SessionCommand> CreateSetTabExtensionAppIDCommand(
const SessionID& tab_id,
const std::string& extension_id) {
return CreateSetTabExtensionAppIDCommand(kCommandSetExtensionAppID,
tab_id.id(),
extension_id);
}
std::unique_ptr<SessionCommand> CreateSetTabUserAgentOverrideCommand(
const SessionID& tab_id,
const std::string& user_agent_override) {
return CreateSetTabUserAgentOverrideCommand(kCommandSetTabUserAgentOverride,
tab_id.id(),
user_agent_override);
}
std::unique_ptr<SessionCommand> CreateSetWindowAppNameCommand(
const SessionID& window_id,
const std::string& app_name) {
return CreateSetWindowAppNameCommand(kCommandSetWindowAppName,
window_id.id(),
app_name);
}
bool ReplacePendingCommand(BaseSessionService* base_session_service,
std::unique_ptr<SessionCommand>* command) {
// We optimize page navigations, which can happen quite frequently and
// is expensive. And activation is like Highlander, there can only be one!
if ((*command)->id() != kCommandUpdateTabNavigation &&
(*command)->id() != kCommandSetActiveWindow) {
return false;
}
for (auto i = base_session_service->pending_commands().rbegin();
i != base_session_service->pending_commands().rend(); ++i) {
SessionCommand* existing_command = i->get();
if ((*command)->id() == kCommandUpdateTabNavigation &&
existing_command->id() == kCommandUpdateTabNavigation) {
std::unique_ptr<base::Pickle> command_pickle(
(*command)->PayloadAsPickle());
base::PickleIterator iterator(*command_pickle);
SessionID::id_type command_tab_id;
int command_nav_index;
if (!iterator.ReadInt(&command_tab_id) ||
!iterator.ReadInt(&command_nav_index)) {
return false;
}
SessionID::id_type existing_tab_id;
int existing_nav_index;
{
// Creating a pickle like this means the Pickle references the data from
// the command. Make sure we delete the pickle before the command, else
// the pickle references deleted memory.
std::unique_ptr<base::Pickle> existing_pickle(
existing_command->PayloadAsPickle());
iterator = base::PickleIterator(*existing_pickle);
if (!iterator.ReadInt(&existing_tab_id) ||
!iterator.ReadInt(&existing_nav_index)) {
return false;
}
}
if (existing_tab_id == command_tab_id &&
existing_nav_index == command_nav_index) {
// existing_command is an update for the same tab/index pair. Replace
// it with the new one. We need to add to the end of the list just in
// case there is a prune command after the update command.
base_session_service->EraseCommand((i.base() - 1)->get());
base_session_service->AppendRebuildCommand(std::move(*command));
return true;
}
return false;
}
if ((*command)->id() == kCommandSetActiveWindow &&
existing_command->id() == kCommandSetActiveWindow) {
base_session_service->SwapCommand(existing_command,
(std::move(*command)));
return true;
}
}
return false;
}
bool IsClosingCommand(SessionCommand* command) {
return command->id() == kCommandTabClosed ||
command->id() == kCommandWindowClosed;
}
void RestoreSessionFromCommands(
const std::vector<std::unique_ptr<SessionCommand>>& commands,
std::vector<std::unique_ptr<SessionWindow>>* valid_windows,
SessionID::id_type* active_window_id) {
IdToSessionTab tabs;
IdToSessionWindow windows;
DVLOG(1) << "RestoreSessionFromCommands " << commands.size();
if (CreateTabsAndWindows(commands, &tabs, &windows, active_window_id)) {
AddTabsToWindows(&tabs, &windows);
SortTabsBasedOnVisualOrderAndClear(&windows, valid_windows);
UpdateSelectedTabIndex(valid_windows);
}
// AddTabsToWindows should have processed all the tabs.
DCHECK_EQ(0u, tabs.size());
// SortTabsBasedOnVisualOrderAndClear should have processed all the windows.
DCHECK_EQ(0u, windows.size());
}
} // namespace sessions
| [
"hedonist.ky@gmail.com"
] | hedonist.ky@gmail.com |
e1a08a7b706463bc9dd2865027e05940b0e88fb4 | 1df8839f8d5310b8e6f2e6d5c21e883193b1a33d | /SphHarEvol.1.1/SphHarEvolRing.1.4.cpp | 90081462b22885efe1cf49a3cab108c4988bde75 | [] | no_license | evelynshank/paperclip_nouveau | 12f094c002681dfee678b4631d667b58bb7c25ec | 3ebd177e40f03e67415bed7ca744dc302920f10b | refs/heads/master | 2022-09-16T00:35:57.271117 | 2020-06-01T19:27:01 | 2020-06-01T19:27:01 | 268,607,625 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,942 | cpp |
// Written by: Suren Gourapura
// Date: 10/28/17
// Goal: The goal is to take a given theta angle and spread in theta to evolve an antenna using spherical harmonics that best satisfies it.
// Additionally, the user defines the number of spherical harmonics used
#include <iostream>
#include <string>
#include <math.h>
#include <iomanip>
#include <ctime>
#include <stdlib.h>
#include <vector>
using namespace std;
double Pi = 3.14159265359;
int PopMAX = 100;
// Code modified from https://codereview.stackexchange.com/questions/110793/insertion-sort-in-c
void insertionSort(double array[], int length){
int i,j;
for (i = 1; i < length; i++) {
double temp = array[i];
for (j = i; j > 0 && array[j - 1] < temp; j--) {
array[j] = array[j - 1];
}
array[j] = temp;
}
}
double integrateSpecies(vector<vector<double> >& pop, int SphHarMAX, int species, double Theta, double Spread){
double Min, Max;
// Make sure that the maximum is less than or equal to 180 degrees and the minimum is greater than or equal to 0
if (Theta + Spread/2.0 > 180){Max = 180;}
else{Max = Theta + Spread/2.0;}
if (Theta - Spread/2.0 < 0){Min = 0;}
else{Min = Theta - Spread/2.0;}
// We need to only integrate over the specified number of spherical harmonics, not all of them. So, we store which spherical harmonics to turn on as an additional binary coefficient.
int Sph[13];
for (int i = 0; i < 13; i++){
if (i < SphHarMAX){
Sph[i]=1;
}
else{
Sph[i]=0;
}
}
double Sum = 0;
// Sum the spherical harmonic values by half-degree increments from the Min to Max theta values
for (double degree = Min * Pi / 180; degree <= Max *Pi / 180; degree = degree + Pi/360){
Sum += pow(
//Y00
Sph[0]*pop[species][0]*(1/2.0)*(1/sqrt(Pi))
//Y01
+Sph[1]*pop[species][1]*(1/2.0)*sqrt(3/Pi)*cos(degree)
//Y02
+Sph[2]*pop[species][2]*(1/4.0)*sqrt(5/Pi)*(3*pow(cos(degree), 2) - 1)
//Y03
+Sph[3]*pop[species][3]*(1/4.0)*sqrt(7/Pi)*(5*pow(cos(degree),3) - 3*cos(degree))
//Y04
+Sph[4]*pop[species][4]*(3/16.0)*sqrt(1/Pi)*(35*pow(cos(degree),4) - 30*pow(cos(degree),2) + 3)
//Y05
+Sph[5]*pop[species][5]*(1/16.0)*sqrt(11/Pi)*(63*pow(cos(degree),5) - 70*pow(cos(degree),3) + 15*cos(degree))
//Y06
+Sph[6]*pop[species][6]*(1/32.0)*sqrt(13/Pi)*(231*pow(cos(degree),6) - 315*pow(cos(degree),4) + 105*pow(cos(degree),2) - 5 )
//Y07
+Sph[7]*pop[species][7]*(1/32.0)*sqrt(15/Pi)*(429*pow(cos(degree),7) - 693*pow(cos(degree),5) + 315*pow(cos(degree),3) - 35*cos(degree))
//Y08
+Sph[8]*pop[species][8]*(1/256.0)*sqrt(17/Pi)*(6435*pow((cos(degree)),8) - 12012*pow(cos(degree),6) + 6930*pow(cos(degree),4) - 1260*pow(cos(degree),2) + 35)
//Y09
+Sph[9]*pop[species][9]*(1/256.0)*sqrt(19/Pi)*(12155*pow((cos(degree)),9) - 25740*pow(cos(degree),7) + 18018*pow(cos(degree),5) - 4620*pow(cos(degree),3) + 315*cos(degree))
//Y10
+Sph[10]*pop[species][10]*(1/512.0)*sqrt(21/Pi)*(46189*pow(cos(degree),10) - 109395*pow((cos(degree)),8) + 90090*pow(cos(degree),6) - 30030*pow(cos(degree),4) + 3465*pow(cos(degree),2) - 63)
//Y011
+Sph[11]*pop[species][11]*(1/512.0)*sqrt(23/Pi)*(88179*pow(cos(degree),11) - 230945*pow(cos(degree),9) + 218790*pow((cos(degree)),7) - 90090*pow(cos(degree),5) + 15015*pow(cos(degree),3) - 693*cos(degree))
//Y012
+Sph[12]*pop[species][12]*(5/2048.0)*sqrt(1/Pi)*(676039*pow(cos(degree),12) - 1939938*pow(cos(degree),10) + 2078505*pow((cos(degree)),8) - 1021020*pow(cos(degree),6) + 225225*pow(cos(degree),4) - 18018*pow(cos(degree),2) + 231)
, 2)*sin(degree);
}
// Finally, we give the summed values of the spherical harmonic from theta min to theta max as the test score (a rough kind of integration by .5 degree increments)
return Sum;
}
int main()
{
double Theta, Spread;
int SphHarMAX;
int Gen = 0;
srand(time(NULL));
/*// Enter the goal theta and spread
cout << "Enter the number of spherical harmonics (1-13), goal theta and spread (in degrees), and generations in the following format: #SphHar theta spread generations" << endl;
cin >> SphHarMAX;
cin >> Theta;
cin >> Spread;
cin >> Gen;
*/
SphHarMAX = 3;
Theta = 90;
Spread = 20;
Gen = 300;
// Create the population with user specified number of spherical harmonics
double pop[PopMAX][SphHarMAX];
// Randomly fill the population. First step is to give each value in each species random number between -1 and 1. Then, we normalize the species values to 1
for (int i = 0; i < PopMAX; i++){
for (int j = 0; j < SphHarMAX; j++){
pop[i][j] = ((double)rand() / (double)(RAND_MAX))*2 - 1; // gives a random value between -1 and 1
}
}
// We divide all coefficients by their integral over all space to normalize to 1
// To pass this population off to functions, we make a 2D vector with the same values called vPop
vector<vector<double> >vPop;
vPop.resize(PopMAX);
for(int i=0; i<PopMAX; i++){
vPop[i].resize(SphHarMAX);
}
for(int i=0; i<PopMAX; i++){
for(int j=0; j<SphHarMAX; j++){
vPop[i][j] = pop[i][j];
}
}
// Now we normalize
for (int i = 0; i < PopMAX; i++){
double counter = pow(integrateSpecies(vPop, SphHarMAX, i, 90, 180)*0.0548594, 0.5);
for (int j = 0; j < SphHarMAX; j++){
pop[i][j] = pop[i][j] / counter;
}
}
// Now, we evolve. We loop the following code for each generation
for (int g = 1; g <= Gen; g++){
// cout << endl << "Generation: " << g << endl;
// The first objective is to calculate how well our current population's species are doing
double testScores[100];
// To pass this population off to functions, we again make a 2D vector with the same values called vPop
vector<vector<double> >vPop;
vPop.resize(PopMAX);
for(int i=0; i<PopMAX; i++){
vPop[i].resize(SphHarMAX);
}
for(int i=0; i < PopMAX; i++){
for(int j=0; j < SphHarMAX; j++){
vPop[i][j] = pop[i][j];
}
}
// Now, to test the curent population, we integrate each species from [theta-spread/2] to [theta + spread/2]
for (int i = 0; i < PopMAX; i++){
testScores[i] = integrateSpecies(vPop, SphHarMAX, i, Theta, Spread)*0.0548594;
}
// The following matrix will hold the next generation's species. In the end of the evolution, we will make pop = nextPop, so the next evolution afterwards will act on nextPop
double nextPop[PopMAX][SphHarMAX] = {};
// Evolution Algorithim 1: Take the 10 species with the best scores and pass them onto nextPop
// We want to organize the population by their testScores, so we make a temporary matrix to hold the ranked initial population:rankedPop
// Also, a temporary ordered testScores array: rankedTestScores
double rankedPop[PopMAX][SphHarMAX] = {};
double rankedTestScores[PopMAX] = {};
// First, equate the test scores with the ranked test scores. Then we sort the ranked test scores: greatest to least
for (int i=0; i < PopMAX; i++){
rankedTestScores[i] = testScores[i];
}
insertionSort(rankedTestScores, PopMAX);
// Next, we find where testScores = rankedTestScores to place the pop species in the right place in rankedPop
for (int i=0; i < PopMAX; i++){
for (int k=0; k < PopMAX; k++){
if (testScores[k] == rankedTestScores[i]){
for (int l=0; l < SphHarMAX; l++){ // We need to copy the whole of the species in the kth position to rankedPop in the ith position
rankedPop[i][l] = pop[k][l];
}
}
}
}
// We print out the highest ranking species's score and it's array in mathematica format, for easy plotting
cout <<rankedTestScores[0]<< endl;
// cout << "Generation: " << g << " First Score in Mathematica Format with score "<< rankedTestScores[0]<< " : " << endl;
// for (int i = 0; i <= SphHarMAX-1; i++){
// cout << "m1Y0" << i<< " = " << rankedPop[0][i] << endl;
// }*/
// Finally, we copy over the top 10 best species from pop to nextPop
for (int i = 0; i < 10; i++){
for (int j = 0; j < SphHarMAX; j++){
nextPop[i][j]= rankedPop[i][j];
}
}
// Evolution Algorithim 2: Take 10 random species, find the one with the best score, and [randomly mutate one of it's array values to obtain an offspring] 10 times.
// Do this whole algorithim 3 times
for(int a2 = 1; a2 <= 3; a2++){
int choose10[10]; // Create an array with 10 random values, 0-99. This array determines the 10 random species that will undergo a tournament selection (a.k.a. simply choosing the highest score species out of the 10)
for (int i = 0; i < 10; i++){
choose10[i]= rand() % 100;
}
// Since we have pop already organized from best to worst, we simply find the lowest value in choose10 to find the winner of the tournament. The winning species is called: Algorithim 2 Best Value
int Alg2BestVal = choose10[0]; // Assume the best species is the first one
for (int i = 1; i < 10; i++){
if (Alg2BestVal > choose10[i]){ // If another species in the choose10 array has a lower value, it is now the best species
Alg2BestVal = choose10[i];
}
}
// Now, we mutate one part of the species's array, pop[Alg2BestVal][], to create an offspring. We do this 10 times.
int mutateLocation[10]; // Create the locations for mutation of the 10 offspring
for (int i = 0; i < 10; i++){
mutateLocation[i] = rand() % SphHarMAX;
}
// We do the process below 10 times, (to spots 10*a2 to 19*a2 in nextPop)
for (int i = 0; i < 10; i++){
for (int j = 0; j < SphHarMAX; j++){
nextPop[i + 10*a2][j]= rankedPop[Alg2BestVal][j]; // Copy the Alg2BestVal species over. Note: a2 is added to be able to do the whole of Algorithm 2, 3 times
}
for (int j = 0; j < SphHarMAX; j++){
if(mutateLocation[i] == j){ // make sure that the location to be mutated is chosen randomly, by using mutateLocation[]
nextPop[i + 10*a2][j] = ((double)rand() / (double)(RAND_MAX))-.5;// Mutate this location
}
}
}
// We will normalize the whole next population after all evolutionary algorithims
}
// Evolution Algorithim 3: Take 20 random species, run two seperate tournaments to find 2 parents, and [swap a random array location with each other to obtain two offspring (for both combinations)] 5 times.
// We do this Algorithm 5 times, for a total of 50 offspring
for(int a3 = 1; a3 <= 5; a3++){
int choose10A[10], choose10B[10]; // Create 2 arrays with 10 random values, 0-99. These arrays determine the 20 random species that will undergo two seperate tournament selections
int Alg3BestValA = 0, Alg3BestValB = 0;
while (Alg3BestValA == Alg3BestValB){ // To make sure that the 2 parents aren't the same species, we run the following as long as they are the same
for (int i = 0; i < 10; i++){
choose10A[i]= rand() % 100;
choose10B[i]= rand() % 100;
}
// Since we have pop already organized from best to worst, we simply find the lowest value in choose10 to find the winners of the tournaments. The winning species are called: Algorithim 2 Best Value A/B
Alg3BestValA = choose10A[0]; // Assume the best species are the first ones
Alg3BestValB = choose10B[0];
for (int i = 1; i < 10; i++){
if (Alg3BestValA > choose10A[i]){ // If a lower value is found, make best value that lower value
Alg3BestValA = choose10A[i];
}
if (Alg3BestValB > choose10B[i]){
Alg3BestValB = choose10B[i];
}
}
}
// Now, we swap one part of the species's arrays in both ways to create 2 offspring. We do this 5 times, normalizing after each one
int swapLocation[5]; // Create the locations for swapping
for (int i = 0; i < 5; i++){
swapLocation[i] = rand() % SphHarMAX;
}
// We do the process below 5 times, (to spots 40*a3 to 49*a3 in nextPop)
for (int i = 0; i < 5; i++){
// First, we copy over the two parents in the 10 offspring spots in nextPop, in an A,B,A,B,... pattern
for (int j = 0; j < SphHarMAX; j++){
nextPop[(i*2) + 10*a3 + 30][j]= rankedPop[Alg3BestValA][j]; // Copy the Alg3BestVal[A and B] species over. Note: a3 is added to be able to do the whole of Algorithm 3, 5 times
nextPop[(i*2 + 1) + 10*a3 + 30][j]= rankedPop[Alg3BestValB][j];
}
for (int j = 0; j < SphHarMAX; j++){
if(swapLocation[i] == j){ // make sure that the location to be swapped is chosen using swapLocation[]
double temp = nextPop[(i*2) + 10*a3 + 30][j];
nextPop[(i*2) + 10*a3 + 30][j] = nextPop[(i*2+1) + 10*a3 + 30][j];
nextPop[(i*2+1) + 10*a3 + 30][j] = temp;
}
}
}
}
// Evolution Algorithim 4: Introduce 10 random species into the population
// First step is to give each value in each species random number between -1 and 1. Then, we normalize the species values to 1
for (int i = 0; i < 10; i++){
for (int j = 0; j < SphHarMAX; j++){
nextPop[90 + i][j] = ((double)rand() / (double)(RAND_MAX))*2- 1; // gives a random value between -1 and 1
}
}
// Now we normalize nextPop: We divide all coefficients by their integral over all space to normalize to 1
// To pass this population off to functions, we make a 2D vector with the same values called vPop
for(int i=0; i < PopMAX; i++){
for(int j=0; j < SphHarMAX; j++){
vPop[i][j] = nextPop[i][j];
}
}
// Now we normalize
for (int i = 0; i < PopMAX; i++){
double counter = pow(integrateSpecies(vPop, SphHarMAX, i, 90, 180)*0.0548594, 0.5);
for (int j = 0; j < SphHarMAX; j++){
nextPop[i][j] = nextPop[i][j] / counter;
}
}
// Finally, we equate the old pop to the new pop, allowing the next loop to operate on the new population
for (int i = 0; i < PopMAX; i++){
for (int j = 0; j < SphHarMAX; j++){
pop[i][j] = nextPop[i][j];
}
}
} // End of Evolution
/*
// The work is done, now time to see the results of the final generation! We follow the same ranking protocol
double finalScores[100];
for(int i=0; i < PopMAX; i++){
for(int j=0; j < SphHarMAX; j++){
vPop[i][j] = pop[i][j];
}
}
// Now, to test the curent population, we integrate each species from [theta-spread/2] to [theta + spread/2]
for (int i = 0; i < PopMAX; i++){
finalScores[i] = integrateSpecies(vPop, SphHarMAX, i, Theta, Spread)*0.0548594;
}
// We want to organize the population by their testScores, so we make a temporary matrix to hold the ranked initial population:rankedPop
// Also, a temporary ordered testScores array: rankedTestScores
double rankedPop[PopMAX][SphHarMAX] = {};
double rankedFinalScores[PopMAX] = {};
// First, equate the test scores with the ranked test scores. Then we sort the ranked test scores: greatest to least
for (int i=0; i < PopMAX; i++){
rankedFinalScores[i] = finalScores[i];
}
insertionSort(rankedFinalScores, PopMAX);
// Next, we find where testScores = rankedTestScores to place the pop species in the right place in rankedPop
for (int i = 0; i < PopMAX; i++){
for (int k = 0; k < PopMAX; k++){
if (finalScores[k] == rankedFinalScores[i]){
for (int l = 0; l < SphHarMAX; l++){ // We need to copy the whole of the species in the kth position to rankedPop in the ith position
rankedPop[i][l] = pop[k][l];
}
}
}
}
// We print out the highest ranking species's scores and it's arrays in mathematica format, for easy plotting
cout << endl << endl << "Final Results:" << endl;
for (int i = 0; i < 5; i++){
cout << "# " << i+1 << " In Mathematica Format with score "<< rankedFinalScores[i]<< " : " << endl;
for (int j = 0; j < SphHarMAX; j++){
cout << "m1Y0" << j << " = " << rankedPop[i][j] << endl;
}
cout << endl;
}
// We also print out the whole population, to see the spread of the scores:
cout << endl << endl << "Final Population:" << endl;
for (int i = 0; i < PopMAX; i++){
cout << "Species " << i << " with score "<< rankedFinalScores[i]<< " : " << endl;
for (int j = 0; j < SphHarMAX; j++){
cout << rankedPop[i][j] << " ";
}
cout << endl;
}
*/
return 0;
}
| [
"evelyn.shank@protonmail.com"
] | evelyn.shank@protonmail.com |
8ffe68351b121050d725b3566d46e257a2927ede | 2442bf3f201bf7e2ce000640c0523546f4c1219e | /Solutions/Rotate List/main.cpp | 33b313dd80d436eb44767a97fd1c7751228a51c6 | [
"MIT"
] | permissive | Crayzero/LeetCodeProgramming | aeefd2cf00705334d031b35a2b98f4ddef44730d | b10ebe22c0de1501722f0f5c934c0c1902a26789 | refs/heads/master | 2021-01-17T15:12:40.116004 | 2015-06-17T12:27:57 | 2015-06-17T12:27:57 | 33,850,297 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,213 | cpp | #include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x): val(x), next(NULL) {}
};
class Solution {
public:
ListNode *rotateRight(ListNode *head, int k) {
if (head == NULL) {
return NULL;
}
ListNode *p = head;
ListNode *p_end = p;
int cnt = 0;
while(k--) {
p_end = p_end->next;
cnt++;
if (p_end == NULL) {
p_end = head;
k = k % cnt;
}
}
if (p_end == p) {
return head;
}
while(p_end->next != NULL) {
p = p->next;
p_end = p_end->next;
}
p_end->next = head;
ListNode *new_head = p->next;
p->next = NULL;
return new_head;
}
};
int main()
{
ListNode *a = new ListNode(1);
ListNode *b = new ListNode(2);
ListNode *c = new ListNode(3);
ListNode *d = new ListNode(4);
ListNode *e = new ListNode(5);
a->next = b;
b->next = c;
c->next = d;
d->next = e;
Solution s;
a = s.rotateRight(a, 12);
for(;a; a=a->next) {
cout<<a->val<<" ";
}
return 0;
}
| [
"chen154556138@163.com"
] | chen154556138@163.com |
e19c9fe3713244ea964c19b434a470a3c8304766 | 4c38590326080dedf2105fd337f303dbfef78b42 | /tmp.cpp | f789515b225abb838429b5fb63aef127abc92fe5 | [] | no_license | hubert-he/codes | 1a06cfe7a1e4dc324846f2abc97d5c9f641084ef | b067b47006e4c16bb2ea5381b840b285d6c1cd8a | refs/heads/master | 2021-01-13T01:40:20.290289 | 2015-08-26T23:50:49 | 2015-08-26T23:50:49 | 40,354,457 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,395 | cpp | /*******************************************************************
* Copyright (C) Jerry Jiang
*
* File Name : swap.cpp
* Author : Jerry Jiang
* Create Time : 2012-3-24 4:19:31
* Mail : jbiaojerry@gmail.com
* Blog : http://blog.csdn.net/jerryjbiao
*
* Description : 简单的程序诠释C++ STL算法系列之十五
* 变易算法 : 元素交换swap
*
* 原型:
template <class T> void swap ( T& a, T& b )
{
T c(a); a=b; b=c;
}
******************************************************************/
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main ()
{
int x = 10, y = 20; // x:10 y:20
swap(x, y); // x:20 y:10
cout << "x= " << x << "y=" << y << endl;
vector<int> first (4, x), second (6, y); // first:4x20 second:6x10
swap(first, second); // first:6x10 second:4x20
cout << "first contains:";
//使用一般的iterator方式输出first
for (vector<int>::iterator it=first.begin(); it != first.end(); ++it)
{
cout << " " << *it;
}
cout << endl;
cout << "second contains: ";
//使用copy()来实现second的输出
copy(second.begin(), second.end(), ostream_iterator<int>(cout, " "));
cout << endl;
return 0;
}
| [
"a17674@126.com"
] | a17674@126.com |
560b81fe5c659add526ff9ff84fbebdb12b37e5b | 9bc1d3164daeef5727418b5c7d2d3693dbaf5816 | /04/ex03/Character.hpp | 1a9cb2b9c3580da60525fdf565c208d3c4022130 | [] | no_license | l-yohai/CPP_Modules | 719e24b92a69d88e8dd7b160770c489189ececbe | afd040814084b87169260c27700081320b2b2abc | refs/heads/master | 2022-12-24T19:17:06.304446 | 2020-10-02T16:22:16 | 2020-10-02T16:22:16 | 284,696,561 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,411 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* Character.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: yohlee <yohlee@student.42seoul.kr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/26 23:28:07 by yohlee #+# #+# */
/* Updated: 2020/09/27 05:42:51 by yohlee ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CHARACTER_HPP
# define CHARACTER_HPP
# include "ICharacter.hpp"
# include "AMateria.hpp"
class Character : public ICharacter
{
private:
std::string _name;
AMateria * _inventory[4];
public:
Character(std::string name);
Character(const Character & other);
Character& operator=(const Character & other);
~Character(void);
virtual std::string const & getName() const;
virtual void equip(AMateria* m);
virtual void unequip(int idx);
virtual void use(int idx, ICharacter& target);
};
#endif | [
"yohan9612@naver.com"
] | yohan9612@naver.com |
e7fbfd631c57c8151c1d4e89ee4169a8ffdb1b19 | f88ee3877e76725d9a963ca88f3ec1708d9569f8 | /module01/cmdargs/src/main.cpp | f5a470ac6514af8a99322102d97ee4a175262d9d | [] | no_license | djtorel/learning-cpp-safaribooks | 79ba95686ef8927226ac4c4563c8c991beab4cd0 | 69284341b53bf25730888b0d2018f0d489d955e7 | refs/heads/master | 2021-01-01T20:22:11.068464 | 2017-08-01T02:39:00 | 2017-08-01T02:39:00 | 98,824,653 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 349 | cpp | // main.cpp
#include <iostream>
int main(int argc, char* argv[]) {
if (argc < 6) {
std::cerr << "Invalid number of arugments - at least 5 required" << std::endl;
return 1;
}
std::cout << "Total arguments: " << argc << std::endl;
for (int i{0}; i < argc; i++) {
std::cout << "arg[" << i << "] = " << argv[i] << std::endl;
}
} | [
"dtorruellas@gmail.com"
] | dtorruellas@gmail.com |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.