blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 3
264
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
85
| license_type
stringclasses 2
values | repo_name
stringlengths 5
140
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 905
values | visit_date
timestamp[us]date 2015-08-09 11:21:18
2023-09-06 10:45:07
| revision_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-17 19:19:19
| committer_date
timestamp[us]date 1997-09-14 05:04:47
2023-09-06 06:22:19
| github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 22
values | gha_event_created_at
timestamp[us]date 2012-06-07 00:51:45
2023-09-14 21:58:39
⌀ | gha_created_at
timestamp[us]date 2008-03-27 23:40:48
2023-08-21 23:17:38
⌀ | gha_language
stringclasses 141
values | src_encoding
stringclasses 34
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 3
10.4M
| extension
stringclasses 115
values | content
stringlengths 3
10.4M
| authors
sequencelengths 1
1
| author_id
stringlengths 0
158
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
444549f960cc758acad2b0a75737f984902a9cd3 | 86f414c9e44f88734896c8e657024df94a468ed3 | /libraries/Adafruit_BME280_Library/Adafruit_BME280.h | d79ac433d5ee26831b2636ddd26a4bd20ae5a709 | [
"BSD-3-Clause"
] | permissive | smeilard/beeWatch | a038fdf65e5f38564030524b0982125de5389659 | cf59fac18ddc8405b156d3e7aafe266713f6be89 | refs/heads/master | 2020-04-30T12:34:42.801446 | 2020-02-05T07:36:21 | 2020-02-05T07:36:21 | 176,830,066 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 10,621 | h | /*!
* @file Adafruit_BME280.h
*
* Designed specifically to work with the Adafruit BME280 Breakout
* ----> http://www.adafruit.com/products/2650
*
* These sensors use I2C or SPI to communicate, 2 or 4 pins are required
* to interface.
*
* Adafruit invests time and resources providing this open source code,
* please support Adafruit and open-source hardware by purchasing
* products from Adafruit!
*
* Written by Kevin "KTOWN" Townsend for Adafruit Industries.
*
* BSD license, all text here must be included in any redistribution.
*
*/
#ifndef __BME280_H__
#define __BME280_H__
#if (ARDUINO >= 100)
#include "Arduino.h"
#else
#include "WProgram.h"
#endif
#include <Adafruit_Sensor.h>
#include <Wire.h>
/**************************************************************************/
/*!
@brief default I2C address
*/
/**************************************************************************/
#define BME280_ADDRESS (0x76)
/*=========================================================================*/
/**************************************************************************/
/*!
@brief Register addresses
*/
/**************************************************************************/
enum
{
BME280_REGISTER_DIG_T1 = 0x88,
BME280_REGISTER_DIG_T2 = 0x8A,
BME280_REGISTER_DIG_T3 = 0x8C,
BME280_REGISTER_DIG_P1 = 0x8E,
BME280_REGISTER_DIG_P2 = 0x90,
BME280_REGISTER_DIG_P3 = 0x92,
BME280_REGISTER_DIG_P4 = 0x94,
BME280_REGISTER_DIG_P5 = 0x96,
BME280_REGISTER_DIG_P6 = 0x98,
BME280_REGISTER_DIG_P7 = 0x9A,
BME280_REGISTER_DIG_P8 = 0x9C,
BME280_REGISTER_DIG_P9 = 0x9E,
BME280_REGISTER_DIG_H1 = 0xA1,
BME280_REGISTER_DIG_H2 = 0xE1,
BME280_REGISTER_DIG_H3 = 0xE3,
BME280_REGISTER_DIG_H4 = 0xE4,
BME280_REGISTER_DIG_H5 = 0xE5,
BME280_REGISTER_DIG_H6 = 0xE7,
BME280_REGISTER_CHIPID = 0xD0,
BME280_REGISTER_VERSION = 0xD1,
BME280_REGISTER_SOFTRESET = 0xE0,
BME280_REGISTER_CAL26 = 0xE1, // R calibration stored in 0xE1-0xF0
BME280_REGISTER_CONTROLHUMID = 0xF2,
BME280_REGISTER_STATUS = 0XF3,
BME280_REGISTER_CONTROL = 0xF4,
BME280_REGISTER_CONFIG = 0xF5,
BME280_REGISTER_PRESSUREDATA = 0xF7,
BME280_REGISTER_TEMPDATA = 0xFA,
BME280_REGISTER_HUMIDDATA = 0xFD
};
/**************************************************************************/
/*!
@brief calibration data
*/
/**************************************************************************/
typedef struct
{
uint16_t dig_T1; ///< temperature compensation value
int16_t dig_T2; ///< temperature compensation value
int16_t dig_T3; ///< temperature compensation value
uint16_t dig_P1; ///< pressure compensation value
int16_t dig_P2; ///< pressure compensation value
int16_t dig_P3; ///< pressure compensation value
int16_t dig_P4; ///< pressure compensation value
int16_t dig_P5; ///< pressure compensation value
int16_t dig_P6; ///< pressure compensation value
int16_t dig_P7; ///< pressure compensation value
int16_t dig_P8; ///< pressure compensation value
int16_t dig_P9; ///< pressure compensation value
uint8_t dig_H1; ///< humidity compensation value
int16_t dig_H2; ///< humidity compensation value
uint8_t dig_H3; ///< humidity compensation value
int16_t dig_H4; ///< humidity compensation value
int16_t dig_H5; ///< humidity compensation value
int8_t dig_H6; ///< humidity compensation value
} bme280_calib_data;
/*=========================================================================*/
/*
class Adafruit_BME280_Unified : public Adafruit_Sensor
{
public:
Adafruit_BME280_Unified(int32_t sensorID = -1);
bool begin(uint8_t addr = BME280_ADDRESS);
void getTemperature(float *temp);
void getPressure(float *pressure);
float pressureToAltitude(float seaLevel, float atmospheric, float temp);
float seaLevelForAltitude(float altitude, float atmospheric, float temp);
void getEvent(sensors_event_t*);
void getSensor(sensor_t*);
private:
uint8_t _i2c_addr;
int32_t _sensorID;
};
*/
/**************************************************************************/
/*!
@brief Class that stores state and functions for interacting with BME280 IC
*/
/**************************************************************************/
class Adafruit_BME280 {
public:
/**************************************************************************/
/*!
@brief sampling rates
*/
/**************************************************************************/
enum sensor_sampling {
SAMPLING_NONE = 0b000,
SAMPLING_X1 = 0b001,
SAMPLING_X2 = 0b010,
SAMPLING_X4 = 0b011,
SAMPLING_X8 = 0b100,
SAMPLING_X16 = 0b101
};
/**************************************************************************/
/*!
@brief power modes
*/
/**************************************************************************/
enum sensor_mode {
MODE_SLEEP = 0b00,
MODE_FORCED = 0b01,
MODE_NORMAL = 0b11
};
/**************************************************************************/
/*!
@brief filter values
*/
/**************************************************************************/
enum sensor_filter {
FILTER_OFF = 0b000,
FILTER_X2 = 0b001,
FILTER_X4 = 0b010,
FILTER_X8 = 0b011,
FILTER_X16 = 0b100
};
/**************************************************************************/
/*!
@brief standby duration in ms
*/
/**************************************************************************/
enum standby_duration {
STANDBY_MS_0_5 = 0b000,
STANDBY_MS_10 = 0b110,
STANDBY_MS_20 = 0b111,
STANDBY_MS_62_5 = 0b001,
STANDBY_MS_125 = 0b010,
STANDBY_MS_250 = 0b011,
STANDBY_MS_500 = 0b100,
STANDBY_MS_1000 = 0b101
};
// constructors
Adafruit_BME280(void);
Adafruit_BME280(int8_t cspin);
Adafruit_BME280(int8_t cspin, int8_t mosipin, int8_t misopin, int8_t sckpin);
bool begin(void);
bool begin(TwoWire *theWire);
bool begin(uint8_t addr);
bool begin(uint8_t addr, TwoWire *theWire);
bool init();
void setSampling(sensor_mode mode = MODE_NORMAL,
sensor_sampling tempSampling = SAMPLING_X16,
sensor_sampling pressSampling = SAMPLING_X16,
sensor_sampling humSampling = SAMPLING_X16,
sensor_filter filter = FILTER_OFF,
standby_duration duration = STANDBY_MS_0_5
);
void takeForcedMeasurement();
float readTemperature(void);
float readPressure(void);
float readHumidity(void);
float readAltitude(float seaLevel);
float seaLevelForAltitude(float altitude, float pressure);
private:
TwoWire *_wire;
void readCoefficients(void);
bool isReadingCalibration(void);
uint8_t spixfer(uint8_t x);
void write8(byte reg, byte value);
uint8_t read8(byte reg);
uint16_t read16(byte reg);
uint32_t read24(byte reg);
int16_t readS16(byte reg);
uint16_t read16_LE(byte reg); // little endian
int16_t readS16_LE(byte reg); // little endian
uint8_t _i2caddr;
int32_t _sensorID;
int32_t t_fine;
int8_t _cs, _mosi, _miso, _sck;
bme280_calib_data _bme280_calib;
// The config register
struct config {
// inactive duration (standby time) in normal mode
// 000 = 0.5 ms
// 001 = 62.5 ms
// 010 = 125 ms
// 011 = 250 ms
// 100 = 500 ms
// 101 = 1000 ms
// 110 = 10 ms
// 111 = 20 ms
unsigned int t_sb : 3;
// filter settings
// 000 = filter off
// 001 = 2x filter
// 010 = 4x filter
// 011 = 8x filter
// 100 and above = 16x filter
unsigned int filter : 3;
// unused - don't set
unsigned int none : 1;
unsigned int spi3w_en : 1;
unsigned int get() {
return (t_sb << 5) | (filter << 2) | spi3w_en;
}
};
config _configReg;
// The ctrl_meas register
struct ctrl_meas {
// temperature oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_t : 3;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_p : 3;
// device mode
// 00 = sleep
// 01 or 10 = forced
// 11 = normal
unsigned int mode : 2;
unsigned int get() {
return (osrs_t << 5) | (osrs_p << 2) | mode;
}
};
ctrl_meas _measReg;
// The ctrl_hum register
struct ctrl_hum {
// unused - don't set
unsigned int none : 5;
// pressure oversampling
// 000 = skipped
// 001 = x1
// 010 = x2
// 011 = x4
// 100 = x8
// 101 and above = x16
unsigned int osrs_h : 3;
unsigned int get() {
return (osrs_h);
}
};
ctrl_hum _humReg;
};
#endif
| [
"[email protected]"
] | |
51f4bc541e111b5f77dc97ccffb7bc57a336bc26 | b4542e6b5fbd0798ab799bdd6760a2cb07c5848a | /a03_threads/worker.cpp | f4764dec780133e15d6d0d68df683ca312f2ce7e | [] | no_license | bryanthphan/CS-570-Operating-Systems | 54e1234caa49a63ca30f74a0f9f49850f14a4391 | d204420104caa59c6b203459919735bdedfdfe24 | refs/heads/master | 2020-05-27T12:33:24.067667 | 2019-05-27T22:04:52 | 2019-05-27T22:04:52 | 188,619,064 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 298 | cpp | #include <stdio.h>
#include <pthread.h>
#include <stdint.h>
extern "C" void *worker(void *VoidPtr) {
/**converts void pointer to a value of int */
int arg = (intptr_t)VoidPtr;
/**squares the value */
int value = arg*arg;
printf("%d\n", value);
//fflush(stdout);
pthread_exit(NULL);
}
| [
"[email protected]"
] | |
72f208f21f9a8237e2810ec32fb62096ce988ca7 | 8b0f2f8fd8d612977cd785d063734a16778b7a33 | /fileinfo.h | b090b5c7deb2785a09195c85fd3f912fd037f09b | [] | no_license | lcapaldo/fim | 381226e473eccc3b0bbeed55ee3ee8faa1cfe01c | 46f94a7f557d1c5c722783a86befccb88f4e7903 | refs/heads/master | 2020-05-19T10:27:58.159680 | 2011-11-06T00:16:39 | 2011-11-06T00:16:39 | 2,640,149 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 270 | h | #ifndef H_FIM_FILEINFO
#define H_FIM_FILEINFO
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
namespace fim {
class fileinfo {
public:
::std::string filename;
::std::string dirname;
struct stat stat_block;
};
}
#endif
| [
"[email protected]"
] | |
24af78e005d7e9415d2d9a0a9ae991f0d38dbbc8 | 30e1bc9bab608105c8d837315877e0041e74d3d4 | /dupa.cpp | 93ca8428325f7e68223e349447bdae4fe67b8c89 | [] | no_license | tester2137/hello-world | 06def51c1f7bd7389c59f760f92f58962f73b7d7 | 6d39f0f64be8e498eb3c3356e2467afea7cb9198 | refs/heads/master | 2021-01-10T02:58:34.824161 | 2015-11-01T08:40:41 | 2015-11-01T08:40:41 | 45,332,749 | 0 | 0 | null | 2015-11-01T08:40:41 | 2015-11-01T09:09:51 | null | UTF-8 | C++ | false | false | 43 | cpp | Jakiś tam nowy plik z nową zawartością
| [
"[email protected]"
] | |
b69f8148d0d75b6b818b0dff0efaf122511d3478 | 699fb4c8577f76fa70772c4b1322c0ac8674976b | /algo_probs/21.merge-two-sorted-lists.cpp | b380f9abf15c27ec4be9ba88cb59f68445fc0252 | [] | no_license | realprocrastinator/leetcode | 8ca7a915b22a295532f9ae21ad9df0eefb14dfa0 | f62ffaa1523812a637ed66c165ed0be7d52576b8 | refs/heads/main | 2023-02-18T05:44:20.926360 | 2021-01-24T08:12:07 | 2021-01-24T08:12:07 | 307,085,374 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,349 | cpp | /*
* @lc app=leetcode id=21 lang=cpp
*
* [21] Merge Two Sorted Lists
*/
// @lc code=start
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (!l1) {
return l2;
}
if (!l2) {
return l1;
}
// dummy head
auto dummy = ListNode();
auto *curr = &dummy;
// dispatch and attach to dummy
while(l1 != nullptr && l2 != nullptr) {
// cout << l1->val << "," << l2->val << '\n';
if(l1->val <= l2->val) {
curr->next = l1;
l1 = l1->next;
curr = curr->next;
curr->next = nullptr;
} else {
curr->next = l2;
l2 = l2->next;
curr = curr->next;
curr->next = nullptr;
}
}
// sort out the rest
if (l1) {
curr->next = l1;
}
if (l2) {
curr->next = l2;
}
return dummy.next;
}
};
// @lc code=end
| [
"[email protected]"
] | |
4a1b4ed24c5a95ddeed89230ef987a8cdc9e40f7 | fc9c216c13b011f16017589482b9139970bd71ea | /GameEngineCore/EngineActorClasses.cpp | 548207bb6bb5ae75556b815196b5e74a27704771 | [
"MIT"
] | permissive | oceancx/SpireMiniEngine | 7e07d9429b0acc6ec3330765751d41cad1550473 | 150797ed06685454e718f708bc63ad3d703bc1e3 | refs/heads/master | 2021-01-23T00:53:34.997101 | 2017-03-02T04:24:03 | 2017-03-02T04:24:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,016 | cpp | #include "Engine.h"
#include "SkeletalMeshActor.h"
#include "StaticMeshActor.h"
#include "CameraActor.h"
#include "FreeRoamCameraController.h"
#include "ArcBallCameraController.h"
#include "MotionGraphMeshActor.h"
#include "AnimationVisualizationActor.h"
#include "DirectionalLightActor.h"
#include "AtmosphereActor.h"
#include "TerrainActor.h"
#include "ToneMappingActor.h"
namespace GameEngine
{
#define REGISTER_ACTOR_CLASS(name) engine->RegisterActorClass(#name, []() {return new name##Actor(); });
void RegisterEngineActorClasses(Engine * engine)
{
REGISTER_ACTOR_CLASS(StaticMesh);
REGISTER_ACTOR_CLASS(SkeletalMesh);
REGISTER_ACTOR_CLASS(Camera);
REGISTER_ACTOR_CLASS(FreeRoamCameraController);
REGISTER_ACTOR_CLASS(ArcBallCameraController);
REGISTER_ACTOR_CLASS(MotionGraphMesh);
REGISTER_ACTOR_CLASS(AnimationVisualization);
REGISTER_ACTOR_CLASS(DirectionalLight);
REGISTER_ACTOR_CLASS(Atmosphere);
REGISTER_ACTOR_CLASS(Terrain);
REGISTER_ACTOR_CLASS(ToneMapping);
}
} | [
"[email protected]"
] | |
6795179e3bd5919030520126842703d04cf5167d | 54f316dbed8b6e1b28d96f2455e989100c91cca4 | /KV_Store_Engine_TaurusDB_Race_stage2/example/kv_store/tcp_server.cc | 8bf2673a967e41af3b4f543eacdde563baf67d5b | [
"MIT"
] | permissive | bk2earth/KV_Store_Engine_TaurusDB_Race | e634bc966b62a29af5036cf21f909c70d1883f0c | b025879e5aa827800919354b56c474639ec34b62 | refs/heads/master | 2022-03-16T16:59:05.846859 | 2019-08-21T07:32:28 | 2019-08-21T07:32:28 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,077 | cc | #include "tcp_server.h"
#include <unistd.h>
#include <thread>
#include <memory>
#include <chrono>
#include <condition_variable>
#include "nanomsg/nn.h"
#include "nanomsg/reqrep.h"
#include "utils.h"
#define NN_LOG(level, msg) KV_LOG(level) << msg << " failed. error: " << nn_strerror(nn_errno())
TcpServer::TcpServer() {
}
TcpServer::~TcpServer() {
stopAll();
}
int TcpServer::Run(const char * url, std::shared_ptr<RpcProcess> rpc_process) {
auto & inst = getInst();
int fd = inst.start(url);
if (fd != -1) {
std::thread recv(&TcpServer::processRecv, fd, rpc_process);
recv.detach();
}
return fd;
}
void TcpServer::Stop(int fd) {
getInst().stop(fd);
}
void TcpServer::StopAll() {
getInst().stopAll();
sleep(1);
}
TcpServer & TcpServer::getInst() {
static TcpServer server;
return server;
}
int TcpServer::start(const char * url) {
int fd = nn_socket(AF_SP, NN_REP);
if (fd < 0) {
NN_LOG(ERROR, "nn_socket");
return -1;
}
if (nn_bind(fd, url) < 0) {
NN_LOG(ERROR, "nn_bind with fd: " << fd);
nn_close(fd);
return -1;
}
mutex_.lock();
fds_.emplace_back(fd);
mutex_.unlock();
KV_LOG(INFO) << "bind on " << url << " success with fd: " << fd;
return fd;
}
void TcpServer::stop(int fd) {
if (fd < 0) {
KV_LOG(ERROR) << "error with fd: " << fd;
return;
}
mutex_.lock();
auto it = std::find(fds_.begin(), fds_.end(), fd);
if (it != fds_.end()) {
mutex_.unlock();
KV_LOG(ERROR) << "stop with fd: " << fd;
return ;
}
fds_.erase(it);
mutex_.unlock();
nn_close(fd);
KV_LOG(INFO) << "stop: " << fd;
}
void TcpServer::stopAll() {
std::lock_guard<std::mutex> lock(mutex_);
for (auto & fd : fds_) {
fds_.clear();
}
fds_.clear();
}
void TcpServer::processRecv(int fd, std::shared_ptr<RpcProcess> process) {
if (fd == -1 || process == nullptr) {
return ;
}
std::mutex mtx;
std::condition_variable cv;
std::function<void (char *, int)> cb =
[&] (char * buf, int len) {
if (buf == nullptr || len < 0) {
KV_LOG(ERROR) << "reply callback param error, buf is nullptr or len =" << len;
return;
}
int rc = nn_send(fd, buf, len, 0);
if (rc < 0) {
NN_LOG(ERROR, "nn_send with fd: " << fd);
} else {
cv.notify_one();
}
};
char * recv_buf;
//local process no more than 50ms, or client will retry
std::chrono::milliseconds duration(50);
while(1) {
std::unique_lock<std::mutex> lock(mtx);
cv.wait_for(lock, duration);
int rc = nn_recv(fd, &recv_buf, NN_MSG, 0);
if (rc < 0) {
NN_LOG(ERROR, "nn_recv with fd: " << fd);
break;
}
char * buf = new char [rc];
memcpy(buf, recv_buf, rc);
nn_freemsg(recv_buf);
process->Insert(buf, rc, cb);
}
}
| [
"[email protected]"
] | |
6f45f63eb158ce94d24c2d48dca573320847f495 | ed9da529d65279fa7904494fd5f9abcf682b6547 | /ParticlePlay.h | 6df36fbe4a9a962e8082d33546446005a65f2a80 | [] | no_license | AnnoyedSloth/Emeth | 772a9d63bdeb6157f7e4f7902efe0482c69d56a3 | a6396a63e48e13a71973b2e5458fc1080592a0ba | refs/heads/master | 2020-03-29T08:28:40.847853 | 2018-11-04T18:59:09 | 2018-11-04T18:59:09 | 128,533,609 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 579 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Actor.h"
#include "ParticlePlay.generated.h"
UCLASS()
class EMETH_API AParticlePlay : public AActor
{
GENERATED_BODY()
UPROPERTY(EditDefaultsOnly, Category = Effect)
class UParticleSystem* explosionFX;
public:
// Sets default values for this actor's properties
AParticlePlay(const FObjectInitializer& ObjectInitializer);
protected:
// Called when the game starts or when spawned
virtual void BeginPlay() override;
};
| [
"[email protected]"
] | |
8a3d2ec382f430ad5dbb56ebc1eb319395b68752 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/ComputerSystemElementSettingData/tests/ComputerSystemElementSettingData.Tests/UNIX_ComputerSystemElementSettingDataFixture.cpp | 0cbd907ccc86777ec4787ca19ef560753fba4833 | [
"MIT"
] | permissive | brunolauze/openpegasus-providers | 3244b76d075bc66a77e4ed135893437a66dd769f | f24c56acab2c4c210a8d165bb499cd1b3a12f222 | refs/heads/master | 2020-04-17T04:27:14.970917 | 2015-01-04T22:08:09 | 2015-01-04T22:08:09 | 19,707,296 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,647 | cpp | //%LICENSE////////////////////////////////////////////////////////////////
//
// Licensed to The Open Group (TOG) under one or more contributor license
// agreements. Refer to the OpenPegasusNOTICE.txt file distributed with
// this work for additional information regarding copyright ownership.
// Each contributor licenses this file to you under the OpenPegasus Open
// Source License; you may not use this file except in compliance with the
// License.
//
// 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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#include "UNIX_ComputerSystemElementSettingDataFixture.h"
#include <ComputerSystemElementSettingData/UNIX_ComputerSystemElementSettingDataProvider.h>
UNIX_ComputerSystemElementSettingDataFixture::UNIX_ComputerSystemElementSettingDataFixture()
{
}
UNIX_ComputerSystemElementSettingDataFixture::~UNIX_ComputerSystemElementSettingDataFixture()
{
}
void UNIX_ComputerSystemElementSettingDataFixture::Run()
{
CIMName className("UNIX_ComputerSystemElementSettingData");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_ComputerSystemElementSettingData _p;
UNIX_ComputerSystemElementSettingDataProvider _provider;
Uint32 propertyCount;
CIMOMHandle omHandle;
_provider.initialize(omHandle);
_p.initialize();
for(int pIndex = 0; _p.load(pIndex); pIndex++)
{
CIMInstance instance = _provider.constructInstance(className,
nameSpace,
_p);
CIMObjectPath path = instance.getPath();
cout << path.toString() << endl;
propertyCount = instance.getPropertyCount();
for(Uint32 i = 0; i < propertyCount; i++)
{
CIMProperty propertyItem = instance.getProperty(i);
if (propertyItem.getType() == CIMTYPE_REFERENCE) {
CIMValue subValue = propertyItem.getValue();
CIMInstance subInstance;
subValue.get(subInstance);
CIMObjectPath subPath = subInstance.getPath();
cout << " Name: " << propertyItem.getName().getString() << ": " << subPath.toString() << endl;
Uint32 subPropertyCount = subInstance.getPropertyCount();
for(Uint32 j = 0; j < subPropertyCount; j++)
{
CIMProperty subPropertyItem = subInstance.getProperty(j);
cout << " Name: " << subPropertyItem.getName().getString() << " - Value: " << subPropertyItem.getValue().toString() << endl;
}
}
else {
cout << " Name: " << propertyItem.getName().getString() << " - Value: " << propertyItem.getValue().toString() << endl;
}
}
cout << "------------------------------------" << endl;
cout << endl;
}
_p.finalize();
}
| [
"[email protected]"
] | |
3fb5fcd7af6c03233c3d234574dedcc31b6fc817 | 0faebfb92745a4c42c3e3a9f5093882ca9d1e1db | /tests/unit_tests/main.cc | 890dc9e08caaada22a28300aec94eb96864b06d7 | [
"BSD-3-Clause"
] | permissive | ChristopherBilg/ntcp2 | 202e92a6f006fe8ebdb4b49f33a5220fe1e8bce5 | cbc68d99bb9035be545365ac99d24c3a9f43e45f | refs/heads/master | 2022-01-13T07:26:38.700549 | 2018-12-26T03:49:24 | 2019-01-18T01:29:49 | 443,884,820 | 1 | 0 | BSD-3-Clause | 2022-01-02T22:37:06 | 2022-01-02T22:37:05 | null | UTF-8 | C++ | false | false | 1,619 | cc | /* copyright (c) 2018, oneiric
* all rights reserved.
*
* redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * neither the name of the copyright holder nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* this software is provided by the copyright holders and contributors "as is"
* and any express or implied warranties, including, but not limited to, the
* implied warranties of merchantability and fitness for a particular purpose are
* disclaimed. in no event shall the copyright holder or contributors be liable
* for any direct, indirect, incidental, special, exemplary, or consequential
* damages (including, but not limited to, procurement of substitute goods or
* services; loss of use, data, or profits; or business interruption) however
* caused and on any theory of liability, whether in contract, strict liability,
* or tort (including negligence or otherwise) arising in any way out of the use
* of this software, even if advised of the possibility of such damage.
*/
#define CATCH_CONFIG_MAIN
#include <catch2/catch.hpp>
| [
"[email protected]"
] | |
03a5c72e954acddd553d0d430ea3298a5f81b5b8 | 03a146294aee9187472fc89f6d58d08bcf7dccab | /end-2-term-projects/wcc2/load-geojson-test/src/vv_extrude_font.cpp | f5550ab471b6a8da1fec33b6c3391f9d10890e87 | [] | no_license | vvzen/MACA | c36f0113e1e65cd296769d2c60097c45039f61d6 | e7fb422939c7627e493fd95fa4d3a7fdb700af6f | refs/heads/master | 2021-10-08T15:04:48.061607 | 2018-12-13T19:56:36 | 2018-12-13T19:56:36 | 113,078,541 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,250 | cpp | #include "vv_extrude_font.h"
//--------------------------------------------------------------
// Original credits go to jefftimeisten, see https://forum.openframeworks.cc/t/extrude-text-into-3d/6938
//
// This method returns a vector containing the vbo meshes required
// to render the front, back and sides of each character in the given string.
// ALERT! Spaces inside the passed string will be converted to underscores.
//
// @example:
//
// void ofApp::setup(){
// my_extruded_word is a vector<ofVboMesh>
// my_extruded_word = extrude_mesh_from_text(word, font, extrusion_depth, scale);
// }
//
// void ofApp::draw(){
// ofPushMatrix();
// ofScale(1, -1, 1); // flip y axis
// for (int m = 0; m < my_extruded_word.size(); m++){
// my_extruded_word.at(m).draw();
// }
// ofPopMatrix();
// }
//--------------------------------------------------------------
vector<ofVboMesh> extrude_mesh_from_text(string word, ofTrueTypeFont & font, float extrusion_depth, float scale=1, bool get_front_only=false){
// replace spaces with underscores
std::replace(word.begin(), word.end(), ' ', '_');
// contains all of the paths of the current word
// last argument is the numer of samples
vector <ofPath> word_paths = get_string_as_sampled_points(font, word, 60);
vector <ofVboMesh> front_meshes, back_meshes, side_meshes;
// meshes for the sides and the front of the 3d extruded text
vector<ofVboMesh> all_meshes; // returned meshese (sides + front + back)
// for every character, get its path
for (int i = 0; i < word_paths.size(); i++){
ofVboMesh current_char_mesh;
// 1. create the front mesh using a temporary ofPath and then extract its tessellation
// for every character break it out to polylines
// (simply a collection of the inner and outer points)
vector <ofPolyline> char_polylines = word_paths.at(i).getOutline();
ofVboMesh front; // the final vbos used to store the vertices
ofPath front_path; // a temp path used for computing the tessellation of the letter shape
// now we build an ofPath using the vertices from the character polylines
// first loop is for each polyline in the character
for (int c = 0; c < char_polylines.size(); c++){
// FRONT AND BACK
// this loop is for each point on the polyline
for (int p = 0; p < char_polylines[c].size(); p++){
if (p == 0){
front_path.moveTo(char_polylines[c][p]);
}
else {
front_path.lineTo(char_polylines[c][p]);
}
}
}
front = front_path.getTessellation();
ofVec3f * front_vertices = front.getVerticesPointer();
// compute the front by just offsetting the vertices of the required amount
ofVboMesh back = front_path.getTessellation();
ofVec3f * back_vertices = back.getVerticesPointer();
for (int v = 0; v < front.getNumVertices(); v++){
front_vertices[v].z += extrusion_depth;
// scale the mesh
front_vertices[v] *= scale;
back_vertices[v] *= scale;
}
current_char_mesh.append(front);
if (!get_front_only) current_char_mesh.append(back);
all_meshes.push_back(current_char_mesh);
if (!get_front_only) {
// 2. make the extruded sides
vector <ofPolyline> lines = word_paths.at(i).getOutline();
for (int j = 0; j < char_polylines.size(); j++){
// SIDES
ofVboMesh side;
vector <ofPoint> points = char_polylines.at(j).getVertices();
// vector <ofPoint> points = char_polylines[c];
int k = 0;
for (k = 0; k < points.size()-1; k++){
// skip half of the points
ofPoint p1 = points.at(k+0);
ofPoint p2 = points.at(k+1);
// // scale the mesh
p1 *= scale;
p2 *= scale;
side.addVertex(p1);
side.addVertex(p2);
side.addVertex(ofPoint(p1.x, p1.y, p1.z + extrusion_depth * scale));
side.addVertex(ofPoint(p2.x, p2.y, p2.z + extrusion_depth * scale));
side.addVertex(p2);
}
// connect the last to the first
ofPoint p1 = points.at(k);
ofPoint p2 = points.at(0);
// scale the mesh
p1 *= scale;
p2 *= scale;
side.addVertex(p1);
side.addVertex(p2);
side.addVertex(ofPoint(p1.x, p1.y, p1.z + extrusion_depth * scale));
side.addVertex(ofPoint(p1.x, p1.y, p1.z + extrusion_depth * scale));
side.addVertex(ofPoint(p2.x, p2.y, p2.z + extrusion_depth * scale));
side.addVertex(p2);
side.setMode(OF_PRIMITIVE_TRIANGLE_STRIP);
all_meshes.push_back(side);
}
}
}
return all_meshes;
}
//--------------------------------------------------------------
// this handy method can be used as a substitute of the default font.getStringAsPoints()
// since it gives you the chance to resample the polylines and get a lower number of points (thus optimising speed)
//--------------------------------------------------------------
vector <ofPath> get_string_as_sampled_points(ofTrueTypeFont & font, string s, int num_of_samples){
vector <ofPath> string_paths;
vector <ofTTFCharacter> paths = font.getStringAsPoints(s);
// find the biggest character in terms of perimeter (used for uniform resampling)
int max_perimeter = 0;
for (int i = 0; i < paths.size(); i++){
vector <ofPolyline> polylines = paths[i].getOutline();
for (int j = 0; j < polylines.size(); j++){
if (polylines[j].getPerimeter() > max_perimeter) max_perimeter = polylines[j].getPerimeter();
}
}
// for every character, get its path
for (int i = 0; i < paths.size(); i++){
// for every character break it out to polylines
vector <ofPolyline> polylines = paths[i].getOutline();
// this path will store the new points sampled
ofPath current_path;
// for every polyline, resample it
for (int j = 0; j < polylines.size(); j++){
// int num_of_points = ofMap(polylines[j].getPerimeter(), 0, max_perimeter, 0, num_of_samples, true);
int num_of_points = num_of_samples;
for (int i = 0; i < num_of_points; i++){
if (i == 0){
current_path.moveTo(ofPoint(polylines[j].getPointAtPercent(float(i+1) / num_of_points)));
}
else {
current_path.lineTo(ofPoint(polylines[j].getPointAtPercent(float(i+1) / num_of_points)));
}
}
current_path.close();
}
string_paths.push_back(current_path);
}
return string_paths;
} | [
"[email protected]"
] | |
8cedcb9ff77440be23479d64f909ce4703c87b5d | f207164511f0dfe3f01f6e0c21fd7548e626397f | /dom/media/mediasource/ResourceQueue.h | 78d60169a838d3977ca0d8662c8676c7dd5a477e | [] | no_license | PortableApps/palemoon27 | 24dbac1a4b6fe620611f4fb6800a29ae6f008d37 | 3d7e107cc639bc714906baad262a3492372e05d7 | refs/heads/master | 2023-08-15T12:32:23.822300 | 2021-10-11T01:54:45 | 2021-10-11T01:54:45 | 416,058,642 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,758 | h | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef MOZILLA_RESOURCEQUEUE_H_
#define MOZILLA_RESOURCEQUEUE_H_
#include "nsDeque.h"
#include "MediaData.h"
namespace mozilla {
class ErrorResult;
// A SourceBufferResource has a queue containing the data that is appended
// to it. The queue holds instances of ResourceItem which is an array of the
// bytes. Appending data to the SourceBufferResource pushes this onto the
// queue.
// Data is evicted once it reaches a size threshold. This pops the items off
// the front of the queue and deletes it. If an eviction happens then the
// MediaSource is notified (done in SourceBuffer::AppendData) which then
// requests all SourceBuffers to evict data up to approximately the same
// timepoint.
struct ResourceItem {
explicit ResourceItem(MediaLargeByteBuffer* aData);
size_t SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) const;
nsRefPtr<MediaLargeByteBuffer> mData;
};
class ResourceQueue : private nsDeque {
public:
ResourceQueue();
// Returns the logical byte offset of the start of the data.
uint64_t GetOffset();
// Returns the length of all items in the queue plus the offset.
// This is the logical length of the resource.
uint64_t GetLength();
// Copies aCount bytes from aOffset in the queue into aDest.
void CopyData(uint64_t aOffset, uint32_t aCount, char* aDest);
void AppendItem(MediaLargeByteBuffer* aData);
// Tries to evict at least aSizeToEvict from the queue up until
// aOffset. Returns amount evicted.
uint32_t Evict(uint64_t aOffset, uint32_t aSizeToEvict,
ErrorResult& aRv);
uint32_t EvictBefore(uint64_t aOffset, ErrorResult& aRv);
uint32_t EvictAll();
size_t SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) const;
#if defined(DEBUG)
void Dump(const char* aPath);
#endif
private:
ResourceItem* ResourceAt(uint32_t aIndex) const;
// Returns the index of the resource that contains the given
// logical offset. aResourceOffset will contain the offset into
// the resource at the given index returned if it is not null. If
// no such resource exists, returns GetSize() and aOffset is
// untouched.
uint32_t GetAtOffset(uint64_t aOffset, uint32_t *aResourceOffset);
ResourceItem* PopFront();
// Logical length of the resource.
uint64_t mLogicalLength;
// Logical offset into the resource of the first element in the queue.
uint64_t mOffset;
};
} // namespace mozilla
#endif /* MOZILLA_RESOURCEQUEUE_H_ */
| [
"[email protected]"
] | |
de419d5c37c2f2ad656e4fb9bcb38f89417b8a71 | a7229f75af58bbe6e5dff85566324baf650aa089 | /meikaiCbasic/c9/e9-10.cpp | efd6518519edce1417109c90cff6f6b17f2c1314 | [
"MIT"
] | permissive | CC-WO/meikaiCbasic | beca7f7a837a0fff7128a7e3e3cc5f19121864d9 | a049de67b3bdbbf4185a6452936a4482df4b98f6 | refs/heads/main | 2023-01-30T11:53:18.397878 | 2020-12-12T11:53:33 | 2020-12-12T11:53:33 | 320,818,488 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 441 | cpp | //文字列str内のすべての数字文字を削除する関数を作成せよ
#include <stdio.h>
void del_digit(char str[])
{
int ma[] = { 0 };
unsigned i = 0;
while (str[i]){
if (str[i] >= '0'&& str[i] <= '9')
str[i] = '\0';
i++;
}
}
int main(void)
{
char sa[100];
printf("文字列を入力してください:");
scanf_s("%s", sa);
del_digit(sa);
printf("%s\n", sa);
return(0);
} | [
"[email protected]"
] | |
2939f1229da089925a3ab40345a9fa8f7e6b55cb | 747e2d79f77c64094de69df9128a4943c170d171 | /Info/Info/Items/IndexedItemInfoManager.cpp | 2b3fb67d646396cbf0b2e7f5c703ceba041a5fb4 | [
"MIT"
] | permissive | Teles1/LuniaAsio | 8854b6d59e5b2622dec8eb0d74c4e4a6cafc76a1 | 62e404442cdb6e5523fc6e7a5b0f64a4471180ed | refs/heads/main | 2023-06-14T00:39:11.740469 | 2021-07-05T23:29:44 | 2021-07-05T23:29:44 | 383,286,395 | 0 | 0 | MIT | 2021-07-05T23:29:45 | 2021-07-05T23:26:46 | C++ | UTF-8 | C++ | false | false | 3,588 | cpp | #include "IndexedItemInfoManager.h"
#include <Core/GameConstants.h>
namespace Lunia {
namespace XRated {
namespace Database {
namespace Info {
void IndexedItemInfoManager::LoadBinaryData()
{
loader = CreateLoader(L"Database/ItemInfos.b");
itemManager = CreateIndexedManagerWithMap(loader);
categoryManager = CreateIndexedManagerWithElement(loader, L"Categorys");
unidentifiedItemManager = CreateIndexedManagerWithMap(loader);
itemManager->Load(L"Database/ItemInfosIndex.b");
categoryManager->Load(L"Database/ItemCategoryListIndex.b");
categoryManager->Get(CategoryList);
unidentifiedItemManager->Load(L"Database/UnIdentifiedItemInfosIndex.b");
}
void IndexedItemInfoManager::MakeIndexAndSave()
{
Lunia::XRated::Database::Info::ItemInfo data1;
Lunia::XRated::UnidentifiedItemInfo data2;
loader = CreateLoader(L"Database/ItemInfos.b");
itemManager = CreateIndexedManagerWithMap(loader, data1);
unidentifiedItemManager = CreateIndexedManagerWithMap(loader, data2);
categoryManager = CreateIndexedManagerWithElement(loader, L"Categorys", CategoryList);
itemManager->Save(L"Database/ItemInfosIndex.b");
categoryManager->Save(L"Database/ItemCategoryListIndex.b");
unidentifiedItemManager->Save(L"Database/UnIdentifiedItemInfosIndex.b");
}
Lunia::XRated::Database::Info::ItemInfo* IndexedItemInfoManager::Retrieve(uint32 hash)
{
ItemInfoMap::iterator ita = Items.find(hash);
if (ita != Items.end())
return &ita->second;
else
{
if (itemManager == NULL) return NULL;
Lunia::XRated::Database::Info::ItemInfo data;
if (itemManager->Get(hash, data))
{
Items[hash] = data;
return &Items[hash];
}
else
return NULL;
}
}
Lunia::XRated::Database::Info::ItemInfo* IndexedItemInfoManager::Retrieve(const wchar_t* id)
{
return Retrieve(Lunia::StringUtil::Hash(id));
}
Lunia::XRated::UnidentifiedItemInfo* IndexedItemInfoManager::RetrieveUnidentifiedItem(Lunia::uint32 hash)
{
UnidentifiedItemInfoMap::iterator ita = UnidentifiedItems.find(hash);
if (ita != UnidentifiedItems.end())
return &ita->second;
else
{
if (unidentifiedItemManager == NULL) return NULL;
Lunia::XRated::UnidentifiedItemInfo data;
if (unidentifiedItemManager->Get(hash, data))
{
UnidentifiedItems[hash] = data;
return &UnidentifiedItems[hash];
}
else
{
std::map<uint32, UnidentifiedItemInfo>::iterator iter = eventUnidentifiedItems.find(hash);
if (iter != eventUnidentifiedItems.end())
return &iter->second;
else
return NULL;
}
}
}
Lunia::XRated::UnidentifiedItemInfo* IndexedItemInfoManager::RetrieveUnidentifiedItem(const wchar_t* id)
{
return RetrieveUnidentifiedItem(Lunia::StringUtil::Hash(id));
}
bool IndexedItemInfoManager::Remove(Lunia::uint32 hash)
{
ItemInfoMap::iterator it = Items.find(hash);
if (it != Items.end())
{
Items.erase(it);
return true;
}
UnidentifiedItemInfoMap::iterator ita = UnidentifiedItems.find(hash);
if (ita != UnidentifiedItems.end())
{
UnidentifiedItems.erase(ita);
return true;
}
return false;
}
bool IndexedItemInfoManager::Remove(const wchar_t* id)
{
return Remove(Lunia::StringUtil::Hash(id));
}
}
}
}
} | [
"[email protected]"
] | |
a3a7ca1de9df3384b225402c9cc334f4fb707a08 | 85f1cd01c68731a30bff2b99a9e21e5d3a81fb70 | /math/kangtuo.cpp | d6d843d570531a6adbc13867db642eb9ab92410d | [] | no_license | ddayzzz/algorithm-and-basic-apps | f146ee9a31a61d92c963d6a14d17c59f3de67740 | 7ea0cedd32df0b8d207e85696e30105e87b003c8 | refs/heads/master | 2020-04-01T06:24:17.842635 | 2019-10-09T15:11:51 | 2019-10-09T15:11:51 | 152,945,967 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp |
#include <iostream>
using namespace std;
using ll = long long;
ll fact[11];
void factor()
{
fact[0] = fact[1] = 1;
for (int j = 2; j <= 10; ++j)
{
fact[j] = fact[j - 1] * j;
}
}
bool flag[10];
int main()
{
// 使用逆康托展开
factor(); // 初始化
int n, r, t, j, l;
int init = 10;
cin >> n;
n--;
do {
--init;
if (init < 0)
break;
t = n / fact[init]; // 这个是商, 表示有几个数字 < 他
r = n % fact[init]; // 这个是余数
// 查找是否已经标记了
// 注意, 比t个大的是要忽略掉已经被标记的数字。纯标记是无用的,因为下一个未标记的位置不一定会比所有的 t 大
// 需要定义另外的索引, 用来记录出现第一个可用的位置的次数
for (j = 1, l = 0; l <= t; ++j)
{
if (!flag[j])
++l;
}
flag[--j] = true;
cout << j - 1;
n = r;
} while (true);
cout << endl;
return 0;
} | [
"[email protected]"
] | |
0922a188cbb98736d4b9fe4d3d62bbf5e2fc6576 | 3a95eb459a1ce5e27105bb66e7c57e9bf0ee5e11 | /VoIP/WavePlayback.h | e6b59c868757359349e6db96e42cfa79452f61ca | [] | no_license | nwaycn/jrtp-transmit | d8e709f48092ebcfc9e53ee52af3d2632bb6eac3 | 0c93362713dc39dfe1dcf0ece0b212f2a1fda191 | refs/heads/master | 2016-09-12T21:12:02.588491 | 2016-04-12T04:00:48 | 2016-04-12T04:00:48 | 56,027,408 | 1 | 1 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 754 | h | // WavePlayback.h: interface for the CWavePlayback class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_WAVEPLAYBACK_H__592109B9_0102_4857_B5CB_58B445201331__INCLUDED_)
#define AFX_WAVEPLAYBACK_H__592109B9_0102_4857_B5CB_58B445201331__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "WaveOut.h"
#include "AudioCode.h"
class CWavePlayback : public CWaveOut
{
public:
BOOL Playback(char* pBuffer,UINT uiSize);
CWavePlayback(CAudioCode* pCode);
virtual ~CWavePlayback();
protected:
// ±àÂëÊý¾Ý
char m_AudioBuffer[102400];
// ±àÂëÆ÷
CAudioCode* m_pACode;
};
#endif // !defined(AFX_WAVEPLAYBACK_H__592109B9_0102_4857_B5CB_58B445201331__INCLUDED_)
| [
"李浩"
] | 李浩 |
1db5ece1dc9144d8c2bb3d725ed6258652c7fe4d | b4cf2927124d04541ef6947d9ab4bda83a8fed84 | /2practica/Practica2/ejercicio4.h | 52c737cf95e7c43685508a8b39bdb5d5814eea89 | [] | no_license | santichialvo/practica-imagenes | 663ca2597b807a89377e548bad3991b1c10cf087 | 06e6e0fea4336e2fc7475f1800f3802d32d94380 | refs/heads/master | 2021-01-25T09:39:00.907847 | 2017-06-09T15:31:59 | 2017-06-09T15:31:59 | 93,871,849 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,212 | h | #include <iostream>
#include "pdi_functions.h"
#include "utils.h"
#include <math.h>
#include <cstdio>
using namespace std;
void ejercicio4(char** argv)
{
Mat img;
img = imread(argv[1],1);
if (img.empty()) cout << "Error loading the image" << endl;
// la transformo a un canal
cvtColor(img,img,CV_BGR2GRAY);
Mat *bitplanes = new Mat[8];
float *ecm = new float[8];
Mat imgf(img.rows,img.cols,CV_64F);
normalize(img, imgf, 0.0, 1.0, CV_MINMAX, CV_64F);
for(int i=0;i<8;i++) {
bitplanes[i] = Mat(img.rows,img.cols,0);
ecm[i] = 0;
for(int j=0;j<img.rows;j++) {
for(int k=0;k<img.cols;k++) {
// planos de bits
// bitplanes[i].at<uchar>(j,k) = (1<<i)&img.at<uchar>(j,k);
// sucesivos planos subiendo la significancia
bitplanes[i].at<uchar>(j,k) = img.at<uchar>(j,k)>>(7-i);
}
}
normalize(bitplanes[i], bitplanes[i], 0.0, 1.0, CV_MINMAX, CV_64F);
ecm[i] = 0;
for(int j=0;j<img.rows;j++)
for(int k=0;k<img.cols;k++)
ecm[i] += pow(bitplanes[i].at<double>(j,k)-imgf.at<double>(j,k),2);
ecm[i] /= (img.rows*img.cols);
printf("ECM de la imagen %d: %f \n",i,ecm[i]);
}
ShowMultipleImages(bitplanes, 8, 4, img.rows, img.cols, 10);
waitKey(0);
}
| [
"[email protected]"
] | |
fa53ac0f98b083c9dda6b8b8410106fc5cf55df9 | c7272e93df5e9f68c36385308da28a944e300d9d | /26. Remove Duplicates from Sorted Array.h | 897919028aaa66fefb52938ab83834ea994e1dac | [
"MIT"
] | permissive | Mids/LeetCode | 368a941770bc7cb96a85a7b523d77446717a1f31 | 589b9e40acfde6e2dde37916fc1c69a3ac481070 | refs/heads/master | 2023-08-13T13:39:11.476092 | 2021-09-26T09:29:18 | 2021-09-26T09:29:18 | 326,600,963 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 536 | h | //
// Created by jin on 1/11/2021.
//
#ifndef LEETCODE_26_REMOVE_DUPLICATES_FROM_SORTED_ARRAY_H
#define LEETCODE_26_REMOVE_DUPLICATES_FROM_SORTED_ARRAY_H
using namespace std;
class Solution {
public:
int result = 0, val;
int size;
int removeDuplicates(vector<int> &nums) {
size = nums.size();
if (size == 0) return 0;
for (int i = 1; i < size; ++i) {
val = nums[i];
if (nums[result] != val) {
nums[++result] = val;
}
}
return result + 1;
}
};
#endif //LEETCODE_26_REMOVE_DUPLICATES_FROM_SORTED_ARRAY_H
| [
"[email protected]"
] | |
2958e2bfcc79bc44d827fb7e02ee849155fc8f19 | 021927adc43d514a80b73bdcf9a3f7f2ded464bc | /Geometry/src/Geometry/Measure/Perimeter.cpp | f8e068e67eb28075e6ac5139cfbbb0861ae3bdbf | [
"Apache-2.0"
] | permissive | edson-a-soares/geometric_acyclic_visitor | f0e044ba9587253770b0a888cb1a4900fcedb302 | b2aff910d8606d4ad264d53f6e66aa03141e5cf6 | refs/heads/master | 2021-01-21T09:53:44.402004 | 2017-03-06T18:30:30 | 2017-03-06T18:30:30 | 83,348,712 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,334 | cpp | #include <cmath>
#include <iostream>
#include "Geometry/Measure/Perimeter.h"
namespace Geometry
{
namespace Measure
{
Perimeter::Perimeter(Calculation::Perimeter & perimeter)
: calculator(perimeter)
{ }
void Perimeter::visit(Polygon::Square & quadrilateral)
{
std::cout << "Perimeter: "
<< calculator.calculate(quadrilateral)
<< std::endl;
}
void Perimeter::visit(Polygon::Rectangle & quadrilateral)
{
std::cout << "Perimeter: "
<< calculator.calculate(quadrilateral)
<< std::endl;
}
void Perimeter::visit(Polygon::Scalene & triangle)
{
std::cout << "Perimeter: "
<< calculator.calculate(triangle)
<< std::endl;
}
void Perimeter::visit(Polygon::Isosceles & triangle)
{
std::cout << "Perimeter: "
<< calculator.calculate(triangle)
<< std::endl;
}
void Perimeter::visit(Polygon::Equilateral & triangle)
{
std::cout << "Perimeter: "
<< calculator.calculate(triangle)
<< std::endl;
}
}
}
| [
"[email protected]"
] | |
be5f2c2d416f95c1c7a3a1a2e5407fd6d64e56b7 | 7e027baea80b756ee5d54ef6dc2590437250af28 | /level_zero/tools/source/sysman/sysman_device/sysman_device_imp.h | 6ce2533aadabcc269d0b0844bbc91444eaf98ecc | [
"MIT"
] | permissive | raiyanla/compute-runtime | fb3bcb39b74facec80fb80489a602a28e7c11ec0 | 43433244f9d17e9c989116808757705754ddbfee | refs/heads/master | 2021-03-16T11:18:16.394432 | 2020-03-12T23:33:22 | 2020-03-15T21:13:19 | 246,900,824 | 0 | 0 | MIT | 2020-03-12T18:07:51 | 2020-03-12T18:07:50 | null | UTF-8 | C++ | false | false | 1,263 | h | /*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#pragma once
#include <level_zero/zet_api.h>
#include "os_sysman_device.h"
#include "sysman_device.h"
#include <vector>
namespace L0 {
class SysmanDeviceImp : public sysmanDevice {
public:
void init() override;
ze_result_t deviceGetProperties(zet_sysman_properties_t *pProperties) override;
SysmanDeviceImp(OsSysman *pOsSysman, ze_device_handle_t hCoreDevice) : pOsSysman(pOsSysman),
hCoreDevice(hCoreDevice) { pOsSysmanDevice = nullptr; };
~SysmanDeviceImp() override;
SysmanDeviceImp(OsSysmanDevice *pOsSysmanDevice, ze_device_handle_t hCoreDevice) : pOsSysmanDevice(pOsSysmanDevice),
hCoreDevice(hCoreDevice) { init(); };
// Don't allow copies of the sysmanDeviceImp object
SysmanDeviceImp(const SysmanDeviceImp &obj) = delete;
SysmanDeviceImp &operator=(const SysmanDeviceImp &obj) = delete;
private:
OsSysman *pOsSysman;
OsSysmanDevice *pOsSysmanDevice;
zet_sysman_properties_t sysmanProperties;
ze_device_handle_t hCoreDevice;
};
} // namespace L0
| [
"[email protected]"
] | |
1fe605fce29a214d572363c937bd21cb1d6ed7c5 | 2786c37ab338ed279aa2a535d9a8143aa2e82b57 | /libs/foe_imex/src/log.hpp | eae3c457b411cc8f3e004ba9ee3f5ee9e87233df | [
"Apache-2.0",
"MIT"
] | permissive | StableCoder/foe-engine | 12cdcc226bb5d1941adb72b53f8fc159ed7533c6 | b494fad60a36f0b11c526a5648277643edd4095f | refs/heads/main | 2023-08-21T18:30:50.777210 | 2023-08-21T00:33:05 | 2023-08-21T00:33:05 | 307,215,754 | 16 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 133 | hpp | // Copyright (C) 2021 George Cave.
//
// SPDX-License-Identifier: Apache-2.0
#include <foe/log.h>
FOE_DECLARE_LOG_CATEGORY(foeImex) | [
"[email protected]"
] | |
bf0013936603aa5bc2ccb861547f52a07f8d8dfb | b73c4889fc75167bca03a7e784a9bb6ff001db18 | /dft.h | 7700acace48e174c06f0a9f46ae9666cdd56c7d5 | [
"MIT"
] | permissive | Atrix256/BlueNoiseDitherPatternGeneration | a3a81e49fe85f9ae5020b1c1439b5179c7c2bf2c | 5120a9e0bcd26c22eb22f803d5add068d0335cd3 | refs/heads/master | 2020-05-27T17:56:30.218213 | 2019-06-19T12:15:13 | 2019-06-19T12:15:13 | 188,732,287 | 16 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,813 | h | #pragma once
#include "simple_fft/fft_settings.h"
#include "simple_fft/fft.h"
#include "misc.h"
#include <algorithm>
#include <vector>
struct ComplexImage2D
{
ComplexImage2D(size_t w, size_t h)
{
m_width = w;
m_height = h;
pixels.resize(w*h, real_type(0.0f));
}
size_t m_width;
size_t m_height;
std::vector<complex_type> pixels;
complex_type& operator()(size_t x, size_t y)
{
return pixels[y*m_width + x];
}
const complex_type& operator()(size_t x, size_t y) const
{
return pixels[y*m_width + x];
}
};
template <typename T>
void DFT(const std::vector<T>& imageSrc, std::vector<T>& imageDest, size_t width)
{
// convert the source image to float and store it in a complex image so it can be DFTd
ComplexImage2D complexImageIn(width, width);
for (size_t index = 0, count = width * width; index < count; ++index)
complexImageIn.pixels[index] = float(imageSrc[index]) / float(std::numeric_limits<T>::max());
// DFT the image to get frequency of the samples
const char* error = nullptr;
ComplexImage2D complexImageOut(width, width);
simple_fft::FFT(complexImageIn, complexImageOut, width, width, error);
// TODO: for some reason, the DC is huge. i'm not sure why...
complexImageOut(0, 0) = 0.0f;
// get the magnitudes and max magnitude
std::vector<float> magnitudes;
float maxMag = 0.0f;
{
magnitudes.resize(width * width, 0.0f);
float* dest = magnitudes.data();
for (size_t y = 0; y < width; ++y)
{
size_t srcY = (y + width / 2) % width;
for (size_t x = 0; x < width; ++x)
{
size_t srcX = (x + width / 2) % width;
const complex_type& c = complexImageOut(srcX, srcY);
float mag = float(sqrt(c.real()*c.real() + c.imag()*c.imag()));
maxMag = std::max(mag, maxMag);
*dest = mag;
++dest;
}
}
}
// normalize the magnitudes and convert it back to a type T image
//const float c = 1.0f / log(1.0f / 255.0f + maxMag);
{
imageDest.resize(width * width);
const float* src = magnitudes.data();
T* dest = imageDest.data();
for (size_t y = 0; y < width; ++y)
{
for (size_t x = 0; x < width; ++x)
{
//float normalized = c * log(1.0f / 255.0f + *src);
float normalized = *src / maxMag;
float value = Lerp(0, float(std::numeric_limits<T>::max() + 1), normalized);
value = Clamp(0.0f, float(std::numeric_limits<T>::max()), value);
*dest = T(value);
++src;
++dest;
}
}
}
} | [
"[email protected]"
] | |
7c1959c60d0d12046c5eb4baab9e9fc854a9c87b | 164435576ed3e2e9a77a7e8afc3c3359b8ff8801 | /URI/1037.cpp | 1c8c4bc48d7c8168ea814274c38d119f7543e8ec | [] | no_license | mostasimbillah/Programming-Contest | 3debd5ef4075b5f77713e35c48a096fffcecbd9c | 7cdcd516ae5e032c89d42967d8d62370cd7b1b69 | refs/heads/master | 2020-04-16T02:25:54.803337 | 2017-03-24T17:31:59 | 2017-03-24T17:31:59 | 56,076,731 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 479 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
float a;
cin >> a;
if(a>=0&& a<=25 )
{
cout << "Intervalo [0,25]\n";
}
if(a>25 && a<=50)
{
cout << "Intervalo (25,50]\n";
}
if(a>50 && a<=75)
{
cout << "Intervalo (50,75]\n";
}
if(a>75 && a<=100)
{
cout << "Intervalo (75,100]\n";
}
if(a<0 || a>100)
{
cout << "Fora de intervalo\n";
}
return 0;
}
| [
"[email protected]"
] | |
14fa7345dcb80eca173d2fc705588de1accf096b | a3f3c7f7e522217729659e9698e6500dc372bd5a | /Soggy/MyGame/Generated Code/MyGame_SoggyClass.h | eb9ebf6b6d7bf4da96a803d7b352daacd19dae7d | [] | no_license | YellowNoise/DigipenCPP | 0e2b418be9bac72d38614c745f267c4ea0b80a15 | 37345c53334569ecdd98664489a733d8a11b4817 | refs/heads/master | 2021-08-08T20:50:54.726993 | 2017-11-11T05:54:33 | 2017-11-11T05:54:33 | 110,069,247 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,216 | h | #ifndef _MYGAME_SOGGYCLASS_H_
#define _MYGAME_SOGGYCLASS_H_
class SoggyClass:public ProjectFun::Sprite
{
public:
SoggyClass();
SoggyClass(const std::vector<ProjectFun::SpriteAnimationPtr> & animations);
SoggyClass(const SoggyClass & other);
~SoggyClass() ;
SoggyClass * Clone();
void Destroy() ;
void Save(Core::File & file) const;
void Load(Core::File & file) ;
void NetworkSave(ProjectFun::NetworkFile &file) const;
void NetworkLoad(ProjectFun::NetworkFile &file) ;
void NetworkSyncSend(ProjectFun::NetworkFile &file) const;
void NetworkSyncReceive(ProjectFun::NetworkFile & file) ;
void OnStart() ;
void OnEnd() ;
void OnClone(const SoggyClass & other) ;
void inputfn() ;
void ApplyMovement() ;
void ClampSpeed() ;
void jump() ;
void applygrav() ;
int moveforce;
int xmove;
int ymove;
int jumpforce;
int gravforce;
int jumpcounter;
int jumpcountermax;
bool isjumping;
bool intheair;
bool ismoving;
bool ismovingleft;
int blink;
ProjectFun::StateMachine<SoggyClass>::StateMachinePtr PlatformSM;
bool PlatformSM_OnGround_inair(float dt);
bool PlatformSM_OnGround_inair_1(float dt);
bool PlatformSM_inair_OnGround(float dt);
void PlatformSM_OnGround_OnEnter(float dt);
void PlatformSM_OnGround_OnUpdate(float dt);
void PlatformSM_inair_OnEnter(float dt);
void PlatformSM_inair_OnUpdate(float dt);
ProjectFun::StateMachine<SoggyClass>::StateMachinePtr animationsm;
bool animationsm_Idle_Walk(float dt);
bool animationsm_Idle_Win(float dt);
bool animationsm_Idle_Jump(float dt);
bool animationsm_Walk_Idle(float dt);
bool animationsm_Walk_Jump(float dt);
bool animationsm_Jump_Idle(float dt);
void animationsm_Idle_OnEnter(float dt);
void animationsm_Win_OnEnter(float dt);
void animationsm_Win_OnUpdate(float dt);
void animationsm_Walk_OnEnter(float dt);
void animationsm_Jump_OnEnter(float dt);
protected:
void Update(float dt) ;
private:
DECLARE_OBJECT(SoggyClass);
};
ProjectFun::StateMachine<SoggyClass>::StateMachinePtr Create_SoggyClass_PlatformSM_StateMachine(SoggyClass *owner);
ProjectFun::StateMachine<SoggyClass>::StateMachinePtr Create_SoggyClass_animationsm_StateMachine(SoggyClass *owner);
#endif
| [
"[email protected]"
] | |
e54ee79c9eb5ccd8c1b935a63ae0d373ab934268 | a5f0c2f50d0a8e9ac038dd416594aeb6be64ecf6 | /src/pow.cpp | d12b1d1a87098f76df82d09e81629a9d1d4b0f93 | [
"MIT"
] | permissive | materia-project2/materia | 68864e4d9aaf929947602e63a0dc90bb9801b0f5 | 97da7c927eb29f63c34c11df296320cb7c855761 | refs/heads/master | 2021-07-24T00:38:47.868240 | 2017-11-01T18:45:53 | 2017-11-01T18:45:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,966 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "pow.h"
#include "arith_uint256.h"
#include "chain.h"
#include "primitives/block.h"
#include "uint256.h"
#include "util.h"
unsigned int GetNextWorkRequired(const CBlockIndex* pindexLast, const CBlockHeader *pblock, const Consensus::Params& params)
{
unsigned int nProofOfWorkLimit = UintToArith256(params.powLimit).GetCompact();
// Genesis block
if (pindexLast == NULL)
return nProofOfWorkLimit;
// Only change once per difficulty adjustment interval
if ((pindexLast->nHeight+1) % params.DifficultyAdjustmentInterval() != 0)
{
if (params.fPowAllowMinDifficultyBlocks)
{
// Special difficulty rule for testnet:
// If the new block's timestamp is more than 2* 10 minutes
// then allow mining of a min-difficulty block.
if (pblock->GetBlockTime() > pindexLast->GetBlockTime() + params.nPowTargetSpacing*2)
return nProofOfWorkLimit;
else
{
// Return the last non-special-min-difficulty-rules-block
const CBlockIndex* pindex = pindexLast;
while (pindex->pprev && pindex->nHeight % params.DifficultyAdjustmentInterval() != 0 && pindex->nBits == nProofOfWorkLimit)
pindex = pindex->pprev;
return pindex->nBits;
}
}
return pindexLast->nBits;
}
// Go back by what we want to be 14 days worth of blocks
// Materia: 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 = params.DifficultyAdjustmentInterval()-1;
if ((pindexLast->nHeight+1) != params.DifficultyAdjustmentInterval())
blockstogoback = params.DifficultyAdjustmentInterval();
// 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);
return CalculateNextWorkRequired(pindexLast, pindexFirst->GetBlockTime(), params);
}
unsigned int CalculateNextWorkRequired(const CBlockIndex* pindexLast, int64_t nFirstBlockTime, const Consensus::Params& params)
{
if (params.fPowNoRetargeting)
return pindexLast->nBits;
// Limit adjustment step
int64_t nActualTimespan = pindexLast->GetBlockTime() - nFirstBlockTime;
if (nActualTimespan < params.nPowTargetTimespan/4)
nActualTimespan = params.nPowTargetTimespan/4;
if (nActualTimespan > params.nPowTargetTimespan*4)
nActualTimespan = params.nPowTargetTimespan*4;
// Retarget
arith_uint256 bnNew;
arith_uint256 bnOld;
bnNew.SetCompact(pindexLast->nBits);
bnOld = bnNew;
// Materia: intermediate uint256 can overflow by 1 bit
bool fShift = bnNew.bits() > 235;
if (fShift)
bnNew >>= 1;
bnNew *= nActualTimespan;
bnNew /= params.nPowTargetTimespan;
if (fShift)
bnNew <<= 1;
const arith_uint256 bnPowLimit = UintToArith256(params.powLimit);
if (bnNew > bnPowLimit)
bnNew = bnPowLimit;
return bnNew.GetCompact();
}
bool CheckProofOfWork(uint256 hash, unsigned int nBits, const Consensus::Params& params)
{
bool fNegative;
bool fOverflow;
arith_uint256 bnTarget;
bnTarget.SetCompact(nBits, &fNegative, &fOverflow);
// Check range
if (fNegative || bnTarget == 0 || fOverflow || bnTarget > UintToArith256(params.powLimit))
return false;
// Check proof of work matches claimed amount
if (UintToArith256(hash) > bnTarget)
return false;
return true;
}
| [
"[email protected]"
] | |
4332cceb3b8694ec50b0ff0febb29e2d9879b8c7 | d2b5d39d639825bf890e801295880c8d400bb5fa | /future/futurerecord.h | 46d3ea3026a12fa0db243dd3d75e3d2ee270ff16 | [] | no_license | wdy0401/gpp_qt | e02962f9d77db8238e36de8a5c48201115aaee4b | 8a6ebd7c4e961c412eef3cebaf9e424bee25234e | refs/heads/master | 2020-04-12T08:59:37.731528 | 2018-07-03T08:04:01 | 2018-07-03T08:04:01 | 26,100,182 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 801 | h | #ifndef FUTURERECORD
#define FUTURERECORD
//维护两份 对应着两个map 一份是snapshot 一份是有时限or个数限制的queue
//有两个map 一个是对应到一个snapshot 一个是对应到snap串
#include<map>
#include<list>
#include<deque>
#include"futuresnapshot.h"
class Futurerecord
{
public:
void updaterecord(std::string InstrumentID, long tm, double BidPrice1 ,double AskPrice1, double BidSize1 ,double AskSize1);
void set_maxqueuelength(unsigned int);
std::map<std::string,Futuresnapshot> get_futuresnapshot();
Futuresnapshot get_lastsnapshot();
private:
std::map<std::string,std::list<Futuresnapshot> > _futurequeue;
std::map<std::string,Futuresnapshot> _futuresnapshot;
Futuresnapshot _lastsnapshot;
unsigned int _maxqueuelength;
};
#endif | [
"[email protected]"
] | |
fdde25c01b94cc78c3bd9f626ea29841cd53a070 | 373b2be982b461bc1c31b52eff5102a6f2b18b9a | /TGA/CG_Demo/header/cCube.h | dcfb26a9482b033d60bc82cf56f4214d2aa99c7a | [] | no_license | LuisJC96/Graphics | 266c476c298c03f5d315a47f4131a57559cfae0f | a4bd5fd07a031f6e3a8cbcd156c9177242de9ec7 | refs/heads/master | 2020-04-29T01:05:36.801381 | 2019-03-15T04:40:15 | 2019-03-15T04:40:15 | 175,718,898 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,048 | h | #pragma once
#ifdef __APPLE__
// For XCode only: New C++ terminal project. Build phases->Compile with libraries: add OpenGL and GLUT
// Import this whole code into a new C++ file (main.cpp, for example). Then run.
// Reference: https://en.wikibooks.org/wiki/OpenGL_Programming/Installation/Mac
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <GLUT/glut.h>
#endif
#ifdef _WIN32
// For VS on Windows only: Download CG_Demo.zip. UNZIP FIRST. Double click on CG_Demo/CG_Demo.sln
// Run
#include "freeglut.h"
#endif
#ifdef __unix__
// For Linux users only: g++ CG_Demo.cpp -lglut -lGL -o CG_Demo
// ./CG_Demo
// Reference: https://www.linuxjournal.com/content/introduction-opengl-programming
#include "GL/freeglut.h"
#include "GL/gl.h"
#endif
#include <stdio.h>
#include <math.h>
#include <time.h>
#include "cTexture.h"
#ifndef __CUBE
#define __CUBE
class Cube
{
public:
Cube ( float side,
bool use_mipmaps );
~Cube ( void );
void draw ( void );
private:
float side;
float hside;
Texture targas[6];
};
#endif __CUBE
| [
"[email protected]"
] | |
8ad9ff203bb7bc03def92c3c0e3686d70aed322d | 786de89be635eb21295070a6a3452f3a7fe6712c | /psddl_pds2psana/tags/V00-01-06/include/fccd.ddl.h | d8172094eeb05ed436710ec5264ebe3dd854afce | [] | no_license | connectthefuture/psdmrepo | 85267cfe8d54564f99e17035efe931077c8f7a37 | f32870a987a7493e7bf0f0a5c1712a5a030ef199 | refs/heads/master | 2021-01-13T03:26:35.494026 | 2015-09-03T22:22:11 | 2015-09-03T22:22:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,802 | h | #ifndef PSDDL_PDS2PSANA_FCCD_DDL_H
#define PSDDL_PDS2PSANA_FCCD_DDL_H 1
// *** Do not edit this file, it is auto-generated ***
#include <vector>
#include <boost/shared_ptr.hpp>
#include "psddl_psana/fccd.ddl.h"
#include "psddl_pdsdata/fccd.ddl.h"
namespace psddl_pds2psana {
namespace FCCD {
class FccdConfigV1 : public Psana::FCCD::FccdConfigV1 {
public:
typedef PsddlPds::FCCD::FccdConfigV1 XtcType;
typedef Psana::FCCD::FccdConfigV1 PsanaType;
FccdConfigV1(const boost::shared_ptr<const XtcType>& xtcPtr);
virtual ~FccdConfigV1();
virtual uint16_t outputMode() const;
virtual uint32_t width() const;
virtual uint32_t height() const;
virtual uint32_t trimmedWidth() const;
virtual uint32_t trimmedHeight() const;
const XtcType& _xtcObj() const { return *m_xtcObj; }
private:
boost::shared_ptr<const XtcType> m_xtcObj;
};
class FccdConfigV2 : public Psana::FCCD::FccdConfigV2 {
public:
typedef PsddlPds::FCCD::FccdConfigV2 XtcType;
typedef Psana::FCCD::FccdConfigV2 PsanaType;
FccdConfigV2(const boost::shared_ptr<const XtcType>& xtcPtr);
virtual ~FccdConfigV2();
virtual uint16_t outputMode() const;
virtual uint8_t ccdEnable() const;
virtual uint8_t focusMode() const;
virtual uint32_t exposureTime() const;
virtual const float* dacVoltages() const;
virtual const uint16_t* waveforms() const;
virtual uint32_t width() const;
virtual uint32_t height() const;
virtual uint32_t trimmedWidth() const;
virtual uint32_t trimmedHeight() const;
virtual std::vector<int> dacVoltages_shape() const;
virtual std::vector<int> waveforms_shape() const;
const XtcType& _xtcObj() const { return *m_xtcObj; }
private:
boost::shared_ptr<const XtcType> m_xtcObj;
};
} // namespace FCCD
} // namespace psddl_pds2psana
#endif // PSDDL_PDS2PSANA_FCCD_DDL_H
| [
"[email protected]@b967ad99-d558-0410-b138-e0f6c56caec7"
] | [email protected]@b967ad99-d558-0410-b138-e0f6c56caec7 |
5398b405935a1e1e89fe312102a74f4938c116a9 | c927840f6cbbe2d0a84950c74deadb7159737d2e | /src/elements/subcomponents/MachineLabelExploration.cpp | 476c1ed695012d6236c5bfa2317a9efeb2943a69 | [
"MIT"
] | permissive | robocup-logistics/rcll_status_board | a777e795173f75800a75a7ca55b60284382cb942 | 2358ca07d72ad090408c0810071b95c03416b02c | refs/heads/master | 2021-07-05T09:28:39.791232 | 2018-07-20T08:06:11 | 2018-07-20T08:06:11 | 218,782,911 | 0 | 0 | MIT | 2021-01-20T10:28:42 | 2019-10-31T14:18:12 | null | UTF-8 | C++ | false | false | 6,766 | cpp | /*
The MIT License (MIT)
Copyright (c) 2017-2018 Florian Eith <[email protected]>
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.
*/
#include <MachineLabelExploration.h>
// MachineLabelExploration ####################################################################
rcll_draw::MachineLabelExploration::MachineLabelExploration(rcll_draw::Team team){
blbl_machinename.setAlignment(rcll_draw::CenterLeft);
blbl_status1.setAlignment(rcll_draw::CenterCenter);
blbl_status2.setAlignment(rcll_draw::CenterCenter);
if (team == rcll_draw::CYAN){
blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);
blbl_machinename.setFrontColor(rcll_draw::C_WHITE);
} else if (team == rcll_draw::MAGENTA){
blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);
blbl_machinename.setFrontColor(rcll_draw::C_WHITE);
} else {
blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);
blbl_machinename.setFrontColor(rcll_draw::C_WHITE);
}
blbl_status1.setBackgroundColor(rcll_draw::C_GREY_LIGHT);
blbl_status2.setBackgroundColor(rcll_draw::C_GREY_LIGHT);
blbl_status1.setFrontColor(rcll_draw::C_BLACK);
blbl_status2.setFrontColor(rcll_draw::C_BLACK);
blbl_machinename.setBorderColor(rcll_draw::C_WHITE);
blbl_status1.setBorderColor(rcll_draw::C_WHITE);
blbl_status2.setBorderColor(rcll_draw::C_WHITE);
blbl_machinename.setFontSize(0.9);
blbl_status1.setFontSize(0.7);
blbl_status2.setFontSize(0.7);
img_status1.setImage(rcll_draw::readImage(rcll_draw::getFile(4,4)));
img_status2.setImage(rcll_draw::readImage(rcll_draw::getFile(4,4)));
}
rcll_draw::MachineLabelExploration::~MachineLabelExploration(){
}
void rcll_draw::MachineLabelExploration::setGeometry(int x, int y, int w, int h){
if (!short_display){
blbl_machinename.setSize(w * 0.34, h);
blbl_status1.setSize(w * 0.33, h);
blbl_status2.setSize(w * 0.33, h);
img_status1.setScale(0.25);
img_status2.setScale(0.25);
blbl_machinename.setFontSize(0.9);
blbl_machinename.setPos(x, y);
blbl_status1.setPos(x + w * 0.34, y);
blbl_status2.setPos(x + w * 0.67, y);
img_status1.setPos(x + w * 0.57, y + (h - img_status1.getH())/2);
img_status2.setPos(x + w * 0.9, y + (h - img_status2.getH())/2);
} else {
blbl_machinename.setSize(w * 0.5, h);
blbl_status1.setSize(w * 0.25, h);
blbl_status2.setSize(w * 0.25, h);
img_status1.setScale(0.25);
img_status2.setScale(0.25);
blbl_machinename.setFontSize(1.0);
blbl_machinename.setPos(x, y);
blbl_status1.setPos(x + w * 0.5, y);
blbl_status2.setPos(x + w * 0.75, y);
img_status1.setPos(x + w * 0.5 + (w * 0.25 - img_status1.getW())/2, y + (h - img_status1.getH())/2);
img_status2.setPos(x + w * 0.75 + (w * 0.25 - img_status2.getW())/2, y + (h - img_status2.getH())/2);
}
}
void rcll_draw::MachineLabelExploration::setShortDisplay(bool short_display){
this->short_display = short_display;
}
void rcll_draw::MachineLabelExploration::setMachine(rcll_vis_msgs::Machine &machine){
blbl_machinename.setContent(" " + machine.name_long + " (" + machine.name_short + ")");
blbl_status1.setBackgroundColor(rcll_draw::C_GREY_LIGHT);
blbl_status2.setBackgroundColor(rcll_draw::C_GREY_LIGHT);
std::string status1, status2;
if (machine.machine_status_exploration1 == 0){
status1 = "unreported";
img_status1.setImage(rcll_draw::readImage(rcll_draw::getFile(4,4)));
} else if (machine.machine_status_exploration1 == 1){
status1 = "correct";
img_status1.setImage(rcll_draw::readImage(rcll_draw::getFile(5,4)));
} else if (machine.machine_status_exploration1 == 2){
status1 = "wrong";
img_status1.setImage(rcll_draw::readImage(rcll_draw::getFile(6,4)));
} else {
status1 = "unknown";
img_status1.setImage(rcll_draw::readImage(""));
}
if (machine.machine_status_exploration2 == 0){
status2 = "unreported";
img_status2.setImage(rcll_draw::readImage(rcll_draw::getFile(4,4)));
} else if (machine.machine_status_exploration2 == 1){
status2 = "correct";
img_status2.setImage(rcll_draw::readImage(rcll_draw::getFile(5,4)));
} else if (machine.machine_status_exploration2 == 2){
status2 = "wrong";
img_status2.setImage(rcll_draw::readImage(rcll_draw::getFile(6,4)));
} else {
status2 = "unknown";
img_status2.setImage(rcll_draw::readImage(""));
}
if (!short_display){
blbl_status1.setContent(status1);
blbl_status2.setContent(status2);
}
}
void rcll_draw::MachineLabelExploration::setHeader(std::string status1, std::string status2){
blbl_machinename.setContent("");
blbl_status1.setContent(status1);
blbl_status2.setContent(status2);
blbl_machinename.setBackgroundColor(rcll_draw::C_BLACK);
blbl_status1.setBackgroundColor(rcll_draw::C_BLACK);
blbl_status2.setBackgroundColor(rcll_draw::C_BLACK);
blbl_machinename.setFrontColor(rcll_draw::C_WHITE);
blbl_status1.setFrontColor(rcll_draw::C_WHITE);
blbl_status2.setFrontColor(rcll_draw::C_WHITE);
blbl_machinename.setFontSize(1.0);
blbl_status1.setFontSize(1.0);
blbl_status2.setFontSize(1.0);
img_status1.setImage(rcll_draw::readImage(""));
img_status2.setImage(rcll_draw::readImage(""));
}
void rcll_draw::MachineLabelExploration::draw(cv::Mat &mat){
blbl_machinename.draw(mat);
blbl_status1.draw(mat);
blbl_status2.draw(mat);
img_status1.draw(mat, rcll_draw::getColor(rcll_draw::C_WHITE));
img_status2.draw(mat, rcll_draw::getColor(rcll_draw::C_WHITE));
}
| [
"[email protected]"
] | |
9f7fc41f4227c0491ae544891cf7560214d46dc2 | e4b7519f8bd1fdd52afb9acc9d81977506285cee | /CPP/0901-1000/0967-Numbers-with-Same-Consecutive-Differences.cpp | 1ea8846dcb045abd120a31c00a1dd7b70db21103 | [
"BSD-3-Clause"
] | permissive | orangezeit/leetcode | e247ab03abbf4822eeaf555606fb4a440ee44fcf | b4dca0bbd93d714fdb755ec7dcf55983a4088ecd | refs/heads/master | 2021-06-10T03:05:14.655802 | 2020-10-02T06:31:12 | 2020-10-02T06:31:12 | 137,080,784 | 2 | 0 | null | 2018-06-12T14:17:30 | 2018-06-12T14:07:20 | null | UTF-8 | C++ | false | false | 856 | cpp | class Solution {
public:
void bt(int& curr, unordered_set<int>& nums, const int& K, int& N) {
if (N == 1) {
nums.insert(curr);
return;
}
int digit = curr % 10;
if (digit + K <= 9) {
curr *= 10;
curr += digit + K;
N--;
bt(curr, nums, K, N);
N++;
curr /= 10;
}
if (digit - K >= 0) {
curr *= 10;
curr += digit - K;
N--;
bt(curr, nums, K, N);
N++;
curr /= 10;
}
}
vector<int> numsSameConsecDiff(int N, int K) {
unordered_set<int> nums;
for (int i = 1; i <= 9; ++i) {
bt(i, nums, K, N);
}
if (N == 1) nums.insert(0);
return vector<int>(nums.begin(), nums.end());
}
};
| [
"[email protected]"
] | |
ad380f0b5f07ec6406367cbd7ca459c3ecb232ea | b68e70f001d185d11b6dd7a3df156297a97b1e9a | /dp/sherlock_cost.cpp | 441340d74821263ba23bfd2a13e249003e6c00e6 | [] | no_license | Leonab/CompetitiveP | b737dbc2bbf5ab48b36780fa57a6c8db0aa08282 | 81ebd2c63b11671226a0195c0c409d8532916e24 | refs/heads/master | 2020-12-07T23:23:48.527344 | 2017-03-25T18:14:06 | 2017-03-25T18:14:06 | 67,944,887 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 685 | cpp | #include<bits/stdc++.h>
using namespace std;
#define rep(i,N) for(int (i)=0;(i)<(N);(i)++)
#define repi(i,j,N) for(int (i)=(j);(i)<(N);(i)++)
#define sz(a) int((a).size())
#define pb push_back
#define mp make_pair
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef pair<int,int> ii;
int b[100000];
int dp[100000][2];
int main()
{
int t;
cin>>t;
while (t--) {
memset(dp, 0, sizeof(dp));
int n;
cin>>n;
for (int i=0;i<n;i++)
cin >> b[i];
for (int i=1;i<n;i++) {
dp[i][0] = max(dp[i - 1][0], dp[i - 1][1] + abs(b[i - 1] - 1));
dp[i][1] = max(dp[i - 1][0] + abs(b[i] - 1), dp[i - 1][1]);
}
cout<<max(dp[n - 1][0], dp[n - 1][1]) << endl;
}
return 0;
}
| [
"[email protected]"
] | |
f110847621c89331499c285253b6eafaf5dcf6bc | ce7cd2b2f9709dbadf613583d9816c862003b38b | /SRC/common/IO/bitoverlay.C | 58922f48a06d2c5960716041cc507a4cae0194f1 | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | usnistgov/OOF3D | 32b01a25154443d29d0c44d5892387e8ef6146fa | 7614f8ea98a095e78c62c59e8952c0eb494aacfc | refs/heads/master | 2023-05-25T13:01:20.604025 | 2022-02-18T20:24:54 | 2022-02-18T20:24:54 | 29,606,158 | 34 | 7 | null | 2015-02-06T19:56:26 | 2015-01-21T19:04:14 | Python | UTF-8 | C++ | false | false | 2,708 | c | // -*- C++ -*-
/* This software was produced by NIST, an agency of the U.S. government,
* and by statute is not subject to copyright in the United States.
* Recipients of this software assume all responsibilities associated
* with its operation, modification and maintenance. However, to
* facilitate maintenance we ask that before distributing modified
* versions of this software, you first contact the authors at
* [email protected].
*/
#include <oofconfig.h>
#include "common/IO/bitoverlay.h"
#include "common/trace.h"
#include "common/tostring.h"
BitmapOverlay::BitmapOverlay(const Coord *size, const ICoord *isize)
: fg(CColor(1., 1., 1.)),
bg(CColor(0., 0., 0.)),
data(*isize)
{
resize(size, isize);
tintAlpha = 1.0;
voxelAlpha = 1.0;
}
BitmapOverlay::~BitmapOverlay() {}
void BitmapOverlay::resize(const Coord *size, const ICoord *isize) {
size_ = *size;
sizeInPixels_ = *isize;
clear();
}
void BitmapOverlay::clear() {
data.resize(sizeInPixels_);
data.clear(false);
// ++timestamp;
}
void BitmapOverlay::invert() {
data.invert();
}
void BitmapOverlay::set(const ICoord *pixel) {
data.set(pixel);
// ++timestamp;
}
void BitmapOverlay::set(const ICoordVector *pixels) {
for(ICoordVector::const_iterator i=pixels->begin();i!=pixels->end();++i)
if(data.contains(*i))
data.set(&*i);
// ++timestamp;
}
void BitmapOverlay::reset(const ICoordVector *pixels) {
for(ICoordVector::const_iterator i=pixels->begin();i!=pixels->end();++i)
if(data.contains(*i))
data.reset(&*i);
// ++timestamp;
}
void BitmapOverlay::reset(const ICoord *pixel) {
data.reset(pixel);
// ++timestamp;
}
void BitmapOverlay::toggle(const ICoord *pixel) {
data.toggle(pixel);
// ++timestamp;
}
void BitmapOverlay::toggle(const ICoordVector *pixels) {
for(ICoordVector::const_iterator i=pixels->begin();i!=pixels->end();++i)
if(data.contains(*i))
data.toggle(&*i);
// ++timestamp;
}
bool BitmapOverlay::get(const ICoord *pixel) const {
if(data.contains(*pixel))
return data.get(*pixel);
return false;
}
void BitmapOverlay::copy(const BitmapOverlay *other) {
data = other->data.clone();
// avoid taking address of temporary
const CColor x(other->fg);
setColor(&x);
tintAlpha = other->getTintAlpha();
voxelAlpha = other->getVoxelAlpha();
}
void BitmapOverlay::setColor(const CColor *color) {
fg = *color;
if(fg.getRed() == 0.0) {
bg.setRed(1.0);
bg.setGreen(1.0);
bg.setBlue(1.0);
}
else {
bg.setRed(0.0);
bg.setBlue(0.0);
bg.setGreen(0.0);
}
}
// CColor BitmapOverlay::getBG() const {
// return bg;
// }
// CColor BitmapOverlay::getFG() const {
// return fg;
// }
| [
"[email protected]"
] | |
9a2ebee07bf19644b3dbf61482871e5b153dbb68 | 8c98fad4302e25c89e57ae068e33d899d00bf58a | /lab4/windows/Prob3Server.cpp | 35fe10e4b872a12ef685901473bf1c7bdd1e6c56 | [] | no_license | BKmarian/Sisteme-de-operare-Proiectare-si-Securitate | 9da0041004873d143cc4039cdb673be4a0054647 | a5e6944b4c0f008bda5614872c1c659adc99c8de | refs/heads/master | 2021-04-18T20:21:49.597566 | 2018-06-05T17:35:48 | 2018-06-05T17:35:48 | 126,720,493 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,679 | cpp | #include <windows.h>
#include <stdio.h>
#include <tchar.h>
#include <strsafe.h>
#include <map>
#define BUFSIZE 512
DWORD WINAPI InstanceThread(LPVOID);
std::map<int, int> sumMap;
int _tmain(VOID)
{
BOOL fConnected = FALSE;
DWORD dwThreadId = 0;
HANDLE hPipe = INVALID_HANDLE_VALUE, hThread = NULL;
LPTSTR lpszPipename = TEXT("\\\\.\\pipe\\mynamedpipe");
// The main loop creates an instance of the named pipe and
// then waits for a client to connect to it. When the client
// connects, a thread is created to handle communications
// with that client, and this loop is free to wait for the
// next client connect request. It is an infinite loop.
for (;;)
{
_tprintf(TEXT("\nPipe Server: Main thread awaiting client connection on %s\n"), lpszPipename);
hPipe = CreateNamedPipe(
lpszPipename, // pipe name
PIPE_ACCESS_DUPLEX, // read/write access
PIPE_TYPE_MESSAGE | // message type pipe
PIPE_READMODE_MESSAGE | // message-read mode
PIPE_WAIT, // blocking mode
PIPE_UNLIMITED_INSTANCES, // max. instances
BUFSIZE, // output buffer size
BUFSIZE, // input buffer size
0, // client time-out
NULL); // default security attribute
if (hPipe == INVALID_HANDLE_VALUE)
{
_tprintf(TEXT("CreateNamedPipe failed, GLE=%d.\n"), GetLastError());
return -1;
}
// Wait for the client to connect; if it succeeds,
// the function returns a nonzero value. If the function
// returns zero, GetLastError returns ERROR_PIPE_CONNECTED.
fConnected = ConnectNamedPipe(hPipe, NULL) ?
TRUE : (GetLastError() == ERROR_PIPE_CONNECTED);
if (fConnected)
{
printf("Client connected, creating a processing thread.\n");
// Create a thread for this client.
hThread = CreateThread(
NULL, // no security attribute
0, // default stack size
InstanceThread, // thread proc
(LPVOID)hPipe, // thread parameter
0, // not suspended
&dwThreadId); // returns thread ID
if (hThread == NULL)
{
_tprintf(TEXT("CreateThread failed, GLE=%d.\n"), GetLastError());
return -1;
}
else CloseHandle(hThread);
}
else
// The client could not connect, so close the pipe.
CloseHandle(hPipe);
}
return 0;
}
DWORD WINAPI InstanceThread(LPVOID lpvParam)
// This routine is a thread processing function to read from and reply to a client
// via the open pipe connection passed from the main loop. Note this allows
// the main loop to continue executing, potentially creating more threads of
// of this procedure to run concurrently, depending on the number of incoming
// client connections.
{
HANDLE hHeap = GetProcessHeap();
TCHAR* pchRequest = (TCHAR*)HeapAlloc(hHeap, 0, BUFSIZE * sizeof(TCHAR));
TCHAR* pchReply = (TCHAR*)HeapAlloc(hHeap, 0, BUFSIZE * sizeof(TCHAR));
DWORD cbBytesRead = 0, cbReplyBytes = 0, cbWritten = 0, cbBytesRead2 = 0;
HANDLE hPipe = NULL;
int processId, temp;
BOOL fSuccess = false, fSuccess2 = false;
// Do some extra error checking since the app will keep running even if this
// thread fails.
if (lpvParam == NULL)
{
printf("\nERROR - Pipe Server Failure:\n");
printf(" InstanceThread got an unexpected NULL value in lpvParam.\n");
printf(" InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, 0, pchReply);
if (pchRequest != NULL) HeapFree(hHeap, 0, pchRequest);
return (DWORD)-1;
}
if (pchRequest == NULL)
{
printf("\nERROR - Pipe Server Failure:\n");
printf(" InstanceThread got an unexpected NULL heap allocation.\n");
printf(" InstanceThread exitting.\n");
if (pchReply != NULL) HeapFree(hHeap, 0, pchReply);
return (DWORD)-1;
}
if (pchReply == NULL)
{
printf("\nERROR - Pipe Server Failure:\n");
printf(" InstanceThread got an unexpected NULL heap allocation.\n");
printf(" InstanceThread exitting.\n");
if (pchRequest != NULL) HeapFree(hHeap, 0, pchRequest);
return (DWORD)-1;
}
// Print verbose messages. In production code, this should be for debugging only.
printf("InstanceThread created, receiving and processing messages.\n");
// The thread's parameter is a handle to a pipe object instance.
hPipe = (HANDLE)lpvParam;
// MyCode
while (1)
{
fSuccess = ReadFile(hPipe, &processId, sizeof(processId), &cbBytesRead, NULL);
fSuccess2 = ReadFile(hPipe, &temp, sizeof(temp), &cbBytesRead2, NULL);
if (!fSuccess || cbBytesRead == 0 || !fSuccess2 || cbBytesRead2 == 0)
{
if (GetLastError() == ERROR_BROKEN_PIPE)
{
_tprintf(TEXT("InstanceThread: client disconnected.\n"), GetLastError());
}
else
{
_tprintf(TEXT("InstanceThread ReadFile failed, GLE=%d.\n"), GetLastError());
}
break;
}
printf("recieved procId = %d , nr = %d\n", processId, temp);
if (sumMap[processId] != NULL)
sumMap[processId] = sumMap[processId] + temp;
else
sumMap[processId] = temp;
fSuccess = WriteFile(hPipe, &sumMap[processId], sizeof(sumMap[processId]), &cbWritten, NULL);
if (!fSuccess)
{
_tprintf(TEXT("InstanceThread WriteFile failed, GLE=%d.\n"), GetLastError());
break;
}
printf("Sent sum = %d\n", sumMap[processId]);
}
DisconnectNamedPipe(hPipe);
// Flush the pipe to allow the client to read the pipe's contents
// before disconnecting. Then disconnect the pipe, and close the
// handle to this pipe instance.
FlushFileBuffers(hPipe);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
HeapFree(hHeap, 0, pchRequest);
HeapFree(hHeap, 0, pchReply);
printf("InstanceThread exitting.\n");
return 1;
} | [
"[email protected]"
] | |
9a6a8067bf95a41d7f80c66ba1a67be463197fee | 78b337c794b02372620ffbb6674073c6f0d1fd3d | /Mather/Mathter/Transforms/ViewBuilder.hpp | 0136ec2b0b8180d1e0a9dc3c01f1541961da190d | [
"MIT"
] | permissive | eglowacki/yaget_dependencies | 1fb0298f5af210fcc0f8e2c7052a97be5134f0fc | 7bbaaef4d968b9f1cd54963331017ac499777a1f | refs/heads/master | 2023-06-27T18:10:29.104169 | 2021-07-17T19:38:16 | 2021-07-17T19:38:16 | 261,091,491 | 0 | 0 | MIT | 2021-02-27T21:20:16 | 2020-05-04T05:51:17 | C++ | ISO-8859-2 | C++ | false | false | 6,157 | hpp | //L=============================================================================
//L This software is distributed under the MIT license.
//L Copyright 2021 Péter Kardos
//L=============================================================================
#pragma once
#include "../Matrix/MatrixImpl.hpp"
#include "../Vector.hpp"
namespace mathter {
template <class T, int Dim, bool Packed>
class ViewBuilder {
using VectorT = Vector<T, Dim, Packed>;
public:
ViewBuilder(const VectorT& eye, const VectorT& target, const std::array<VectorT, size_t(Dim - 2)>& bases, const std::array<bool, Dim>& flipAxes)
: eye(eye), target(target), bases(bases), flipAxes(flipAxes) {}
ViewBuilder& operator=(const ViewBuilder&) = delete;
template <class U, eMatrixOrder Order, eMatrixLayout Layout, bool MPacked>
operator Matrix<U, Dim + 1, Dim + 1, Order, Layout, MPacked>() const {
Matrix<U, Dim + 1, Dim + 1, Order, Layout, MPacked> m;
Set(m);
return m;
}
template <class U, eMatrixLayout Layout, bool MPacked>
operator Matrix<U, Dim, Dim + 1, eMatrixOrder::PRECEDE_VECTOR, Layout, MPacked>() const {
Matrix<U, Dim, Dim + 1, eMatrixOrder::PRECEDE_VECTOR, Layout, MPacked> m;
Set(m);
return m;
}
template <class U, eMatrixLayout Layout, bool MPacked>
operator Matrix<U, Dim + 1, Dim, eMatrixOrder::FOLLOW_VECTOR, Layout, MPacked>() const {
Matrix<U, Dim + 1, Dim, eMatrixOrder::FOLLOW_VECTOR, Layout, MPacked> m;
Set(m);
return m;
}
private:
template <class U, int Rows, int Columns, eMatrixOrder Order, eMatrixLayout Layout, bool MPacked>
void Set(Matrix<U, Rows, Columns, Order, Layout, MPacked>& matrix) const {
VectorT columns[Dim];
std::array<const VectorT*, Dim - 1> crossTable = {};
for (int i = 0; i < (int)bases.size(); ++i) {
crossTable[i] = &bases[i];
}
crossTable.back() = &columns[Dim - 1];
auto elem = [&matrix](int i, int j) ->U& {
return Order == eMatrixOrder::FOLLOW_VECTOR ? matrix(i, j) : matrix(j, i);
};
// calculate columns of the rotation matrix
int j = Dim - 1;
columns[j] = Normalize(eye - target); // right-handed: camera look towards -Z
do {
--j;
columns[Dim - j - 2] = Normalize(Cross(crossTable));
// shift bases
for (int s = 0; s < j; ++s) {
crossTable[s] = crossTable[s + 1];
}
crossTable[j] = &columns[Dim - j - 2];
} while (j > 0);
// flip columns
for (int i = 0; i < Dim; ++i) {
if (flipAxes[i]) {
columns[i] *= -T(1);
}
}
// copy columns to matrix
for (int i = 0; i < Dim; ++i) {
for (int j = 0; j < Dim; ++j) {
elem(i, j) = columns[j][i];
}
}
// calculate translation of the matrix
for (int j = 0; j < Dim; ++j) {
elem(Dim, j) = -Dot(eye, columns[j]);
}
// clear additional elements
constexpr int AuxDim = Rows < Columns ? Rows : Columns;
if (AuxDim > Dim) {
for (int i = 0; i < Dim; ++i) {
elem(i, AuxDim - 1) = 0;
}
elem(Dim, AuxDim - 1) = 1;
}
}
const VectorT eye;
const VectorT target;
const std::array<VectorT, size_t(Dim - 2)> bases;
const std::array<bool, Dim> flipAxes;
};
/// <summary> Creates a general, n-dimensional camera look-at matrix. </summary>
/// <param name="eye"> The camera's position. </param>
/// <param name="target"> The camera's target. </param>
/// <param name="bases"> Basis vectors fixing the camera's orientation. </param>
/// <param name="flipAxis"> Set any element to true to flip an axis in camera space. </param>
/// <remarks> The camera looks down the vector going from <paramref name="eye"/> to
/// <paramref name="target"/>, but it can still rotate around that vector. To fix the rotation,
/// an "up" vector must be provided in 3 dimensions. In higher dimensions,
/// we need multiple up vectors. Unfortunately I can't remember how these
/// basis vectors are used, but they are orthogonalized to each-other and to the look vector.
/// I can't remember the order of orthogonalization. </remarks>
template <class T, int Dim, bool Packed, size_t BaseDim, size_t FlipDim>
auto LookAt(const Vector<T, Dim, Packed>& eye,
const Vector<T, Dim, Packed>& target,
const std::array<Vector<T, Dim, Packed>, BaseDim>& bases,
const std::array<bool, FlipDim>& flipAxes) {
static_assert(BaseDim == Dim - 2, "You must provide 2 fewer bases than the dimension of the transform.");
static_assert(Dim == FlipDim, "You must provide the same number of flips as the dimension of the transform.");
return ViewBuilder<T, Dim, Packed>(eye, target, bases, flipAxes);
}
/// <summary> Creates a 2D look-at matrix. </summary>
/// <param name="eye"> The camera's position. </param>
/// <param name="target"> The camera's target. </param>
/// <param name="positiveYForward"> True if the camera looks towards +Y in camera space, false if -Y. </param>
/// <param name="flipX"> True to flip X in camera space. </param>
template <class T, bool Packed>
auto LookAt(const Vector<T, 2, Packed>& eye, const Vector<T, 2, Packed>& target, bool positiveYForward, bool flipX) {
return LookAt(eye, target, std::array<Vector<T, 2, Packed>, 0>{}, std::array{ flipX, positiveYForward });
}
/// <summary> Creates a 3D look-at matrix. </summary>
/// <param name="eye"> The camera's position. </param>
/// <param name="target"> The camera's target. </param>
/// <param name="up"> Up direction in world space. </param>
/// <param name="positiveZForward"> True if the camera looks towards +Z in camera space, false if -Z. </param>
/// <param name="flipX"> True to flip X in camera space. </param>
/// <param name="flipY"> True to flip Y in camera space. </param>
/// <remarks> The camera space X is selected to be orthogonal to both the look direction and the <paramref name="up"/> vector.
/// Afterwards, the <paramref name="up"/> vector is re-orthogonalized to the camera-space Z and X vectors. </remarks>
template <class T, bool Packed>
auto LookAt(const Vector<T, 3, Packed>& eye, const Vector<T, 3, Packed>& target, const Vector<T, 3, Packed>& up, bool positiveZForward, bool flipX, bool flipY) {
return LookAt(eye, target, std::array<Vector<T, 3, Packed>, 1>{ up }, std::array<bool, 3>{ flipX, flipY, positiveZForward });
}
} // namespace mathter | [
"[email protected]"
] | |
6bb0d95675cf5ab354c5ed5047a8581b711c4ccf | 8c46e25bce5f8a77f746cac2f7b7f9a54d50c99d | /2020/day22.cc | 7f610c14fa2bf01e754ad8940d616952ad70b5ed | [] | no_license | AusCoder/AdventOfCode | a6f2289d326b097ad114555f99feeaac4927e133 | 51749d9ebde277642de255751dc2363e32a4c399 | refs/heads/master | 2022-01-19T23:30:16.719206 | 2022-01-11T11:37:43 | 2022-01-11T11:37:43 | 228,608,850 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,158 | cc | #include "bits-and-bobs.hh"
using namespace std;
struct Decks {
deque<int> player1;
deque<int> player2;
};
inline bool operator==(const Decks &d1, const Decks &d2) {
bool player1Match =
(d1.player1.size() == d2.player1.size()) &&
std::equal(d1.player1.cbegin(), d1.player1.cend(), d2.player1.cbegin());
bool player2Match =
(d1.player2.size() == d2.player2.size()) &&
std::equal(d1.player2.cbegin(), d1.player2.cend(), d2.player2.cbegin());
return player1Match && player2Match;
}
Decks parseDecks(const vector<string> &lines) {
deque<int> player1;
auto it = lines.cbegin();
assert(it++->starts_with("Player"));
while (!it->empty()) {
player1.push_back(std::stoi(*it++));
}
it++;
deque<int> player2;
assert(it++->starts_with("Player"));
while (!it->empty()) {
player2.push_back(std::stoi(*it++));
}
return {std::move(player1), std::move(player2)};
}
long calculateScore(const Decks &decks) {
// calculate score
int mult = 1;
long score = 0;
const auto &winner = !decks.player1.empty() ? decks.player1 : decks.player2;
for (auto it = winner.rbegin(); it != winner.rend(); it++) {
score += mult++ * *it;
}
return score;
}
void part1(const vector<string> &lines) {
Decks decks = parseDecks(lines);
// play the game
while (!(decks.player1.empty() || decks.player2.empty())) {
if (decks.player1.front() > decks.player2.front()) {
decks.player1.push_back(decks.player1.front());
decks.player1.push_back(decks.player2.front());
} else if (decks.player1.front() < decks.player2.front()) {
decks.player2.push_back(decks.player2.front());
decks.player2.push_back(decks.player1.front());
} else {
assert(false);
}
}
// calculate score
print(calculateScore(decks));
}
struct Game {
Decks decks;
// some kind of hash or memory thing to remember previous
// rounds of this game.
vector<Decks> previousRounds;
void saveCurrentDeck() { previousRounds.push_back(decks); }
bool seenCurrentDeckBefore() const {
return std::any_of(
previousRounds.cbegin(), previousRounds.cend(),
[this](const auto &previousDecks) { return previousDecks == decks; });
}
};
bool calculateIsPlayer1Winner(Game &game) {
Decks &decks = game.decks;
while (!(decks.player1.empty() || decks.player2.empty())) {
// some check if we have seen this state before
if (game.seenCurrentDeckBefore()) {
return true;
}
// add new state to game state cache
game.saveCurrentDeck();
// play the game
int player1Card = decks.player1.front();
int player2Card = decks.player2.front();
decks.player1.pop_front();
decks.player2.pop_front();
int player1Size = decks.player1.size();
int player2Size = decks.player2.size();
bool player1IsWinner = true;
if ((player1Size >= player1Card) && (player2Size >= player2Card)) {
// new game
deque<int> newPlayer1Deck;
std::copy_n(decks.player1.cbegin(), player1Card,
std::back_inserter(newPlayer1Deck));
deque<int> newPlayer2Deck;
std::copy_n(decks.player2.cbegin(), player2Card,
std::back_inserter(newPlayer2Deck));
// Caching the results using initial game state
// doesn't seem to be needed
Game newGame{{std::move(newPlayer1Deck), std::move(newPlayer2Deck)}};
player1IsWinner = calculateIsPlayer1Winner(newGame);
} else if (player1Card > player2Card) {
player1IsWinner = true;
} else if (player1Card < player2Card) {
player1IsWinner = false;
} else {
assert(false);
}
if (player1IsWinner) {
decks.player1.push_back(player1Card);
decks.player1.push_back(player2Card);
} else {
decks.player2.push_back(player2Card);
decks.player2.push_back(player1Card);
}
}
return !decks.player1.empty();
}
void part2(const vector<string> &lines) {
Decks decks = parseDecks(lines);
Game game{decks};
calculateIsPlayer1Winner(game);
print(calculateScore(game.decks));
}
int main() {
auto lines = readLinesFromFile("input/day22.txt");
part1(lines);
part2(lines);
}
| [
"[email protected]"
] | |
f68f2635e24586a0d65bfd0b5dec4fa994cc1239 | c36b164f0ae2343dbe6c26d4a0568a1e8fb3a4c8 | /PWGHF/hfe/AliAnalysisTaskHaHFECorrel.h | 8adc09d5a895fc972acbea0dbec2f74e8417c0cb | [] | permissive | simons27/AliPhysics | 5150401364164e9eb14f7e6d9c164f2c437d7767 | 716dc4e036c00b8a030c5eeefe0e47204afdf18c | refs/heads/master | 2022-12-11T12:13:03.995771 | 2020-08-27T11:36:13 | 2020-08-27T11:36:13 | 286,996,653 | 0 | 0 | BSD-3-Clause | 2020-08-12T11:31:09 | 2020-08-12T11:31:09 | null | UTF-8 | C++ | false | false | 48,651 | h | /**************************************************************************
* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
#ifndef ALIANALYSISTASKHAHFECORREL_H
#define ALIANALYSISTASKHAHFECORREL_H
class THnSparse;
class TH2F;
class TProfile;
class TLorentzVector;
class AliEMCALTrack;
class AliMagF;
class AliESDEvent;
class AliAODEvent;
class AliAODMCParticle;
class AliAODMCHeader;
class AliGenEventHeader;
class AliVEvent;
class AliEMCALGeometry;
class AliAnalysisFilter;
class AliESDtrackCuts;
class AliESDtrack;
class AliHFEcontainer;
class AliHFEcuts;
class AliHFEpid;
class AliHFEpidQAmanager;
class AliCFManager;
class AliPIDResponse;
class AliMultSelection;
class AliEventPoolManager;
class AliAODv0KineCuts;
class AliESDv0KineCuts;
class AliVertexingHFUtils;
//class AliExternalTrackParam;
#include "AliAODv0KineCuts.h"
#include "AliMCEventHandler.h"
#include "AliMCEvent.h"
#include "AliMCParticle.h"
#include "AliStack.h"
#include "AliAnalysisTaskSE.h"
#include "AliEventCuts.h"
#include "TDatabasePDG.h"
#include <vector>
class AliAnalysisTaskHaHFECorrel : public AliAnalysisTaskSE {
public:
AliAnalysisTaskHaHFECorrel();
AliAnalysisTaskHaHFECorrel(const char *name);
~AliAnalysisTaskHaHFECorrel();
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual void Terminate(Option_t *);
//******************** ANALYSIS
AliVTrack* FindLPAndHFE(TObjArray* RedTracksHFE, const AliVVertex *pVtx, Int_t nMother, Int_t listMother[], Double_t mult, Bool_t &EvContTP, Bool_t &EvContNTP, Double_t EventWeight);
void FindPhotonicPartner(Int_t iTracks, AliVTrack* track, const AliVVertex *pVtx, Int_t nMother, Int_t listMother[], Int_t &LSPartner, Int_t &ULSPartner, Int_t *LSPartnerID, Int_t *ULSPartnerID, Float_t *LSPartnerWeight, Float_t *ULSPartnerWeight, Bool_t &trueULSPartner, Bool_t &isPhotonic, Float_t &MCPartnerPt, Float_t &RecPartnerPt, Double_t EventWeight, Double_t mult);
void CheckPhotonicPartner(AliVTrack* Vtrack, Bool_t Tagged, Float_t& MCPartnerPt, Float_t RecPartnerPt, Double_t EventWeight);
void CorrelateElectron(TObjArray* RedTracksHFE);
void CorrelateLP(AliVTrack* LPtrack, const AliVVertex* pVtx, Int_t nMother, Int_t listMother[], TObjArray* RedTracksHFE, Double_t EventWeight);
void CorrelateLPMixedEvent(AliVTrack* LPtrack, Float_t mult, Float_t zVtx, Float_t maxPt, Bool_t EvContTP, Bool_t EvContNTP, Double_t EventWeight);
void CorrelateHadron(TObjArray* RedTracksHFE, const AliVVertex* pVtx, Int_t nMother, Int_t listMother[], Float_t mult, Float_t maxPt, Double_t EventWeight);
void CorrelateHadronMixedEvent(Float_t mult, const AliVVertex* zVtx, Float_t maxPt, Int_t nMother, Int_t listMother[], Bool_t EvContTP, Bool_t EvContNTP, Double_t EventWeight);
void CorrelateWithHadrons(AliVTrack* TriggerTrack, const AliVVertex* pVtx, Int_t nMother, Int_t listMother[], Bool_t FillHadron, Bool_t FillLP,Bool_t** NonElecIsTrigger, Double_t *NonElecIsTriggerPt, Double_t *NonElecIsTriggerWeight, Int_t NumElectronsInEvent, Double_t EventWeight);
void MCTruthCorrelation(TObjArray* MCRedTracks, Bool_t AfterEventCuts, Int_t RecLPLabel, Float_t pVtxZ, Float_t mult, Int_t &LPinAcceptance, Int_t &LP, Double_t EventWeight);
//********************MC
void MCEfficiencyCorrections(const AliVVertex * RecVertex, Double_t EventWeight);
Int_t HFEisCharmOrBeauty(Int_t ElectronIndex);
//*********************ANALYSIS Helper
Bool_t ChargedHadronTrackCuts(const AliVVertex *pVtx,AliVTrack *Htrack, Int_t nMother, Int_t listMother[], Double_t EventWeight, Bool_t fillHists=kFALSE);
Bool_t ChargedHadronPIDCuts(AliVTrack *Htrack, Double_t EventWeight);;
Bool_t AssoHadronPIDCuts(AliVTrack *Htrack, Double_t EventWeight);
Bool_t InclElecTrackCuts(const AliVVertex *pVtx,AliVTrack *ietrack, Int_t nMother, Int_t listMother[], Double_t EventWeight, Bool_t fillHists=kFALSE);
Bool_t InclElecPIDCuts(AliVTrack *track, Double_t EventWeight, Bool_t fillHists=kFALSE);
Bool_t PhotElecPIDCuts(AliVTrack *track, Double_t EventWeight);
Bool_t PhotElecTrackCuts(const AliVVertex *pVtx,AliVTrack *aetrack, Int_t nMother, Int_t listMother[], Double_t EventWeight);
void PhotULSLSElectronAcceptance(const AliVVertex *pVtx, Float_t mult, Int_t nMother, Int_t listMother[], Double_t EventWeight);
void EvaluateTaggingEfficiency(AliVTrack * track, Int_t LSPartner, Int_t ULSPartner, Bool_t trueULSPartner, Double_t EventWeight, Double_t mult, Double_t recEffE);
Bool_t CloneAndReduceTrackList(TObjArray* RedTracks, AliVTrack* track, Int_t LSPartner, Int_t ULSPartner, Int_t *LSPartnerID, Int_t *ULSPartnerID, Float_t *LSPartnerWeight, Float_t *ULSPartnerWeight, Bool_t trueULSPartner, Float_t MCPartnerPt, Float_t RecPartnerPt, Bool_t isPhotonic, Bool_t isHadron);
void BinLogX(TAxis *axis);
void SetPDGAxis(TAxis *axis, std::vector<TString> PDGLabel);
void SetTriggerAxis(TAxis *axis);
void CheckHadronIsTrigger(Double_t ptE, Bool_t *HadronIsTrigger);
void CheckElectronIsTrigger(Double_t ptH, Bool_t *ElectronIsTrigger) ;
Bool_t PassEventBias( const AliVVertex *pVtx, Int_t nMother, Int_t *listMother, Double_t EventWeight);
//************** SETTINGS
void SetMC (Bool_t IsMC) { fIsMC=IsMC;};
void SetAODanalysis(Bool_t IsAOD) {fIsAOD = IsAOD;};
void SetTender (Bool_t UseTender) {fUseTender = UseTender;};
void SetPeriod (Double_t period) {fWhichPeriod = period;};
void SetEpos (Bool_t UseEpos) {fUseEPOS = UseEpos;};
void SetOnlyEfficiency() {
fTRDQA = kFALSE;
fCorrHadron = kFALSE;
fCorrLParticle = kFALSE;
fMixedEvent = kFALSE;
fMCTrueCorrelation = kFALSE;
}
void SetEleVarOpt(Int_t VarOption);
void SetHadVarOpt(Int_t VarOption);
void SetPhotVarOpt(Int_t PhotVarOpt);
void SetVtxVarOpt(Int_t VtxVarOpt) {fVarZVTXCut=VtxVarOpt;};
void SetTRDQA(Bool_t TRDQA) {fTRDQA=TRDQA;};
void SetPtMinEvent(Double_t PtMin) {fMinPtEvent=PtMin;};
void SetPtMaxEvent(Double_t PtMax) {fMaxPtEvent=PtMax;};
void SetMinNTr(Double_t MinNTr) {fMinNTr=MinNTr;};
void SetMaxNTr(Double_t MaxNTr) {fMaxNTr=MaxNTr;};
void SetEtaMax(Double_t EtaMax) {
fMaxElectronEta = TMath::Abs(EtaMax);
fMinElectronEta = -TMath::Abs(EtaMax);
};
void SetTPCnCut(Int_t TPCnCut) {fTPCnCut = TPCnCut;};
void SetTPCnCutdEdx(Int_t TPCnCutdEdx) {fTPCndEdxCut = TPCnCutdEdx;};
void SetITSnCut (Int_t ITSnCut) {fITSnCut = ITSnCut;};
void SetITSSharedClusterCut (Float_t ITSSharedCluster) {fITSSharedClusterCut=ITSSharedCluster;};
void SetPhotElecPtCut (Double_t AssPtCut) {fPhotElecPtCut = AssPtCut;};
void SetPhotElecTPCnCut (Int_t AssTPCnCut) {fPhotElecTPCnCut = AssTPCnCut;};
void SetPhotElecITSrefitCut(Bool_t AssITSrefitCut) {fPhotElecITSrefitCut = AssITSrefitCut;};
void SetPhotCorrCase(Int_t PhotCorrCase) {fPhotCorrCase = PhotCorrCase;};
void SetHTPCnCut(Int_t HTPCnCut) {fHTPCnCut = HTPCnCut;}
void SetHITSrefitCut(Bool_t HITSrefitCut) {fHITSrefitCut = HITSrefitCut;};
void SetHTPCrefitCut(Bool_t HTPCrefitCut) {fHTPCrefitCut = HTPCrefitCut;};
void SetUseTRD(Bool_t UseTRD) {fUseTRD = UseTRD;}
void SetUseITSsa(Bool_t UseITSsa) {fUseITSsa = UseITSsa;}
void SetSigmaITScut(Double_t SigmaITScut) {fSigmaITScut = SigmaITScut;};
void SetSigmaTOFcut(Double_t SigmaTOFcut) {fSigmaTOFcut = SigmaTOFcut;};
void SetSigmaTPCcut(Double_t SigmaTPCcut) {fSigmaTPCcutLow = SigmaTPCcut;};
void SetRecEff(Bool_t RecEff) {
fRecEff=RecEff;
}
void SetTagEff(Bool_t TagEff) {
fTagEff=TagEff;
}
void SetOneTimeCheck(Bool_t OneTimeCheck) {
fOneTimeCheck = OneTimeCheck;
}
void SetHadronCorrelation(Bool_t CorrHadron) {
fCorrHadron = CorrHadron;
};
void SetLPCorrelation(Bool_t CorrLP) {
fCorrLParticle = CorrLP;
};
void SetMCTruthCorrelation(Bool_t MCTruthCorr) {
fMCTrueCorrelation = MCTruthCorr;
};
void SetUseEventWeights(Bool_t UseEventWeights) {
fUseEventWeights = UseEventWeights;
};
void SetOpeningAngleCut(Bool_t OpeningAngleCut) {fOpeningAngleCut=OpeningAngleCut;};
void SetInvmassCut(Double_t InvmassCut) {fInvmassCut=InvmassCut;};
void SetPi0WeightToData(TH1F & WPion) {fCorrectPiontoData = WPion; fCorrectPiontoData.SetName("fCorrectPiontoData");};
void SetEtaWeightToData(TH1F & WEta) {fCorrectEtatoData = WEta; fCorrectEtatoData.SetName("fCorrectEtatoData");};
void SetBGWeight(TH2F & BGWeight) {fBgWeight = BGWeight; fBgWeight.SetName("fBgWeight");};
void SetHadRecEff(TH3F & HadRecEff) {fHadRecEff = HadRecEff; fHadRecEff.SetName("fHadRecEff");};
void SetEleRecEff(TH3F & EleRecEff) {fEleRecEff = EleRecEff; fEleRecEff.SetName("fEleRecEff");};
// void SetSPDnTrAvg(TProfile & SPDnTrAvg) {fSPDnTrAvg = SPDnTrAvg; fSPDnTrAvg.SetName("fSPDnTrAvg");}
void SetSPDConfigHist(TH1I & SPDConfigHist) {fSPDConfigHist = SPDConfigHist; fSPDConfigHist.SetName("SPDConfigHist");
/* for (Int_t i=1; i<300; i++) { */
/* printf("%i, %s, %10.2f, %s, %10.2f", i, fSPDConfigHist.GetXaxis()->GetBinLabel(i), fSPDConfigHist.GetBinContent(i), SPDConfigHist.GetXaxis()->GetBinLabel(i) , SPDConfigHist.GetBinContent(i)); */
/* } */
};
void SetSPDConfigProfiles(TH3F & SPDConfigProfiles) {fSPDConfigProfiles = SPDConfigProfiles; fSPDConfigProfiles.SetName("fSPDConfigProfiles");}
void SetNonTagCorr(TH1F & NonTagCorr) {fNonTagCorr = NonTagCorr; fNonTagCorr.SetName("fNonTagCorr");}
void SetTriggerWeight(TH3F & TriggerWeight){fTriggerWeight = TriggerWeight; fTriggerWeight.SetName("fTriggerWeight");}
void SetVtxWeight(TH2F & VtxWeight) {fVtxWeight = VtxWeight; fVtxWeight.SetName("fVtxWeight");};
Bool_t ESDkTrkGlobalNoDCA(AliVTrack* Vtrack);
private:
Bool_t IsPhotonicElectron(Int_t Label1) const;
Bool_t HaveSameMother(Int_t Label1, Int_t Label2) const;
Double_t GetDeltaPhi(Double_t phiA,Double_t phiB) const;
Double_t GetDeltaEta(Double_t etaA,Double_t etaB) const;
Double_t Eta2y(Double_t pt, Double_t m, Double_t eta) const;
Double_t GetHadronRecEff(Int_t run, Double_t pt, Double_t phi, Double_t eta, Double_t zVtx);
Double_t GetElectronRecEff(Int_t run, Double_t pt, Double_t phi, Double_t eta, Double_t zVtx);
Double_t GetTriggerWeight(Int_t run, Double_t minV0, Double_t nTrAcc);
Double_t GetVtxWeight(Int_t run, Double_t nTrAcc);
Double_t GetNonTagCorr(Double_t ptTrack, Double_t ptAsso);
Double_t Sphericity(const TObjArray* tracks, Double_t MaxEta, Double_t MinPt);
Bool_t Thrust(const TObjArray* tracks, Double_t t[2], Double_t MaxEta, Double_t MinPt);
Int_t CheckParticleOrigin(Int_t Label);
Int_t fRunNumber; //
Bool_t fUseTender; // Use tender
Int_t fWhichPeriod; // period
Bool_t fUseEPOS; //
Bool_t fUseKFforPhotonicPartner; //default ist DCA
Float_t fMaxPtEvent; //
Float_t fMinPtEvent; //
Int_t fMaxNTr; //
Int_t fMinNTr; //
Int_t fVarZVTXCut; //
Double_t fMaxElectronEta; //
Double_t fMinElectronEta; //
Double_t fMaxHadronEta; //
Double_t fMinHadronEta; //
// HFECuts
Int_t fVarEleOpt; //
Bool_t fElectronkAny; // True: kAny, False: kBoth
Bool_t fElectronkFirst; // True: kFirst, False: kBoth
Int_t fTPCnCut; // TPC number of clusters for tagged electron
Int_t fTPCndEdxCut; //
Int_t fITSnCut; // ITs number of clusters for tagged electrons
Float_t fITSSharedClusterCut; //
Double_t fEleDCAr; //
Double_t fEleDCAz; //
Bool_t fUseTRD; //
Bool_t fUseITSsa; // Use ITSsa tracks
Double_t fSigmaITScut; // ITS nSigma cut
Double_t fSigmaTOFcut; // TOF nSigma cut
Double_t fSigmaTPCcutLow; // lower TPC nSigma cut
Double_t fSigmaTPCcutHigh; //
// Photonic Electrons
Int_t fVarPhotOpt; //
Double_t fPhotElecPtCut; // pt cut for associated electron
Double_t fPhotElecSigmaTPCcut; //
Int_t fPhotElecTPCnCut; // TPC number of clusters for associated electron
Bool_t fPhotElecITSrefitCut; // ITS refit for associated electron
Int_t fPhotCorrCase; //
// Associate Hadron (non Electron)
Double_t fAssNonEleTPCcut; //
// Hadron Cut
Int_t fVarHadOpt; //
Int_t fHTPCnCut; // TPC number of clusters for trigger hadron
Bool_t fHITSrefitCut; // ITS refit for trigger hadron
Bool_t fHTPCrefitCut; // TPC refit for trigger hadron
Double_t fHadDCAr; //
Double_t fHadDCAz; //
Bool_t fHadkAny; //
Bool_t fHadTOFmatch; // matching to TOF bunch crossing ID to suppress pileup
Double_t fOpeningAngleCut; // openingAngle cut for non-HFE selection
Double_t fInvmassCut; // invariant mass cut for non-HFE selection
Double_t fChi2Cut; //! used?? Chi2 cut for non-HFE selection
Double_t fDCAcut; //! used?? DCA cut for non-HFE selection
// ******* Switch for analysis modes
Bool_t fTRDQA; // TRDQA
Bool_t fMCTrueCorrelation; //
Bool_t fUseEventWeights; //
Bool_t fCorrHadron; // Choose Hadron-HFE Correl
Bool_t fCorrLParticle; // Choose LP-HFE Correl
Bool_t fMixedEvent; // Fill Mixed Event for the cases chosen above
Bool_t fPionEtaProduction; //
Bool_t fRecEff; //
Bool_t fTagEff; //
Bool_t fHadCont; //
Bool_t fOneTimeCheck; //
Bool_t fLParticle; // Is LP found?
AliESDEvent *fESD; //! ESD object
AliESDtrackCuts *fesdTrackCuts; //!
AliAODEvent *fAOD; //! AOD object
AliVEvent *fVevent; //! VEvent
AliPIDResponse *fpidResponse; //! PID response
AliMultSelection *fMultSelection; //! MulSelection
AliCentrality *fCentrality; //! Centrality
AliEventPoolManager *fPoolMgr; //! event pool manager
TH3F *fPoolIsFilled; //! check if pool is filled
AliMCEvent *fMC; //! MC object
AliStack *fStack; //! stack
AliAODMCParticle *fMCparticle; //! MC particle
TClonesArray *fMCarray; //! MC array
AliAODMCHeader *fMCheader; //! MC header
TDatabasePDG *PdgTable; //!
std::map<Int_t, Int_t> PDGMap; //!
TClonesArray *fTracks_tender; //Tender tracks
TClonesArray *fCaloClusters_tender; //Tender clusters
AliEventCuts fEventCuts; //! Test AliEventCuts
AliHFEcuts *fCuts; //! Cut Collection
Bool_t fIsMC; // flag for MC analysis
Bool_t fIsAOD; // flag for AOD analysis
AliCFManager *fCFM; //! Correction Framework Manager
AliHFEpid *fPID; //! PID
AliHFEpidQAmanager *fPIDqa; //! PID QA manager
TList *fOutputList; //! output list
TList *fOutputListMain; //!
TList *fOutputListLP; //!
TList *fOutputListHadron; //!
TList *fOutputListQA; //!
TH1F *fNoEvents; //! no of events for different cuts
TH2F *fNoEventsNTr; //! no of events for different cuts
TH2F *fMCNoEvents; //! no of events for different cuts
TH2F *fHFENoEvents; //! no of events for different cuts
TH3F *fDiffractiveType; //!
TH2F *fV0ACTrueInel; //!
TH2F *fV0TrueMinInel; //!
TH3F *fV0TrueMinInelNTr; //!
TH2F *fV0ACTriggered; //!
TH2F *fV0MinTriggered; //!
TH3F *fV0MinTriggeredNTr; //!
TH3F fTriggerWeight;
TH2F *fVtxEtaNTr; //!
TH2F *fVtxBeforeNTrAcc; //!
TH2F *fVtxAfterNTrAcc; //!
TH1F *fVtxRecBeforeNTr; //!
TH2F *fVtxRecAfterNTr; //!
TH2F fVtxWeight;
TH2F *fTrkpt; //! track pt for different cuts
TH2F *fEtaVtxZ; //! Eta vs Vtx z (check for ITS acceptance problem)
TH2F *fSPDVtxRes; //!
TH2F *fDiffSPDPrimVtx; //!
TH2F *fSPDnTrAcc; //!
TH2F *fSPDnTrCorrMax; //!
TH2F *fSPDnTrGen; //!
TH2F *fDiffSPDMCVtx; //!
THnSparseF *fnTrAccMaxGen; //!
THnSparseF *fnTrAccGen; //!
TH2F *fnTrAccGenTrueInel; //!
//TH2F *fnTrAccGenTrueInelTrig; //!
//TH2F *fnTrAccGenTrueInelVtxQA; //!
//TH2F *fnTrAccGenTrueInelVtxEx; //!
THnSparseF *fnTrAccMinGen; //!
THnSparseF *fnTrAccMeanGen; //!
THnSparseF *fnTrAccMax; //!
THnSparseF *fnTrAccMin; //!
THnSparseF *fnTrAccMean; //!
TH3F *fMCThrustTagged; //!
TH3F *fMCSpherTagged; //!
TH3F *fRecLPTagged; //!
TH3F *fMultCorrTagged; //!
TH3F *fNHadTagged; //!
TH3F *fNHadTaggedA; //!
TH3F *fNHadTaggedB; //!
TH3F *fNHadTaggedC; //!
TH3F *fMeanPtTagged; //!
TH3F *fMeanPtTaggedA; //!
TH3F *fMeanPtTaggedB; //!
TH3F *fMeanPtTaggedC; //!
TH3F *fMCThrustNTagged; //!
TH3F *fMCSpherNTagged; //!
TH3F *fRecLPNTagged; //!
TH3F *fMultCorrNTagged; //!
TH3F *fNHadNTagged; //!
TH3F *fNHadNTaggedA; //!
TH3F *fNHadNTaggedB; //!
TH3F *fNHadNTaggedC; //!
TH3F *fMeanPtNTagged; //!
TH3F *fMeanPtNTaggedA; //!
TH3F *fMeanPtNTaggedB; //!
TH3F *fMeanPtNTaggedC; //!
TH3F *fPt2Tagged; //!
TH3F *fPt2NTagged; //!
TH2F *fMothMCThrustTagged; //!
TH2F *fMothMCSpherTagged; //!
TH2F *fMothRecLPTagged; //!
TH2F *fMothMultCorrTagged; //!
TH2F *fMothNHadTagged; //!
TH2F *fMothMeanPtTagged; //!
TH2F *fMothMCThrustNTagged; //!
TH2F *fMothMCSpherNTagged; //!
TH2F *fMothRecLPNTagged; //!
TH2F *fMothMultCorrNTagged; //!
TH2F *fMothNHadNTagged; //!
TH2F *fMothMeanPtNTagged; //!
TH2F *fMCThrustTaggedH; //!
TH2F *fMCSpherTaggedH; //!
TH2F *fRecLPTaggedH; //!
TH2F *fMultCorrTaggedH; //!
TH2F *fNHadTaggedH; //!
TH2F *fMeanPtTaggedH; //!
TH2F *fMCThrustNTaggedH; //!
TH2F *fMCSpherNTaggedH; //!
TH2F *fRecLPNTaggedH; //!
TH2F *fMultCorrNTaggedH; //!
TH2F *fNHadNTaggedH; //!
TH2F *fMeanPtNTaggedH; //!
TH2F *fMothMCThrustTaggedH; //!
TH2F *fMothMCSpherTaggedH; //!
TH2F *fMothRecLPTaggedH; //!
TH2F *fMothMultCorrTaggedH; //!
TH2F *fMothNHadTaggedH; //!
TH2F *fMothMeanPtTaggedH; //!
TH2F *fMothMCThrustNTaggedH; //!
TH2F *fMothMCSpherNTaggedH; //!
TH2F *fMothRecLPNTaggedH; //!
TH2F *fMothMultCorrNTaggedH; //!
TH2F *fMothNHadNTaggedH; //!
TH2F *fMothMeanPtNTaggedH; //!
THnSparse *fMultiplicity; //! multiplicity distribution
TH3F *fSPDMultiplicity; //!
Int_t *fRunList; //!
TH2F *fElectronTrackCuts; //!
TH2F *fElectronTrackTPCChi2; //!
TH2F *fElectronTrackTPCCrossedRows; //!
TH2F *fElectronTrackTPCNcls; //!
TH2F *fElectronTrackTPCNclsdEdx; //!
TH2F *fElectronTrackTPCFrac; //!
TH2F *fElectronTrackITSNcls; //!
TH2F *fElectronTrackITSChi2; //!
TH3F *fElectronTrackITSLayer; //!
TH3F *fElectronTrackRefit; //!
TH3F *fElectronTrackDCA; //!
THnSparseF* fElectronTrackITSCuts; //!
THnSparseF* fPhotTrackITSCuts; //!
TH2F *fHadronTrackCuts; //!
TH2F *fHadronTrackTPCNcls; //!
TH3F *fHadronTrackRefit; //!
TH3F *fHadronTrackDCA; //!
TH3F *fHadronTrackDCA_woITSAny;//!
TH3F *fHadronTrackDCA_wITSAny; //!
TH2F *fHistITSnSig; //! ITS sigma vs p
TH2F *fHistTOFnSig; //! TOF sigma vs p
TH2F *fHistTPCnSig; //! TPC sigma vs p
TH2F *fHistTPCnSigITScut; //! TPC sigma vs p (ITS cut)
TH2F *fHistTPCnSigTOFcut; //! TPC sigma vs p (TOF cut)
TH2F *fHistTPCnSigITSTOFcut; //! TPC sigma vs p (ITS+TOF cuts)
TH2F *fHistITSnSigTOFTPCcut; //! ITS sigma vs p (TPC+TOF cuts)
THnSparse *fCheckNHadronScaling; //!
THnSparse *fCheckNPhotHadScaling; //!
TH3F *fCheckTaggedEvent; //!
TH2F *fHadContPvsPt; //!
TH3F *fHadContEtaPhiPt; //!
TH3F *fHadContTPCEtaPhiPt; //!
THnSparse *fHadContPPhiEtaTPC; //!
THnSparse *fHadContamination; //! HadronicContaminationTOF
THnSparse *fHadContaminationPt; //! HadronicContaminationTOF
THnSparse *fHadContMC; //!
THnSparse *fHadContMCPt; //!
TH3F *fInclElecPtEta; //! inclusive electron p
TH3F *fInclElecPtEtaWRecEff; //! inclusive electron p
TH1F *fInclElecP; //! inclusive electron p
TH2F *fULSElecPt; //! ULS electron pt (after IM cut)
TH2F *fULSElecPtWRecEff; //! ULS electron pt (after IM cut)
TH2F *fLSElecPt; //! LS electron pt (after IM cut)
TH2F *fLSElecPtWRecEff; //! LS electron pt (after IM cut)
TH2F *fInvmassLS; //! Inv mass of LS (e,e)
TH2F *fInvmassULS; //! Inv mass of ULS (e,e)
TH3F *fInvmassMCTrue; //! Inv mass of ULS (e,e)
TH3F *fRecMCInvMass; //!
TH1F *fPhotMixULS; //!
TH2F *fPhotMixLS; //!
TH2F *fPhotPt1PtMTag; //!
TH2F *fPhotPt1PtMNTag; //!
THnSparseF *fPhotPt1Pt2; //!
TH2F *fPhotPt1Pt2Only; //!
THnSparseF *fPhotPt1Pt2Corr; //!
THnSparseF *fPhotPt1Pt2MC; //!
THnSparseF *fPhotPt1RecPt2; //!
THnSparseF *fPhotPt1RecPt2Corr; //!
THnSparseF *fPhotPt1RecPt2Rec; //!
THnSparseF *fPhotPt1RecPt2RecCorr; //!
THnSparseF *fPhotPt1Pt2Rec; //!
THnSparseF *fPhotPt1Pt2RecCorr; //!
TH2F *fPhotPt2MCRec; //!
THnSparseF *fPhotPt1E; //!
THnSparseF *fPhotPt1Pt2E; //!
THnSparseF *fPhotPt1ECorr; //!
THnSparseF *fPhotPt1Pt2ECorr; //!
THnSparseF *fPhotPt1Mass; //!
THnSparseF *fPhotPt1Mom; //!
TH2F *fOpeningAngleLS; //! opening angle for LS pairs
TH2F *fOpeningAngleULS; //! opening angle for ULS pairs
TH2F *fCheckLSULS; //! check no of LS/ULS partner per electron
TH3F *fTagEtaPt1Pt2; //!
TH3F *fTagEtaPhiPt; //!
TH3F *fTagEtaZvtxPt; //!
TH3F *fTagEtaPhiPtwW; //!
TH3F *fTagEtaZvtxPtwW; //!
TH3F *fNonTagEtaPt1Pt2; //!
TH3F *fNonTagEtaPhiPt; //!
TH3F *fNonTagEtaZvtxPt; //!
TH3F *fNonTagEtaPhiPtwW; //!
TH3F *fNonTagEtaZvtxPtwW; //!
THnSparse *fTagMotherPt; //!
TH2F *fTagEffInclMult; //!
TH2F *fTagEffULSMult; //!
TH3F *fTagEffInclBGMult; //!
TH3F *fTagEffULSBGMult; //!
TH2F *fTagTruePairsMult; //!
TH2F *fTagEffInclMultWoW; //!
TH2F *fTagEffULSMultWoW; //!
TH3F *fTagEffInclBGMultWoW; //!
TH3F *fTagEffULSBGMultWoW; //!
TH2F *fTagTruePairsMultWoW; //!
TH2F *fTagEffInclMultWoWS; //!
TH2F *fTagEffULSMultWoWS; //!
TH3F *fTagEffInclBGMultWoWS; //!
TH3F *fTagEffULSBGMultWoWS; //!
TH2F *fTagTruePairsMultWoWS; //!
THnSparse *fTagEffIncl; //!
THnSparse *fTagEffLS; //!
THnSparse *fTagEffULS; //!
THnSparse *fTagTruePairs; //!
THnSparse *fTagEffInclWoWeight; //!
THnSparse *fTagEffLSWoWeight; //!
THnSparse *fTagEffULSWoWeight; //!
THnSparse *fTagTruePairsWoWeight; //!
TH1F fCorrectPiontoData;
Double_t GetPionWeight(Double_t pt);
TH1F fCorrectEtatoData;
Double_t GetEtaWeight(Double_t pt);
TH2F fBgWeight;
Double_t GetBackgroundWeight(Int_t PDGMother, Double_t pt);
TH3F fHadRecEff;
TH3F fEleRecEff;
Int_t fSPDConfig;
TH1I fSPDConfigHist;
TH3F fSPDConfigProfiles;
TProfile* fSPDnTrAvg; //!
TH1F fNonTagCorr;
Int_t fAssPtHad_Nbins;
TArrayF fAssPtHad_Xmin;
TArrayF fAssPtHad_Xmax;
Int_t fAssPtElec_Nbins;
TArrayF fAssPtElec_Xmin;
TArrayF fAssPtElec_Xmax;
// HFE HFE
TH1F *fElecTrigger; //! trigger electron vs pt
TH2F *fInclElecPhi; //! electron (trigger): phi vs pt
TH2F *fInclElecEta; //! electron (trigger): phi vs pt
TH2F *fInclElecPhiEta; //! electron (trigger): phi vs pt
TH2F *fULSElecPhi; //! phi vs pt for electrons from ULS pairs
TH2F *fLSElecPhi; //! phi vs pt for electrons from LS pairs
TH2F *fElecDphi; //! inlcusive electron: dPhi vs pt of triggered electron
TH2F *fULSElecDphi; //! electron from ULS pairs: dPhi vs pt of triggered electron
TH2F *fLSElecDphi; //! electron from LS pairs: dPhi vs pt of triggered electron
TH2F *fULSElecDphiDiffMethod; //! electron from ULS pairs: dPhi vs pt of triggered electron
TH2F *fLSElecDphiDiffMethod; //! electron from LS pairs: dPhi vs pt of triggered electron
TH1F *fNoPartnerNoT; //!
THnSparse *fNoPartnerNoTPt2; //!
TH1F *fTPartnerNoT; //!
THnSparse *fTPartnerNoTPt2; //!
TH3F *fElecHadTrigger; //!
TH2F *fElecHadTriggerLS; //!
TH2F *fElecHadTriggerULS; //!
TH2F *fElecHadTriggerLSNoP; //!
TH2F *fElecHadTriggerULSNoP; //!
TH2F *fElecHadTriggerLSNoPCorr; //!
TH2F *fElecHadTriggerULSNoPCorr; //!
TH2F *fElecHadTriggerULSNoPCorrTrue; //!
TH2F *fHadContTrigger; //!
TH2F *fHadElecTrigger; //!
TH2F *fNonElecHadTrigger; //!
TH2F *fHadNonElecTrigger; //!
THnSparse *fInclElecHa; //!
THnSparse *fLSElecHa; //!
THnSparse *fULSElecHa; //!
THnSparse *fULSElecHaTrue; //!
THnSparse *fSignalElecHa; //!
THnSparse *fBackgroundElecHa; //!
THnSparse *fBackgroundElecHaULSLS; //!
THnSparse *fMCElecHaHadron; //!
THnSparse *fElecHaHa; //!
THnSparse *fElecHaLSNoPartner; //!
THnSparse *fElecHaULSNoPartner; //!
THnSparse *fElecHaLSNoPartnerCorrTrue; //!
THnSparse *fElecHaULSNoPartnerCorrTrue; //!
THnSparse *fElecHaLSNoPartnerCorr; //!
THnSparse *fElecHaULSNoPartnerCorr; //!
THnSparse *fMCElecHaTruePartner; //!
THnSparse *fMCElecHaNoPartner; //!
TH3F *fMCElecHaTruePartnerTrigger; //!
TH3F *fMCElecHaTruePartnerTriggerWW; //!
TH3F *fMCElecHaNoPartnerTrigger; //!
TH3F *fMCElecHaNoPartnerTriggerWW; //!
THnSparse *fElecHaMixedEvent; //!
THnSparse *fLSElecHaMixedEvent; //!
THnSparse *fULSElecHaMixedEvent; //!
THnSparse *fULSNoPartnerElecHaMixedEvent; //!
THnSparse *fTagHaMixedEvent; //!
THnSparse *fNonTagHaMixedEvent; //!
TH3F *fElecLPTrigger; //!
TH2F *fElecLPTriggerULS; //!
TH2F *fElecLPTriggerULSNoP; //!
TH2F *fElecLPTriggerULSNoPCorr;//!
TH2F *fHadContLPTrigger; //!
TH2F *fLPElecTrigger; //!
TH2F *fLPNonElecTrigger; //!
TH2F *fNonElecLPTrigger; //!
THnSparse *fInclElecLP; //!
THnSparse *fULSElecLP; //!
THnSparse *fULSElecLPTrue; //!
THnSparse *fSignalElecLP; //!
THnSparse *fBackgroundElecLP; //!
THnSparse *fBackgroundElecLPULSLS; //!
THnSparse *fMCElecLPHadron; //!
THnSparse *fElecLPHa; //!
THnSparse *fElecLPULSNoPartner; //!
THnSparse *fElecLPULSNoPartnerCorrTrue; //!
THnSparse *fElecLPULSNoPartnerCorr; //!
THnSparse *fMCElecLPTruePartner; //!
THnSparse *fMCElecLPNoPartner; //!
TH2F *fMCElecLPTruePartnerTrigger; //!
TH2F *fMCElecLPTruePartnerTriggerWW; //!
TH2F *fMCElecLPNoPartnerTrigger; //!
TH2F *fMCElecLPNoPartnerTriggerWW; //!
THnSparse *fElecLPMixedEvent; //!
THnSparse *fULSElecLPMixedEvent; //!
THnSparse *fTagLPMixedEvent; //!
THnSparse *fNonTagLPMixedEvent; //!
TH2F *fCheckMCVertex; //!
TH2F *fCheckMCPtvsRecPtHad; //!
TH2F *fCheckMCEtavsRecEtaHad; //!
TH2F *fCheckMCPhivsRecPhiHad; //!
THnSparse *fMCHadPtEtaPhiVtx; //!
TH2F *fRecHadMCSecondaryCont; //!
THnSparse *fRecHadMCPtEtaPhiVtx; //!
THnSparse *fRecHadPtEtaPhiVtx; //!
THnSparse *fRecHadPtEtaPhiVtxWRecEff; //!
TH2F *fCheckMCPtvsRecPtEle; //!
TH1F *fRecHFE; //!
THnSparse *fMCElecPtEtaPhiVtx; //!
TH2F *fRecElecMCSecondaryCont; //!
THnSparse *fRecElecPtEtaPhiVtx; //!
THnSparse *fRecElecPtEtaPhiVtxWRecEff; //!
THnSparse *fRecElecMCPtEtaPhiVtx; //!
TH1F *fMCElecPDG; //!
THnSparse *fMCElecPtEtaPhiStrictVtx; //!
THnSparse *fMCPi0Prod; //!
THnSparse *fMCEtaProd; //!
THnSparse *fMCPiPlusProd; //!
THnSparse *fMCPiPlusProdV2; //!
THnSparse *fMCBGProd; //!
THnSparse *fMCLeadingParticle; //!
TH3F *fCompareLPRecCheck; //!
AliEventPoolManager *fMCTruePoolMgr; //! event pool manager
THnSparse *fTrueMCHadronEventCuts; //!
THnSparse *fTrueMCHadronEventCutsZvtx;//!
THnSparse *fTrueMCHadronEventCutsZvtxMEv; //!
THnSparse *fTrueMCHadron; //!
TH3F *fTrueMCElecHaTriggerEventCuts; //!
TH3F *fTrueMCElecHaTrigger; //!
THnSparse *fTrueMCLPEventCuts; //!
THnSparse *fTrueMCLPEventCutsZvtx; //!
THnSparse *fTrueMCLPEventCutsZvtxMEv; //!
THnSparse *fTrueMCLP; //!
TH3F *fTrueMCElecLPTriggerEventCuts; //!
TH3F *fTrueMCElecLPTrigger; //!
TH3F *fTrueElectronEta; //!
TH2F *fRecHFEEtaWRecEff; //!
TH2F *fTrueLPinAcceptanceEta; //!
TH2F *fTrueLPEta; //!
TH2F *fRecLPEta; //!
TH2F *fTrueHadronEta; //!
TH2F *fRecHadronEtaWRecEff; //!
TH3F *fCompareLP; //!
AliESDv0KineCuts *fV0cutsESD; //! ESD V0 cuts
AliAODv0KineCuts *fV0cuts; //! AOD V0 cuts
TObjArray *fV0electrons; //! array with pointer to identified particles from V0 decays (electrons)
TObjArray *fV0pions; //! array with pointer to identified particles from V0 decays (pions)
TObjArray *fV0protons; //! array with pointer to identified particles from V0 decays (ptotons)
TH2F *fhArmenteros; //!
TH1F *fEventsPerRun; //!
TH2F *fTRDnTrackRun; //!
Int_t *fV0tags; //!
void FindV0CandidatesAOD(AliAODEvent *Event);
void FindV0CandidatesESD(AliESDEvent *Event);
void ClearV0PIDList();
void TRDQA(Int_t RunNumber, const AliVVertex *pVtx, Int_t nMother, Int_t listMother[], Double_t EventWeight);
void FillV0Histograms(AliVTrack* track, Int_t Species, Int_t RunNumber);
THnSparse *fTRDEtaPhi; //!
THnSparse *fTRDNTracklets; //!
THnSparse *fTRDV0NTracklets; //!
THnSparse *fTRDSpectra; //!
THnSparse *fTRDV0Spectra; //!
THnSparse *fTRDMCSpectra; //!
AliAnalysisTaskHaHFECorrel(const AliAnalysisTaskHaHFECorrel&);
AliAnalysisTaskHaHFECorrel& operator=(const AliAnalysisTaskHaHFECorrel&);
ClassDef(AliAnalysisTaskHaHFECorrel, 5);
};
// class storing reduced track information for mixed event pool
class AliBasicParticleHaHFE : public AliVParticle
{
public:
AliBasicParticleHaHFE()
: fID(0), fEta(0), fPhi(0), fpT(0), fCharge(0), fULSpartner(0), fLSpartner(0) , fIDLSPartner(0), fIDULSPartner(0), fWeightLSPartner(0), fWeightULSPartner(0), fTrueULSPartner(kFALSE), fTruePartnerMCPt(-999), fTruePartnerRecPt(-999), fIsPhotonic(kFALSE), fIsHadron(kFALSE), fLabel(0)
{
fExtTrackParam = AliExternalTrackParam();
}
AliBasicParticleHaHFE(Int_t id, Float_t eta, Float_t phi, Float_t pt, Short_t charge, Short_t LS, Short_t ULS, Int_t *LSPartner, Int_t *ULSPartner, Float_t *LSPartnerWeight, Float_t *ULSPartnerWeight, Bool_t trueULSPartner, Float_t truePartnerMCPt, Float_t truePartnerRecPt, Bool_t isPhotonic, Bool_t isHadron, Int_t label, AliExternalTrackParam & ExtTrackParam)
: fID(id), fEta(eta), fPhi(phi), fpT(pt), fCharge(charge), fULSpartner(ULS), fLSpartner(LS), fIDLSPartner(0), fIDULSPartner(0), fWeightLSPartner(0), fWeightULSPartner(0), fTrueULSPartner(trueULSPartner), fTruePartnerMCPt(truePartnerMCPt), fTruePartnerRecPt(truePartnerRecPt), fIsPhotonic(isPhotonic), fIsHadron(isHadron), fLabel(label), fExtTrackParam(ExtTrackParam)
{
fIDLSPartner = new Int_t[LS];
fIDULSPartner = new Int_t[ULS];
fWeightLSPartner = new Float_t[LS];
fWeightULSPartner = new Float_t[ULS];
for (Int_t i=0; i<LS; i++) {
fIDLSPartner[i]=LSPartner[i];
fWeightLSPartner[i]=LSPartnerWeight[i];
}
for (Int_t i=0; i<ULS; i++) {
fIDULSPartner[i]=ULSPartner[i];
fWeightULSPartner[i]=ULSPartnerWeight[i];
}
fExtTrackParam = ExtTrackParam;
}
virtual ~AliBasicParticleHaHFE() {
if (fIDLSPartner) delete[] fIDLSPartner;
if (fIDULSPartner) delete[] fIDULSPartner;
if (fWeightLSPartner) delete[] fWeightLSPartner;
if (fWeightULSPartner) delete[] fWeightULSPartner;
}
AliBasicParticleHaHFE(const AliBasicParticleHaHFE &CopyClass)
: fID(CopyClass.fID), fEta(CopyClass.fEta), fPhi(CopyClass.fPhi), fpT(CopyClass.fpT), fCharge(CopyClass.fCharge), fULSpartner(CopyClass.fULSpartner), fLSpartner(CopyClass.fLSpartner), fIDLSPartner(0), fIDULSPartner(0), fWeightLSPartner(0), fWeightULSPartner(0), fTrueULSPartner(CopyClass.fTrueULSPartner), fTruePartnerMCPt(CopyClass.fTruePartnerMCPt),fTruePartnerRecPt(CopyClass.fTruePartnerRecPt),fIsPhotonic(CopyClass.fIsPhotonic), fIsHadron(CopyClass.fIsHadron), fLabel(CopyClass.fLabel), fExtTrackParam(CopyClass.fExtTrackParam)
{
fIDLSPartner = new Int_t[CopyClass.fLSpartner];
fIDULSPartner = new Int_t[CopyClass.fULSpartner];
for (Int_t i=0; i<fLSpartner; i++) {fIDLSPartner[i]=CopyClass.fIDLSPartner[i];}
for (Int_t i=0; i<fULSpartner; i++) {fIDULSPartner[i]=CopyClass.fIDULSPartner[i];}
fWeightLSPartner = new Float_t[CopyClass.fLSpartner];
fWeightULSPartner = new Float_t[CopyClass.fULSpartner];
for (Int_t i=0; i<fLSpartner; i++) {fWeightLSPartner[i]=CopyClass.fWeightLSPartner[i];}
for (Int_t i=0; i<fULSpartner; i++) {fWeightULSPartner[i]=CopyClass.fWeightULSPartner[i];}
}
AliBasicParticleHaHFE& operator=(const AliBasicParticleHaHFE &CopyClass)
{
if (this==&CopyClass) return *this;
if (fIDLSPartner) delete[] fIDLSPartner;
if (fIDULSPartner) delete[] fIDULSPartner;
if (fWeightLSPartner) delete[] fWeightLSPartner;
if (fWeightULSPartner) delete[] fWeightULSPartner;
fID=CopyClass.fID;
fEta=CopyClass.fEta;
fPhi=CopyClass.fPhi;
fpT=CopyClass.fpT;
fCharge=CopyClass.fCharge;
fULSpartner=CopyClass.fULSpartner;
fLSpartner=CopyClass.fLSpartner;
fTrueULSPartner=CopyClass.fTrueULSPartner;
fTruePartnerMCPt=CopyClass.fTruePartnerMCPt;
fTruePartnerRecPt=CopyClass.fTruePartnerRecPt;
fIsPhotonic=CopyClass.fIsPhotonic;
fIsHadron=CopyClass.fIsHadron;
fIDLSPartner = new Int_t[CopyClass.fLSpartner];
fIDULSPartner = new Int_t[CopyClass.fULSpartner];
for (Int_t i=0; i<fLSpartner; i++) {fIDLSPartner[i]=CopyClass.fIDLSPartner[i];}
for (Int_t i=0; i<fULSpartner; i++) {fIDULSPartner[i]=CopyClass.fIDULSPartner[i];}
fWeightLSPartner = new Float_t[CopyClass.fLSpartner];
fWeightULSPartner = new Float_t[CopyClass.fULSpartner];
for (Int_t i=0; i<fLSpartner; i++) {fWeightLSPartner[i]=CopyClass.fWeightLSPartner[i];}
for (Int_t i=0; i<fULSpartner; i++) {fWeightULSPartner[i]=CopyClass.fWeightULSPartner[i];}
fLabel=CopyClass.fLabel;
fExtTrackParam = CopyClass.fExtTrackParam;
return *this;
}
// kinematics
virtual Double_t Px() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Py() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Pz() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Pt() const { return fpT; }
virtual Double_t P() const { AliFatal("Not implemented"); return 0; }
virtual Bool_t PxPyPz(Double_t[3]) const { AliFatal("Not implemented"); return 0; }
virtual Double_t Xv() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Yv() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Zv() const { AliFatal("Not implemented"); return 0; }
virtual Bool_t XvYvZv(Double_t[3]) const { AliFatal("Not implemented"); return 0; }
virtual Double_t OneOverPt() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Phi() const { return fPhi; }
virtual Double_t Theta() const { AliFatal("Not implemented"); return 0; }
virtual Double_t E() const { AliFatal("Not implemented"); return 0; }
virtual Double_t M() const { AliFatal("Not implemented"); return 0; }
virtual Double_t Eta() const { return fEta; }
virtual Double_t Y() const { AliFatal("Not implemented"); return 0; }
virtual Short_t Charge() const { return fCharge; }
virtual Int_t GetLabel() const { return fLabel; }
// PID
virtual Int_t PdgCode() const { AliFatal("Not implemented"); return 0; }
virtual const Double_t *PID() const { AliFatal("Not implemented"); return 0; }
virtual Short_t LS() const {return fLSpartner; }
virtual Short_t ULS() const {return fULSpartner; }
virtual Short_t ID() const {return fID;}
virtual Int_t LSPartner(Int_t i) const {return fIDLSPartner[i];}
virtual Int_t ULSPartner(Int_t i) const {return fIDULSPartner[i];}
virtual Float_t LSPartnerWeight(Int_t i) const {return fWeightLSPartner[i];}
virtual Float_t ULSPartnerWeight(Int_t i) const {return fWeightULSPartner[i];}
virtual Bool_t TruePartner() const {return fTrueULSPartner;}
virtual Float_t TruePartnerMCPt() const {return fTruePartnerMCPt;}
virtual Float_t TruePartnerRecPt() const {return fTruePartnerRecPt;}
virtual Bool_t IsPhotonic() const {return fIsPhotonic;}
virtual Bool_t IsHadron() const {return fIsHadron;}
AliExternalTrackParam GetExtTrackParam() {return fExtTrackParam;};
// virtual Int_t PDG() const {return fPDG;}
private:
Int_t fID; // particle id
Float_t fEta; // eta
Float_t fPhi; // phi
Float_t fpT; // pT
Short_t fCharge; // charge
Short_t fULSpartner; // no of ULS partner
Short_t fLSpartner; // no of LS partner
Int_t* fIDLSPartner; //! particle id of LS Partner
Int_t* fIDULSPartner; //! partilce id of ULS partner
Float_t* fWeightLSPartner; //! CorrWeight for NoPartner
Float_t* fWeightULSPartner; //! CorrWeight for NoPartner
Bool_t fTrueULSPartner; // check if true partner was tagged
Float_t fTruePartnerMCPt; // only for
Float_t fTruePartnerRecPt; //
Bool_t fIsPhotonic; //
Bool_t fIsHadron; // only for MC
Int_t fLabel; //
AliExternalTrackParam fExtTrackParam; //
ClassDef(AliBasicParticleHaHFE, 6); // class which contains only quantities requires for this analysis to reduce memory consumption for event mixing
};
#endif
| [
"[email protected]"
] | |
c255a493401403351d94b46a54ec66a73cea7fc8 | 950c627e015df14fbf768ba057c298689e29102c | /src/ball_chaser/src/drive_bot.cpp | 511e1f42f77e27bfb6c5a0a4c0487c6c9751ed25 | [] | no_license | FarouQQQ/RoboticsSoftwareEngineerNano-Project2 | 1dc06e3871ce33c0bc7c9b0f27df80f3213c6f8c | c0e75c4b72ad35712837a370ee1d758c3f99c97b | refs/heads/main | 2023-02-08T09:47:39.514458 | 2020-12-29T17:11:25 | 2020-12-29T17:11:25 | 324,985,688 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,961 | cpp | #include "ros/ros.h"
#include "geometry_msgs/Twist.h"
//TODO: Include the ball_chaser "DriveToTarget" header file
#include "ball_chaser/DriveToTarget.h"
// ROS::Publisher motor commands;
ros::Publisher motor_command_publisher;
// TODO: Create a handle_drive_request callback function that executes whenever a drive_bot service is requested
// This function should publish the requested linear x and angular velocities to the robot wheel joints
// After publishing the requested velocities, a message feedback should be returned with the requested wheel velocities
bool handle_drive_request(ball_chaser::DriveToTarget::Request& req,ball_chaser::DriveToTarget::Response& res)
{
ROS_INFO("DriveToTarget Request has been recived linear_x:%1.2f ,angular_z:%1.2f",(float)req.linear_x, (float)req.angular_z);
//Publish commands:
geometry_msgs::Twist motorCommands;
motorCommands.linear.x = req.linear_x;
motorCommands.angular.z = req.angular_z;
motor_command_publisher.publish(motorCommands);
//Response message
res.msg_feedback = "Motor command set - linear_x: " + std::to_string(req.linear_x) + " , angular_z: " + std::to_string(req.angular_z);
ROS_INFO_STREAM(res.msg_feedback);
}
int main(int argc, char** argv)
{
// Initialize a ROS node
ros::init(argc, argv, "drive_bot");
// Create a ROS NodeHandle object
ros::NodeHandle n;
// Inform ROS master that we will be publishing a message of type geometry_msgs::Twist on the robot actuation topic with a publishing queue size of 10
motor_command_publisher = n.advertise<geometry_msgs::Twist>("/cmd_vel", 10);
// TODO: Define a drive /ball_chaser/command_robot service with a handle_drive_request callback function
ros::ServiceServer service = n.advertiseService("/ball_chaser/command_robot", handle_drive_request);
ROS_INFO("Ready to send drive commands");
// TODO: Handle ROS communication events
ros::spin();
return 0;
} | [
"[email protected]"
] | |
1f0d14d859c355a43d7c7537e06909d17832cc3a | 0ca8541fc410efcd82c450e5fb83ba183d7ffb4b | /10000-14999/10799.cpp | 00400f26a03083a249bd1d7cda6eaf5bddcfbf7f | [] | no_license | mttw2820/BaekJoon_cpp | 85ecb68f2f5274e28ce75b6cf60b1f9ac0d82e64 | 9ff110d5f372b96fd9be17fa096edd237a77daf6 | refs/heads/main | 2023-05-05T17:41:50.896038 | 2021-05-03T14:45:33 | 2021-05-03T14:45:33 | 328,638,856 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 558 | cpp | //BaekJoon_10799
//쇠막대기
/*
* 제한 시간 : 1s
* 정답 비율 : 61.102%
*/
#include <iostream>
#include <stack>
#include <string.h>
using namespace std;
int main() {
char brac[100001];
stack<int> st;
int cnt = 0, total = 0;
scanf("%s", brac);
for (int i = 0; brac[i]; i++) {
if (brac[i] == '(') {
st.push(cnt);
}
else if (brac[i] == ')') {
// 레이저인 경우
if (st.top() == cnt) {
cnt++;
st.pop();
}
else {
total += (cnt - st.top() + 1);
st.pop();
}
}
}
printf("%d\n", total);
return 0;
} | [
"[email protected]"
] | |
32f99b7de47f57a987d9d1d60d8a890438ae435f | 5bb8950289abb2099c634ec46c6cd846afeae4f2 | /z-old/Boids/Vector.h | 4304e6278332453522621a978886ca8e8f0b6d97 | [
"Apache-2.0"
] | permissive | jan-polivka/PX4514-swarming | ae7c5bbadfdb919841b76866f72123a09b2a4266 | f6f7cedae4b26d0f2d2f686ab1854326cc6a50cc | refs/heads/master | 2020-04-18T03:00:20.165939 | 2019-04-05T07:00:44 | 2019-04-05T07:00:44 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,515 | h | // Vector.h
//
// INTERFACE: Class for 3-vectors with double precision
//
// (c) 1996 Christopher Kline <[email protected]>
#ifndef __VECTOR_H
#define __VECTOR_H
#include <math.h>
#include <stdarg.h>
#include <iostream.h>
#include <stdlib.h>
// ---------------- VECTORS CLASS ------------------
class Vector {
public:
double x, y, z; // direction with magnitude
Vector(void); // Default constructor
Vector( double a, double b, double c); // Constructor
void Set(double a, double b, double c); // Set each component of the vector
void SetDirection(const Vector &d); // Set the direction of the vector without modifying the length
void CopyDirection(const Vector &d); // Set the direction of this vector to be the same as the direction of the argument
void SetMagnitude(const double m); // Set the magnitude of the vector without modifying the direction
void CopyMagnitude(const Vector &v); // Set the magnitude of this vector to be the same as the magnitude of the argument
void Normalize(void); // Normalize the vector to have a length of 1
double Length(void); // Return the magnitude (length) of this vector
Vector &operator=(const Vector &b); // ex: a = b
double &operator[](const int index); // ex: a[1] (same as a.y)
friend int operator!=(const Vector &a, const Vector &b); // ex: a != b
friend int operator==(const Vector &a, const Vector &b); // ex: a == b
friend Vector operator+(const Vector &a, const Vector &b); // ex: a + b
friend Vector operator-(const Vector &a, const Vector &b); // ex: a - b
friend Vector operator-(const Vector &a); // ex: -a
friend Vector &operator+=(Vector &a, const Vector &b); // ex: a += b
friend Vector &operator-=(Vector &a, const Vector &b); // ex: a -= b
friend Vector operator%(const Vector &a, const Vector &b); // ex: a % b (cross product)
friend double operator*(const Vector &a, const Vector &b); // ex: a * b (dot product)
friend Vector operator*(const double &a, const Vector &b); // ex: a * b (scalar multiplication)
friend Vector operator*(const Vector &a, const double &b); // ex: a * b (scalar multiplication)
friend Vector &operator*=(Vector &a, const double &b); // ex: a *= b (scalar multiplication + assignment)
friend Vector operator/(const Vector &a, const double &b); // ex: a / b (scalar divide)
friend Vector &operator/=(Vector &a, const double &b); // ex: a /= b (scalar divide + assignment)
friend double Magnitude(const Vector &a); // Returns the length of the argument
friend double AngleBetween(const Vector &a, const Vector &b);// Returns the angle (in radians!) between the two arguments
private:
};
// ------------ CALCULATIONS USING VECTORS --------------
Vector Direction(const Vector &a);
Vector Direction(const double &x, const double &y, const double &z);
Vector Average(int numvectors, Vector a, ...);
// --------------- I/O OPERATORS ------------------------
ostream &operator<<(ostream &strm, const Vector &v);
//-----------------------------------------------------
// INLINE FUNCTIONS
//-----------------------------------------------------
#define VLENSQRD(a, b, c) ((a)*(a) + (b)*(b) + (c)*(c))
#define VLEN(a, b, c) sqrt(VLENSQRD(a, b, c))
inline void
Vector::Set(double a, double b, double c) {
x = a;
y = b;
z = c;
}
inline void
Vector::Normalize(void) {
double mag = VLEN(x, y, z);
if (mag == 0)
return;
x /= mag;
y /= mag;
z/= mag;
}
inline Vector::Vector(void) {
Set(0, 0, 0);
}
inline Vector::Vector( double a, double b, double c) {
Set(a, b, c);
}
inline Vector &
Vector::operator=(const Vector &b) { // example: a = b
x = b.x;
y = b.y;
z = b.z;
return(*this);
}
inline void
Vector::SetMagnitude(const double m) {
this->Normalize();
*this *= m;
}
inline void
Vector::CopyMagnitude(const Vector &v) {
SetMagnitude(Magnitude(v));
}
inline void
Vector::SetDirection(const Vector &d) {
double m = Magnitude(*this);
Vector v = d;
v.Normalize();
*this = v * m;
}
inline void
Vector::CopyDirection(const Vector &d) {
SetDirection(Direction(d));
}
inline double
Vector::Length(void) {
return Magnitude(*this);
}
inline double &
Vector::operator[](const int index) { // example: a[1] (same as a.y)
if (index == 0)
return(x);
else if (index == 1)
return(y);
else if (index == 2)
return(z);
else {
cerr << "WARNING: You're using subscripting to access a nonexistant vector component (one other than x, y, or z). THIS IS BAD!!\n";
exit(888);
return(z); // this will never get called, but prevents compiler warnings...
}
}
inline int
operator!=(const Vector &a, const Vector &b) { // example: a 1= b
return(a.x != b.x || a.y != b.y || a.z != b.z);
}
inline int
operator==(const Vector &a, const Vector &b) { // example: a == b
return(a.x == b.x && a.y == b.y && a.z == b.z);
}
inline Vector
operator+(const Vector &a, const Vector &b) { // example: a + b
Vector c(a.x+b.x, a.y+b.y, a.z+b.z);
return(c);
}
inline Vector
operator-(const Vector &a, const Vector &b) { // example: a - b
Vector c(a.x-b.x, a.y-b.y, a.z-b.z);
return(c);
}
inline Vector
operator-(const Vector &a) { // example: -a
Vector c(-a.x, -a.y, -a.z);
return(c);
}
inline Vector &
operator+=(Vector &a, const Vector &b) { // example: a += b
a = a + b;
return(a);
}
inline Vector &
operator-=(Vector &a, const Vector &b) { // example: a -= b
a = a - b;
return(a);
}
inline Vector
operator%(const Vector &a, const Vector &b) { // example: a % b (cross product)
Vector c(a.y*b.z - a.z*b.y, a.z*b.x - a.x*b.z, a.x*b.y - a.y*b.x);
return(c);
}
inline double
operator*(const Vector &a, const Vector &b) { // example: a * b (dot product)
return(a.x*b.x + a.y*b.y + a.z*b.z);
}
inline Vector
operator*(const double &a, const Vector &b) { // example: a * b (scalar multiplication)
Vector c = b;
c.x *= a;
c.y *= a;
c.z *= a;
return(c);
}
inline Vector
operator*(const Vector &a, const double &b) { // example: a * b (scalar multiplication)
return(b * a);
}
inline Vector &
operator*=(Vector &a, const double &b) { // example: a *= b (scalar multiplication + assignment)
a = a * b;
return(a);
}
inline Vector
operator/(const Vector &a, const double &b) { // example: a / b (scalar divide)
if (b == 0)
cerr << "WARNING: You're dividing a vector by a zero-length scalar! NOT GOOD!\n";
Vector c = a*(1/b);
return(c);
}
inline Vector &
operator/=(Vector &a, const double &b) { // example: a / b (scalar divide + assignment)
a = a/b;
return(a);
}
inline ostream &
operator<<(ostream &strm, const Vector &v) {
return strm << "[" << v.x << ", " << v.y << ", " << v.z << "]";
}
inline Vector
Direction(const Vector &a) {
Vector u = a;
u.Normalize();
return(u);
}
inline Vector
Direction(const double &x, const double &y, const double &z) {
return Direction(Vector(x, y, z));
}
inline double
Magnitude(const Vector &a) {
return VLEN(a.x, a.y, a.z);
}
inline double
AngleBetween(const Vector &a, const Vector &b) {
// returns angle between a and b in RADIANS
return acos((a*b)/(Magnitude(a)*Magnitude(b)));
}
#undef VLEN
#endif /* #ifndef __VECTOR_H */
| [
"[email protected]"
] | |
4713d8398e5fe69e4a2d918f32ca7b1a393175ee | 5e3fac6568bc351c0500b87fb4842d23cb14646e | /logdevice/common/client_read_stream/ClientReadStreamScd.h | 00c6db8f246dc9c7b92c49a3bbfb3c81dda2956b | [
"BSD-3-Clause"
] | permissive | ahmad-diaa/LogDevice | ab7be8721095164eda33a4de468d6e76d034a4bf | d9caf3ede45cbfadac96f1e1670c6ab4acfce136 | refs/heads/master | 2020-06-04T18:37:15.067334 | 2019-06-20T06:01:46 | 2019-06-20T06:06:32 | 192,147,164 | 0 | 0 | NOASSERTION | 2019-06-16T03:45:48 | 2019-06-16T03:45:47 | null | UTF-8 | C++ | false | false | 18,902 | h | /**
* 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.
*/
#pragma once
#include <boost/noncopyable.hpp>
#include <folly/FBVector.h>
#include "logdevice/common/FailureDomainNodeSet.h"
#include "logdevice/common/ShardID.h"
#include "logdevice/common/client_read_stream/ClientReadStreamFailureDetector.h"
#include "logdevice/common/client_read_stream/ClientReadStreamSenderState.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/protocol/START_Message.h"
#include "logdevice/common/types_internal.h"
#include "logdevice/include/types.h"
namespace facebook { namespace logdevice {
class Timer;
/**
* @file Contains the logic of the Single Copy Delivery (SCD) optimization
* that makes it possible to receive only one copy of each record, saving
* network bandwidth and CPU.
*
* When SCD is active, storage shards only send records for which they are
* the primary recipient in that record's copyset, causing each record to
* be sent once (assuming the record's copyset is equal in each copy).
*
* @see doc/single-copy-delivery.md for more information about scd and
* how storage shards decide whether or not to send a copy.
*
* This class contains the logic for failover mechanisms of the SCD
* optimization, which is always triggered by the client.
* We maintain a list of filtered out ShardIDs that we send to the storage
* shards via the START message. This list is used by the shards to know
* which shards are filtered out, and to send the records those shards
* were supposed to send if they are next in the copyset.
*
* The filtered out list is formed of two sublists:
* - the shards down list contains shards that the client knows are down;
* - the shards slow list contains shards that are much slower than the
* others, and by filtering them out we can failover to a healthier
* shard;
*
* There are different failover and recovery scenarios that we handle:
*
* 1. Immediate failover to ALL_SEND_ALL due to missing records.
* checkNeedsFailoverToAllSendAll() is the method that verifies if
* there is a reason to immediately switch to ALL_SEND_ALL mode. This
* function is called each time a gap or record is received.
* If at some point the number of shards that can't send
* next_lsn_to_deliver_ is measured to be equal to readSetSize(), we do
* the failover because this means that the storage shard that is
* supposed to send next_lsn_to_deliver_ does not have it or thinks
* it's not supposed to send it.
*
* 2. Rewinding the stream due to some connection failures.
* When ClientReadStream determines that a storage shard cannot send us
* its records, it calls addToShardsDownAndScheduleRewind(). This
* function ensures we soon rewind the stream with that shard in the
* filtered out list. ClientReadStream calls
* addToShardsDownAndScheduleRewind() when:
* - It could not send START because sendStartMessage() failed;
* - A shard sent STARTED with status=E::AGAIN or an unexpected status;
* - The socket to a storage shard was closed.
*
* 3. Immediate primary failover due to checksum fail.
* If we receive a record with a checksum fail, ClientReadStream calls
* addToShardsDownAndScheduleRewind() similarly.
*
* 4. Immediate primary failover due to a shard rebuilding.
* If we receive a STARTED(status=E::REBUILDING), ClientReadStream calls
* addToShardsDownAndScheduleRewind() similarly.
*
* 5. Optional primary failover due to a slow shard. If a shard (or set of
* shards) is slower at completing windows that all the other shards,
* we will add it to the shards slow list and rewind the stream.
* @see ClientReadStreamFailureDetector.
*
* 6. Failover to ALL_SEND_ALL because we are stuck:
* In rare cases where we can not make progress for some time and there
* are too many shards that are stuck, we failover to ALL_SEND_ALL mode.
* The `all_send_all_failover_timer_` timer takes care of detecting
* that.
*
* 7. Recovery to SCD:
* When in ALL_SEND_ALL mode, we switch back to SCD when the window is
* slid.
*
* 8. Removing shards from the shards down list.
* When a shard sends a record, ClientReadStream calls
* scheduleRewindIfShardBackUp() which checks if the shard is in the
* shards down list but has been sending records not in an
* under-replicated region. If that's the case, a rewind is scheduled to
* remove the shard from the shards down list.
*
* 9. Removing shards from the shards slow list.
* Shards will be removed from the slow shards list if we need to add
* another shard to the filtered out list, and we can't do that without
* the filtered out list satisfying the replication requirements. When
* this happens we will remove from the list the oldest slow shard
* We don't actively remove from the slow shards list whenever we detect
* that shards stop being slow because this can cause ping-ponging
* between adding/removing the shard from the list and thus doing
* unnecessary rewinds.
*/
class ClientReadStream;
class ClientReadStreamScd : public boost::noncopyable {
public:
enum class Mode { SCD, ALL_SEND_ALL, LOCAL_SCD };
ClientReadStreamScd(ClientReadStream* owner, Mode mode);
~ClientReadStreamScd();
/**
* @return true if we are currently in SCD or LOCAL_SCD mode.
*/
bool isActive() const {
return mode_ == Mode::SCD || mode_ == Mode::LOCAL_SCD;
}
/**
* @return true if we are currently in LOCAL_SCD mode.
*/
bool localScdEnabled() const {
return mode_ == Mode::LOCAL_SCD;
}
/**
* Called when settings are updated.
*/
void onSettingsUpdated();
/**
* Called when a storage shard's next lsn changed.
*/
void onShardNextLsnChanged(ShardID shard, lsn_t next);
/**
* Called when a storage shard's authoritative status changed.
*/
void setShardAuthoritativeStatus(ShardID shard, AuthoritativeStatus status);
/**
* Called by ClientReadStream::rewind(). Apply any scheduled changes to
* transition to ALL_SEND_ALL or SCD if `scheduled_mode_transition_` is set.
*
* If SCD is currently active or if `scheduled_mode_transition_`==SCD, apply
* any scheduled changes to the filtered out list.
*
* This function may decide that it's best to continue in ALL_SEND_ALL mode if
* there have been no changes to the filtered out list.
*/
void applyScheduledChanges();
/**
* Schedule a rewind to the given mode.
* This function asserts that the current mode is not the requested mode.
*/
void scheduleRewindToMode(Mode mode, std::string reason);
/**
* When in SCD mode, check how many shards do not have the next record to be
* shipped. If this number is equal to the number of shards we are reading
* from, failover to all send all mode.
*
* Called when:
* - the cluster is shrunk (@see noteShardsRemovedFromConfig);
* - a gap is received, or a record with lsn > next_lsn_to_deliver_ is
* received (@see updateGapState).
*
* @return true If we failed over to all send all mode, false otherwise.
*/
bool checkNeedsFailoverToAllSendAll();
/**
* Check if the given shard was in the shards down list and has been sending
* data. If that's the case, remove it from the shards down list and schedule
* a rewind.
*/
void scheduleRewindIfShardBackUp(ClientReadStreamSenderState& state);
// Called whenever a window is slid.
void onWindowSlid(lsn_t hi, filter_version_t filter_version);
/**
* @return List of shards to be filtered out, including both shards down and
* shards slow.
*/
const small_shardset_t& getFilteredOut() const {
return filtered_out_.getAllShards();
}
/**
* @return List of shards considered down.
*/
const small_shardset_t& getShardsDown() const {
return filtered_out_.getShardsDown();
}
/**
* @return List of shards considered slow.
*/
const small_shardset_t& getShardsSlow() const {
return filtered_out_.getShardsSlow();
}
/**
* Update the storage shard set that the filtered out list is based on.
*
* If any shards were removed from the filtered out list we will also
* schedule a rewind.
* Switch to all send all mode instead if the conditions are now held,
* which can happen if all the remaining shards sent us a record with lsn >
* next_lsn_to_deliver_.
*
* @return true if a rewind was scheduled
*/
bool updateStorageShardsSet(const StorageSet& storage_set,
const std::shared_ptr<ServerConfig>& cfg,
const ReplicationProperty& replication);
/**
* Called when we are unable to read from a storage shard because either:
* - ClientReadStream::sendStartMessage() returned -1;
* - ClientReadStream::onStartSent() is called with status != E::OK;
* - ClientReadStream::onStarted() is called with msg.header_.status ==
* E::AGAIN or E::REBUILDING (or an unexpected error);
* - ClientReadStream::onSocketClosed() is called;
* - a storage shard sent a CHECKSUM_FAIL gap.
* - a storage shard's authoritative status is changed to UNDERREPLICATION,
* AUTHORITATIVE_EMPTY, or UNAVAILABLE.
*
* Append the shard to `pending_immediate_scd_failover_` and schedule a
* rewind. When the rewind happens in the next iteration of the event loop,
* shards in `pending_immediate_scd_failover_` will be added to the shards
* down list.
*
* Note: this function does not rewind the streams synchronously so that it
* can be called multiple times in a row and the streams rewinded only once,
* and also in order to not have sendStart() be called from within the call
* stack of another call to sendStart().
*
* @return True if the rewind was scheduled (or if there is already a rewind
* scheduled), or False if the given shard is already in the shards down list.
*/
bool addToShardsDownAndScheduleRewind(const ShardID&, std::string reason);
/**
* Called when ClientReadStream changed the GapState of a sender.
* Used to maintain a proper accounting of the number of shards in the
* filtered out list that have gap state in (GapState::GAP,
* GapState::UNDER_REPLICATED).
*/
void
onSenderGapStateChanged(ClientReadStreamSenderState& state,
ClientReadStreamSenderState::GapState prev_gap_state);
/**
* Returns the number of shards that are in filtered out list but sent a
* record or gap with lsn > next_lsn_to_deliver_.
*/
nodeset_size_t getGapShardsFilteredOut() const {
return gap_shards_filtered_out_;
}
nodeset_size_t getUnderReplicatedShardsNotBlacklisted() const {
return under_replicated_shards_not_blacklisted_;
}
private:
// ClientReadStream that owns us.
ClientReadStream* owner_;
/**
* Set to Mode::SCD when single copy delivery (scd) is active. When scd is
* active we will receive only one copy of every record in steady state.
*/
Mode mode_;
/**
* Number of shards for which the smallest LSN that might be delivered by that
* shard is strictly greater than next_lsn_to_deliver_ and that shard is
* currently in the filtered out list.
*
* Note: we do not bother adjusting this value each time we add or remove a
* shard from the filtered out list because we immediately rewind the stream
* when doing this, which blows away the gap state and resets this value to
* zero.
*/
nodeset_size_t gap_shards_filtered_out_ = 0;
/**
* Number of shards in GapState::UNDER_REPLICATED that are not in known down.
*/
nodeset_size_t under_replicated_shards_not_blacklisted_ = 0;
/**
* There are two failover timers. One that rewinds the streams while adding
* shards to the shards down list and one that rewinds the streams in all send
* all mode.
* This struct keeps data common to these two timers.
*/
struct FailoverTimer {
typedef std::function<bool(small_shardset_t new_nodes_down)> Callback;
FailoverTimer(ClientReadStreamScd* scd,
std::chrono::milliseconds period,
Callback cb);
void cancel();
void activate();
// The timer object.
std::unique_ptr<Timer> timer_;
// Period of the timer.
std::chrono::milliseconds period_;
// LSN of the next record we expected to deliver the last time the timer
// expired. Each time the timer expires, we check next_lsn_to_deliver_
// against this value. If the values are equal this means we could not make
// progress during the timer's period.
lsn_t next_lsn_to_deliver_at_last_tick_;
// Callback called when the timer ticks and we were not able to make any
// progress. new_nodes_down is the list of shards that should be added to
// the known down list. The callback should return true if the timer should
// be re-activated.
Callback cb_;
ClientReadStreamScd* scd_;
void callback();
friend class ClientReadStreamTest;
};
// Read the settings to configure the ClientReadStreamFailureDetector.
// This may cause a rewind to be scheduled if the outliers change as a result
// (because we disabled outlier detector or moved to observe only mode).
void configureOutlierDetector();
// Must be called when:
// * the BlacklistState of a shard changed;
// * the authoritative status of a shard changed;
// * the read set changed.
// If the outlier detector is enabled, notify it of the change.
void updateFailureDetectorWorkingSet();
// Activate the given timer.
void activateTimer(FailoverTimer& timer);
// When in single copy delivery mode, this timer will trigger at a regular
// interval and check if we need to change the shards down list and rewind the
// stream.
FailoverTimer shards_down_failover_timer_;
// The callback for this timer.
bool shardsDownFailoverTimerCallback(small_shardset_t down);
// When in single copy delivery mode, this timer will trigger at a regular
// interval and check if we need to failover to all send all mode.
FailoverTimer all_send_all_failover_timer_;
// The callback for this timer.
bool allSendAllFailoverTimerCallback(small_shardset_t down);
/**
* When in single copy delivery mode, maintains the list of filtered out
* shards sent to storage shards.
*/
class FilteredOut {
public:
enum class ShardState : bool { FILTERED = true, NOT_FILTERED = false };
using FailureDomain =
FailureDomainNodeSet<ShardState, HashEnum<ShardState>>;
// Returns the shards down list.
const small_shardset_t& getShardsDown() const {
return shards_down_;
}
// Returns the shards slow list.
const small_shardset_t& getShardsSlow() const {
return shards_slow_;
}
// Returns all the filtered out shards.
const small_shardset_t& getAllShards() const {
return all_shards_;
}
// Returns the new shards slow list.
const ShardSet& getNewShardsSlow() const {
return new_shards_slow_;
}
// Returns the new shards down list.
const ShardSet& getNewShardsDown() const {
return new_shards_down_;
}
// Schedule a change to the list of slow shards.
// @returns true if the change was scheduled or false if the scheduled list
// of slow shards is already equal to `outliers`.
bool deferredChangeShardsSlow(ShardSet outliers);
// Schedule given shard to be added to the shards down/slow list the next
// time applyDeferredChanges is called.
// @returns whether the shard was added
bool deferredAddShardDown(ShardID shard);
// The given shard will be removed from the shards down list the next time
// applyDeferredChanges is called.
// @returns whether the shard was removed
bool deferredRemoveShardDown(ShardID shard);
// Applies all deferred changes to the shard down/slow list.
// @returns whether there were any changes at all to be applied
bool applyDeferredChanges();
// Removes the shard from the filtered out list (including shards
// down/slow list). Returns true if the shard was in the list.
// If the shard was not in the list but was scheduled to be added,
// cancel that.
bool eraseShard(ShardID shard);
// Clear all the lists and any scheduled change.
void clear();
private:
// The current shards slow/down list
small_shardset_t shards_slow_;
small_shardset_t shards_down_;
// The union of the shards down and shards slow list.
small_shardset_t all_shards_;
// Shards that are scheduled to replace the shards down/slow list.
ShardSet new_shards_down_;
// Shards that are scheduled to be added to the shards slow list, mapped
// to the time this scheduling happened.
ShardSet new_shards_slow_;
friend class ClientReadStreamScd_FilteredOutTest;
};
std::unique_ptr<ClientReadStreamFailureDetector> outlier_detector_;
FilteredOut filtered_out_;
// Callback called by ClientReadStreamFailureDetector when it detects
// outliers. Will blacklist the outliers according to SCD rules if the
// outlier detector is not configured in observe-only mode.
void onOutliersChanged(ShardSet outliers, std::string reason);
// Blacklist a set of outliers according to SCD rules. No-op if this read
// stream is in ALL_SEND_ALL mode.
void rewindWithOutliers(ShardSet outliers, std::string reason);
// Utility method to get from client settings whether the detection of slow
// shards is enabled.
bool isSlowShardsDetectionEnabled();
/**
* Checks if we need to rewind after the storage shards set has been updated.
*
* @return true if the streams were rewound.
*/
bool maybeRewindAfterShardsUpdated(bool shards_udpated);
// When a rewind is scheduled, this is set to Mode::SCD or Mode::ALL_SEND_ALL
// if this rewind should cause a transition to SCD or ALL_SEND_ALL mode
// respectively.
folly::Optional<Mode> scheduled_mode_transition_;
// Returns true if a transition to the given mode is scheduled.
bool scheduledTransitionTo(Mode mode) {
return scheduled_mode_transition_.hasValue() &&
scheduled_mode_transition_.value() == mode;
}
friend class ClientReadStreamTest;
friend class ClientReadStreamScd_FilteredOutTest;
};
}} // namespace facebook::logdevice
| [
"[email protected]"
] | |
ff8498db86b29d35c7afcbdf03082cde9deeba6c | 262b63935444b45317f9dabdb1f6577ea343fe69 | /src/Qpu.cpp | fbfa3cd0484bd65c4ca3c904d3c262a7d5ea36ce | [
"MIT",
"BSD-3-Clause"
] | permissive | PookyFan/QPUWrapper | 88134902d6b654aa92789230ee31f8f1e323c546 | 79f86559d31d3468672ccc33b2477e6053d8e2bf | refs/heads/main | 2023-02-25T09:01:26.259721 | 2021-01-30T00:32:40 | 2021-01-30T00:32:40 | 329,715,037 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,314 | cpp | #include <bcm_host.h>
#include <sched.h>
#include "MailboxRequest.hpp"
#include "Qpu.hpp"
#include "utils.hpp"
//Memory allocation flags
constexpr uint32_t MEM_FLAG_DIRECT = 1 << 2;
constexpr uint32_t MEM_FLAG_COHERENT = 2 << 2;
constexpr uint32_t MEM_FLAG_NO_INIT = 1 << 5;
//VideoCore registers addresses (descriptions available in official VideoCore4 documentation at https://docs.broadcom.com/docs/12358545 )
//Actually these are indices for accessing 32-bit registers as table of uint32_t elements, thus address is always divided by 4
//The addresses have offset of 0xC00000 probably to access registers in no-cache mode (not sure about that, though)
constexpr uint32_t V3D_IDENT1 = 0xC00004 / sizeof(uint32_t);
constexpr uint32_t V3D_L2CACTL = 0xC00020 / sizeof(uint32_t);
constexpr uint32_t V3D_SLCACTL = 0xC00024 / sizeof(uint32_t);
constexpr uint32_t V3D_SQRSV0 = 0xC00410 / sizeof(uint32_t);
constexpr uint32_t V3D_SQRSV1 = 0xC00414 / sizeof(uint32_t);
constexpr uint32_t V3D_SRQPC = 0xC00430 / sizeof(uint32_t);
constexpr uint32_t V3D_SRQUA = 0xC00434 / sizeof(uint32_t);
constexpr uint32_t V3D_SRQUL = 0xC00438 / sizeof(uint32_t);
constexpr uint32_t V3D_SRQCS = 0xC0043C / sizeof(uint32_t);
constexpr uint32_t V3D_VPMBASE = 0xC00504 / sizeof(uint32_t);
constexpr uint32_t V3D_DBCFG = 0xC00E00 / sizeof(uint32_t); //This isn't documented, but seems to disallow IRQ on QPUs when set to 0
constexpr uint32_t V3D_DBQITE = 0xC00E2C / sizeof(uint32_t);
constexpr uint32_t V3D_DBQITC = 0xC00E30 / sizeof(uint32_t);
//Other addresses
constexpr uint32_t PI1_SDRAM_ADDRESS = 0x40000000;
//Other constants
constexpr uint32_t MEMORY_ALIGN = QPUWrapper::PAGE_SIZE;
constexpr uint32_t ENABLE_QPU = 1;
constexpr uint32_t DISABLE_QPU = 0;
constexpr uint32_t RESERVE_ENABLED = 0xE;
constexpr uint32_t RESERVE_DISABLED = 0xF;
namespace QPUWrapper
{
uint32_t busAddressToPhysicalAddress(uint32_t busAddr)
{
return busAddr & ~0xC0000000;
}
Qpu::Qpu()
{
//Initialize mailbox
openMailbox();
//Enable QPU
MailboxRequest request(RequestType::SetQpuState);
request << ENABLE_QPU;
if(*sendMailboxRequest(request) != 0)
throw std::runtime_error("Qpu::Qpu(): could not enable QPU");
//Set proper memory allocation flag (apparently only RPI1 and Zero (W) can use cached memory)
memAllocFlags = MEM_FLAG_DIRECT | MEM_FLAG_NO_INIT | (bcm_host_get_sdram_address() == PI1_SDRAM_ADDRESS ? MEM_FLAG_COHERENT : 0);
//Map peripherals address to process' address space
unsigned int peripheralAddress = bcm_host_get_peripheral_address();
size_t peripheralMemSize = bcm_host_get_peripheral_size();
peripherals = MappedMemory(reinterpret_cast<volatile uint32_t*>(mapPhysicalAddress(peripheralAddress, peripheralMemSize)), peripheralMemSize);
//Get real number of QPU instances
uint32_t ident1 = peripherals[V3D_IDENT1];
int slicesCount = (ident1 >> 4) & 0xF;
int qpuInstancesPerSlice = (ident1 >> 8) & 0xF;
qpuCount = slicesCount * qpuInstancesPerSlice;
//Reserve all available QPU instances (for now disable executing programs on them)
reserveQpus(0);
//Give QPU programs maximum ammount of VPM memory (in multiples of quadruple 32-bit 16-way vectors)
peripherals[V3D_VPMBASE] = 16;
}
Qpu::~Qpu()
{
//Free all QPU instances
peripherals[V3D_SQRSV0] = 0;
peripherals[V3D_SQRSV1] = 0;
//Disable QPU
MailboxRequest request(RequestType::SetQpuState);
request << DISABLE_QPU;
sendMailboxRequest(request);
//Unmap perihperals address
unmapPhysicalAddress(bcm_host_get_peripheral_address(), peripherals.getGenericDataPointer(), peripherals.getMappedBlockSize());
}
Qpu& Qpu::getQpuWrapperInstance()
{
if(instance == nullptr)
instance = new Qpu();
return *instance;
}
std::future<ExecutionResult> Qpu::executeProgram(QpuProgram &program, std::chrono::microseconds timeout)
{
program.prepareToExecute();
return std::async(std::launch::async, &Qpu::runProgram, this, std::ref(program), timeout);
}
void Qpu::reserveQpus(int useCount)
{
uint32_t reservationConfig = 0;
for(int i = 0; i <= 7 && i < qpuCount; ++i)
reservationConfig |= ((useCount > i ? RESERVE_ENABLED : RESERVE_DISABLED) << (i * 4));
peripherals[V3D_SQRSV0] = reservationConfig;
reservationConfig = 0;
for(int i = 8; i < qpuCount; ++i)
reservationConfig |= ((useCount > i ? RESERVE_ENABLED : RESERVE_DISABLED) << ((i - 8) * 4));
peripherals[V3D_SQRSV1] = reservationConfig;
}
void Qpu::unlockGpuMemory(uint32_t memoryHandle)
{
MailboxRequest request(RequestType::MemoryUnlock);
request << memoryHandle;
sendMailboxRequest(request);
}
void Qpu::freeGpuMemory(uint32_t memoryHandle, uint32_t physicalAddress, void *mappedAddress, size_t size)
{
MailboxRequest request(RequestType::MemoryDeallocation);
request << memoryHandle;
unmapPhysicalAddress(physicalAddress, mappedAddress, size);
sendMailboxRequest(request);
}
GpuAddress Qpu::lockGpuMemory(uint32_t memoryHandle)
{
MailboxRequest request(RequestType::MemoryLock);
request << memoryHandle;
return *sendMailboxRequest(request);
}
std::tuple<uint32_t, GpuAddress, void*> Qpu::allocateGpuMemory(size_t size)
{
MailboxRequest request(RequestType::MemoryAllocation);
request << size << MEMORY_ALIGN << memAllocFlags;
uint32_t memoryHandle = *sendMailboxRequest(request);
GpuAddress gpuAddress = lockGpuMemory(memoryHandle);
unlockGpuMemory(memoryHandle);
void *localAddress = mapPhysicalAddress(busAddressToPhysicalAddress(gpuAddress), size);
return { memoryHandle, gpuAddress, localAddress };
}
ExecutionResult Qpu::runProgram(QpuProgram &program, std::chrono::microseconds timeout)
{
std::lock_guard lck(programExecutionMutex);
//Check how many programs are queued at the moment and how many have already finished
int queued = peripherals[V3D_SRQCS] & 0x3F;
int finished = (peripherals[V3D_SRQCS] >> 16) & 0xFF;
if(int freeQpus = qpuCount - queued; freeQpus < program.instancesCount)
return ExecutionResult::QpuBusy;
else
reserveQpus(program.instancesCount);
//Do not use interrupts
peripherals[V3D_DBCFG] = 0;
peripherals[V3D_DBQITE] = 0;
peripherals[V3D_DBQITC] = 0xFFFF;
//Clear all caches
peripherals[V3D_L2CACTL] = (1<<2);
peripherals[V3D_SLCACTL] = 0b1111<<24 | 0b1111<<16 | 0b1111<<8 | 0b1111<<0;
//Enqueue program on QPU instances
program.isProgramExecuted = true;
for(int i = 0; i < program.instancesCount; ++i)
{
peripherals[V3D_SRQUA] = program.programMemory.gpuAddress
+ program.codeSectionSize
+ i * program.uniformsPerInstanceCount * sizeof(uint32_t);
peripherals[V3D_SRQUL] = program.uniformsPerInstanceCount;
peripherals[V3D_SRQPC] = program.programMemory.gpuAddress;
}
auto timeStart = std::chrono::steady_clock::now();
int finishedTarget = (finished + program.instancesCount) % 256; //The counter rolls back to 0 when it counts to 256
do
{
sched_yield(); //Give it some time while not blocking other threads
if(std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::steady_clock::now() - timeStart).count() > timeout.count())
return ExecutionResult::Timeout;
finished = (peripherals[V3D_SRQCS] >> 16) & 0xFF;
} while(finished != finishedTarget);
reserveQpus(0);
program.isProgramExecuted = false;
return ExecutionResult::Success;
}
/* Static field initialization */
Qpu *Qpu::instance = nullptr;
} | [
"[email protected]"
] | |
b32c02b160c3547a1be5b7a50e62d6edb1e7b0cd | 93b24e6296dade8306b88395648377e1b2a7bc8c | /client/Client/CEGUI/CEGUI/include/CEGUIPropertyHelper.h | 057529d07dac41667188278bc472669720d3827c | [] | no_license | dahahua/pap_wclinet | 79c5ac068cd93cbacca5b3d0b92e6c9cba11a893 | d0cde48be4d63df4c4072d4fde2e3ded28c5040f | refs/heads/master | 2022-01-19T21:41:22.000190 | 2013-10-12T04:27:59 | 2013-10-12T04:27:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,232 | h | /************************************************************************
filename: CEGUIPropertyHelper.h
created: 6/7/2004
author: Paul D Turner
purpose: Interface to the PropertyHelper class
*************************************************************************/
/*************************************************************************
Crazy Eddie's GUI System (http://www.cegui.org.uk)
Copyright (C)2004 - 2005 Paul D Turner ([email protected])
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
*************************************************************************/
#ifndef _CEGUIPropertyHelper_h_
#define _CEGUIPropertyHelper_h_
#include "CEGUIWindow.h"
// Start of CEGUI namespace section
namespace CEGUI
{
/*!
\brief
Helper class used to convert various data types to and from the format expected in Propery strings
*/
class CEGUIEXPORT PropertyHelper
{
public:
static float stringToFloat(const String& str);
static UINT stringToUint(const String& str);
static int stringToInt(const String& str);
static bool stringToBool(const String& str);
static Size stringToSize(const String& str);
static Point stringToPoint(const String& str);
static Rect stringToRect(const String& str);
static MetricsMode stringToMetricsMode(const String& str);
static const Image* stringToImage(const String& str);
static colour stringToColour(const String& str);
static ColourRect stringToColourRect(const String& str);
static UDim stringToUDim(const String& str);
static UVector2 stringToUVector2(const String& str);
static URect stringToURect(const String& str);
static HookMode stringToHookMode( const String& str );
static String floatToString(float val);
static String uintToString(UINT val);
static String intToString(int val);
static String boolToString(bool val);
static String sizeToString(const Size& val);
static String pointToString(const Point& val);
static String rectToString(const Rect& val);
static String metricsModeToString(MetricsMode val);
static String imageToString(const Image* const val);
static String colourToString(const colour& val);
static String colourRectToString(const ColourRect& val);
static String udimToString(const UDim& val);
static String uvector2ToString(const UVector2& val);
static String urectToString(const URect& val);
static String hookModeToString( const HookMode& val );
};
} // End of CEGUI namespace section
#endif // end of guard _CEGUIPropertyHelper_h_
| [
"[email protected]"
] | |
5ea919aa0f23b75c0f376cdb77bd33acb68b12fb | 2ba94892764a44d9c07f0f549f79f9f9dc272151 | /Engine/Source/Editor/SceneOutliner/Public/SceneOutlinerFilters.h | 78d45dd3eb57992a372774b926c09684947e6509 | [
"BSD-2-Clause",
"LicenseRef-scancode-proprietary-license"
] | permissive | PopCap/GameIdea | 934769eeb91f9637f5bf205d88b13ff1fc9ae8fd | 201e1df50b2bc99afc079ce326aa0a44b178a391 | refs/heads/master | 2021-01-25T00:11:38.709772 | 2018-09-11T03:38:56 | 2018-09-11T03:38:56 | 37,818,708 | 0 | 0 | BSD-2-Clause | 2018-09-11T03:39:05 | 2015-06-21T17:36:44 | null | UTF-8 | C++ | false | false | 6,818 | h | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "IFilter.h"
#include "FilterCollection.h"
#include "ITreeItem.h"
#include "FolderTreeItem.h"
#include "ActorTreeItem.h"
#include "WorldTreeItem.h"
namespace SceneOutliner
{
/** Enum to specify how items that are not explicitly handled by this filter should be managed */
enum class EDefaultFilterBehaviour : uint8 { Pass, Fail };
/** Enum that defines how a tree item should be dealt with in the case where it appears in the tree, but doesn't match the filter (eg if it has a matching child) */
enum class EFailedFilterState : uint8 { Interactive, NonInteractive };
/** A filter that can be applied to any type in the tree */
class FOutlinerFilter : public ITreeItemVisitor, public IFilter<const ITreeItem&>
{
public:
/** Event that is fired if this filter changes */
DECLARE_DERIVED_EVENT(FOutlinerFilter, IFilter<const ITreeItem&>::FChangedEvent, FChangedEvent);
virtual FChangedEvent& OnChanged() override { return ChangedEvent; }
/** Enum that defines how a tree item should be dealt with in the case where it appears in the tree, but doesn't match the filter (eg if it has a matching child) */
EFailedFilterState FailedItemState;
protected:
/** The event that broadcasts whenever a change occurs to the filter */
FChangedEvent ChangedEvent;
/** Default result of the filter when not overridden in derived classes */
const EDefaultFilterBehaviour DefaultBehaviour;
/** Constructor to specify the default result of a filter */
FOutlinerFilter(EDefaultFilterBehaviour InDefaultBehaviour, EFailedFilterState InFailedFilterState = EFailedFilterState::NonInteractive)
: FailedItemState(InFailedFilterState), DefaultBehaviour(InDefaultBehaviour)
{}
/** Overridden in derived types to filter actors */
virtual bool PassesFilter(const AActor* Actor) const { return DefaultBehaviour == EDefaultFilterBehaviour::Pass; }
/** Overridden in derived types to filter worlds */
virtual bool PassesFilter(const UWorld* World) const { return DefaultBehaviour == EDefaultFilterBehaviour::Pass; }
/** Overridden in derived types to filter folders */
virtual bool PassesFilter(FName Folder) const { return DefaultBehaviour == EDefaultFilterBehaviour::Pass; }
private:
/** Transient result from the filter operation. Only valid until the next invocation of the filter. */
mutable bool bTransientFilterResult;
virtual void Visit(const FActorTreeItem& ActorItem) const override
{
if (const AActor* Actor = ActorItem.Actor.Get())
{
bTransientFilterResult = PassesFilter(Actor);
}
else
{
bTransientFilterResult = false;
}
}
virtual void Visit(const FWorldTreeItem& WorldItem) const override
{
if (const UWorld* World = WorldItem.World.Get())
{
bTransientFilterResult = PassesFilter(World);
}
else
{
bTransientFilterResult = false;
}
}
virtual void Visit(const FFolderTreeItem& FolderItem) const override
{
bTransientFilterResult = PassesFilter(FolderItem.Path);
}
/** Check whether the specified item passes our filter */
virtual bool PassesFilter( const ITreeItem& InItem ) const override
{
InItem.Visit(*this);
return bTransientFilterResult;
}
};
DECLARE_DELEGATE_RetVal_OneParam( bool, FActorFilterPredicate, const AActor* );
DECLARE_DELEGATE_RetVal_OneParam( bool, FWorldFilterPredicate, const UWorld* );
DECLARE_DELEGATE_RetVal_OneParam( bool, FFolderFilterPredicate, FName );
/** Predicate based filter for the outliner */
struct FOutlinerPredicateFilter : public FOutlinerFilter
{
/** Predicate used to filter actors */
mutable FActorFilterPredicate ActorPred;
/** Predicate used to filter worlds */
mutable FWorldFilterPredicate WorldPred;
/** Predicate used to filter Folders */
mutable FFolderFilterPredicate FolderPred;
FOutlinerPredicateFilter(FActorFilterPredicate InActorPred, EDefaultFilterBehaviour InDefaultBehaviour, EFailedFilterState InFailedFilterState = EFailedFilterState::NonInteractive)
: FOutlinerFilter(InDefaultBehaviour, InFailedFilterState)
, ActorPred(InActorPred)
{}
FOutlinerPredicateFilter(FWorldFilterPredicate InWorldPred, EDefaultFilterBehaviour InDefaultBehaviour, EFailedFilterState InFailedFilterState = EFailedFilterState::NonInteractive)
: FOutlinerFilter(InDefaultBehaviour, InFailedFilterState)
, WorldPred(InWorldPred)
{}
FOutlinerPredicateFilter(FFolderFilterPredicate InFolderPred, EDefaultFilterBehaviour InDefaultBehaviour, EFailedFilterState InFailedFilterState = EFailedFilterState::NonInteractive)
: FOutlinerFilter(InDefaultBehaviour, InFailedFilterState)
, FolderPred(InFolderPred)
{}
virtual bool PassesFilter(const AActor* Actor) const override
{
return ActorPred.IsBound() ? ActorPred.Execute(Actor) : DefaultBehaviour == EDefaultFilterBehaviour::Pass;
}
virtual bool PassesFilter(const UWorld* World) const override
{
return WorldPred.IsBound() ? WorldPred.Execute(World) : DefaultBehaviour == EDefaultFilterBehaviour::Pass;
}
virtual bool PassesFilter(FName Folder) const override
{
return FolderPred.IsBound() ? FolderPred.Execute(Folder) : DefaultBehaviour == EDefaultFilterBehaviour::Pass;
}
};
/** Scene outliner filter class. This class abstracts the filtering of both actors and folders and allows for filtering on both types */
struct FOutlinerFilters : public TFilterCollection<const ITreeItem&>
{
/** Overridden to ensure we only ever have FOutlinerFilters added */
int32 Add(const TSharedPtr<FOutlinerFilter>& Filter)
{
return TFilterCollection::Add(Filter);
}
/** Test whether this tree item passes all filters, and set its interactive state according to the filter it failed (if applicable) */
bool TestAndSetInteractiveState(ITreeItem& InItem) const
{
bool bPassed = true;
// Default to interactive
InItem.Flags.bInteractive = true;
for (const auto& Filter : ChildFilters)
{
if (!Filter->PassesFilter(InItem))
{
bPassed = false;
InItem.Flags.bInteractive = StaticCastSharedPtr<FOutlinerFilter>(Filter)->FailedItemState == EFailedFilterState::Interactive;
// If this has failed, but is still interactive, we carry on to see if any others fail *and* set to non-interactive
if (!InItem.Flags.bInteractive)
{
return false;
}
}
}
return bPassed;
}
/** Add a filter predicate to this filter collection */
template<typename T>
void AddFilterPredicate(T Predicate, EDefaultFilterBehaviour InDefaultBehaviour = EDefaultFilterBehaviour::Fail, EFailedFilterState InFailedFilterState = EFailedFilterState::NonInteractive)
{
Add(MakeShareable(new FOutlinerPredicateFilter(Predicate, InDefaultBehaviour, InFailedFilterState)));
}
};
} | [
"[email protected]"
] | |
60d4635c85dc79470e30a35528447474feb01de5 | 56b752e2de45e6b4eb58d0b0cd89584969dddc71 | /Component/Component.cpp | d3db684aab434cd3594c1f82c3ccbfcd449a124d | [] | no_license | sambsp/RayTracing | d2b69f10704a716d6724b6cc826bdb603f0916b5 | f0293d9136b0c238e0f327adf8fa28be7b8c6a98 | refs/heads/main | 2023-04-21T06:00:39.263239 | 2021-05-05T14:23:02 | 2021-05-05T14:23:02 | 363,355,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 64 | cpp | //
// Created by 周华 on 2021/5/4.
//
#include "Component.h"
| [
"[email protected]"
] | |
35ef84730b8cf67d0cfc58cd8a9c432291bc35a1 | 411ab7c07e92cc575ce6044927fe842114ad1b8b | /test4assentmang/threadworkz.cpp | e6ae1f901d52a001b67a01b1bf044c79d9feada1 | [] | no_license | zeplaz/symecodev | 5a1df6322bba351bb5ea3c8c29f2577307f8a1b5 | 1894303fa17c97b9799144fa9792e4b0f1973b05 | refs/heads/master | 2021-09-29T03:45:47.587611 | 2018-11-23T16:52:20 | 2018-11-23T16:52:20 | 154,870,745 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,925 | cpp |
//$gcc test.cpp -lpthread
#include <pthread.h>
#include <stdio.h>
#include <queue>
#include <stack.h>
#define NUM_THREADS 5;
int t_error_code;
struct tH_dastrc
{
int tH_id;
void *status;
char* messg;
void* data; //stack<mesg*>
struct tH_dastrc *prOther_thrz_data;
struct tasks_strc *pr_tasks_data;
};
struct tasks_strc
{bool task_complete = false;
int task_id;
int type;
char* cmdz;
char* typenamez;
};
// inlizetasks()
// tasks xs Graphics
// taskys y logic,z funcions()
//when new task is created();
//}
int create_task(int request, int& taskcounter,void* task_data )
{
struct tasks_strc *this_data;
this_data = (struct tasks_strc *) task_data;
this_data->task_id= taskcounter+1;
//requestlist
switch (request)
{
case 0 :
printf ("stuff about case onetaskzdatastucapend etf \n") ;
this_data->typenamez = 'somedatatask';
this_data->type =0;
this_data->cmdz ='skfilv_docverwatch_cmd_lizcom{radiooutout__}//4dddSPKLZ';
break;
case 1 :
printf ("stuff about case twoone renderequest etf \n") ;
this_data->typenamez = 'renderequest';
this_data->type =1;
this_data->cmdz ='render vertexarrayz';
break;
case 2 :
printf ("senderequest somelogic stuff \n") ;
this_data->typenamez = 'logic';
this_data->type =2;
this_data->cmdz ='comput logic';
break;
case 3 :
printf ("createobjects,phisz,updaterz \n") ;
this_data->typenamez = 'creatobjupdate?';
this_data->type =3;
this_data->cmdz ='gen_update;_gen_ph_obj';
break;
}
//this_data.id = taskcounter++;
taskQue->push(this_data);
taskcounter++;
return (tasks.id);
}
void update_taskz(int& taskcounter,void* task_data ){
{ struct tasks_strc *this_data;
this_data = (struct tasks_strc *) task_data;
}
if (this_data->task_complete=true)
prinf ("task flag comleate checked, destorying..\n");
destroy_task(this_data->id);
}
void* inilz_rutine(void *threadArg)
{
struct tH_datastrc *this_data;
this_data = (struct tH_datastrc *) threadArg;
this_data->messg = 'clear';
}
void* assenttaskto_thread(&queue<tasks_strc*> ref_queoftaskz,pthread_attr_t attr )
{
struct tH_datastrc *Assign_data;
while ( !ref_queoftaskz->isEmpty())
{ for( i = 0; i < NUM_THREADS; i++ )
{
Assign_data[i].thread_id = i; //(void *)&??[i]);
Assign_data[i].pr_tasks_data = ref_queoftaskz->top();
t_error_code = pthread_create(
&thread[i], attr, inilz_rutine,(void *)&tH_dastrc[i]);
if(t_error_code)
{
printf ("Error in thread production ZCODE_/; %s \n", t_error_code);
}
}
}
}
//int run_threads()
//{
// create threads
// for( i = 0; i < NUM_THREADS; i++ )
// {
// }
//return ()
//} //pthread_create (&thread[i], attr, start_rutine, arg)
int main ()
{
pthread_t threads[NUM_THREADS];
pthread_attr_t attr;
// deal further with attrbute settings?
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE);
const int n = 15;
int* thread_id;
int thread_count=0;
//int* pr_resquestz;
int taskconttotal=0;
int taskpending=0;
int taskactive=0;
queue<tasks_strc*> taskQue;
stack<tasks_strc*> taskStack;
std::unique_ptr<int[]> array_requestz_buffer(new int[n]);
//request buffer?
//run_threads() = new thread_id[]
while (!requestz=-1)
{
//pr_resquestz=
printf("info about stuff. enter request -1 break,infocde:totaltak: %s,pendingt: %s,active_t: %s \n"
,taskconttotal,taskpending, taskactive )
std::cin >> array_requestz_buffer[taskconttotal];
if ( 0 != array_requestz_buffer[taskconttotal])
taskconttotal++;
if (taskconttotal) ==0)
(break;)
create_task(array_requestz_buffer[taskconttotal], &taskconttotal,void* task_data )
taskpending++;
}
if (taskpending >0)
{
new thread_id[assenttaskto_thread(&taskQue)];}
//destoryandexit
pthread_attr_destroy(&attr);
for( i = 0; i < NUM_THREADS; i++ )
{
t_error_code = pthread_join(threads[i], &status);
if (t_error_code) {
printf ("Error:unable to join,ErCODe_; %s \n", t_error_code);
}
}
//final pointer cleanup.
delete[] array_requestz_buffer;
pthread_exit(NULL);
}
| [
"[email protected]"
] | |
ba6394528fe5ed8ec9d0f5c1702046f8190293c3 | e5386f56cc7ccd48c11752e4a5ae7ed21d38876d | /algorithmPractise/BinaryTree/rebuildTree.cpp | 721315aad5e89481da6bfdca90d783a6cebf1d93 | [] | no_license | shaoyuncen/Algorithm | 65bb4b5ab5199bcf98d85dec5c48e04970a21879 | b72843431d8f6703e424004e04be30e1a374abad | refs/heads/master | 2021-06-09T03:37:23.732956 | 2019-08-12T01:50:33 | 2019-08-12T01:50:33 | 111,802,635 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | #include "tree.h"
#include <iostream>
TreeNode* rebuild(char* pstr, char* istr, int n)
{
if(n<=0)
return NULL;
TreeNode* root=new TreeNode(*pstr);
char* iter;
for(iter=istr;iter<istr+n;++iter)
if(*iter==*pstr)
break;
int k = iter-istr;
root->left = rebuild(pstr+1,istr,k);
root->right = rebuild(pstr+k+1,iter+1,n-k-1);
} | [
"[email protected]"
] | |
984fec586def212f314d627058706af048476e2e | 7924c1e4c8c78888b8ed91d178a0a693d1ffd796 | /src/Core/IListener.h | 7e968f1b4f504cd9feb5fb132aae8255079afdf1 | [] | no_license | PivkoDev/ReMind | 5bca490285cb445a1dc767d8a2188b884b421e0c | e8705449d98d24a67bcb0d7aaa2aa3ba9f90d219 | refs/heads/master | 2020-08-15T17:34:34.264392 | 2019-10-23T20:32:17 | 2019-10-23T20:32:17 | 215,381,116 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 389 | h | #pragma once
class IListener
{
public:
virtual ~IListener() = 0;
//drawing functions
virtual void notifyBeginFrame() = 0;
virtual void notifyDisplayFrame() = 0;
virtual void notifyEndFrame() = 0;
virtual void notifyReshape(int width,
int height,
int previous_width,
int previous_height) = 0;
};
inline IListener::~IListener() {
//implementation of pure virtual destructor
} | [
"[email protected]"
] | |
4293237abad7f125e007fd3e95738fd66eea5ab9 | a2e04e4eac1cf93bb4c1d429e266197152536a87 | /Cpp/SDK/BP_PromptActor_BootyStorage_classes.h | 40c238a9b456dee706c9e4ea68980aeb45bb1a84 | [] | no_license | zH4x-SDK/zSoT-SDK | 83a4b9fcdf628637613197cf644b7f4d101bb0cb | 61af221bee23701a5df5f60091f96f2cf929846e | refs/heads/main | 2023-07-16T18:23:41.914014 | 2021-08-27T15:44:23 | 2021-08-27T15:44:23 | 400,555,804 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,387 | h | #pragma once
// Name: SoT, Version: 2.2.1.1
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass BP_PromptActor_BootyStorage.BP_PromptActor_BootyStorage_C
// 0x0010 (FullSize[0x0418] - InheritedSize[0x0408])
class ABP_PromptActor_BootyStorage_C : public ABP_PromptActorBase_C
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x0408(0x0008) (ZeroConstructor, Transient, DuplicateTransient)
class UBP_PromptCoordinator_BootyStorage_C* PromptCoordinator; // 0x0410(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor)
static UClass* StaticClass()
{
static UClass* ptr = UObject::FindClass("BlueprintGeneratedClass BP_PromptActor_BootyStorage.BP_PromptActor_BootyStorage_C");
return ptr;
}
void UserConstructionScript();
void ReceiveBeginPlay();
void ReceiveEndPlay(TEnumAsByte<Engine_EEndPlayReason> EndPlayReason);
void ExecuteUbergraph_BP_PromptActor_BootyStorage(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"[email protected]"
] | |
f5a3a1000f08509dc206c58f829922d745815a3d | 0bb2876a278f069aed3f353fe3e3c09261138801 | /Code Forces/B_Prinzessin_der_Verurteilung.cpp | f1a790563f5ba204113fc5af4b20f0fbc1e4aa4a | [] | no_license | ranveerraj248/DS-Algo-Basic | 8de95240ff25a7c36852eb690b020009365e40c5 | 2339ce00c2929fc354a57c8d600ea7f0e34964fe | refs/heads/main | 2023-06-25T14:04:56.938052 | 2021-07-29T03:55:11 | 2021-07-29T03:55:11 | 390,592,397 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,342 | cpp | #include <bits/stdc++.h>
typedef long long ll;
using namespace std;
int main()
{
int t = 1;
cin >> t;
while (t--)
{
set<string> ourset;
ll n;
cin >> n;
string str;
cin >> str;
int flag = 0;
for (int i = 0; i < n; i++)
{
string st = "";
st += str[i];
ourset.insert(st);
}
for (int i = 0; i < n - 1; i++)
{
string st = "";
st += str[i];
st += str[i + 1];
ourset.insert(st);
}
for (int i = 0; i < n - 2; i++)
{
string st = "";
st += str[i];
st += str[i + 1];
st += str[i + 2];
ourset.insert(st);
}
for (char i = 'a'; i <= 'z'; i++)
{
string st = "";
st += i;
if (!ourset.count(st) > 0)
{
cout << st << endl;
flag = 1;
break;
}
}
if (flag == 1)
continue;
for (char i = 'a'; i <= 'z'; i++)
{
string st = "";
st += i;
for (char j = 'a'; j <= 'z'; j++)
{
string st1 = st;
st1 += j;
if (!ourset.count(st1) > 0)
{
cout << st1 << endl;
flag = 1;
break;
}
}
if (flag == 1)
break;
}
if (flag == 1)
continue;
for (char i = 'a'; i <= 'z'; i++)
{
string st = "";
st += i;
for (char j = 'a'; j <= 'z'; j++)
{
string st1 = st;
st1 += j;
for (char k = 'a'; k <= 'z'; k++)
{
string st2 = st1;
st2 += k;
if (!ourset.count(st2) > 0)
{
cout << st2 << endl;
flag = 1;
break;
}
}
if (flag == 1)
break;
}
if (flag == 1)
break;
}
}
return 0;
} | [
"[email protected]"
] | |
20dfb1a5679638fe7b14d276d3a7227fad8f5369 | 0f5f4134eb187e13e82ba15c46e634534a0fb608 | /cpp_src/7/decimal/decimal | 7d1631baac7d160ab681454145430054eb3137cc | [] | no_license | degieusz/sii_vim_local | 250ed6e41404796cc96db926c5eb24ca1cb4a65b | 22c3628cd2e9f85209ada1972cf87cef853c8cc0 | refs/heads/master | 2020-03-22T09:46:49.040079 | 2018-07-05T14:16:31 | 2018-07-05T14:16:31 | 139,860,024 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,611 | // <decimal> -*- C++ -*-
// Copyright (C) 2009-2017 Free Software Foundation, Inc.
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/** @file decimal/decimal
* This is a Standard C++ Library header.
*/
// ISO/IEC TR 24733
// Written by Janis Johnson <[email protected]>
#ifndef _GLIBCXX_DECIMAL
#define _GLIBCXX_DECIMAL 1
#pragma GCC system_header
#include <bits/c++config.h>
#ifndef _GLIBCXX_USE_DECIMAL_FLOAT
#error This file requires compiler and library support for ISO/IEC TR 24733 \
that is currently not available.
#endif
namespace std
{
/**
* @defgroup decimal Decimal Floating-Point Arithmetic
* @ingroup numerics
*
* Classes and functions for decimal floating-point arithmetic.
* @{
*/
/** @namespace std::decimal
* @brief ISO/IEC TR 24733 Decimal floating-point arithmetic.
*/
namespace decimal
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
class decimal32;
class decimal64;
class decimal128;
// 3.2.5 Initialization from coefficient and exponent.
static decimal32 make_decimal32(long long __coeff, int __exp);
static decimal32 make_decimal32(unsigned long long __coeff, int __exp);
static decimal64 make_decimal64(long long __coeff, int __exp);
static decimal64 make_decimal64(unsigned long long __coeff, int __exp);
static decimal128 make_decimal128(long long __coeff, int __exp);
static decimal128 make_decimal128(unsigned long long __coeff, int __exp);
/// Non-conforming extension: Conversion to integral type.
long long decimal32_to_long_long(decimal32 __d);
long long decimal64_to_long_long(decimal64 __d);
long long decimal128_to_long_long(decimal128 __d);
long long decimal_to_long_long(decimal32 __d);
long long decimal_to_long_long(decimal64 __d);
long long decimal_to_long_long(decimal128 __d);
// 3.2.6 Conversion to generic floating-point type.
float decimal32_to_float(decimal32 __d);
float decimal64_to_float(decimal64 __d);
float decimal128_to_float(decimal128 __d);
float decimal_to_float(decimal32 __d);
float decimal_to_float(decimal64 __d);
float decimal_to_float(decimal128 __d);
double decimal32_to_double(decimal32 __d);
double decimal64_to_double(decimal64 __d);
double decimal128_to_double(decimal128 __d);
double decimal_to_double(decimal32 __d);
double decimal_to_double(decimal64 __d);
double decimal_to_double(decimal128 __d);
long double decimal32_to_long_double(decimal32 __d);
long double decimal64_to_long_double(decimal64 __d);
long double decimal128_to_long_double(decimal128 __d);
long double decimal_to_long_double(decimal32 __d);
long double decimal_to_long_double(decimal64 __d);
long double decimal_to_long_double(decimal128 __d);
// 3.2.7 Unary arithmetic operators.
decimal32 operator+(decimal32 __rhs);
decimal64 operator+(decimal64 __rhs);
decimal128 operator+(decimal128 __rhs);
decimal32 operator-(decimal32 __rhs);
decimal64 operator-(decimal64 __rhs);
decimal128 operator-(decimal128 __rhs);
// 3.2.8 Binary arithmetic operators.
#define _DECLARE_DECIMAL_BINARY_OP_WITH_DEC(_Op, _T1, _T2, _T3) \
_T1 operator _Op(_T2 __lhs, _T3 __rhs);
#define _DECLARE_DECIMAL_BINARY_OP_WITH_INT(_Op, _Tp) \
_Tp operator _Op(_Tp __lhs, int __rhs); \
_Tp operator _Op(_Tp __lhs, unsigned int __rhs); \
_Tp operator _Op(_Tp __lhs, long __rhs); \
_Tp operator _Op(_Tp __lhs, unsigned long __rhs); \
_Tp operator _Op(_Tp __lhs, long long __rhs); \
_Tp operator _Op(_Tp __lhs, unsigned long long __rhs); \
_Tp operator _Op(int __lhs, _Tp __rhs); \
_Tp operator _Op(unsigned int __lhs, _Tp __rhs); \
_Tp operator _Op(long __lhs, _Tp __rhs); \
_Tp operator _Op(unsigned long __lhs, _Tp __rhs); \
_Tp operator _Op(long long __lhs, _Tp __rhs); \
_Tp operator _Op(unsigned long long __lhs, _Tp __rhs);
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal32, decimal32, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal32, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal64, decimal64, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal32, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal64, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(+, decimal128, decimal128, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(+, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal32, decimal32, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal32, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal64, decimal64, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal32, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal64, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(-, decimal128, decimal128, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(-, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal32, decimal32, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal32, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal64, decimal64, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal32, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal64, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(*, decimal128, decimal128, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(*, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal32, decimal32, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal32, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal64, decimal64, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal32, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal64, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal32)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal64)
_DECLARE_DECIMAL_BINARY_OP_WITH_DEC(/, decimal128, decimal128, decimal128)
_DECLARE_DECIMAL_BINARY_OP_WITH_INT(/, decimal128)
#undef _DECLARE_DECIMAL_BINARY_OP_WITH_DEC
#undef _DECLARE_DECIMAL_BINARY_OP_WITH_INT
// 3.2.9 Comparison operators.
#define _DECLARE_DECIMAL_COMPARISON(_Op, _Tp) \
bool operator _Op(_Tp __lhs, decimal32 __rhs); \
bool operator _Op(_Tp __lhs, decimal64 __rhs); \
bool operator _Op(_Tp __lhs, decimal128 __rhs); \
bool operator _Op(_Tp __lhs, int __rhs); \
bool operator _Op(_Tp __lhs, unsigned int __rhs); \
bool operator _Op(_Tp __lhs, long __rhs); \
bool operator _Op(_Tp __lhs, unsigned long __rhs); \
bool operator _Op(_Tp __lhs, long long __rhs); \
bool operator _Op(_Tp __lhs, unsigned long long __rhs); \
bool operator _Op(int __lhs, _Tp __rhs); \
bool operator _Op(unsigned int __lhs, _Tp __rhs); \
bool operator _Op(long __lhs, _Tp __rhs); \
bool operator _Op(unsigned long __lhs, _Tp __rhs); \
bool operator _Op(long long __lhs, _Tp __rhs); \
bool operator _Op(unsigned long long __lhs, _Tp __rhs);
_DECLARE_DECIMAL_COMPARISON(==, decimal32)
_DECLARE_DECIMAL_COMPARISON(==, decimal64)
_DECLARE_DECIMAL_COMPARISON(==, decimal128)
_DECLARE_DECIMAL_COMPARISON(!=, decimal32)
_DECLARE_DECIMAL_COMPARISON(!=, decimal64)
_DECLARE_DECIMAL_COMPARISON(!=, decimal128)
_DECLARE_DECIMAL_COMPARISON(<, decimal32)
_DECLARE_DECIMAL_COMPARISON(<, decimal64)
_DECLARE_DECIMAL_COMPARISON(<, decimal128)
_DECLARE_DECIMAL_COMPARISON(>=, decimal32)
_DECLARE_DECIMAL_COMPARISON(>=, decimal64)
_DECLARE_DECIMAL_COMPARISON(>=, decimal128)
_DECLARE_DECIMAL_COMPARISON(>, decimal32)
_DECLARE_DECIMAL_COMPARISON(>, decimal64)
_DECLARE_DECIMAL_COMPARISON(>, decimal128)
_DECLARE_DECIMAL_COMPARISON(>=, decimal32)
_DECLARE_DECIMAL_COMPARISON(>=, decimal64)
_DECLARE_DECIMAL_COMPARISON(>=, decimal128)
#undef _DECLARE_DECIMAL_COMPARISON
/// 3.2.2 Class decimal32.
class decimal32
{
public:
typedef float __decfloat32 __attribute__((mode(SD)));
// 3.2.2.2 Construct/copy/destroy.
decimal32() : __val(0.e-101DF) {}
// 3.2.2.3 Conversion from floating-point type.
explicit decimal32(decimal64 __d64);
explicit decimal32(decimal128 __d128);
explicit decimal32(float __r) : __val(__r) {}
explicit decimal32(double __r) : __val(__r) {}
explicit decimal32(long double __r) : __val(__r) {}
// 3.2.2.4 Conversion from integral type.
decimal32(int __z) : __val(__z) {}
decimal32(unsigned int __z) : __val(__z) {}
decimal32(long __z) : __val(__z) {}
decimal32(unsigned long __z) : __val(__z) {}
decimal32(long long __z) : __val(__z) {}
decimal32(unsigned long long __z) : __val(__z) {}
/// Conforming extension: Conversion from scalar decimal type.
decimal32(__decfloat32 __z) : __val(__z) {}
#if __cplusplus >= 201103L
// 3.2.2.5 Conversion to integral type.
// Note: explicit per n3407.
explicit operator long long() const { return (long long)__val; }
#endif
// 3.2.2.6 Increment and decrement operators.
decimal32& operator++()
{
__val += 1;
return *this;
}
decimal32 operator++(int)
{
decimal32 __tmp = *this;
__val += 1;
return __tmp;
}
decimal32& operator--()
{
__val -= 1;
return *this;
}
decimal32 operator--(int)
{
decimal32 __tmp = *this;
__val -= 1;
return __tmp;
}
// 3.2.2.7 Compound assignment.
#define _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(_Op) \
decimal32& operator _Op(decimal32 __rhs); \
decimal32& operator _Op(decimal64 __rhs); \
decimal32& operator _Op(decimal128 __rhs); \
decimal32& operator _Op(int __rhs); \
decimal32& operator _Op(unsigned int __rhs); \
decimal32& operator _Op(long __rhs); \
decimal32& operator _Op(unsigned long __rhs); \
decimal32& operator _Op(long long __rhs); \
decimal32& operator _Op(unsigned long long __rhs);
_DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(+=)
_DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(-=)
_DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(*=)
_DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT(/=)
#undef _DECLARE_DECIMAL32_COMPOUND_ASSIGNMENT
private:
__decfloat32 __val;
public:
__decfloat32 __getval(void) { return __val; }
void __setval(__decfloat32 __x) { __val = __x; }
};
/// 3.2.3 Class decimal64.
class decimal64
{
public:
typedef float __decfloat64 __attribute__((mode(DD)));
// 3.2.3.2 Construct/copy/destroy.
decimal64() : __val(0.e-398dd) {}
// 3.2.3.3 Conversion from floating-point type.
decimal64(decimal32 d32);
explicit decimal64(decimal128 d128);
explicit decimal64(float __r) : __val(__r) {}
explicit decimal64(double __r) : __val(__r) {}
explicit decimal64(long double __r) : __val(__r) {}
// 3.2.3.4 Conversion from integral type.
decimal64(int __z) : __val(__z) {}
decimal64(unsigned int __z) : __val(__z) {}
decimal64(long __z) : __val(__z) {}
decimal64(unsigned long __z) : __val(__z) {}
decimal64(long long __z) : __val(__z) {}
decimal64(unsigned long long __z) : __val(__z) {}
/// Conforming extension: Conversion from scalar decimal type.
decimal64(__decfloat64 __z) : __val(__z) {}
#if __cplusplus >= 201103L
// 3.2.3.5 Conversion to integral type.
// Note: explicit per n3407.
explicit operator long long() const { return (long long)__val; }
#endif
// 3.2.3.6 Increment and decrement operators.
decimal64& operator++()
{
__val += 1;
return *this;
}
decimal64 operator++(int)
{
decimal64 __tmp = *this;
__val += 1;
return __tmp;
}
decimal64& operator--()
{
__val -= 1;
return *this;
}
decimal64 operator--(int)
{
decimal64 __tmp = *this;
__val -= 1;
return __tmp;
}
// 3.2.3.7 Compound assignment.
#define _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(_Op) \
decimal64& operator _Op(decimal32 __rhs); \
decimal64& operator _Op(decimal64 __rhs); \
decimal64& operator _Op(decimal128 __rhs); \
decimal64& operator _Op(int __rhs); \
decimal64& operator _Op(unsigned int __rhs); \
decimal64& operator _Op(long __rhs); \
decimal64& operator _Op(unsigned long __rhs); \
decimal64& operator _Op(long long __rhs); \
decimal64& operator _Op(unsigned long long __rhs);
_DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(+=)
_DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(-=)
_DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(*=)
_DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT(/=)
#undef _DECLARE_DECIMAL64_COMPOUND_ASSIGNMENT
private:
__decfloat64 __val;
public:
__decfloat64 __getval(void) { return __val; }
void __setval(__decfloat64 __x) { __val = __x; }
};
/// 3.2.4 Class decimal128.
class decimal128
{
public:
typedef float __decfloat128 __attribute__((mode(TD)));
// 3.2.4.2 Construct/copy/destroy.
decimal128() : __val(0.e-6176DL) {}
// 3.2.4.3 Conversion from floating-point type.
decimal128(decimal32 d32);
decimal128(decimal64 d64);
explicit decimal128(float __r) : __val(__r) {}
explicit decimal128(double __r) : __val(__r) {}
explicit decimal128(long double __r) : __val(__r) {}
// 3.2.4.4 Conversion from integral type.
decimal128(int __z) : __val(__z) {}
decimal128(unsigned int __z) : __val(__z) {}
decimal128(long __z) : __val(__z) {}
decimal128(unsigned long __z) : __val(__z) {}
decimal128(long long __z) : __val(__z) {}
decimal128(unsigned long long __z) : __val(__z) {}
/// Conforming extension: Conversion from scalar decimal type.
decimal128(__decfloat128 __z) : __val(__z) {}
#if __cplusplus >= 201103L
// 3.2.4.5 Conversion to integral type.
// Note: explicit per n3407.
explicit operator long long() const { return (long long)__val; }
#endif
// 3.2.4.6 Increment and decrement operators.
decimal128& operator++()
{
__val += 1;
return *this;
}
decimal128 operator++(int)
{
decimal128 __tmp = *this;
__val += 1;
return __tmp;
}
decimal128& operator--()
{
__val -= 1;
return *this;
}
decimal128 operator--(int)
{
decimal128 __tmp = *this;
__val -= 1;
return __tmp;
}
// 3.2.4.7 Compound assignment.
#define _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(_Op) \
decimal128& operator _Op(decimal32 __rhs); \
decimal128& operator _Op(decimal64 __rhs); \
decimal128& operator _Op(decimal128 __rhs); \
decimal128& operator _Op(int __rhs); \
decimal128& operator _Op(unsigned int __rhs); \
decimal128& operator _Op(long __rhs); \
decimal128& operator _Op(unsigned long __rhs); \
decimal128& operator _Op(long long __rhs); \
decimal128& operator _Op(unsigned long long __rhs);
_DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(+=)
_DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(-=)
_DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(*=)
_DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT(/=)
#undef _DECLARE_DECIMAL128_COMPOUND_ASSIGNMENT
private:
__decfloat128 __val;
public:
__decfloat128 __getval(void) { return __val; }
void __setval(__decfloat128 __x) { __val = __x; }
};
#define _GLIBCXX_USE_DECIMAL_ 1
_GLIBCXX_END_NAMESPACE_VERSION
} // namespace decimal
// @} group decimal
} // namespace std
#include <decimal/decimal.h>
#endif /* _GLIBCXX_DECIMAL */
| [
"[email protected]"
] | ||
8cc9475c6d9eb2fdab61b055cde4c52ee4821d65 | 485d3f55401c0b2cba22419cf9aafbe2ba7b714b | /tests/vector/members.hpp | 8bf3aa99d43d3449d268c977e0a8af3d16009108 | [] | no_license | Buom01/ft_containers | 57810f87153a25b08eff525869aa920374fdea19 | 3083c6a08e2673ff83ef0c7fb3d149957f1d7445 | refs/heads/master | 2023-03-12T15:17:46.033164 | 2022-07-22T12:26:55 | 2022-07-22T12:26:55 | 516,740,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,378 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* members.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: badam <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/07/13 14:08:39 by badam #+# #+# */
/* Updated: 2021/11/16 16:04:48 by badam ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef TESTS_VECTOR_MEMBERS_HPP
# define TESTS_VECTOR_MEMBERS_HPP
template <class container>
int vector_memberstypes_1(container &vector)
{
static_cast<void>(vector);
typename container::value_type T;
typename container::allocator_type Allocator;
typename container::size_type SizeType;
typename container::difference_type DifferenceType;
typename container::reference Reference = T;
typename container::const_reference ConstReference = T;
typename container::pointer Pointer;
typename container::const_pointer ConstPointer;
typename container::iterator Iterator;
typename container::const_iterator ConstIterator;
typename container::reverse_iterator ReverseIterator;
typename container::const_reverse_iterator ConstReverseIterator;
static_cast<void>(T);
static_cast<void>(Allocator);
static_cast<void>(SizeType);
static_cast<void>(DifferenceType);
static_cast<void>(Reference);
static_cast<void>(ConstReference);
static_cast<void>(Pointer);
static_cast<void>(ConstPointer);
static_cast<void>(Iterator);
static_cast<void>(ConstIterator);
static_cast<void>(ReverseIterator);
static_cast<void>(ConstReverseIterator);
return (0);
}
template <class container>
int vector_memberstypes_2(container &vector)
{
static_cast<void>(vector);
typename container::size_type SizeType = 0;
typename container::difference_type DifferenceType = 0;
if (--SizeType < 0)
return (1);
if (--DifferenceType >= 0)
return (2);
return (0);
}
template <class container>
int vector_contructors(container &vector)
{
typename container::allocator_type alloc = typename container::allocator_type();
if (vector.get_allocator() != alloc)
return (1);
container vector2(alloc);
if (vector2.get_allocator() != alloc)
return (2);
container vector3(static_cast<std::size_t>(5), 1, alloc);
if (vector3.get_allocator() != alloc)
return (3);
if (vector3.size() != 5 || vector3.empty())
return (4);
if (vector3[0] != 1 || vector3[4] != 1)
return (5);
vector.push_back(1);
vector.push_back(2);
vector.push_back(3);
container vector5(vector.begin(), vector.end(), alloc);
if (vector5.get_allocator() != alloc)
return (6);
if (vector5.size() != 3 || vector5.empty())
return (7);
if (vector5[0] != 1 || vector5[1] != 2 || vector5[2] != 3)
return (8);
container vector6(vector);
if (vector6.get_allocator() != alloc)
return (6);
if (vector6.size() != 3 || vector6.empty())
return (7);
if (vector6[0] != 1 || vector6[1] != 2 || vector6[2] != 3)
return (8);
return (0);
}
template <class container>
int vector_equal(container &vector)
{
container vector1;
vector1.push_back(1);
vector = vector1;
if (vector.size() != 1 || vector.empty())
return (1);
if (vector[0] != 1)
return (2);
container vector2;
vector2.push_back(2);
vector2.push_back(3);
vector2.push_back(4);
vector = vector2;
return (0);
}
template <class container>
int vector_assign_1(container &vector)
{
vector.assign(0, 0);
if (vector.size() != 0 || !vector.empty())
return (1);
vector.assign(10, 0);
return (0);
}
template <class container>
int vector_assign_2(container &vector)
{
vector.push_back(2);
vector.assign(10, 1);
if (vector.size() != 10 || vector.empty())
return (1);
return (0);
}
template <class container>
int vector_assign_3(container &vector)
{
vector.push_back(2);
vector.assign(10, 1);
if (vector.size() != 10 || vector.empty())
return (1);
vector.assign(5, 2);
if (vector.size() != 5 || vector.empty())
return (1);
return (0);
}
template <class container>
int vector_assign_4(container &vector)
{
container vector2;
vector2.push_back(0);
vector2.push_back(1);
vector2.push_back(2);
vector2.push_back(3);
vector2.push_back(4);
vector.assign(vector2.begin(), vector2.end());
if (vector.size() != 5 || vector.empty())
return (1);
return (0);
}
template <class container>
int vector_assign_5(container &vector)
{
container vector2;
vector2.push_back(0);
vector2.push_back(1);
vector2.push_back(2);
vector2.push_back(3);
vector2.push_back(4);
vector.push_back(9);
vector.assign(vector2.begin(), vector2.begin());
if (vector.size() != 0 || !vector.empty())
return (1);
return (0);
}
template <class container>
int vector_assign_6(container &vector)
{
container vector2;
vector.push_back(9);
vector.assign(vector2.begin(), vector2.end());
if (vector.size() != 0 || !vector.empty())
return (1);
return (0);
}
#endif
| [
"[email protected]"
] | |
b3b6f5c0612ef2f1cc7b8927ad2fdddab5f34d90 | 80381a7ff3e81a6a963e49749d851dcaf28e5c94 | /1180.cpp | 9260d6d56e87914a0bdc82a837235e2baaae9fdd | [] | no_license | k0sk/aoj | 936ed9efdbeb82446c5411082e010c75e11ee7a4 | bb2615dd63ed82a46e34b10139a52e9ffc7181be | refs/heads/master | 2016-08-04T05:56:56.712440 | 2015-11-14T00:51:54 | 2015-11-14T00:51:54 | 16,225,679 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,338 | cpp | #include <iostream>
#include <cstdio>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <string>
#include <vector>
#include <map>
#include <stack>
#include <queue>
#include <map>
#include <climits>
#include <sstream>
using namespace std;
typedef long long ll;
#define REP(i, N) for (int i = 0; i < (int)N; i++)
const int MAX_L = 6 + 1;
int get_max(string str, int L) {
char max_num[MAX_L] = "000000";
max_num[L] = '\0';
for (int i = 0; i < str.size(); i++) max_num[i] = str[i];
sort(max_num, max_num + L, greater<char>());
return atoi(max_num);
}
int get_min(string str, int L) {
char min_num[MAX_L] = "000000";
min_num[L] = '\0';
for (int i = 0; i < str.size(); i++) min_num[i] = str[i];
sort(min_num, min_num + L);
return atoi(min_num);
}
int main() {
ll a[21];
int L;
string num;
stringstream ss;
while (cin >> num >> L) {
a[0] = atoi(num.c_str());
int i, j;
for (j = 1; j < 21; j++) {
ss << a[j - 1];
int max_num = get_max(ss.str(), L);
int min_num = get_min(ss.str(), L);
a[j] = max_num - min_num;
for (i = 0; i <= j; i++) {
if (a[j] == a[i]) break;
}
}
printf("%d %lld %d\n", j, a[i], i - j);
}
return 0;
}
| [
"[email protected]"
] | |
af5fed068627a81ee73e44bde50a4cc4753c5e51 | b38ab36ce6710bda9c495301d1d7b8769cfd454b | /projects/GoldMiner/Classes/GameOverMenuLoader.h | 39558d12635166c12c37b427c3c0eddedb7deccc | [] | no_license | wjf1616/TheMiners | 604fa141dbbe614a87ea88a1d9d9a4bc60678070 | afdb2eab217ad90434736d9580e942d5622bf929 | refs/heads/master | 2021-01-10T02:21:26.861908 | 2016-01-06T10:18:58 | 2016-01-06T10:18:58 | 48,987,660 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 375 | h | #ifndef __GAMEOVERMENULOADER_H__
#define __GAMEOVERMENULOADER_H__
#include "GameOverMenu.h"
/* Forward declaration. */
class CCBReader;
class GameOverMenuLoader : public cocos2d::extension::CCLayerLoader {
public:
CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(GameOverMenuLoader, loader);
protected:
CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(GameOverMenu);
};
#endif | [
"[email protected]"
] | |
45783703709496f6779db9c8c557f95277b2218d | eb6fca7cb8a4425c8fba4a2a9c68fde2ced2077e | /Asteroids/src/Texture.cpp | f9947f973cc253e477755faa370d1e79af0f3d92 | [] | no_license | hzwr/Asteroids | fdd8c7125fb062f9b9ca7fb315a33faf9bffdc54 | d8808cb9b99015783c8e941782970320227fd85a | refs/heads/main | 2023-07-13T23:17:04.888168 | 2021-08-18T04:30:28 | 2021-08-18T04:30:28 | 368,767,885 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,578 | cpp | #include "Texture.h"
#include "Texture.h"
#include <SOIL/SOIL.h>
#include <GL/glew.h>
#include <SDL/SDL.h>
#include "Renderer.h"
Texture::Texture()
: mWidth(0)
, mHeight(0)
{
}
Texture::~Texture()
{
}
bool Texture::Load(const std::string &fileName)
{
int channels = 0;
unsigned char *image = SOIL_load_image(fileName.c_str(),
&mWidth, &mHeight, &channels, SOIL_LOAD_AUTO);
if (image == nullptr)
{
SDL_Log("SOIL failed to load image %s: %s", fileName.c_str(), SOIL_last_result());
return false;
}
GLCall(glGenTextures(1, &m_textureID));
//GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID));
//// Copy image data to OpenGL
//GLCall(glTexImage2D(GL_TEXTURE_2D, 0, format, mWidth, mHeight, 0, format,
// GL_UNSIGNED_BYTE, image));
//// Enable linear filtering
//GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
//GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
//// Wrap mode
//GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE));
//GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE));
//NEW
//
if (image)
{
int format = GL_RGB;
if (channels == 4)
{
format = GL_RGBA;
}
glBindTexture(GL_TEXTURE_2D, m_textureID);
glTexImage2D(GL_TEXTURE_2D, 0, format, mWidth, mHeight, 0, format, GL_UNSIGNED_BYTE, image);
glGenerateMipmap(GL_TEXTURE_2D);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
}
//
// Free the image from memory
SOIL_free_image_data(image);
return true;
}
void Texture::Unload()
{
GLCall(glDeleteTextures(1, &m_textureID));
}
void Texture::CreateFromSurface(SDL_Surface *surface)
{
mWidth = surface->w;
mHeight = surface->h;
// Generate a GL texture
GLCall(glGenTextures(1, &m_textureID));
GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID));
GLCall(glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, mWidth, mHeight, 0, GL_BGRA,
GL_UNSIGNED_BYTE, surface->pixels));
// Use linear filtering
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR));
GLCall(glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR));
}
void Texture::Bind(unsigned int slot /*= 0*/) const
{
GLCall(glActiveTexture(GL_TEXTURE0 + slot));
GLCall(glBindTexture(GL_TEXTURE_2D, m_textureID));
}
void Texture::Unbind() const
{
GLCall(glBindTexture(GL_TEXTURE_2D, 0));
}
| [
"[email protected]"
] | |
5a6e13c014e93c96026e22550059a1782eda7ef8 | 899894a5ac533115db8fbcfc87191308b9f2aaa2 | /src/enc.cpp | 820cac671c06de4cd486ce7f8a3e82707a2d9242 | [] | no_license | xixian4682468/IMX6Q_VPU_Module | eff62777549719f8d1fc4886f62968fbbb003797 | 01f2827918098b3039385854ac422354dca9989e | refs/heads/master | 2020-04-16T19:00:22.144217 | 2019-01-19T11:44:07 | 2019-01-19T11:44:07 | 165,843,345 | 1 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 41,325 | cpp | /*
* Copyright 2004-2013 Freescale Semiconductor, Inc.
*
* Copyright (c) 2006, Chips & Media. All rights reserved.
*/
/*
* The code contained herein is licensed under the GNU General Public
* License. You may obtain a copy of the GNU General Public License
* Version 2 or later at the following locations:
*
* http://www.opensource.org/licenses/gpl-license.html
* http://www.gnu.org/copyleft/gpl.html
*/
#include <sys/stat.h>
#include <sys/time.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "vpu_test.h"
#include "vpu_jpegtable.h"
//******************************************************
EncOutputInfo outinfo = {0};//***********设置为全局
//******************************************************
/* V4L2 capture buffers are obtained from here */
extern struct capture_testbuffer cap_buffers[];
/* When app need to exit */
extern int quitflag;
#define FN_ENC_QP_DATA "enc_qp.log"
#define FN_ENC_SLICE_BND_DATA "enc_slice_bnd.log"
#define FN_ENC_MV_DATA "enc_mv.log"
#define FN_ENC_SLICE_DATA "enc_slice.log"
static FILE *fpEncSliceBndInfo = NULL;
static FILE *fpEncQpInfo = NULL;
static FILE *fpEncMvInfo = NULL;
static FILE *fpEncSliceInfo = NULL;
void SaveEncMbInfo(u8 *mbParaBuf, int size, int MbNumX, int EncNum)
{
int i;
if(!fpEncQpInfo)
fpEncQpInfo = fopen(FN_ENC_QP_DATA, "w+");
if(!fpEncQpInfo)
return;
if(!fpEncSliceBndInfo)
fpEncSliceBndInfo = fopen(FN_ENC_SLICE_BND_DATA, "w+");
if(!fpEncSliceBndInfo)
return;
fprintf(fpEncQpInfo, "FRAME [%1d]\n", EncNum);
fprintf(fpEncSliceBndInfo, "FRAME [%1d]\n", EncNum);
for(i=0; i < size; i++) {
fprintf(fpEncQpInfo, "MbAddr[%4d]: MbQs[%2d]\n", i, mbParaBuf[i] & 63);
fprintf(fpEncSliceBndInfo, "MbAddr[%4d]: Slice Boundary Flag[%1d]\n",
i, (mbParaBuf[i] >> 6) & 1);
}
fprintf(fpEncQpInfo, "\n");
fprintf(fpEncSliceBndInfo, "\n");
fflush(fpEncQpInfo);
fflush(fpEncSliceBndInfo);
}
void SaveEncMvInfo(u8 *mvParaBuf, int size, int MbNumX, int EncNum)
{
int i;
if(!fpEncMvInfo)
fpEncMvInfo = fopen(FN_ENC_MV_DATA, "w+");
if(!fpEncMvInfo)
return;
fprintf(fpEncMvInfo, "FRAME [%1d]\n", EncNum);
for(i=0; i<size/4; i++) {
u16 mvX = (mvParaBuf[0] << 8) | (mvParaBuf[1]);
u16 mvY = (mvParaBuf[2] << 8) | (mvParaBuf[3]);
if(mvX & 0x8000) {
fprintf(fpEncMvInfo, "MbAddr[%4d:For ]: Avail[0] Mv[%5d:%5d]\n", i, 0, 0);
} else {
mvX = (mvX & 0x7FFF) | ((mvX << 1) & 0x8000);
fprintf(fpEncMvInfo, "MbAddr[%4d:For ]: Avail[1] Mv[%5d:%5d]\n", i, mvX, mvY);
}
mvParaBuf += 4;
}
fprintf(fpEncMvInfo, "\n");
fflush(fpEncMvInfo);
}
void SaveEncSliceInfo(u8 *SliceParaBuf, int size, int EncNum)
{
int i, nMbAddr, nSliceBits;
if(!fpEncSliceInfo)
fpEncSliceInfo = fopen(FN_ENC_SLICE_DATA, "w+");
if(!fpEncSliceInfo)
return;
fprintf(fpEncSliceInfo, "EncFrmNum[%3d]\n", EncNum);
for(i=0; i<size / 8; i++) {
nMbAddr = (SliceParaBuf[2] << 8) | SliceParaBuf[3];
nSliceBits = (int)(SliceParaBuf[4] << 24)|(SliceParaBuf[5] << 16)|
(SliceParaBuf[6] << 8)|(SliceParaBuf[7]);
fprintf(fpEncSliceInfo, "[%2d] mbIndex.%3d, Bits.%d\n", i, nMbAddr, nSliceBits);
SliceParaBuf += 8;
}
fprintf(fpEncSliceInfo, "\n");
fflush(fpEncSliceInfo);
}
void jpgGetHuffTable(EncMjpgParam *param)
{
/* Rearrange and insert pre-defined Huffman table to deticated variable. */
memcpy(param->huffBits[DC_TABLE_INDEX0], lumaDcBits, 16); /* Luma DC BitLength */
memcpy(param->huffVal[DC_TABLE_INDEX0], lumaDcValue, 16); /* Luma DC HuffValue */
memcpy(param->huffBits[AC_TABLE_INDEX0], lumaAcBits, 16); /* Luma DC BitLength */
memcpy(param->huffVal[AC_TABLE_INDEX0], lumaAcValue, 162); /* Luma DC HuffValue */
memcpy(param->huffBits[DC_TABLE_INDEX1], chromaDcBits, 16); /* Chroma DC BitLength */
memcpy(param->huffVal[DC_TABLE_INDEX1], chromaDcValue, 16); /* Chroma DC HuffValue */
memcpy(param->huffBits[AC_TABLE_INDEX1], chromaAcBits, 16); /* Chroma AC BitLength */
memcpy(param->huffVal[AC_TABLE_INDEX1], chromaAcValue, 162); /* Chorma AC HuffValue */
}
void jpgGetQMatrix(EncMjpgParam *param)
{
/* Rearrange and insert pre-defined Q-matrix to deticated variable. */
memcpy(param->qMatTab[DC_TABLE_INDEX0], lumaQ2, 64);
memcpy(param->qMatTab[AC_TABLE_INDEX0], chromaBQ2, 64);
memcpy(param->qMatTab[DC_TABLE_INDEX1], param->qMatTab[DC_TABLE_INDEX0], 64);
memcpy(param->qMatTab[AC_TABLE_INDEX1], param->qMatTab[AC_TABLE_INDEX0], 64);
}
void jpgGetCInfoTable(EncMjpgParam *param)
{
int format = param->mjpg_sourceFormat;
memcpy(param->cInfoTab, cInfoTable[format], 6 * 4);
}
static int
enc_readbs_reset_buffer(struct encode *enc, PhysicalAddress paBsBufAddr, int bsBufsize)
{
u32 vbuf;
vbuf = enc->virt_bsbuf_addr + paBsBufAddr - enc->phy_bsbuf_addr;
//return vpu_write(enc->cmdl, (void *)vbuf, bsBufsize);
return vpu_write(enc->cmdl, (char *)vbuf, bsBufsize); //g++ : void* -> char*
}
static int
enc_readbs_ring_buffer(EncHandle handle, struct cmd_line *cmd,
u32 bs_va_startaddr, u32 bs_va_endaddr, u32 bs_pa_startaddr,
int defaultsize)
{
RetCode ret;
int space = 0, room;
PhysicalAddress pa_read_ptr, pa_write_ptr;
u32 target_addr, size;
ret = vpu_EncGetBitstreamBuffer(handle, &pa_read_ptr, &pa_write_ptr,
(Uint32 *)&size);
if (ret != RETCODE_SUCCESS) {
err_msg("EncGetBitstreamBuffer failed\n");
return -1;
}
/* No space in ring buffer */
if (size <= 0)
return 0;
if (defaultsize > 0) {
if (size < defaultsize)
return 0;
space = defaultsize;
} else {
space = size;
}
if (space > 0) {
target_addr = bs_va_startaddr + (pa_read_ptr - bs_pa_startaddr);
if ( (target_addr + space) > bs_va_endaddr) {
room = bs_va_endaddr - target_addr;
//vpu_write(cmd, (void *)target_addr, room);
vpu_write(cmd, (char *)target_addr, room); //g++ : void* -> char*
//vpu_write(cmd, (void *)bs_va_startaddr,(space - room));
vpu_write(cmd, (char *)bs_va_startaddr,(space - room)); //g++ : void* -> char*
} else {
//vpu_write(cmd, (void *)target_addr, space);
vpu_write(cmd, (char *)target_addr, space); //g++ : void* -> char*
}
ret = vpu_EncUpdateBitstreamBuffer(handle, space);
if (ret != RETCODE_SUCCESS) {
err_msg("EncUpdateBitstreamBuffer failed\n");
return -1;
}
}
return space;
}
static int
encoder_fill_headers(struct encode *enc)
{
EncHeaderParam enchdr_param = {0};
EncHandle handle = enc->handle;
RetCode ret;
int mbPicNum;
/* Must put encode header before encoding */
if (enc->cmdl->format == STD_MPEG4) {
enchdr_param.headerType = VOS_HEADER;
if (cpu_is_mx6x())
goto put_mp4header;
/*
* Please set userProfileLevelEnable to 0 if you need to generate
* user profile and level automaticaly by resolution, here is one
* sample of how to work when userProfileLevelEnable is 1.
*/
enchdr_param.userProfileLevelEnable = 1;
mbPicNum = ((enc->enc_picwidth + 15) / 16) *((enc->enc_picheight + 15) / 16);
if (enc->enc_picwidth <= 176 && enc->enc_picheight <= 144 &&
mbPicNum * enc->cmdl->fps <= 1485)
enchdr_param.userProfileLevelIndication = 8; /* L1 */
/* Please set userProfileLevelIndication to 8 if L0 is needed */
else if (enc->enc_picwidth <= 352 && enc->enc_picheight <= 288 &&
mbPicNum * enc->cmdl->fps <= 5940)
enchdr_param.userProfileLevelIndication = 2; /* L2 */
else if (enc->enc_picwidth <= 352 && enc->enc_picheight <= 288 &&
mbPicNum * enc->cmdl->fps <= 11880)
enchdr_param.userProfileLevelIndication = 3; /* L3 */
else if (enc->enc_picwidth <= 640 && enc->enc_picheight <= 480 &&
mbPicNum * enc->cmdl->fps <= 36000)
enchdr_param.userProfileLevelIndication = 4; /* L4a */
else if (enc->enc_picwidth <= 720 && enc->enc_picheight <= 576 &&
mbPicNum * enc->cmdl->fps <= 40500)
enchdr_param.userProfileLevelIndication = 5; /* L5 */
else
enchdr_param.userProfileLevelIndication = 6; /* L6 */
put_mp4header:
vpu_EncGiveCommand(handle, ENC_PUT_MP4_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
enchdr_param.headerType = VIS_HEADER;
vpu_EncGiveCommand(handle, ENC_PUT_MP4_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
enchdr_param.headerType = VOL_HEADER;
vpu_EncGiveCommand(handle, ENC_PUT_MP4_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
} else if (enc->cmdl->format == STD_AVC) {
if (!enc->mvc_extension || !enc->mvc_paraset_refresh_en) {
enchdr_param.headerType = SPS_RBSP;
vpu_EncGiveCommand(handle, ENC_PUT_AVC_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
if (ret < 0)
return -1;
}
}
if (enc->mvc_extension) {
enchdr_param.headerType = SPS_RBSP_MVC;
vpu_EncGiveCommand(handle, ENC_PUT_AVC_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
}
enchdr_param.headerType = PPS_RBSP;
vpu_EncGiveCommand(handle, ENC_PUT_AVC_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
if (enc->mvc_extension) { /* MVC */
enchdr_param.headerType = PPS_RBSP_MVC;
vpu_EncGiveCommand(handle, ENC_PUT_AVC_HEADER, &enchdr_param);
if (enc->ringBufferEnable == 0 ) {
//ret = enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);
ret = (RetCode)enc_readbs_reset_buffer(enc, enchdr_param.buf, enchdr_param.size);//g++ :'int' to 'RetCode'
if (ret < 0)
return -1;
}
}
} else if (enc->cmdl->format == STD_MJPG) {
if (enc->huffTable)
free(enc->huffTable);
if (enc->qMatTable)
free(enc->qMatTable);
if (cpu_is_mx6x()) {
EncParamSet enchdr_param = {0};
enchdr_param.size = STREAM_BUF_SIZE;
//enchdr_param.pParaSet = malloc(STREAM_BUF_SIZE);
enchdr_param.pParaSet = (Uint8*)malloc(STREAM_BUF_SIZE);//g++ : 'void*' to 'Uint8*'
if (enchdr_param.pParaSet) {
vpu_EncGiveCommand(handle,ENC_GET_JPEG_HEADER, &enchdr_param);
//vpu_write(enc->cmdl, (void *)enchdr_param.pParaSet, enchdr_param.size);
vpu_write(enc->cmdl, (char *)enchdr_param.pParaSet, enchdr_param.size);//g++ :'void*' to 'char*' ****************
free(enchdr_param.pParaSet);
} else {
err_msg("memory allocate failure\n");
return -1;
}
}
}
return 0;
}
void
encoder_free_framebuffer(struct encode *enc)
{
int i;
for (i = 0; i < enc->totalfb; i++) {
framebuf_free(enc->pfbpool[i]);
}
free(enc->fb);
free(enc->pfbpool);
}
int
encoder_allocate_framebuffer(struct encode *enc)
{
EncHandle handle = enc->handle;
int i, enc_stride, src_stride, src_fbid;
int totalfb, minfbcount, srcfbcount, extrafbcount;
RetCode ret;
FrameBuffer *fb;
PhysicalAddress subSampBaseA = 0, subSampBaseB = 0;
struct frame_buf **pfbpool;
EncExtBufInfo extbufinfo = {0};
int enc_fbwidth, enc_fbheight, src_fbwidth, src_fbheight;
minfbcount = enc->minFrameBufferCount;
dprintf(4, "minfb %d\n", minfbcount);
srcfbcount = 1;
enc_fbwidth = (enc->enc_picwidth + 15) & ~15;
enc_fbheight = (enc->enc_picheight + 15) & ~15;
src_fbwidth = (enc->src_picwidth + 15) & ~15;
src_fbheight = (enc->src_picheight + 15) & ~15;
if (cpu_is_mx6x()) {
if (enc->cmdl->format == STD_AVC && enc->mvc_extension) /* MVC */
extrafbcount = 2 + 2; /* Subsamp [2] + Subsamp MVC [2] */
else if (enc->cmdl->format == STD_MJPG)
extrafbcount = 0;
else
extrafbcount = 2; /* Subsamp buffer [2] */
} else
extrafbcount = 0;
enc->totalfb = totalfb = minfbcount + extrafbcount + srcfbcount;
/* last framebuffer is used as src frame in the test */
enc->src_fbid = src_fbid = totalfb - 1;
//fb = enc->fb = calloc(totalfb, sizeof(FrameBuffer));
fb = enc->fb = (FrameBuffer*)calloc(totalfb, sizeof(FrameBuffer));//g++ :'void*' to 'FrameBuffer*'
if (fb == NULL) {
err_msg("Failed to allocate enc->fb\n");
return -1;
}
//pfbpool = enc->pfbpool = calloc(totalfb,sizeof(struct frame_buf *));
pfbpool = enc->pfbpool = (frame_buf **)calloc(totalfb,sizeof(struct frame_buf *));//g++ :'void*' to 'frame_buf**'
if (pfbpool == NULL) {
err_msg("Failed to allocate enc->pfbpool\n");
free(fb);
return -1;
}
if (enc->cmdl->mapType == LINEAR_FRAME_MAP) {
/* All buffers are linear */
for (i = 0; i < minfbcount + extrafbcount; i++)
{
pfbpool[i] = framebuf_alloc(enc->cmdl->format, enc->mjpg_fmt,
enc_fbwidth, enc_fbheight, 0);
if (pfbpool[i] == NULL)
{
goto err1;
}
}
} else {
/* Encoded buffers are tiled */
for (i = 0; i < minfbcount; i++) {
pfbpool[i] = tiled_framebuf_alloc(enc->cmdl->format, enc->mjpg_fmt,
enc_fbwidth, enc_fbheight, 0, enc->cmdl->mapType);
if (pfbpool[i] == NULL)
goto err1;
}
/* sub frames are linear */
for (i = minfbcount; i < minfbcount + extrafbcount; i++) {
pfbpool[i] = framebuf_alloc(enc->cmdl->format, enc->mjpg_fmt,
enc_fbwidth, enc_fbheight, 0);
if (pfbpool[i] == NULL)
goto err1;
}
}
for (i = 0; i < minfbcount + extrafbcount; i++) {
fb[i].myIndex = i;
fb[i].bufY = pfbpool[i]->addrY;
fb[i].bufCb = pfbpool[i]->addrCb;
fb[i].bufCr = pfbpool[i]->addrCr;
fb[i].strideY = pfbpool[i]->strideY;
fb[i].strideC = pfbpool[i]->strideC;
}
if (cpu_is_mx6x() && (enc->cmdl->format != STD_MJPG)) {
subSampBaseA = fb[minfbcount].bufY;
subSampBaseB = fb[minfbcount + 1].bufY;
if (enc->cmdl->format == STD_AVC && enc->mvc_extension) { /* MVC */
extbufinfo.subSampBaseAMvc = fb[minfbcount + 2].bufY;
extbufinfo.subSampBaseBMvc = fb[minfbcount + 3].bufY;
}
}
/* Must be a multiple of 16 */
if (enc->cmdl->rot_angle == 90 || enc->cmdl->rot_angle == 270)
enc_stride = (enc->enc_picheight + 15 ) & ~15;
else
enc_stride = (enc->enc_picwidth + 15) & ~15;
src_stride = (enc->src_picwidth + 15 ) & ~15;
extbufinfo.scratchBuf = enc->scratchBuf;
ret = vpu_EncRegisterFrameBuffer(handle, fb, minfbcount, enc_stride, src_stride,
subSampBaseA, subSampBaseB, &extbufinfo);
if (ret != RETCODE_SUCCESS) {
err_msg("Register frame buffer failed\n");
goto err1;
}
if (enc->cmdl->src_scheme == PATH_V4L2) {
//ret = v4l_capture_setup(enc, enc->src_picwidth, enc->src_picheight, enc->cmdl->fps);
ret = (RetCode)v4l_capture_setup(enc, enc->src_picwidth, enc->src_picheight, enc->cmdl->fps);//cpp :'int' to 'RetCode'
if (ret < 0) {
goto err1;
}
} else {
/* Allocate a single frame buffer for source frame */
pfbpool[src_fbid] = framebuf_alloc(enc->cmdl->format, enc->mjpg_fmt,
src_fbwidth, src_fbheight, 0);
if (pfbpool[src_fbid] == NULL) {
err_msg("failed to allocate single framebuf\n");
goto err1;
}
fb[src_fbid].myIndex = enc->src_fbid;
fb[src_fbid].bufY = pfbpool[src_fbid]->addrY;
fb[src_fbid].bufCb = pfbpool[src_fbid]->addrCb;
fb[src_fbid].bufCr = pfbpool[src_fbid]->addrCr;
fb[src_fbid].strideY = pfbpool[src_fbid]->strideY;
fb[src_fbid].strideC = pfbpool[src_fbid]->strideC;
}
return 0;
err1:
for (i = 0; i < totalfb; i++) {
framebuf_free(pfbpool[i]);
}
free(fb);
free(pfbpool);
return -1;
}
static int
read_from_file(struct encode *enc)
{
u32 y_addr, u_addr, v_addr;
struct frame_buf *pfb = enc->pfbpool[enc->src_fbid];
int divX, divY;
int src_fd = enc->cmdl->src_fd;
int format = enc->mjpg_fmt;
int chromaInterleave = enc->cmdl->chromaInterleave;
int img_size, y_size, c_size;
int ret = 0;
if (enc->src_picwidth != pfb->strideY) {
err_msg("Make sure src pic width is a multiple of 16\n");
return -1;
}
divX = (format == MODE420 || format == MODE422) ? 2 : 1;
divY = (format == MODE420 || format == MODE224) ? 2 : 1;
y_size = enc->src_picwidth * enc->src_picheight;
c_size = y_size / divX / divY;
img_size = y_size + c_size * 2;
y_addr = pfb->addrY + pfb->desc.virt_uaddr - pfb->desc.phy_addr;
u_addr = pfb->addrCb + pfb->desc.virt_uaddr - pfb->desc.phy_addr;
v_addr = pfb->addrCr + pfb->desc.virt_uaddr - pfb->desc.phy_addr;
if (img_size == pfb->desc.size) {
//ret = freadn(src_fd, (void *)y_addr, img_size);
ret = freadn(src_fd, (char *)y_addr, img_size);//g++ :'void*' to 'char*'
} else {
//ret = freadn(src_fd, (void *)y_addr, y_size);
ret = freadn(src_fd, (char *)y_addr, y_size);//g++ :'void*' to 'char*'
if (chromaInterleave == 0) {
//ret = freadn(src_fd, (void *)u_addr, c_size);
ret = freadn(src_fd, (char *)u_addr, c_size);//g++ :'void*' to 'char*'
//ret = freadn(src_fd, (void *)v_addr, c_size);
ret = freadn(src_fd, (char *)v_addr, c_size);//g++ :'void*' to 'char*'
} else {
//ret = freadn(src_fd, (void *)u_addr, c_size * 2);
ret = freadn(src_fd, (char *)u_addr, c_size * 2);//g++ :'void*' to 'char*'
}
}
return ret;
}
static int
encoder_start(struct encode *enc)
{
EncHandle handle = enc->handle;
EncParam enc_param = {0};
EncOpenParam encop = {0};
//EncOutputInfo outinfo = {0};//***********设置为全局
//RetCode ret = 0;
RetCode ret = (RetCode)0;//g++ :'int' to 'RetCode'
int src_fbid = enc->src_fbid, img_size, frame_id = 0;
FrameBuffer *fb = enc->fb;
struct v4l2_buffer v4l2_buf;
int src_scheme = enc->cmdl->src_scheme;
int count = enc->cmdl->count;
struct timeval tenc_begin,tenc_end, total_start, total_end;
int sec, usec, loop_id;
float tenc_time = 0, total_time=0;
PhysicalAddress phy_bsbuf_start = enc->phy_bsbuf_addr;
u32 virt_bsbuf_start = enc->virt_bsbuf_addr;
u32 virt_bsbuf_end = virt_bsbuf_start + STREAM_BUF_SIZE;
/* Must put encode header here before encoding for all codec, except MX6 MJPG */
if (!(cpu_is_mx6x() && (enc->cmdl->format == STD_MJPG))) {
//ret = encoder_fill_headers(enc);
ret = (RetCode)encoder_fill_headers(enc);//g++ :'int' to 'RetCode'
if (ret) {
err_msg("Encode fill headers failed\n");
return -1;
}
}
enc_param.sourceFrame = &enc->fb[src_fbid];
enc_param.quantParam = 23;
enc_param.forceIPicture = 0;
enc_param.skipPicture = 0;
enc_param.enableAutoSkip = 1;
enc_param.encLeftOffset = 0;
enc_param.encTopOffset = 0;
if ((enc_param.encLeftOffset + enc->enc_picwidth) > enc->src_picwidth) {
err_msg("Configure is failure for width and left offset\n");
return -1;
}
if ((enc_param.encTopOffset + enc->enc_picheight) > enc->src_picheight) {
err_msg("Configure is failure for height and top offset\n");
return -1;
}
/* Set report info flag */
if (enc->mbInfo.enable) {
ret = vpu_EncGiveCommand(handle, ENC_SET_REPORT_MBINFO, &enc->mbInfo);
if (ret != RETCODE_SUCCESS) {
err_msg("Failed to set MbInfo report, ret %d\n", ret);
return -1;
}
}
if (enc->mvInfo.enable) {
ret = vpu_EncGiveCommand(handle, ENC_SET_REPORT_MVINFO, &enc->mvInfo);
if (ret != RETCODE_SUCCESS) {
err_msg("Failed to set MvInfo report, ret %d\n", ret);
return -1;
}
}
if (enc->sliceInfo.enable) {
ret = vpu_EncGiveCommand(handle, ENC_SET_REPORT_SLICEINFO, &enc->sliceInfo);
if (ret != RETCODE_SUCCESS) {
err_msg("Failed to set slice info report, ret %d\n", ret);
return -1;
}
}
if (src_scheme == PATH_V4L2) {
//ret = v4l_start_capturing();
ret = (RetCode)v4l_start_capturing();//g++ :'int' to 'RetCode'
if (ret < 0) {
return -1;
}
img_size = enc->src_picwidth * enc->src_picheight;
} else {
img_size = enc->src_picwidth * enc->src_picheight * 3 / 2;
if (enc->cmdl->format == STD_MJPG) {
if (enc->mjpg_fmt == MODE422 || enc->mjpg_fmt == MODE224)
img_size = enc->src_picwidth * enc->src_picheight * 2;
else if (enc->mjpg_fmt == MODE400)
img_size = enc->src_picwidth * enc->src_picheight;
}
}
gettimeofday(&total_start, NULL);
//****************************************************************************
//****************************VPU 硬件压缩循环********************************
//*********************************开始***************************************
/* The main encoding loop */
while (1) {
if (src_scheme == PATH_V4L2) {
//ret = v4l_get_capture_data(&v4l2_buf);
ret = (RetCode)v4l_get_capture_data(&v4l2_buf);//g++ :'int' to 'RetCode'
if (ret < 0) {
goto err2;
}
fb[src_fbid].myIndex = enc->src_fbid + v4l2_buf.index;
fb[src_fbid].bufY = cap_buffers[v4l2_buf.index].offset;
fb[src_fbid].bufCb = fb[src_fbid].bufY + img_size;
if ((enc->cmdl->format == STD_MJPG) &&
(enc->mjpg_fmt == MODE422 || enc->mjpg_fmt == MODE224))
fb[src_fbid].bufCr = fb[src_fbid].bufCb + (img_size >> 1);
else
fb[src_fbid].bufCr = fb[src_fbid].bufCb + (img_size >> 2);
fb[src_fbid].strideY = enc->src_picwidth;
fb[src_fbid].strideC = enc->src_picwidth / 2;
} else {
//ret = read_from_file(enc);
ret = (RetCode)read_from_file(enc);//g++ :'int' to 'RetCode'
if (ret <= 0)
break;
}
/* Must put encode header before each frame encoding for mx6 MJPG */
if (cpu_is_mx6x() && (enc->cmdl->format == STD_MJPG)) {
//ret = encoder_fill_headers(enc);
ret = (RetCode)encoder_fill_headers(enc);//g++ :'int' to 'RetCode'
if (ret) {
err_msg("Encode fill headers failed\n");
goto err2;
}
}
gettimeofday(&tenc_begin, NULL);
//ret = vpu_EncStartOneFrame(handle, &enc_param);
ret = (RetCode)vpu_EncStartOneFrame(handle, &enc_param);//g++ :'int' to 'RetCode'
if (ret != RETCODE_SUCCESS) {
err_msg("vpu_EncStartOneFrame failed Err code:%d\n",ret);
goto err2;
}
loop_id = 0;
while (vpu_IsBusy()) {
vpu_WaitForInt(200);
if (enc->ringBufferEnable == 1) {
//ret = enc_readbs_ring_buffer(handle, enc->cmdl,virt_bsbuf_start, virt_bsbuf_end,phy_bsbuf_start, STREAM_READ_SIZE);
ret = (RetCode)enc_readbs_ring_buffer(handle, enc->cmdl,virt_bsbuf_start, virt_bsbuf_end,phy_bsbuf_start, STREAM_READ_SIZE);//g++ :'int' to 'RetCode'
if (ret < 0) {
goto err2;
}
}
if (loop_id == 20) {
ret = vpu_SWReset(handle, 0);
return -1;
}
loop_id ++;
}
gettimeofday(&tenc_end, NULL);
sec = tenc_end.tv_sec - tenc_begin.tv_sec;
usec = tenc_end.tv_usec - tenc_begin.tv_usec;
if (usec < 0) {
sec--;
usec = usec + 1000000;
}
tenc_time += (sec * 1000000) + usec;
ret = vpu_EncGetOutputInfo(handle, &outinfo);
if (ret != RETCODE_SUCCESS) {
err_msg("vpu_EncGetOutputInfo failed Err code: %d\n",
ret);
goto err2;
}
if (outinfo.skipEncoded)
info_msg("Skip encoding one Frame!\n");
if (outinfo.mbInfo.enable && outinfo.mbInfo.size && outinfo.mbInfo.addr) {
SaveEncMbInfo(outinfo.mbInfo.addr, outinfo.mbInfo.size,
encop.picWidth/16, frame_id);
}
if (outinfo.mvInfo.enable && outinfo.mvInfo.size && outinfo.mvInfo.addr) {
SaveEncMvInfo(outinfo.mvInfo.addr, outinfo.mvInfo.size,
encop.picWidth/16, frame_id);
}
if (outinfo.sliceInfo.enable && outinfo.sliceInfo.size &&
outinfo.sliceInfo.addr) {
SaveEncSliceInfo(outinfo.sliceInfo.addr,
outinfo.sliceInfo.size, frame_id);
}
if (src_scheme == PATH_V4L2) {
v4l_put_capture_data(&v4l2_buf);
}
//****quitflag 用于跳出VPU压缩循环**************
if (quitflag)
break;
if (enc->ringBufferEnable == 0) {
//ret = enc_readbs_reset_buffer(enc, outinfo.bitstreamBuffer, outinfo.bitstreamSize);
ret = (RetCode)enc_readbs_reset_buffer(enc, outinfo.bitstreamBuffer, outinfo.bitstreamSize);//g++ :'int' to 'RetCode'
if (ret < 0) {
err_msg("writing bitstream buffer failed\n");
goto err2;
}
} else
enc_readbs_ring_buffer(handle, enc->cmdl, virt_bsbuf_start,
virt_bsbuf_end, phy_bsbuf_start, 0);
frame_id++;
if ((count != 0) && (frame_id >= count))
break;
}
//****************************************************************************
//****************************VPU 硬件压缩循环********************************
//**********************************结束**************************************
gettimeofday(&total_end, NULL);
sec = total_end.tv_sec - total_start.tv_sec;
usec = total_end.tv_usec - total_start.tv_usec;
if (usec < 0) {
sec--;
usec = usec + 1000000;
}
total_time = (sec * 1000000) + usec;
info_msg("Finished encoding: %d frames\n", frame_id);
info_msg("enc fps = %.2f\n", (frame_id / (tenc_time / 1000000)));
info_msg("total fps= %.2f \n",(frame_id / (total_time / 1000000)));
err2:
if (src_scheme == PATH_V4L2) {
v4l_stop_capturing();
}
/* Inform the other end that no more frames will be sent */
if (enc->cmdl->dst_scheme == PATH_NET) {
vpu_write(enc->cmdl, NULL, 0);
}
if (enc->mbInfo.addr)
free(enc->mbInfo.addr);
if (enc->mbInfo.addr)
free(enc->mbInfo.addr);
if (enc->sliceInfo.addr)
free(enc->sliceInfo.addr);
if (fpEncQpInfo) {
fclose(fpEncQpInfo);
fpEncQpInfo = NULL;
}
if (fpEncSliceBndInfo) {
fclose(fpEncSliceBndInfo);
fpEncSliceBndInfo = NULL;
}
if (fpEncMvInfo) {
fclose(fpEncMvInfo);
fpEncMvInfo = NULL;
}
if (fpEncSliceInfo) {
fclose(fpEncSliceInfo);
fpEncSliceInfo = NULL;
}
/* For automation of test case */
if (ret > 0)
//ret = 0;
ret = (RetCode)0;//g++ :'int' to 'RetCode'
return ret;
}
int
encoder_configure(struct encode *enc)
{
EncHandle handle = enc->handle;
SearchRamParam search_pa = {0};
EncInitialInfo initinfo = {0};
RetCode ret;
MirrorDirection mirror;
if (cpu_is_mx27()) {
search_pa.searchRamAddr = 0xFFFF4C00;
ret = vpu_EncGiveCommand(handle, ENC_SET_SEARCHRAM_PARAM, &search_pa);
if (ret != RETCODE_SUCCESS) {
err_msg("Encoder SET_SEARCHRAM_PARAM failed\n");
return -1;
}
}
if (enc->cmdl->rot_en) {
vpu_EncGiveCommand(handle, ENABLE_ROTATION, 0);
vpu_EncGiveCommand(handle, ENABLE_MIRRORING, 0);
vpu_EncGiveCommand(handle, SET_ROTATION_ANGLE,
&enc->cmdl->rot_angle);
//mirror = enc->cmdl->mirror;
mirror = (MirrorDirection)enc->cmdl->mirror;//g++ :'int' to 'MirrorDirection'
vpu_EncGiveCommand(handle, SET_MIRROR_DIRECTION, &mirror);
}
ret = vpu_EncGetInitialInfo(handle, &initinfo);
if (ret != RETCODE_SUCCESS) {
err_msg("Encoder GetInitialInfo failed\n");
return -1;
}
enc->minFrameBufferCount = initinfo.minFrameBufferCount;
if (enc->cmdl->save_enc_hdr) {
if (enc->cmdl->format == STD_MPEG4) {
SaveGetEncodeHeader(handle, ENC_GET_VOS_HEADER,
"mp4_vos_header.dat");
SaveGetEncodeHeader(handle, ENC_GET_VO_HEADER,
"mp4_vo_header.dat");
SaveGetEncodeHeader(handle, ENC_GET_VOL_HEADER,
"mp4_vol_header.dat");
} else if (enc->cmdl->format == STD_AVC) {
SaveGetEncodeHeader(handle, ENC_GET_SPS_RBSP,
"avc_sps_header.dat");
SaveGetEncodeHeader(handle, ENC_GET_PPS_RBSP,
"avc_pps_header.dat");
}
}
enc->mbInfo.enable = 0;
enc->mvInfo.enable = 0;
enc->sliceInfo.enable = 0;
if (enc->mbInfo.enable) {
//enc->mbInfo.addr = malloc(initinfo.reportBufSize.mbInfoBufSize);
enc->mbInfo.addr = (Uint8*)malloc(initinfo.reportBufSize.mbInfoBufSize);//g++ :'void*' to 'Uint8*
if (!enc->mbInfo.addr)
err_msg("malloc_error\n");
}
if (enc->mvInfo.enable) {
//enc->mvInfo.addr = malloc(initinfo.reportBufSize.mvInfoBufSize);
enc->mvInfo.addr = (Uint8*)malloc(initinfo.reportBufSize.mvInfoBufSize);//g++ :'void*' to 'Uint8*
if (!enc->mvInfo.addr)
err_msg("malloc_error\n");
}
if (enc->sliceInfo.enable) {
//enc->sliceInfo.addr = malloc(initinfo.reportBufSize.sliceInfoBufSize);
enc->sliceInfo.addr = (Uint8*)malloc(initinfo.reportBufSize.sliceInfoBufSize);//g++ :'void*' to 'Uint8*
if (!enc->sliceInfo.addr)
err_msg("malloc_error\n");
}
return 0;
}
void
encoder_close(struct encode *enc)
{
RetCode ret;
ret = vpu_EncClose(enc->handle);
if (ret == RETCODE_FRAME_NOT_COMPLETE) {
vpu_SWReset(enc->handle, 0);
vpu_EncClose(enc->handle);
}
}
int
encoder_open(struct encode *enc)
{
EncHandle handle = {0};
EncOpenParam encop = {0};
Uint8 *huffTable = enc->huffTable;
Uint8 *qMatTable = enc->qMatTable;
int i;
RetCode ret;
/* Fill up parameters for encoding */
encop.bitstreamBuffer = enc->phy_bsbuf_addr;
encop.bitstreamBufferSize = STREAM_BUF_SIZE;
//encop.bitstreamFormat = enc->cmdl->format;
encop.bitstreamFormat = (CodStd)enc->cmdl->format;//g++ :'int' to 'CodStd'
encop.mapType = enc->cmdl->mapType;
encop.linear2TiledEnable = enc->linear2TiledEnable;
/* width and height in command line means source image size */
if (enc->cmdl->width && enc->cmdl->height) {
enc->src_picwidth = enc->cmdl->width;
enc->src_picheight = enc->cmdl->height;
}
/* enc_width and enc_height in command line means encoder output size */
if (enc->cmdl->enc_width && enc->cmdl->enc_height) {
enc->enc_picwidth = enc->cmdl->enc_width;
enc->enc_picheight = enc->cmdl->enc_height;
} else {
enc->enc_picwidth = enc->src_picwidth;
enc->enc_picheight = enc->src_picheight;
}
/* If rotation angle is 90 or 270, pic width and height are swapped */
if (enc->cmdl->rot_angle == 90 || enc->cmdl->rot_angle == 270) {
encop.picWidth = enc->enc_picheight;
encop.picHeight = enc->enc_picwidth;
} else {
encop.picWidth = enc->enc_picwidth;
encop.picHeight = enc->enc_picheight;
}
if (enc->cmdl->fps == 0)
enc->cmdl->fps = 30;
info_msg("Capture/Encode fps will be %d\n", enc->cmdl->fps);
/*Note: Frame rate cannot be less than 15fps per H.263 spec */
encop.frameRateInfo = enc->cmdl->fps;
encop.bitRate = enc->cmdl->bitrate;
encop.gopSize = enc->cmdl->gop;
encop.slicemode.sliceMode = 0; /* 0: 1 slice per picture; 1: Multiple slices per picture */
encop.slicemode.sliceSizeMode = 0; /* 0: silceSize defined by bits; 1: sliceSize defined by MB number*/
encop.slicemode.sliceSize = 4000; /* Size of a slice in bits or MB numbers */
encop.initialDelay = 0;
encop.vbvBufferSize = 0; /* 0 = ignore 8 */
encop.intraRefresh = 0;
encop.sliceReport = 0;
encop.mbReport = 0;
encop.mbQpReport = 0;
encop.rcIntraQp = -1;
encop.userQpMax = 0;
encop.userQpMin = 0;
encop.userQpMinEnable = 0;
encop.userQpMaxEnable = 0;
encop.IntraCostWeight = 0;
encop.MEUseZeroPmv = 0;
/* (3: 16x16, 2:32x16, 1:64x32, 0:128x64, H.263(Short Header : always 3) */
encop.MESearchRange = 3;
encop.userGamma = (Uint32)(0.75*32768); /* (0*32768 <= gamma <= 1*32768) */
encop.RcIntervalMode= 1; /* 0:normal, 1:frame_level, 2:slice_level, 3: user defined Mb_level */
encop.MbInterval = 0;
encop.avcIntra16x16OnlyModeEnable = 0;
encop.ringBufferEnable = enc->ringBufferEnable = 0;
encop.dynamicAllocEnable = 0;
encop.chromaInterleave = enc->cmdl->chromaInterleave;
if(!cpu_is_mx6x() && enc->cmdl->format == STD_MJPG )
{
//qMatTable = calloc(192,1);
qMatTable = (Uint8*)calloc(192,1);//g++ :'void*' to 'Uint8*
if (qMatTable == NULL) {
err_msg("Failed to allocate qMatTable\n");
return -1;
}
//huffTable = calloc(432,1);
huffTable = (Uint8*)calloc(432,1);////g++ :'void*' to 'Uint8*
if (huffTable == NULL) {
free(qMatTable);
err_msg("Failed to allocate huffTable\n");
return -1;
}
/* Don't consider user defined hufftable this time */
/* Rearrange and insert pre-defined Huffman table to deticated variable. */
for(i = 0; i < 16; i += 4)
{
huffTable[i] = lumaDcBits[i + 3];
huffTable[i + 1] = lumaDcBits[i + 2];
huffTable[i + 2] = lumaDcBits[i + 1];
huffTable[i + 3] = lumaDcBits[i];
}
for(i = 16; i < 32 ; i += 4)
{
huffTable[i] = lumaDcValue[i + 3 - 16];
huffTable[i + 1] = lumaDcValue[i + 2 - 16];
huffTable[i + 2] = lumaDcValue[i + 1 - 16];
huffTable[i + 3] = lumaDcValue[i - 16];
}
for(i = 32; i < 48; i += 4)
{
huffTable[i] = lumaAcBits[i + 3 - 32];
huffTable[i + 1] = lumaAcBits[i + 2 - 32];
huffTable[i + 2] = lumaAcBits[i + 1 - 32];
huffTable[i + 3] = lumaAcBits[i - 32];
}
for(i = 48; i < 216; i += 4)
{
huffTable[i] = lumaAcValue[i + 3 - 48];
huffTable[i + 1] = lumaAcValue[i + 2 - 48];
huffTable[i + 2] = lumaAcValue[i + 1 - 48];
huffTable[i + 3] = lumaAcValue[i - 48];
}
for(i = 216; i < 232; i += 4)
{
huffTable[i] = chromaDcBits[i + 3 - 216];
huffTable[i + 1] = chromaDcBits[i + 2 - 216];
huffTable[i + 2] = chromaDcBits[i + 1 - 216];
huffTable[i + 3] = chromaDcBits[i - 216];
}
for(i = 232; i < 248; i += 4)
{
huffTable[i] = chromaDcValue[i + 3 - 232];
huffTable[i + 1] = chromaDcValue[i + 2 - 232];
huffTable[i + 2] = chromaDcValue[i + 1 - 232];
huffTable[i + 3] = chromaDcValue[i - 232];
}
for(i = 248; i < 264; i += 4)
{
huffTable[i] = chromaAcBits[i + 3 - 248];
huffTable[i + 1] = chromaAcBits[i + 2 - 248];
huffTable[i + 2] = chromaAcBits[i + 1 - 248];
huffTable[i + 3] = chromaAcBits[i - 248];
}
for(i = 264; i < 432; i += 4)
{
huffTable[i] = chromaAcValue[i + 3 - 264];
huffTable[i + 1] = chromaAcValue[i + 2 - 264];
huffTable[i + 2] = chromaAcValue[i + 1 - 264];
huffTable[i + 3] = chromaAcValue[i - 264];
}
/* Rearrange and insert pre-defined Q-matrix to deticated variable. */
for(i = 0; i < 64; i += 4)
{
qMatTable[i] = lumaQ2[i + 3];
qMatTable[i + 1] = lumaQ2[i + 2];
qMatTable[i + 2] = lumaQ2[i + 1];
qMatTable[i + 3] = lumaQ2[i];
}
for(i = 64; i < 128; i += 4)
{
qMatTable[i] = chromaBQ2[i + 3 - 64];
qMatTable[i + 1] = chromaBQ2[i + 2 - 64];
qMatTable[i + 2] = chromaBQ2[i + 1 - 64];
qMatTable[i + 3] = chromaBQ2[i - 64];
}
for(i = 128; i < 192; i += 4)
{
qMatTable[i] = chromaRQ2[i + 3 - 128];
qMatTable[i + 1] = chromaRQ2[i + 2 - 128];
qMatTable[i + 2] = chromaRQ2[i + 1 - 128];
qMatTable[i + 3] = chromaRQ2[i - 128];
}
}
if (enc->cmdl->format == STD_MPEG4) {
encop.EncStdParam.mp4Param.mp4_dataPartitionEnable = 0;
enc->mp4_dataPartitionEnable =
encop.EncStdParam.mp4Param.mp4_dataPartitionEnable;
encop.EncStdParam.mp4Param.mp4_reversibleVlcEnable = 0;
encop.EncStdParam.mp4Param.mp4_intraDcVlcThr = 0;
encop.EncStdParam.mp4Param.mp4_hecEnable = 0;
encop.EncStdParam.mp4Param.mp4_verid = 2;
} else if ( enc->cmdl->format == STD_H263) {
encop.EncStdParam.h263Param.h263_annexIEnable = 0;
encop.EncStdParam.h263Param.h263_annexJEnable = 1;
encop.EncStdParam.h263Param.h263_annexKEnable = 0;
encop.EncStdParam.h263Param.h263_annexTEnable = 0;
} else if (enc->cmdl->format == STD_AVC) {
encop.EncStdParam.avcParam.avc_constrainedIntraPredFlag = 0;
encop.EncStdParam.avcParam.avc_disableDeblk = 0;
encop.EncStdParam.avcParam.avc_deblkFilterOffsetAlpha = 6;
encop.EncStdParam.avcParam.avc_deblkFilterOffsetBeta = 0;
encop.EncStdParam.avcParam.avc_chromaQpOffset = 10;
encop.EncStdParam.avcParam.avc_audEnable = 0;
if (cpu_is_mx6x()) {
encop.EncStdParam.avcParam.interview_en = 0;
encop.EncStdParam.avcParam.paraset_refresh_en = enc->mvc_paraset_refresh_en = 0;
encop.EncStdParam.avcParam.prefix_nal_en = 0;
encop.EncStdParam.avcParam.mvc_extension = enc->cmdl->mp4_h264Class;
enc->mvc_extension = enc->cmdl->mp4_h264Class;
encop.EncStdParam.avcParam.avc_frameCroppingFlag = 0;
encop.EncStdParam.avcParam.avc_frameCropLeft = 0;
encop.EncStdParam.avcParam.avc_frameCropRight = 0;
encop.EncStdParam.avcParam.avc_frameCropTop = 0;
encop.EncStdParam.avcParam.avc_frameCropBottom = 0;
if (enc->cmdl->rot_angle != 90 &&
enc->cmdl->rot_angle != 270 &&
enc->enc_picheight == 1080) {
/*
* In case of AVC encoder, when we want to use
* unaligned display width frameCroppingFlag
* parameters should be adjusted to displayable
* rectangle
*/
encop.EncStdParam.avcParam.avc_frameCroppingFlag = 1;
encop.EncStdParam.avcParam.avc_frameCropBottom = 8;
}
} else {
encop.EncStdParam.avcParam.avc_fmoEnable = 0;
encop.EncStdParam.avcParam.avc_fmoType = 0;
encop.EncStdParam.avcParam.avc_fmoSliceNum = 1;
encop.EncStdParam.avcParam.avc_fmoSliceSaveBufSize = 32; /* FMO_SLICE_SAVE_BUF_SIZE */
}
} else if (enc->cmdl->format == STD_MJPG) {
encop.EncStdParam.mjpgParam.mjpg_sourceFormat = enc->mjpg_fmt; /* encConfig.mjpgChromaFormat */
encop.EncStdParam.mjpgParam.mjpg_restartInterval = 60;
encop.EncStdParam.mjpgParam.mjpg_thumbNailEnable = 0;
encop.EncStdParam.mjpgParam.mjpg_thumbNailWidth = 0;
encop.EncStdParam.mjpgParam.mjpg_thumbNailHeight = 0;
if (cpu_is_mx6x()) {
jpgGetHuffTable(&encop.EncStdParam.mjpgParam);
jpgGetQMatrix(&encop.EncStdParam.mjpgParam);
jpgGetCInfoTable(&encop.EncStdParam.mjpgParam);
} else {
encop.EncStdParam.mjpgParam.mjpg_hufTable = huffTable;
encop.EncStdParam.mjpgParam.mjpg_qMatTable = qMatTable;
}
}
ret = vpu_EncOpen(&handle, &encop);
if (ret != RETCODE_SUCCESS) {
if (enc->cmdl->format == STD_MJPG) {
free(qMatTable);
free(huffTable);
}
err_msg("Encoder open failed %d\n", ret);
return -1;
}
enc->handle = handle;
return 0;
}
//int encode_test(void *arg)
void* encode_test(void *arg)//g++ : void* encode_test(void *arg)
{
struct cmd_line *cmdl = (struct cmd_line *)arg;
vpu_mem_desc mem_desc = {0};
vpu_mem_desc scratch_mem_desc = {0};
struct encode *enc;
int ret = 0;
#ifndef COMMON_INIT
vpu_versioninfo ver;
ret = vpu_Init(NULL);
if (ret) {
err_msg("VPU Init Failure.\n");
//return -1;
return NULL; //g++ :'int' to 'void*'
}
ret = vpu_GetVersionInfo(&ver);
if (ret) {
err_msg("Cannot get version info, err:%d\n", ret);
vpu_UnInit();
//return -1;
return NULL; //g++ :'int' to 'void*'
}
info_msg("VPU firmware version: %d.%d.%d_r%d\n", ver.fw_major, ver.fw_minor,
ver.fw_release, ver.fw_code);
info_msg("VPU library version: %d.%d.%d\n", ver.lib_major, ver.lib_minor,
ver.lib_release);
#endif
/* sleep some time so that we have time to start the server */
if (cmdl->dst_scheme == PATH_NET) {
sleep(10);
}
/* allocate memory for must remember stuff */
enc = (struct encode *)calloc(1, sizeof(struct encode));
if (enc == NULL) {
err_msg("Failed to allocate encode structure\n");
//return -1;
return NULL; //g++ :'int' to 'void*'
}
/* get physical contigous bit stream buffer */
mem_desc.size = STREAM_BUF_SIZE;
ret = IOGetPhyMem(&mem_desc);
if (ret) {
err_msg("Unable to obtain physical memory\n");
free(enc);
//return -1;
return NULL; //g++ :'int' to 'void*'
}
/* mmap that physical buffer */
enc->virt_bsbuf_addr = IOGetVirtMem(&mem_desc);
if (enc->virt_bsbuf_addr <= 0) {
err_msg("Unable to map physical memory\n");
IOFreePhyMem(&mem_desc);
free(enc);
//return -1;
return NULL; //g++ :'int' to 'void*'
}
enc->phy_bsbuf_addr = mem_desc.phy_addr;
enc->cmdl = cmdl;
if (enc->cmdl->format == STD_MJPG)
enc->mjpg_fmt = MODE420; /* Please change this per your needs */
if (enc->cmdl->mapType) {
enc->linear2TiledEnable = 1;
enc->cmdl->chromaInterleave = 1; /* Must be CbCrInterleave for tiled */
if (cmdl->format == STD_MJPG) {
err_msg("MJPG encoder cannot support tiled format\n");
//return -1;
return NULL; //g++ :'int' to 'void*'
}
} else
enc->linear2TiledEnable = 0;
/* open the encoder */
ret = encoder_open(enc);
if (ret)
goto err;
/* configure the encoder */
ret = encoder_configure(enc);
if (ret)
goto err1;
/* allocate scratch buf */
if (cpu_is_mx6x() && (cmdl->format == STD_MPEG4) && enc->mp4_dataPartitionEnable) {
scratch_mem_desc.size = MPEG4_SCRATCH_SIZE;
ret = IOGetPhyMem(&scratch_mem_desc);
if (ret) {
err_msg("Unable to obtain physical slice save mem\n");
goto err1;
}
enc->scratchBuf.bufferBase = scratch_mem_desc.phy_addr;
enc->scratchBuf.bufferSize = scratch_mem_desc.size;
}
/* allocate memory for the frame buffers */
ret = encoder_allocate_framebuffer(enc);
if (ret)
goto err1;
/* start encoding */
ret = encoder_start(enc);
/* free the allocated framebuffers */
encoder_free_framebuffer(enc);
err1:
/* close the encoder */
encoder_close(enc);
err:
if (cpu_is_mx6x() && cmdl->format == STD_MPEG4 && enc->mp4_dataPartitionEnable) {
IOFreeVirtMem(&scratch_mem_desc);
IOFreePhyMem(&scratch_mem_desc);
}
/* free the physical memory */
IOFreeVirtMem(&mem_desc);
IOFreePhyMem(&mem_desc);
free(enc);
#ifndef COMMON_INIT
vpu_UnInit();
#endif
//return ret;
return NULL;
//g++ : 由于创建线程时'void*' to 'void* (*)(void*)' 不成功所以将
//int encode_test(void *arg) 改成void* encode_test(void *arg)
//故此地无返回值:'int' to 'void*'
}
| [
"[email protected]"
] | |
df89c1ce7c426147e59e9f01d9b62b4e9e0deee5 | f1aaed1e27416025659317d1f679f7b3b14d654e | /MenuMate/MenuMate/Source/Analysis/ReportBuilders/EndOfDayReportBuilder.h | b60aa15bd131d92875f0421697c1e1cf8644dd03 | [] | no_license | radtek/Pos | cee37166f89a7fcac61de9febb3760d12b823ce5 | f117845e83b41d65f18a4635a98659144d66f435 | refs/heads/master | 2020-11-25T19:49:37.755286 | 2016-09-16T14:55:17 | 2016-09-16T14:55:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,553 | h | #ifndef EndOfDayReportBuilderH
#define EndOfDayReportBuilderH
#include "ReportEnums.h"
#include "BaseReportBuilder.h"
#include "MM_DBCore.h"
#include "GlobalSettings.h"
class EndOfDayReportBuilder : public BaseReportBuilder
{
public:
EndOfDayReportBuilder(ReportType reportType, TGlobalSettings* globalSettings, Database::TDBTransaction* dbTransaction);
~EndOfDayReportBuilder();
protected:
//This function is implemented to help derived concrete classes to reuse the functionality as is if they dont intend to override some of the functionality
//If they need to they can very well do it in PrepareAndCompileSections() pure virtual function carried from the BaseReportBuilder
void AddSectionsToReport(IReport* report);
virtual void AddReportDetailsSection(IReport* report);
virtual void AddCurrentDateDetailsSection(IReport* report);
virtual void AddClientDetailsSection(IReport* report);
virtual void AddSessionDateSection(IReport* report);
virtual void AddMasterBlindBalancesSection(IReport* report);
virtual void AddBlindBalancesSection(IReport* report);
virtual void AddTransactionSummaryGroupSection(IReport* report);
virtual void AddBilledSalesTotalsSection(IReport* report);
virtual void AddComplimentarySalesTotalsSection(IReport* report);
virtual void AddChargeSalesTotalsSection(IReport* report);
virtual void AddTotalsSection(IReport* report);
virtual void AddBreakdownCategoriesSection(IReport* report);
virtual void AddDiscountReportSection(IReport* report);
virtual void AddPointsReportSection(IReport* report);
virtual void AddPatronAverageSection(IReport* report);
virtual void AddProductionInfoSection(IReport* report);
virtual void AddAccountPurchasesSection(IReport* report);
virtual void AddAccountBalancesTabsSection(IReport* report);
virtual void AddAccountBalancesSeatedSection(IReport* report);
virtual void AddHourlySalesSection(IReport* report);
virtual void AddAccumulatedTotalSection(IReport* report);
virtual void AddTaxSummarySection(IReport* report);
virtual void AddServiceChargeSummarSection(IReport* report);
virtual void AddStaffHoursSection(IReport* report);
virtual void AddCommissionTipsSection(IReport* report);
virtual void AddRefundSection(IReport* report);
virtual void AddCancelsSection(IReport* report);
virtual void AddWriteOffSection(IReport* report);
virtual void AddShowRemovalSection(IReport* report);
virtual void AddPriceAdjustmentSection(IReport* report);
virtual void AddMallExportConsolidatedReceipt(IReport* report);
};
#endif
| [
"[email protected]"
] | |
42f500fb859c033e0549a53584a4f512f9f053c3 | 5ecff5e33ed6059a01db710b5185b83a0694ec9a | /contrib/epee/include/storages/http_abstract_invoke.h | 1bd85c43eae8324ba8a2faced32b3426b84bc4e6 | [
"BSD-3-Clause"
] | permissive | ombre-project/ombre | f940c0a440a8eebb1c953db46d9e15e2c89cf9d0 | c8a2e0567ac894b76996c515c48c45b4a8a08719 | refs/heads/master | 2021-08-27T20:56:22.016810 | 2021-08-22T10:34:28 | 2021-08-22T10:34:28 | 177,971,919 | 5 | 16 | NOASSERTION | 2019-09-28T10:00:27 | 2019-03-27T10:33:43 | C++ | UTF-8 | C++ | false | false | 5,453 | h |
// Copyright (c) 2006-2013, Andrey N. Sabelnikov, www.sabelnikov.net
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Andrey N. Sabelnikov nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
#pragma once
#include "net/http_base.h"
#include "net/http_server_handlers_map2.h"
#include "portable_storage_template_helper.h"
#include <boost/utility/string_ref.hpp>
#include <chrono>
#include <string>
namespace epee
{
namespace net_utils
{
template <class t_request, class t_response, class t_transport>
bool invoke_http_json(const boost::string_ref uri, const t_request &out_struct, t_response &result_struct, t_transport &transport, std::chrono::milliseconds timeout = std::chrono::seconds(15), const boost::string_ref method = "GET")
{
std::string req_param;
if(!serialization::store_t_to_json(out_struct, req_param))
return false;
http::fields_list additional_params;
additional_params.push_back(std::make_pair("Content-Type", "application/json; charset=utf-8"));
const http::http_response_info *pri = NULL;
if(!transport.invoke(uri, method, req_param, timeout, std::addressof(pri), std::move(additional_params)))
{
LOG_PRINT_L1("Failed to invoke http request to " << uri);
return false;
}
if(!pri)
{
LOG_PRINT_L1("Failed to invoke http request to " << uri << ", internal error (null response ptr)");
return false;
}
if(pri->m_response_code != 200)
{
LOG_PRINT_L1("Failed to invoke http request to " << uri << ", wrong response code: " << pri->m_response_code);
return false;
}
return serialization::load_t_from_json(result_struct, pri->m_body);
}
template <class t_request, class t_response, class t_transport>
bool invoke_http_bin(const boost::string_ref uri, const t_request &out_struct, t_response &result_struct, t_transport &transport, std::chrono::milliseconds timeout = std::chrono::seconds(15), const boost::string_ref method = "GET")
{
std::string req_param;
if(!serialization::store_t_to_binary(out_struct, req_param))
return false;
const http::http_response_info *pri = NULL;
if(!transport.invoke(uri, method, req_param, timeout, std::addressof(pri)))
{
LOG_PRINT_L1("Failed to invoke http request to " << uri);
return false;
}
if(!pri)
{
LOG_PRINT_L1("Failed to invoke http request to " << uri << ", internal error (null response ptr)");
return false;
}
if(pri->m_response_code != 200)
{
LOG_PRINT_L1("Failed to invoke http request to " << uri << ", wrong response code: " << pri->m_response_code);
return false;
}
return serialization::load_t_from_binary(result_struct, pri->m_body);
}
template <class t_request, class t_response, class t_transport>
bool invoke_http_json_rpc(const boost::string_ref uri, std::string method_name, const t_request &out_struct, t_response &result_struct, t_transport &transport, std::chrono::milliseconds timeout = std::chrono::seconds(15), const boost::string_ref http_method = "GET", const std::string &req_id = "0")
{
epee::json_rpc::request<t_request> req_t = AUTO_VAL_INIT(req_t);
req_t.jsonrpc = "2.0";
req_t.id = req_id;
req_t.method = std::move(method_name);
req_t.params = out_struct;
epee::json_rpc::response<t_response, epee::json_rpc::error> resp_t = AUTO_VAL_INIT(resp_t);
if(!epee::net_utils::invoke_http_json(uri, req_t, resp_t, transport, timeout, http_method))
{
return false;
}
if(resp_t.error.code || resp_t.error.message.size())
{
LOG_ERROR("RPC call of \"" << req_t.method << "\" returned error: " << resp_t.error.code << ", message: " << resp_t.error.message);
return false;
}
result_struct = resp_t.result;
return true;
}
template <class t_command, class t_transport>
bool invoke_http_json_rpc(const boost::string_ref uri, typename t_command::request &out_struct, typename t_command::response &result_struct, t_transport &transport, std::chrono::milliseconds timeout = std::chrono::seconds(15), const boost::string_ref http_method = "GET", const std::string &req_id = "0")
{
return invoke_http_json_rpc(uri, t_command::methodname(), out_struct, result_struct, transport, timeout, http_method, req_id);
}
}
}
| [
"[email protected]"
] | |
e73df4b2ba1f2cfd5b174df77ec069ae06c11c72 | 38ad03bc0cc05cafbe18be6067310c42c95647c3 | /include/devicetools/memory.h | c5a7c13b5d31ba30f2a7c776c742065f7d0e12e0 | [
"MIT"
] | permissive | richardlett/GALATIC | dd656979b7a7baf82c36145d08b815f1beb2c837 | 6eadf2ab153d8272408b4513fcf0d39db183ca1c | refs/heads/main | 2023-06-30T02:06:48.030324 | 2021-07-20T04:41:24 | 2021-07-20T04:41:24 | 376,128,667 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,908 | h | // Project AC-SpGEMM
// https://www.tugraz.at/institute/icg/research/team-steinberger/
//
// Copyright (C) 2018 Institute for Computer Graphics and Vision,
// Graz University of Technology
//
// Author(s): Martin Winter - martin.winter (at) icg.tugraz.at
// Daniel Mlakar - daniel.mlakar (at) icg.tugraz.at
// Rhaleb Zayer - rzayer (at) mpi-inf.mpg.de
// Hans-Peter Seidel - hpseidel (at) mpi-inf.mpg.de
// Markus Steinberger - steinberger ( at ) icg.tugraz.at
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
#ifndef INCLUDED_CUDA_MEMORY
#define INCLUDED_CUDA_MEMORY
#pragma once
#include <cstddef>
#include <cuda_runtime.h>
#include "../../include/devicetools/unique_handle.h"
namespace CU
{
struct MemFreeDeleter
{
void operator ()(CUdeviceptr ptr) const
{
cudaFree(reinterpret_cast<void*>(ptr));
}
};
using unique_ptr = unique_handle<CUdeviceptr, 0ULL, MemFreeDeleter>;
struct pitched_memory
{
pitched_memory(const pitched_memory&) = delete;
pitched_memory& operator =(const pitched_memory&) = delete;
unique_ptr memory;
std::size_t pitch;
pitched_memory() {}
pitched_memory(unique_ptr memory, std::size_t pitch)
: memory(std::move(memory)),
pitch(pitch)
{
}
pitched_memory(pitched_memory&& m)
: memory(std::move(m.memory)),
pitch(m.pitch)
{
}
pitched_memory& operator =(pitched_memory&& m)
{
using std::swap;
swap(memory, m.memory);
pitch = m.pitch;
return *this;
}
};
unique_ptr allocMemory(std::size_t size);
unique_ptr allocMemoryPitched(std::size_t& pitch, std::size_t row_size, std::size_t num_rows, unsigned int element_size);
pitched_memory allocMemoryPitched(std::size_t row_size, std::size_t num_rows, unsigned int element_size);
}
#endif // INCLUDED_CUDA_MEMORY
| [
"[email protected]"
] | |
cff6138c371795c3d0c0ba40092d4f79e068a7e5 | d6293246c2b9b5eb0d8a6799eace0d2a9f608699 | /ex17/dp3.cpp | 018de9cf6f5442d09128d2253bb8028bf36f9100 | [] | no_license | phamanhtuan90/algorithm | 64574995e926954442380cce9c5b74da1e58ee54 | 0583c44487485e0937a263cd4631ce20d33fbea8 | refs/heads/master | 2021-01-21T04:50:58.978829 | 2016-07-26T11:17:10 | 2016-07-26T11:17:10 | 54,105,233 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,494 | cpp | #include <iostream>
#include <fstream>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <algorithm>
#include <vector>
using namespace std;
int h,c;
int arr[111];
struct toado{
int h,c;
};
int d[111];
int range[111];
int maxSum;
toado huong[4] = {
1,-1
,1,0
,1,1
};
int n;
int best[111][111];
int dp[111];
int sum;
void input(){
memset(d,0,sizeof(d));
memset(arr,0,sizeof(arr));
memset(range,0,sizeof(range));
memset(dp, 0, sizeof(dp));
sum = 0;
int a;
n = 0;
while (scanf("%d", &a) > 0) {
if(a == 0) break;
arr[n] = a;
n++;
sum += a;
}
}
int x;
int result;
void solve(){
dp[0] = 1;
for(int i = 0; i < n ; i++){
for(int j = sum; j >= arr[i]; j--){
if( dp[j - arr[i]] == 1){
dp[j] = 1;
}
}
}
while (scanf("%d", &x) > 0) {
if(x == 0) break;
printf("%d ", x);
if(dp[x] == 1){
for(int i = n - 1; i >=0; i--){
if(dp[x - arr[i]] == 1){
printf("%d ", arr[i]);
x = x - arr[i];
}
}
}else{
printf("0");
}
printf("\n");
}
printf("\n");
}
int main()
{
freopen("dp3.txt","r",stdin);
int ntest;
scanf("%d",&ntest);
for(int i = 0; i < ntest; i++){
input();
solve();
}
return 0;
} | [
"[email protected]"
] | |
d9c583b0365dc39dd41ab6f88e8607c4185aaea3 | 6f0085fd3c917c7f278e9676b1c7d8f36b5ca883 | /StageClear.cpp | 63fb86bac96c157fb442f98b48dd3e803b5f8fb8 | [] | no_license | ende1031/ProjectHaku | 65fe8bc0fa972759751d29b8d2c3d420c28a080a | 8fa26df82220602fd71e9e028b84a53384777b4c | refs/heads/master | 2021-01-19T06:49:56.675825 | 2017-06-22T12:10:15 | 2017-06-22T12:10:15 | 87,502,774 | 3 | 0 | null | null | null | null | UHC | C++ | false | false | 1,467 | cpp | #include "StageClear.h"
StageClear::StageClear()
{
}
StageClear::~StageClear()
{
}
void StageClear::Start(Texture texture, Texture texture2)
{
m_bActive = true;
m_pSprite = Device::GetSprite();
m_pTexture = texture.GetTexture(); //밑배경
m_pTexture2 = texture2.GetTexture(); //라이트
m_AniTimer = 0;
m_AniNum = 0;
m_alpaTimer = 0;
m_alpha = 0;
m_alpha2 = 0;
m_color = D3DCOLOR_ARGB(m_alpha, 255, 255, 255);
m_color2 = D3DCOLOR_ARGB(m_alpha2, 255, 255, 255);
m_rect = { 0, 0, (LONG)texture.GetWidth(), (LONG)texture.GetHeight() };
m_vPos = D3DXVECTOR3(0, 0, 0);
m_width = (float)m_rect.right;
m_height = (float)m_rect.bottom;
m_bAlpaUp = true;
}
void StageClear::Update(float deltaTime)
{
FadeIn(&m_alpha, deltaTime);
m_alpaTimer += deltaTime;
if (m_alpaTimer >= 0.02f)
{
if (m_bAlpaUp)
{
m_alpha2 += 10;
m_color2 = D3DCOLOR_ARGB(m_alpha2, 255, 255, 255);
if (m_alpha2 > 180)
m_bAlpaUp = false;
}
else
{
m_alpha2 -= 10;
m_color2 = D3DCOLOR_ARGB(m_alpha2, 255, 255, 255);
if (m_alpha2 < 30)
m_bAlpaUp = true;
}
m_alpaTimer = 0;
}
}
void StageClear::Draw()
{
if (m_bActive)
{
m_pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE);
m_pSprite->Draw(m_pTexture, &m_rect, NULL, &m_vPos, m_color);
m_pSprite->End();
m_pSprite->Begin(D3DXSPRITE_ALPHABLEND | D3DXSPRITE_SORT_TEXTURE);
m_pSprite->Draw(m_pTexture2, &m_rect, NULL, &m_vPos, m_color2);
m_pSprite->End();
}
} | [
"[email protected]"
] | |
c6c45c815dbd6eff26ed6ed25871833d0cc16125 | a671414f8f624acfeb1db81a43a13ba1b780fc37 | /Kernel/Arch/i386/CPU.h | 4d34ff64d1022824c6eea2442062bb7fb54a51be | [
"BSD-2-Clause"
] | permissive | Thecarisma/serenity | 28940e6a1c304e9c330fdb051b179ae687eb15bc | bd1e8bf16639eda528df671e64447febbcffd10a | refs/heads/master | 2020-07-30T07:34:49.840914 | 2019-09-21T22:46:29 | 2019-09-21T22:46:29 | 210,136,929 | 3 | 0 | BSD-2-Clause | 2019-09-22T11:37:41 | 2019-09-22T11:37:41 | null | UTF-8 | C++ | false | false | 9,985 | h | #pragma once
#include <AK/Badge.h>
#include <AK/Noncopyable.h>
#include <Kernel/VM/VirtualAddress.h>
#include <Kernel/kstdio.h>
#define PAGE_SIZE 4096
#define PAGE_MASK 0xfffff000
class MemoryManager;
class PageTableEntry;
struct [[gnu::packed]] TSS32
{
u16 backlink, __blh;
u32 esp0;
u16 ss0, __ss0h;
u32 esp1;
u16 ss1, __ss1h;
u32 esp2;
u16 ss2, __ss2h;
u32 cr3, eip, eflags;
u32 eax, ecx, edx, ebx, esp, ebp, esi, edi;
u16 es, __esh;
u16 cs, __csh;
u16 ss, __ssh;
u16 ds, __dsh;
u16 fs, __fsh;
u16 gs, __gsh;
u16 ldt, __ldth;
u16 trace, iomapbase;
};
union [[gnu::packed]] Descriptor
{
struct {
u16 limit_lo;
u16 base_lo;
u8 base_hi;
u8 type : 4;
u8 descriptor_type : 1;
u8 dpl : 2;
u8 segment_present : 1;
u8 limit_hi : 4;
u8 : 1;
u8 zero : 1;
u8 operation_size : 1;
u8 granularity : 1;
u8 base_hi2;
};
struct {
u32 low;
u32 high;
};
enum Type {
Invalid = 0,
AvailableTSS_16bit = 0x1,
LDT = 0x2,
BusyTSS_16bit = 0x3,
CallGate_16bit = 0x4,
TaskGate = 0x5,
InterruptGate_16bit = 0x6,
TrapGate_16bit = 0x7,
AvailableTSS_32bit = 0x9,
BusyTSS_32bit = 0xb,
CallGate_32bit = 0xc,
InterruptGate_32bit = 0xe,
TrapGate_32bit = 0xf,
};
void set_base(void* b)
{
base_lo = (u32)(b)&0xffff;
base_hi = ((u32)(b) >> 16) & 0xff;
base_hi2 = ((u32)(b) >> 24) & 0xff;
}
void set_limit(u32 l)
{
limit_lo = (u32)l & 0xffff;
limit_hi = ((u32)l >> 16) & 0xff;
}
};
class PageDirectoryEntry {
AK_MAKE_NONCOPYABLE(PageDirectoryEntry);
public:
PageTableEntry* page_table_base() { return reinterpret_cast<PageTableEntry*>(m_raw & 0xfffff000u); }
void set_page_table_base(u32 value)
{
m_raw &= 0xfff;
m_raw |= value & 0xfffff000;
}
u32 raw() const { return m_raw; }
void copy_from(Badge<MemoryManager>, const PageDirectoryEntry& other) { m_raw = other.m_raw; }
enum Flags {
Present = 1 << 0,
ReadWrite = 1 << 1,
UserSupervisor = 1 << 2,
WriteThrough = 1 << 3,
CacheDisabled = 1 << 4,
};
bool is_present() const { return raw() & Present; }
void set_present(bool b) { set_bit(Present, b); }
bool is_user_allowed() const { return raw() & UserSupervisor; }
void set_user_allowed(bool b) { set_bit(UserSupervisor, b); }
bool is_writable() const { return raw() & ReadWrite; }
void set_writable(bool b) { set_bit(ReadWrite, b); }
bool is_write_through() const { return raw() & WriteThrough; }
void set_write_through(bool b) { set_bit(WriteThrough, b); }
bool is_cache_disabled() const { return raw() & CacheDisabled; }
void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); }
void set_bit(u8 bit, bool value)
{
if (value)
m_raw |= bit;
else
m_raw &= ~bit;
}
private:
u32 m_raw;
};
class PageTableEntry {
AK_MAKE_NONCOPYABLE(PageTableEntry);
public:
void* physical_page_base() { return reinterpret_cast<void*>(m_raw & 0xfffff000u); }
void set_physical_page_base(u32 value)
{
m_raw &= 0xfff;
m_raw |= value & 0xfffff000;
}
u32 raw() const { return m_raw; }
enum Flags {
Present = 1 << 0,
ReadWrite = 1 << 1,
UserSupervisor = 1 << 2,
WriteThrough = 1 << 3,
CacheDisabled = 1 << 4,
};
bool is_present() const { return raw() & Present; }
void set_present(bool b) { set_bit(Present, b); }
bool is_user_allowed() const { return raw() & UserSupervisor; }
void set_user_allowed(bool b) { set_bit(UserSupervisor, b); }
bool is_writable() const { return raw() & ReadWrite; }
void set_writable(bool b) { set_bit(ReadWrite, b); }
bool is_write_through() const { return raw() & WriteThrough; }
void set_write_through(bool b) { set_bit(WriteThrough, b); }
bool is_cache_disabled() const { return raw() & CacheDisabled; }
void set_cache_disabled(bool b) { set_bit(CacheDisabled, b); }
void set_bit(u8 bit, bool value)
{
if (value)
m_raw |= bit;
else
m_raw &= ~bit;
}
private:
u32 m_raw;
};
static_assert(sizeof(PageDirectoryEntry) == 4);
static_assert(sizeof(PageTableEntry) == 4);
class IRQHandler;
void gdt_init();
void idt_init();
void sse_init();
void register_interrupt_handler(u8 number, void (*f)());
void register_user_callable_interrupt_handler(u8 number, void (*f)());
void register_irq_handler(u8 number, IRQHandler&);
void unregister_irq_handler(u8 number, IRQHandler&);
void flush_idt();
void flush_gdt();
void load_task_register(u16 selector);
u16 gdt_alloc_entry();
void gdt_free_entry(u16);
Descriptor& get_gdt_entry(u16 selector);
void write_gdt_entry(u16 selector, Descriptor&);
[[noreturn]] static inline void hang()
{
asm volatile("cli; hlt");
for (;;) {
}
}
#define LSW(x) ((u32)(x)&0xFFFF)
#define MSW(x) (((u32)(x) >> 16) & 0xFFFF)
#define LSB(x) ((x)&0xFF)
#define MSB(x) (((x) >> 8) & 0xFF)
#define cli() asm volatile("cli" :: \
: "memory")
#define sti() asm volatile("sti" :: \
: "memory")
#define memory_barrier() asm volatile("" :: \
: "memory")
inline u32 cpu_cr3()
{
u32 cr3;
asm volatile("movl %%cr3, %%eax"
: "=a"(cr3));
return cr3;
}
inline u32 cpu_flags()
{
u32 flags;
asm volatile(
"pushf\n"
"pop %0\n"
: "=rm"(flags)::"memory");
return flags;
}
inline bool are_interrupts_enabled()
{
return cpu_flags() & 0x200;
}
class InterruptFlagSaver {
public:
InterruptFlagSaver()
{
m_flags = cpu_flags();
}
~InterruptFlagSaver()
{
if (m_flags & 0x200)
sti();
else
cli();
}
private:
u32 m_flags;
};
class InterruptDisabler {
public:
InterruptDisabler()
{
m_flags = cpu_flags();
cli();
}
~InterruptDisabler()
{
if (m_flags & 0x200)
sti();
}
private:
u32 m_flags;
};
/* Map IRQ0-15 @ ISR 0x50-0x5F */
#define IRQ_VECTOR_BASE 0x50
struct PageFaultFlags {
enum Flags {
NotPresent = 0x00,
ProtectionViolation = 0x01,
Read = 0x00,
Write = 0x02,
UserMode = 0x04,
SupervisorMode = 0x00,
InstructionFetch = 0x08,
};
};
class PageFault {
public:
PageFault(u16 code, VirtualAddress vaddr)
: m_code(code)
, m_vaddr(vaddr)
{
}
enum class Type {
PageNotPresent = PageFaultFlags::NotPresent,
ProtectionViolation = PageFaultFlags::ProtectionViolation,
};
enum class Access {
Read = PageFaultFlags::Read,
Write = PageFaultFlags::Write,
};
VirtualAddress vaddr() const { return m_vaddr; }
u16 code() const { return m_code; }
Type type() const { return (Type)(m_code & 1); }
Access access() const { return (Access)(m_code & 2); }
bool is_not_present() const { return (m_code & 1) == PageFaultFlags::NotPresent; }
bool is_protection_violation() const { return (m_code & 1) == PageFaultFlags::ProtectionViolation; }
bool is_read() const { return (m_code & 2) == PageFaultFlags::Read; }
bool is_write() const { return (m_code & 2) == PageFaultFlags::Write; }
bool is_user() const { return (m_code & 4) == PageFaultFlags::UserMode; }
bool is_supervisor() const { return (m_code & 4) == PageFaultFlags::SupervisorMode; }
bool is_instruction_fetch() const { return (m_code & 8) == PageFaultFlags::InstructionFetch; }
private:
u16 m_code;
VirtualAddress m_vaddr;
};
struct [[gnu::packed]] RegisterDump
{
u16 ss;
u16 gs;
u16 fs;
u16 es;
u16 ds;
u32 edi;
u32 esi;
u32 ebp;
u32 esp;
u32 ebx;
u32 edx;
u32 ecx;
u32 eax;
u32 eip;
u16 cs;
u16 __csPadding;
u32 eflags;
u32 esp_if_crossRing;
u16 ss_if_crossRing;
};
struct [[gnu::packed]] RegisterDumpWithExceptionCode
{
u16 ss;
u16 gs;
u16 fs;
u16 es;
u16 ds;
u32 edi;
u32 esi;
u32 ebp;
u32 esp;
u32 ebx;
u32 edx;
u32 ecx;
u32 eax;
u16 exception_code;
u16 __exception_code_padding;
u32 eip;
u16 cs;
u16 __csPadding;
u32 eflags;
u32 esp_if_crossRing;
u16 ss_if_crossRing;
};
struct [[gnu::aligned(16)]] FPUState
{
u8 buffer[512];
};
inline constexpr u32 page_base_of(u32 address)
{
return address & 0xfffff000;
}
class CPUID {
public:
CPUID(u32 function) { asm volatile("cpuid"
: "=a"(m_eax), "=b"(m_ebx), "=c"(m_ecx), "=d"(m_edx)
: "a"(function), "c"(0)); }
u32 eax() const { return m_eax; }
u32 ebx() const { return m_ebx; }
u32 ecx() const { return m_ecx; }
u32 edx() const { return m_edx; }
private:
u32 m_eax { 0xffffffff };
u32 m_ebx { 0xffffffff };
u32 m_ecx { 0xffffffff };
u32 m_edx { 0xffffffff };
};
inline void read_tsc(u32& lsw, u32& msw)
{
asm volatile("rdtsc"
: "=d"(msw), "=a"(lsw));
}
struct Stopwatch {
union SplitQword {
struct {
uint32_t lsw;
uint32_t msw;
};
uint64_t qw { 0 };
};
public:
Stopwatch(const char* name)
: m_name(name)
{
read_tsc(m_start.lsw, m_start.msw);
}
~Stopwatch()
{
SplitQword end;
read_tsc(end.lsw, end.msw);
uint64_t diff = end.qw - m_start.qw;
dbgprintf("Stopwatch(%s): %Q ticks\n", m_name, diff);
}
private:
const char* m_name { nullptr };
SplitQword m_start;
};
| [
"[email protected]"
] | |
413c35891e1c92c5c1978511aa594f2db9ad1ab3 | 0f9e4dc408d5a9141af22cd2b37507949b01d52f | /week13/Source.cpp | 6bcbdce6f3e6e7bb30a793af9372e3e7456e2370 | [] | no_license | knot93289/week13 | e48f739446343361b1de029c05fa192dfdf2265a | 3510afb0ac22aba022d9de6a843424bcd1c46118 | refs/heads/master | 2023-01-14T18:31:55.734832 | 2020-11-21T07:17:04 | 2020-11-21T07:17:04 | 314,755,971 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,431 | cpp | #include<iostream>
#include<conio.h>
#include<stdlib.h>
#define MAX_SIZE 5
using namespace std;
int main()
{
int item, choice, i;
int arr_stack[MAX_SIZE];
int top = 0;
int exit = 1;
cout << "\nSimple Stack Example - Array - C++";
do
{
cout << "\n\nnStack Main Menu";
cout << "\n1.Push \n2.Pop \n3.Display \nOthers to exit";
cout << "\nEnter Your Choice : ";
cin >> choice;
switch (choice)
{
case 1:
if (top == MAX_SIZE)
cout << "\n## Stack is Full!";
else
{
cout << "\nEnter The Value to be pushed : ";
cin >> item;
cout << "\n## Position : " << top << ", Pushed Value :" << item;
arr_stack[top++] = item;
}
break;
case 2:
if (top == 0)
cout << "\n## Stack is Empty!";
else
{
--top;
cout << "\n## Position : " << top << ", Popped Value :" << arr_stack[top];
}
break;
case 3:
cout << "\n## Stack Size : " << top;
for (i = (top - 1); i >= 0; i--)
cout << "\n## Position : " << i << ", Value :" << arr_stack[i];
break;
default:
exit = 0;
break;
}
} while (exit);
return 0;
} | [
"[email protected]"
] | |
3e956f2d370da63914b891a53ed909012965cb55 | cfa55f03005047b2de5368c34074c1c100d2450b | /DirectXAnimDLL/AnimationManager.cpp | 7ef9d75925d86842f489573db147274605c38d9b | [] | no_license | C6H8O7/DirectX-animation | 5886df46650f162d3dd4e561cfba791cca7c0c06 | 7a8164ed2e1f75f24d65f0bfccb1dc04e86433ab | refs/heads/master | 2021-01-13T14:54:34.152470 | 2016-12-14T13:53:08 | 2016-12-14T13:53:08 | 76,463,643 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 653 | cpp | #include "stdafx.h"
AnimationManager::AnimationManager()
{
}
AnimationManager::AnimationManager(AnimationManager& _cpy)
{
}
AnimationManager::~AnimationManager()
{
}
AnimationManager *AnimationManager::getSingleton()
{
static AnimationManager instanceUnique;
return &instanceUnique;
}
bool AnimationManager::loadAnimFromFile(std::string _res, std::string _file)
{
AnimationModel *anim = new AnimationModel();
bool ret = anim->loadAnimFromFile(_file);
if(ret)
m_AnimationModelMap[_res] = anim;
else
delete anim;
return ret;
}
AnimationModel *AnimationManager::getAnimation(std::string _res)
{
return m_AnimationModelMap[_res];
} | [
"[email protected]"
] | |
fb69d53ea23c73e81e1ab833b1109fa81d699278 | 37f8b630d5ce916ca2d87d0344bbb24c19cdd72b | /MUSHRAConfig/JuceLibraryCode/JuceLibraryCode2.cpp | 5bc1f5224644b4ca5107c47160953dc6f2f64aaa | [] | no_license | RomanKosobrodov/MUSHRATest | 951f21a7cc58facab714347e4c65e647e6a80ef7 | 4183d07b785a7f3a17265cb054cf810ecd658435 | refs/heads/master | 2020-05-19T23:54:35.021345 | 2012-06-07T08:14:35 | 2012-06-07T08:14:35 | 4,581,320 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 1,149 | cpp | /*
IMPORTANT! This file is auto-generated each time you save your
project - if you alter its contents, your changes may be overwritten!
This file pulls in all the Juce source code, and builds it using the settings
defined in AppConfig.h.
If you want to change the method by which Juce is linked into your app, use the
Jucer to change it, rather than trying to edit this file directly.
*/
#include "AppConfig.h"
#if defined (JUCER_ANDROID_7F0E4A25)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_LINUX_MAKE_7346DA2A)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_VS2010_78A501D)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_VS2008_78A5006)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_VS2005_78A5003)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_XCODE_IPHONE_5BC26AE3)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#elif defined (JUCER_XCODE_MAC_F6D2F4CF)
#include "../../../juce/amalgamation/juce_amalgamated2.cpp"
#endif
| [
"[email protected]"
] | |
9e79c61f615fee6ad88b614a10b7afb9f5128abf | 267f5a81355a3206184d9b838659a7ae90274dea | /Cubic.h | 1965640945deb409d235855d8b08410820a0a1fc | [] | no_license | devmario/spline_cpp | 755951c2615419087959e1f114ff5641ccd26d3a | 21c57957aa1c5dad1035e2fb75f0f499c286451c | refs/heads/master | 2020-04-27T01:05:34.516163 | 2013-04-05T02:09:58 | 2013-04-05T02:09:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 682 | h | //
// Spline.h
// DessertTown
//
// Created by wonhee jang on 13. 4. 5..
// Copyright (c) 2013년 vanillabreeze. All rights reserved.
//
#ifndef __DessertTown__Cubic__
#define __DessertTown__Cubic__
#include <iostream>
namespace Spline {
class Cubic {
public:
float* controll_point;
unsigned int length;
unsigned int number_part;
Cubic() = default;
Cubic(float* _controll_point, unsigned int _length, unsigned int _number_part);
virtual ~Cubic();
virtual float* generate(int* _length);
virtual void p(int _i, float _t, float* _cp, float* _sp, int _idx);
virtual float blend(int _i, float _t);
};
};
#endif /* defined(__DessertTown__Spline__) */
| [
"[email protected]"
] | |
a5f1679c6df5b865a265e32b4d63e77849273111 | af10121e6dcac5c93dcbcf61eb8fb49c653f230c | /pitayaserver/framework/RelayClientSession.h | 3b2f2e4acdead05d2b0b97029c330b4c68c546ae | [] | no_license | imane-jym/gp2 | aa6d2eb68c8b4ad332d9f8c2adb00f071ff2ce0a | 90c9c2297fb73a786eb76022fb83f42488f3ee66 | refs/heads/master | 2021-09-03T03:59:21.038667 | 2018-01-05T11:33:43 | 2018-01-05T11:33:43 | 110,210,897 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,391 | h | /*
* RelayClientSession.h
*
* Created on: 2011-7-13
* Author: yq
*/
#ifndef RELAYCLIENTSESSION_H_
#define RELAYCLIENTSESSION_H_
#include "UserSession.h"
#include "Defines.h"
#include "Timer.h"
#include "Handler.h"
#include <map>
class WorldPacket;
class CClient;
class CRelayClientSession : public CUserSession
{
public:
/// Timers for different object refresh rates
enum RelayTimers
{
USER_UPDATE_TIMER_1s,
USER_UPDATE_TIMER_3s,
USER_UPDATE_TIMER_5s,
USER_UPDATE_TIMER_1min,
USER_UPDATE_TIMER_10min,
USER_UPDATE_TIMER_30min,
USER_UPDATE_COUNT
};
typedef void (CRelayClientSession::*OpcodeHandlerFunc)(WorldPacket &packet);
typedef std::map<uint16, OpcodeHandlerFunc> OpcodeHandlerMap;
CRelayClientSession();
virtual ~CRelayClientSession();
void SetClient(CClient *pClient) { m_pClient = pClient;};
void SetdwKey(int key) { m_dwKey = key;}
unsigned int GetdwKey() { return m_dwKey;}
// void GetdwActiveTime() { return m_dwActiveTime; }
virtual void SendPacket(WorldPacket * packet);
virtual bool Update(time_t diff);
virtual void AddSessionToWorker();
virtual void Offline();
CHandlerClientSession *GetHandler() { return &m_CHandler; }
private:
CClient * m_pClient;
unsigned int m_dwKey;
// uint32_t m_dwActiveTime;
IntervalTimer m_timers[USER_UPDATE_COUNT];
CHandlerClientSession m_CHandler;
};
#endif /* RELAYCLIENTSESSION_H_ */
| [
"[email protected]"
] | |
cb992381a8da9454cb7bf945de786c46682f1dc4 | 0c2f30bb432abf66f4611e51720960c165fa212c | /Src/Mesh.cpp | 42560e7573158efe0ebf79db5b6d2471edcc7955 | [] | no_license | 96no3/OpenGL3DSTGbeta | cacb52649846d47325b31794f8e9ad225a65c78a | ea8c335c19c5b8f5306d598aaf253f6a31064b15 | refs/heads/master | 2020-04-14T05:51:03.959847 | 2018-12-31T13:21:38 | 2018-12-31T13:21:38 | null | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 20,854 | cpp | /**
* @file Mesh.cpp
*/
#include "Mesh.h"
#include <fbxsdk.h>
#include <iostream>
/**
* モデルデータ管理のための名前空間.
*/
namespace Mesh {
/// 頂点データ型.
struct Vertex
{
glm::vec3 position; ///< 座標.
glm::vec4 color; ///< 色.
glm::vec2 texCoord; ///< テクスチャ座標.
glm::vec3 normal; ///< 法線.
glm::vec4 tangent; ///< 接ベクトル
};
/**
* Vertex Buffer Objectを作成する.
*
* @param size 頂点データのサイズ.
* @param data 頂点データへのポインタ.
*
* @return 作成したVBO.
*/
GLuint CreateVBO(GLsizeiptr size, const GLvoid* data)
{
GLuint vbo = 0;
glGenBuffers(1, &vbo);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
return vbo;
}
/**
* Index Buffer Objectを作成する.
*
* @param size インデックスデータのサイズ.
* @param data インデックスデータへのポインタ.
*
* @return 作成したIBO.
*/
GLuint CreateIBO(GLsizeiptr size, const GLvoid* data)
{
GLuint ibo = 0;
glGenBuffers(1, &ibo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, size, data, GL_STATIC_DRAW);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0);
return ibo;
}
/**
* 頂点アトリビュートを設定する.
*
* @param index 頂点アトリビュートのインデックス.
* @param cls 頂点データ型名.
* @param mbr 頂点アトリビュートに設定するclsのメンバ変数名.
*/
#define SetVertexAttribPointer(index, cls, mbr) SetVertexAttribPointerI( \
index, \
sizeof(cls::mbr) / sizeof(float), \
sizeof(cls), \
reinterpret_cast<GLvoid*>(offsetof(cls, mbr)))
void SetVertexAttribPointerI(GLuint index, GLint size, GLsizei stride, const GLvoid* pointer)
{
glEnableVertexAttribArray(index);
glVertexAttribPointer(index, size, GL_FLOAT, GL_FALSE, stride, pointer);
}
/**
* Vertex Array Objectを作成する.
*
* @param vbo VAOに関連付けられるVBO.
* @param ibo VAOに関連付けられるIBO.
*
* @return 作成したVAO.
*/
GLuint CreateVAO(GLuint vbo, GLuint ibo)
{
GLuint vao = 0;
glGenVertexArrays(1, &vao);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
SetVertexAttribPointer(0, Vertex, position);
SetVertexAttribPointer(1, Vertex, color);
SetVertexAttribPointer(2, Vertex, texCoord);
SetVertexAttribPointer(3, Vertex, normal);
SetVertexAttribPointer(4, Vertex, tangent);
glBindVertexArray(0);
return vao;
}
/**
* 4次元FBXベクトルを4次元glmベクトルに変換する.
*
* @param fbxVec FBXベクトル.
*
* @return glmベクトル.
*/
template<typename T>
glm::vec4 ToVec4(const T& fbxVec)
{
return glm::vec4(static_cast<float>(fbxVec[0]), static_cast<float>(fbxVec[1]), static_cast<float>(fbxVec[2]), static_cast<float>(fbxVec[3]));
}
/**
* 3次元FBXベクトルを3次元glmベクトルに変換する.
*
* @param fbxVec FBXベクトル.
*
* @return glmベクトル.
*/
template<typename T>
glm::vec3 ToVec3(const T& fbxVec)
{
return glm::vec3(static_cast<float>(fbxVec[0]), static_cast<float>(fbxVec[1]), static_cast<float>(fbxVec[2]));
}
/**
* 2次元FBXベクトルを2次元glmベクトルに変換する.
*
* @param fbxVec FBXベクトル.
*
* @return glmベクトル.
*/
template<typename T>
glm::vec2 ToVec2(const T& fbxVec)
{
return glm::vec2(static_cast<float>(fbxVec[0]), static_cast<float>(fbxVec[1]));
}
/**
* 頂点パラメータを取得する.
*
* @param mappingMode 使用するインデックスを選択するマッピングモード.
* @param isDirectRef 直接参照モードなら真、間接参照モードなら偽を渡す.
* @param pIndexList 間接参照用のインデックス配列. isDirectRefが偽の場合に使われる.
* @param pList 要素の配列.
* @param cpIndex マッピングモードが頂点単位の場合に使用するインデックス.
* @param polygonVertex マッピングモードがポリゴン単位の場合に使用するインデックス.
* @param defaultValue 未対応マッピングモードの場合に返す値.
*
* @return マッピングモードと参照モードに応じて適切な配列から頂点のパラメータを返す.
* 対応していないマッピングモードの場合はdefaultValueを返す.
*/
template<typename T>
T GetElement(
FbxGeometryElement::EMappingMode mappingMode,
bool isDirectRef,
const FbxLayerElementArrayTemplate<int>* pIndexList,
const FbxLayerElementArrayTemplate<T>* pList,
int cpIndex,
int polygonVertex,
const T& defaultValue)
{
switch (mappingMode) {
case FbxLayerElement::eByControlPoint:
return (*pList)[isDirectRef ? cpIndex : (*pIndexList)[cpIndex]];
case FbxLayerElement::eByPolygonVertex:
return (*pList)[isDirectRef ? polygonVertex : (*pIndexList)[polygonVertex]];
default:
return defaultValue;
}
}
/**
* FBXオブジェクトを破棄するためのヘルパー構造体.
*/
template<typename T>
struct Deleter
{
void operator()(T* p) { if (p) { p->Destroy(); } }
};
/// FBXオブジェクトを管理するためのポインタ型.
template<typename T>
using FbxPtr = std::unique_ptr<T, Deleter<T>>;
/**
* マテリアルの仮データ.
*/
struct TemporaryMaterial
{
glm::vec4 color = glm::vec4(1);
std::vector<uint32_t> indexBuffer;
std::vector<Vertex> vertexBuffer;
std::vector<std::string> textureName;
};
/**
* メッシュの仮データ.
*/
struct TemporaryMesh
{
std::string name;
std::vector<TemporaryMaterial> materialList;
};
/**
* FBXデータを中間データに変換するクラス.
*/
struct FbxLoader
{
bool Load(const char* filename);
bool Convert(FbxNode* node);
bool LoadMesh(FbxNode* node);
std::vector<TemporaryMesh> meshList;
};
/**
* FBXファイルを読み込む.
*
* @param filename FBXファイル名.
*
* @retval true 読み込み成功.
* @retval false 読み込み失敗.
*/
bool FbxLoader::Load(const char* filename)
{
FbxPtr<FbxManager> fbxManager(FbxManager::Create());
if (!fbxManager) {
std::cerr << "ERROR: " << filename << "の読み込みに失敗(FbxManagerの作成に失敗)" << std::endl;
return false;
}
FbxScene* fbxScene = FbxScene::Create(fbxManager.get(), "");
if (!fbxScene) {
std::cerr << "ERROR: " << filename << "の読み込みに失敗(FbxSceneの作成に失敗)" << std::endl;
return false;
}
else {
FbxPtr<FbxImporter> fbxImporter(FbxImporter::Create(fbxManager.get(), ""));
const bool importStatus = fbxImporter->Initialize(filename);
if (!importStatus || !fbxImporter->Import(fbxScene)) {
std::cerr << "ERROR: " << filename << "の読み込みに失敗\n" << fbxImporter->GetStatus().GetErrorString() << std::endl;
return false;
}
}
if (!Convert(fbxScene->GetRootNode())) {
std::cerr << "ERROR: " << filename << "の変換に失敗" << std::endl;
return false;
}
return true;
}
/**
* FBXデータを仮データに変換する.
*
* @param fbxNode 変換対象のFBXノードへのポインタ.
*
* @retval true 変換成功.
* @retval false 変換失敗.
*/
bool FbxLoader::Convert(FbxNode* fbxNode)
{
if (!fbxNode) {
return true;
}
if (!LoadMesh(fbxNode)) {
return false;
}
const int childCount = fbxNode->GetChildCount();
for (int i = 0; i < childCount; ++i) {
if (!Convert(fbxNode->GetChild(i))) {
return false;
}
}
return true;
}
/**
* FBXメッシュを仮データに変換する.
*
* @param fbxNode 変換対象のFBXノードへのポインタ.
*
* @retval true 変換成功.
* @retval false 変換失敗.
*/
bool FbxLoader::LoadMesh(FbxNode* fbxNode)
{
FbxMesh* fbxMesh = fbxNode->GetMesh();
if (!fbxMesh) {
return true;
}
TemporaryMesh mesh;
mesh.name = fbxNode->GetName();
if (!fbxMesh->IsTriangleMesh()) {
std::cerr << "WARNING: " << mesh.name << "には三角形以外の面が含まれています" << std::endl;
}
// マテリアル情報を読み取る.
const int materialCount = fbxNode->GetMaterialCount();
mesh.materialList.reserve(materialCount);
for (int i = 0; i < materialCount; ++i) {
TemporaryMaterial material;
if (FbxSurfaceMaterial* fbxMaterial = fbxNode->GetMaterial(i)) {
// マテリアルの色情報を読み取る.
const FbxClassId classId = fbxMaterial->GetClassId();
if (classId == FbxSurfaceLambert::ClassId || classId == FbxSurfacePhong::ClassId) {
const FbxSurfaceLambert* pLambert = static_cast<const FbxSurfaceLambert*>(fbxMaterial);
material.color = glm::vec4(ToVec3(pLambert->Diffuse.Get()), static_cast<float>(1.0f - pLambert->TransparencyFactor));
}
}
mesh.materialList.push_back(material);
}
// マテリアルリストが空かどうかを調べ、空ならダミーのマテリアルを追加する.
if (mesh.materialList.empty()) {
mesh.materialList.push_back(TemporaryMaterial());
}
// 頂点要素の有無を調べる.
const bool hasColor = fbxMesh->GetElementVertexColorCount() > 0;
const bool hasTexcoord = fbxMesh->GetElementUVCount() > 0;
const bool hasNormal = fbxMesh->GetElementNormalCount() > 0;
const bool hasTangent = fbxMesh->GetElementTangentCount() > 0;
// UVセット名のリストを取得する.
FbxStringList uvSetNameList;
fbxMesh->GetUVSetNames(uvSetNameList);
// 色情報を読み取る準備.
// @note 座標/UV/法線以外のパラメータには直接読み取る関数が提供されていないため、
// 「FbxGeometryElement???」クラスから読み取る必要がある.
FbxGeometryElement::EMappingMode colorMappingMode = FbxLayerElement::eNone;
bool isColorDirectRef = true;
const FbxLayerElementArrayTemplate<int>* colorIndexList = nullptr;
const FbxLayerElementArrayTemplate<FbxColor>* colorList = nullptr;
if (hasColor) {
const FbxGeometryElementVertexColor* fbxColorList = fbxMesh->GetElementVertexColor();
colorMappingMode = fbxColorList->GetMappingMode();
isColorDirectRef = fbxColorList->GetReferenceMode() == FbxLayerElement::eDirect;
colorIndexList = &fbxColorList->GetIndexArray();
colorList = &fbxColorList->GetDirectArray();
}
// 接ベクトルを読み取る準備.
FbxGeometryElement::EMappingMode tangentMappingMode = FbxLayerElement::eNone;
bool isTangentDirectRef = true;
const FbxLayerElementArrayTemplate<int>* tangentIndexList = nullptr;
const FbxLayerElementArrayTemplate<FbxVector4>* tangentList = nullptr;
FbxGeometryElement::EMappingMode binormalMappingMode = FbxLayerElement::eNone;
bool isBinormalDirectRef = true;
const FbxLayerElementArrayTemplate<int>* binormalIndexList = nullptr;
const FbxLayerElementArrayTemplate<FbxVector4>* binormalList = nullptr;
if (hasTangent) {
const FbxGeometryElementTangent* fbxTangentList = fbxMesh->GetElementTangent();
tangentMappingMode = fbxTangentList->GetMappingMode();
isTangentDirectRef = fbxTangentList->GetReferenceMode() == FbxLayerElement::eDirect;
tangentIndexList = &fbxTangentList->GetIndexArray();
tangentList = &fbxTangentList->GetDirectArray();
const FbxGeometryElementBinormal* fbxBinormaltList = fbxMesh->GetElementBinormal();
binormalMappingMode = fbxBinormaltList->GetMappingMode();
isBinormalDirectRef = fbxBinormaltList->GetReferenceMode() == FbxLayerElement::eDirect;
binormalIndexList = &fbxBinormaltList->GetIndexArray();
binormalList = &fbxBinormaltList->GetDirectArray();
}
// 頂点がどのマテリアルに属するかを示すマテリアルインデックスリストを取得する.
const FbxLayerElementArrayTemplate<int>* materialIndexList = nullptr;
if (FbxGeometryElementMaterial* fbxMaterialLayer = fbxMesh->GetElementMaterial()) {
materialIndexList = &fbxMaterialLayer->GetIndexArray();
}
// ポリゴン数にもとづいて、仮データバッファの容量を予約する.
const int polygonCount = fbxMesh->GetPolygonCount();
for (auto& e : mesh.materialList) {
const size_t avarageCapacity = polygonCount / mesh.materialList.size();
e.indexBuffer.reserve(avarageCapacity);
e.vertexBuffer.reserve(avarageCapacity);
}
// 頂点データを変換する.
const FbxAMatrix matTRS(fbxNode->EvaluateGlobalTransform());
const FbxAMatrix matR(FbxVector4(0, 0, 0), matTRS.GetR(), FbxVector4(1, 1, 1));
const FbxVector4* const fbxControlPoints = fbxMesh->GetControlPoints();
int polygonVertex = 0;
for (int polygonIndex = 0; polygonIndex < polygonCount; ++polygonIndex) {
for (int pos = 0; pos < 3; ++pos) {
Vertex v;
const int cpIndex = fbxMesh->GetPolygonVertex(polygonIndex, pos);
// 頂点座標.
v.position = ToVec3(matTRS.MultT(fbxControlPoints[cpIndex]));
// 頂点カラー.
v.color = glm::vec4(1);
if (hasColor) {
switch (colorMappingMode) {
case FbxLayerElement::eByControlPoint:
v.color = ToVec4((*colorList)[
isColorDirectRef ? cpIndex : (*colorIndexList)[cpIndex]]);
break;
case FbxLayerElement::eByPolygonVertex:
v.color = ToVec4((*colorList)[
isColorDirectRef ? polygonVertex : (*colorIndexList)[polygonVertex]]);
break;
default:
break;
}
}
// UV座標.
v.texCoord = glm::vec2(0);
if (hasTexcoord) {
FbxVector2 uv;
bool unmapped;
fbxMesh->GetPolygonVertexUV(polygonIndex, pos, uvSetNameList[0], uv, unmapped);
v.texCoord = ToVec2(uv);
}
// 法線.
v.normal = glm::vec3(0, 0, 1);
if (hasNormal) {
FbxVector4 normal;
fbxMesh->GetPolygonVertexNormal(polygonIndex, pos, normal);
v.normal = glm::normalize(ToVec3(matR.MultT(normal)));
}
// 接ベクトル.
v.tangent = glm::vec4(1, 0, 0, 1);
if (hasTangent) {
const glm::vec3 binormal = ToVec3(matR.MultT(GetElement(binormalMappingMode, isBinormalDirectRef, binormalIndexList,
binormalList, cpIndex, polygonVertex, FbxVector4(0, 1, 0, 1))));
const glm::vec3 tangent = ToVec3(matR.MultT(GetElement(tangentMappingMode, isTangentDirectRef, tangentIndexList,
tangentList, cpIndex, polygonVertex, FbxVector4(1, 0, 0, 1))));
v.tangent = glm::vec4(tangent, 1);
const glm::vec3 binormalTmp = glm::normalize(glm::cross(v.normal, tangent));
if (glm::dot(binormal, binormalTmp) < 0) {
v.tangent.w = -1;
}
}
// 頂点に対応する仮マテリアルに、頂点データとインデックスデータを追加する.
TemporaryMaterial& materialData = mesh.materialList[materialIndexList ? (*materialIndexList)[polygonIndex] : 0];
materialData.indexBuffer.push_back(static_cast<uint32_t>(materialData.vertexBuffer.size()));
materialData.vertexBuffer.push_back(v);
++polygonVertex;
}
}
meshList.push_back(std::move(mesh));
return true;
}
/**
* コンストラクタ.
*
* @param meshName メッシュデータ名.
* @param begin 描画するマテリアルの先頭インデックス.
* @param end 描画するマテリアルの終端インデックス.
*/
Mesh::Mesh(const std::string& meshName, size_t begin, size_t end) : name(meshName), beginMaterial(begin), endMaterial(end)
{
}
/**
* メッシュを描画する.
*
* @param buffer 描画に使用するメッシュバッファへのポインタ.
*/
void Mesh::Draw(const BufferPtr& buffer) const
{
if (!buffer) {
return;
}
if (buffer->GetMesh(name.c_str()).get() != this) {
std::cerr << "WARNING: バッファに存在しないメッシュ'" << name << "'を描画しようとしました" << std::endl;
return;
}
for (size_t i = beginMaterial; i < endMaterial; ++i) {
const Material& m = buffer->GetMaterial(i);
glDrawElementsBaseVertex(GL_TRIANGLES, m.size, m.type, m.offset, m.baseVertex);
}
}
/**
* メッシュバッファを作成する.
*
* @param vboSize バッファに格納可能な総頂点数.
* @param iboSize バッファに格納可能な総インデックス数.
*/
BufferPtr Buffer::Create(int vboSize, int iboSize)
{
struct Impl : Buffer {};
BufferPtr p = std::make_shared<Impl>();
p->vbo = CreateVBO(vboSize * sizeof(Vertex), nullptr);
if (!p->vbo) {
return {};
}
p->ibo = CreateIBO(iboSize * sizeof(uint32_t), nullptr);
if (!p->ibo) {
return {};
}
p->vao = CreateVAO(p->vbo, p->ibo);
if (!p->vao) {
return {};
}
p->PushLevel();
return p;
}
/**
* デストラクタ.
*/
Buffer::~Buffer()
{
if (vao) {
glDeleteVertexArrays(1, &vao);
}
if (ibo) {
glDeleteBuffers(1, &ibo);
}
if (vbo) {
glDeleteBuffers(1, &vbo);
}
}
/**
* メッシュをファイルから読み込む.
*
* @param filename メッシュファイル名.
*
* @retval true 読み込み成功.
* @retval false 読み込み失敗.
*/
bool Buffer::LoadMeshFromFile(const char* filename)
{
FbxLoader loader;
if (!loader.Load(filename)) {
return false;
}
Level& level = levelStack.back();
GLint64 vboSize = 0;
GLint64 iboSize = 0;
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glGetBufferParameteri64v(GL_ARRAY_BUFFER, GL_BUFFER_SIZE, &vboSize);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ibo);
glGetBufferParameteri64v(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &iboSize);
for (TemporaryMesh& e : loader.meshList) {
for (TemporaryMaterial& material : e.materialList) {
const GLsizeiptr verticesBytes = material.vertexBuffer.size() * sizeof(Vertex);
if (level.vboEnd + verticesBytes >= vboSize) {
std::cerr << "WARNING: VBOサイズが不足しています(" << level.vboEnd << '/' << vboSize << ')' << std::endl;
continue;
}
const GLsizei indexSize = static_cast<GLsizei>(material.indexBuffer.size());
const GLsizeiptr indicesBytes = indexSize * sizeof(uint32_t);
if (level.iboEnd + indicesBytes >= iboSize) {
std::cerr << "WARNING: IBOサイズが不足しています(" << level.iboEnd << '/' << iboSize << ')' << std::endl;
continue;
}
glBufferSubData(GL_ARRAY_BUFFER, level.vboEnd, verticesBytes, material.vertexBuffer.data());
glBufferSubData(GL_ELEMENT_ARRAY_BUFFER, level.iboEnd, indicesBytes, material.indexBuffer.data());
const GLint baseVertex = static_cast<uint32_t>(level.vboEnd / sizeof(Vertex));
materialList.push_back({ GL_UNSIGNED_INT, indexSize, reinterpret_cast<GLvoid*>(level.iboEnd), baseVertex, material.color });
level.vboEnd += verticesBytes;
level.iboEnd += indicesBytes;
}
struct Impl : public Mesh {
Impl(const std::string& n, size_t b, size_t e) : Mesh(n, b, e) {}
~Impl() {}
};
const size_t endMaterial = materialList.size();
const size_t beginMaterial = endMaterial - e.materialList.size();
level.meshList.insert(std::make_pair(e.name, std::make_shared<Impl>(e.name, beginMaterial, endMaterial)));
}
return true;
}
/**
* メッシュを取得する.
*
* @param name メッシュ名.
*
* @return nameに対応するメッシュへのポインタ.
*/
const MeshPtr& Buffer::GetMesh(const char* name) const
{
/*auto itr = meshList.find(name);
if (itr == meshList.end()) {
static const MeshPtr dummy;
return dummy;
}
return itr->second;*/
for (const auto& e : levelStack) {
auto itr = e.meshList.find(name);
if (itr != e.meshList.end()) {
return itr->second;
}
}
static const MeshPtr dummy;
return dummy;
}
/**
* マテリアルを取得する.
*
* @param index マテリアルインデックス.
*
* @return indexに対応するマテリアル.
*/
const Material& Buffer::GetMaterial(size_t index) const
{
if (index >= materialList.size()) {
static const Material dummy{ GL_UNSIGNED_BYTE, 0, 0, 0, glm::vec4(1) };
return dummy;
}
return materialList[index];
}
/**
* バッファが保持するVAOをOpenGLの処理対象に設定する.
*/
void Buffer::BindVAO() const
{
glBindVertexArray(vao);
}
/**
* スタックに新しいリソースレベルを追加する.
*/
void Buffer::PushLevel()
{
levelStack.push_back(Level());
ClearLevel();
}
/**
* スタックの末尾にあるリソースレベルを除去する.
*/
void Buffer::PopLevel()
{
if (levelStack.size() > minimalStackSize) {
levelStack.pop_back();
}
}
/**
* 末尾のリソースレベルを空の状態にする.
*/
void Buffer::ClearLevel()
{
Level& currentLevel = levelStack.back();
if (levelStack.size() <= minimalStackSize) {
currentLevel.vboEnd = 0;
currentLevel.iboEnd = 0;
}
else {
const Level& prevLevel = levelStack[levelStack.size() - (minimalStackSize + 1)];
currentLevel.vboEnd = prevLevel.vboEnd;
currentLevel.iboEnd = prevLevel.iboEnd;
}
currentLevel.meshList.clear();
}
}
| [
"[email protected]"
] | |
2935e0fc1ac10768d83f32c64628f39bb6e3574d | 18d519c9d80926bac0272f888f78f38ad4136068 | /.c9/metadata/workspace/OJ/sortLinkedlist/main.cpp | f7876b82ddfa0c27cc6eee67c13d8dd1fb41e966 | [] | no_license | Andos25/coding-exercise | 7cad852a8eceb6c3e8d349fbe3cff6be24072cab | 1dc98382b8a530036c2903104410441a37170bad | refs/heads/master | 2021-01-10T21:18:57.833690 | 2015-06-27T03:03:46 | 2015-06-27T03:03:46 | 28,432,146 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,182 | cpp | {"filter":false,"title":"main.cpp","tooltip":"/OJ/sortLinkedlist/main.cpp","undoManager":{"mark":2,"position":2,"stack":[[{"start":{"row":0,"column":0},"end":{"row":59,"column":0},"action":"insert","lines":["#include \"stdafx.h\"","#include <iostream>","","struct ListNode {","\tint val;","\tListNode *next;","\tListNode(int x) : val(x), next(NULL) {}","};","","void insert(ListNode* head, int count, int* value) {","\thead->val = *value++;","\tListNode* now = head;","\twhile (--count) {","\t\tListNode* node = new ListNode(*value++);","\t\tnow->next = node;","\t\tnow = node;","\t}","}","","ListNode* merge(ListNode* head1, ListNode* head2) {","\tListNode dummy(0);","\tListNode* head = &dummy;","\tListNode* now = head;","\twhile (head1 != NULL && head2 != NULL) {","\t\tif (head1->val < head2->val) {","\t\t\tnow->next = head1;","\t\t\tnow = head1;","\t\t\thead1 = head1->next;","\t\t} else {","\t\t\tnow->next = head2;","\t\t\tnow = head2;","\t\t\thead2 = head2->next;","\t\t}","\t}","\tnow->next = head1 == NULL ? head2 : head1;","\treturn head->next;","}","","ListNode* sortList(ListNode* head) {","\tif (head == NULL || head->next == NULL) ","\t\treturn head;","\tListNode* middle = head;","\tListNode* end = head->next;","\twhile (end != NULL && end->next != NULL) {","\t\tmiddle = middle->next;","\t\tend = end->next->next;","\t}","\tend = middle->next;","\tmiddle->next = NULL;","\treturn merge(sortList(head), sortList(end));","}","","int _tmain(int argc, _TCHAR* argv[]) {","\tint a[] = { 5, 4, 3, 2, 1, 0 };","\tListNode *head = new ListNode(0);","\tinsert(head, 6, a);","\tListNode* newlist = sortList(head);","\treturn 0;","}",""],"id":1}],[{"start":{"row":0,"column":0},"end":{"row":0,"column":19},"action":"remove","lines":["#include \"stdafx.h\""],"id":2}],[{"start":{"row":0,"column":0},"end":{"row":1,"column":0},"action":"remove","lines":["",""],"id":3}]]},"ace":{"folds":[],"scrolltop":0,"scrollleft":0,"selection":{"start":{"row":7,"column":0},"end":{"row":7,"column":0},"isBackwards":false},"options":{"guessTabSize":true,"useWrapMode":false,"wrapToView":true},"firstLineState":0},"timestamp":1435233634552,"hash":"54c015cc0dc388292e2f934fa9c5d30471da6d8c"} | [
"[email protected]"
] | |
46220852d2d42a9a4f56290d34827cfc12342eb0 | cb305a34679fb6e33e7fab3d2477e3eaba29a70a | /system/include/libcxx/__split_buffer | d5b8f0a3ee2c2c2e2e934dbac7aa3fc0b0db6f3f | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] | permissive | juj/emscripten | b40925151a4c1a8b2954816708ffed2165c3bf5b | b22df433afe8c262ec190e595a5c8eb299850460 | refs/heads/master | 2023-08-31T00:57:31.708054 | 2012-04-26T18:05:37 | 2012-04-26T18:05:37 | 4,149,606 | 10 | 2 | NOASSERTION | 2022-11-17T13:11:25 | 2012-04-26T16:19:07 | JavaScript | UTF-8 | C++ | false | false | 22,593 | // -*- C++ -*-
#ifndef _LIBCPP_SPLIT_BUFFER
#define _LIBCPP_SPLIT_BUFFER
#include <__config>
#include <type_traits>
#include <algorithm>
#pragma GCC system_header
_LIBCPP_BEGIN_NAMESPACE_STD
template <bool>
class __split_buffer_common
{
protected:
void __throw_length_error() const;
void __throw_out_of_range() const;
};
template <class _Tp, class _Allocator = allocator<_Tp> >
struct __split_buffer
: private __split_buffer_common<true>
{
private:
__split_buffer(const __split_buffer&);
__split_buffer& operator=(const __split_buffer&);
public:
typedef _Tp value_type;
typedef _Allocator allocator_type;
typedef typename remove_reference<allocator_type>::type __alloc_rr;
typedef allocator_traits<__alloc_rr> __alloc_traits;
typedef value_type& reference;
typedef const value_type& const_reference;
typedef typename __alloc_traits::size_type size_type;
typedef typename __alloc_traits::difference_type difference_type;
typedef typename __alloc_traits::pointer pointer;
typedef typename __alloc_traits::const_pointer const_pointer;
typedef pointer iterator;
typedef const_pointer const_iterator;
pointer __first_;
pointer __begin_;
pointer __end_;
__compressed_pair<pointer, allocator_type> __end_cap_;
typedef typename add_lvalue_reference<allocator_type>::type __alloc_ref;
typedef typename add_lvalue_reference<allocator_type>::type __alloc_const_ref;
_LIBCPP_INLINE_VISIBILITY __alloc_rr& __alloc() _NOEXCEPT {return __end_cap_.second();}
_LIBCPP_INLINE_VISIBILITY const __alloc_rr& __alloc() const _NOEXCEPT {return __end_cap_.second();}
_LIBCPP_INLINE_VISIBILITY pointer& __end_cap() _NOEXCEPT {return __end_cap_.first();}
_LIBCPP_INLINE_VISIBILITY const pointer& __end_cap() const _NOEXCEPT {return __end_cap_.first();}
__split_buffer()
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value);
explicit __split_buffer(__alloc_rr& __a);
explicit __split_buffer(const __alloc_rr& __a);
__split_buffer(size_type __cap, size_type __start, __alloc_rr& __a);
~__split_buffer();
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
__split_buffer(__split_buffer&& __c)
_NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value);
__split_buffer(__split_buffer&& __c, const __alloc_rr& __a);
__split_buffer& operator=(__split_buffer&& __c)
_NOEXCEPT_((__alloc_traits::propagate_on_container_move_assignment::value &&
is_nothrow_move_assignable<allocator_type>::value) ||
!__alloc_traits::propagate_on_container_move_assignment::value);
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
_LIBCPP_INLINE_VISIBILITY iterator begin() _NOEXCEPT {return __begin_;}
_LIBCPP_INLINE_VISIBILITY const_iterator begin() const _NOEXCEPT {return __begin_;}
_LIBCPP_INLINE_VISIBILITY iterator end() _NOEXCEPT {return __end_;}
_LIBCPP_INLINE_VISIBILITY const_iterator end() const _NOEXCEPT {return __end_;}
_LIBCPP_INLINE_VISIBILITY
void clear() _NOEXCEPT
{__destruct_at_end(__begin_);}
_LIBCPP_INLINE_VISIBILITY size_type size() const {return static_cast<size_type>(__end_ - __begin_);}
_LIBCPP_INLINE_VISIBILITY bool empty() const {return __end_ == __begin_;}
_LIBCPP_INLINE_VISIBILITY size_type capacity() const {return static_cast<size_type>(__end_cap() - __first_);}
_LIBCPP_INLINE_VISIBILITY size_type __front_spare() const {return static_cast<size_type>(__begin_ - __first_);}
_LIBCPP_INLINE_VISIBILITY size_type __back_spare() const {return static_cast<size_type>(__end_cap() - __end_);}
_LIBCPP_INLINE_VISIBILITY reference front() {return *__begin_;}
_LIBCPP_INLINE_VISIBILITY const_reference front() const {return *__begin_;}
_LIBCPP_INLINE_VISIBILITY reference back() {return *(__end_ - 1);}
_LIBCPP_INLINE_VISIBILITY const_reference back() const {return *(__end_ - 1);}
void reserve(size_type __n);
void shrink_to_fit() _NOEXCEPT;
void push_front(const_reference __x);
void push_back(const_reference __x);
#if !defined(_LIBCPP_HAS_NO_RVALUE_REFERENCES)
void push_front(value_type&& __x);
void push_back(value_type&& __x);
#if !defined(_LIBCPP_HAS_NO_VARIADICS)
template <class... _Args>
void emplace_back(_Args&&... __args);
#endif // !defined(_LIBCPP_HAS_NO_VARIADICS)
#endif // !defined(_LIBCPP_HAS_NO_RVALUE_REFERENCES)
_LIBCPP_INLINE_VISIBILITY void pop_front() {__destruct_at_begin(__begin_+1);}
_LIBCPP_INLINE_VISIBILITY void pop_back() {__destruct_at_end(__end_-1);}
void __construct_at_end(size_type __n);
void __construct_at_end(size_type __n, const_reference __x);
template <class _InputIter>
typename enable_if
<
__is_input_iterator<_InputIter>::value &&
!__is_forward_iterator<_InputIter>::value,
void
>::type
__construct_at_end(_InputIter __first, _InputIter __last);
template <class _ForwardIterator>
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value,
void
>::type
__construct_at_end(_ForwardIterator __first, _ForwardIterator __last);
_LIBCPP_INLINE_VISIBILITY void __destruct_at_begin(pointer __new_begin)
{__destruct_at_begin(__new_begin, is_trivially_destructible<value_type>());}
void __destruct_at_begin(pointer __new_begin, false_type);
void __destruct_at_begin(pointer __new_begin, true_type);
_LIBCPP_INLINE_VISIBILITY
void __destruct_at_end(pointer __new_last) _NOEXCEPT
{__destruct_at_end(__new_last, is_trivially_destructible<value_type>());}
void __destruct_at_end(pointer __new_last, false_type) _NOEXCEPT;
void __destruct_at_end(pointer __new_last, true_type) _NOEXCEPT;
void swap(__split_buffer& __x)
_NOEXCEPT_(!__alloc_traits::propagate_on_container_swap::value||
__is_nothrow_swappable<__alloc_rr>::value);
bool __invariants() const;
private:
_LIBCPP_INLINE_VISIBILITY
void __move_assign_alloc(__split_buffer& __c, true_type)
_NOEXCEPT_(is_nothrow_move_assignable<allocator_type>::value)
{
__alloc() = _VSTD::move(__c.__alloc());
}
_LIBCPP_INLINE_VISIBILITY
void __move_assign_alloc(__split_buffer& __c, false_type) _NOEXCEPT
{}
_LIBCPP_INLINE_VISIBILITY
static void __swap_alloc(__alloc_rr& __x, __alloc_rr& __y)
_NOEXCEPT_(!__alloc_traits::propagate_on_container_swap::value||
__is_nothrow_swappable<__alloc_rr>::value)
{__swap_alloc(__x, __y, integral_constant<bool,
__alloc_traits::propagate_on_container_swap::value>());}
_LIBCPP_INLINE_VISIBILITY
static void __swap_alloc(__alloc_rr& __x, __alloc_rr& __y, true_type)
_NOEXCEPT_(__is_nothrow_swappable<__alloc_rr>::value)
{
using _VSTD::swap;
swap(__x, __y);
}
_LIBCPP_INLINE_VISIBILITY
static void __swap_alloc(__alloc_rr& __x, __alloc_rr& __y, false_type) _NOEXCEPT
{}
};
template <class _Tp, class _Allocator>
bool
__split_buffer<_Tp, _Allocator>::__invariants() const
{
if (__first_ == nullptr)
{
if (__begin_ != nullptr)
return false;
if (__end_ != nullptr)
return false;
if (__end_cap() != nullptr)
return false;
}
else
{
if (__begin_ < __first_)
return false;
if (__end_ < __begin_)
return false;
if (__end_cap() < __end_)
return false;
}
return true;
}
// Default constructs __n objects starting at __end_
// throws if construction throws
// Precondition: __n > 0
// Precondition: size() + __n <= capacity()
// Postcondition: size() == size() + __n
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::__construct_at_end(size_type __n)
{
__alloc_rr& __a = this->__alloc();
do
{
__alloc_traits::construct(__a, _VSTD::__to_raw_pointer(this->__end_));
++this->__end_;
--__n;
} while (__n > 0);
}
// Copy constructs __n objects starting at __end_ from __x
// throws if construction throws
// Precondition: __n > 0
// Precondition: size() + __n <= capacity()
// Postcondition: size() == old size() + __n
// Postcondition: [i] == __x for all i in [size() - __n, __n)
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::__construct_at_end(size_type __n, const_reference __x)
{
__alloc_rr& __a = this->__alloc();
do
{
__alloc_traits::construct(__a, _VSTD::__to_raw_pointer(this->__end_), __x);
++this->__end_;
--__n;
} while (__n > 0);
}
template <class _Tp, class _Allocator>
template <class _InputIter>
typename enable_if
<
__is_input_iterator<_InputIter>::value &&
!__is_forward_iterator<_InputIter>::value,
void
>::type
__split_buffer<_Tp, _Allocator>::__construct_at_end(_InputIter __first, _InputIter __last)
{
__alloc_rr& __a = this->__alloc();
for (; __first != __last; ++__first)
{
if (__end_ == __end_cap())
{
size_type __old_cap = __end_cap() - __first_;
size_type __new_cap = _VSTD::max<size_type>(2 * __old_cap, 8);
__split_buffer __buf(__new_cap, 0, __a);
for (pointer __p = __begin_; __p != __end_; ++__p, ++__buf.__end_)
__alloc_traits::construct(__buf.__alloc(),
_VSTD::__to_raw_pointer(__buf.__end_), _VSTD::move(*__p));
swap(__buf);
}
__alloc_traits::construct(__a, _VSTD::__to_raw_pointer(this->__end_), *__first);
++this->__end_;
}
}
template <class _Tp, class _Allocator>
template <class _ForwardIterator>
typename enable_if
<
__is_forward_iterator<_ForwardIterator>::value,
void
>::type
__split_buffer<_Tp, _Allocator>::__construct_at_end(_ForwardIterator __first, _ForwardIterator __last)
{
__alloc_rr& __a = this->__alloc();
for (; __first != __last; ++__first)
{
__alloc_traits::construct(__a, _VSTD::__to_raw_pointer(this->__end_), *__first);
++this->__end_;
}
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
__split_buffer<_Tp, _Allocator>::__destruct_at_begin(pointer __new_begin, false_type)
{
while (__begin_ < __new_begin)
__alloc_traits::destroy(__alloc(), __begin_++);
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
__split_buffer<_Tp, _Allocator>::__destruct_at_begin(pointer __new_begin, true_type)
{
__begin_ = __new_begin;
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
__split_buffer<_Tp, _Allocator>::__destruct_at_end(pointer __new_last, false_type) _NOEXCEPT
{
while (__new_last < __end_)
__alloc_traits::destroy(__alloc(), --__end_);
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
__split_buffer<_Tp, _Allocator>::__destruct_at_end(pointer __new_last, true_type) _NOEXCEPT
{
__end_ = __new_last;
}
template <class _Tp, class _Allocator>
__split_buffer<_Tp, _Allocator>::__split_buffer(size_type __cap, size_type __start, __alloc_rr& __a)
: __end_cap_(0, __a)
{
__first_ = __cap != 0 ? __alloc_traits::allocate(__alloc(), __cap) : nullptr;
__begin_ = __end_ = __first_ + __start;
__end_cap() = __first_ + __cap;
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
__split_buffer<_Tp, _Allocator>::__split_buffer()
_NOEXCEPT_(is_nothrow_default_constructible<allocator_type>::value)
: __first_(0), __begin_(0), __end_(0), __end_cap_(0)
{
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
__split_buffer<_Tp, _Allocator>::__split_buffer(__alloc_rr& __a)
: __first_(0), __begin_(0), __end_(0), __end_cap_(0, __a)
{
}
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
__split_buffer<_Tp, _Allocator>::__split_buffer(const __alloc_rr& __a)
: __first_(0), __begin_(0), __end_(0), __end_cap_(0, __a)
{
}
template <class _Tp, class _Allocator>
__split_buffer<_Tp, _Allocator>::~__split_buffer()
{
clear();
if (__first_)
__alloc_traits::deallocate(__alloc(), __first_, capacity());
}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
__split_buffer<_Tp, _Allocator>::__split_buffer(__split_buffer&& __c)
_NOEXCEPT_(is_nothrow_move_constructible<allocator_type>::value)
: __first_(_VSTD::move(__c.__first_)),
__begin_(_VSTD::move(__c.__begin_)),
__end_(_VSTD::move(__c.__end_)),
__end_cap_(_VSTD::move(__c.__end_cap_))
{
__c.__first_ = nullptr;
__c.__begin_ = nullptr;
__c.__end_ = nullptr;
__c.__end_cap() = nullptr;
}
template <class _Tp, class _Allocator>
__split_buffer<_Tp, _Allocator>::__split_buffer(__split_buffer&& __c, const __alloc_rr& __a)
: __end_cap_(__a)
{
if (__a == __c.__alloc())
{
__first_ = __c.__first_;
__begin_ = __c.__begin_;
__end_ = __c.__end_;
__end_cap() = __c.__end_cap();
__c.__first_ = nullptr;
__c.__begin_ = nullptr;
__c.__end_ = nullptr;
__c.__end_cap() = nullptr;
}
else
{
size_type __cap = __c.size();
__first_ = __alloc_traits::allocate(__alloc(), __cap);
__begin_ = __end_ = __first_;
__end_cap() = __first_ + __cap;
typedef move_iterator<iterator> _I;
__construct_at_end(_I(__c.begin()), _I(__c.end()));
}
}
template <class _Tp, class _Allocator>
__split_buffer<_Tp, _Allocator>&
__split_buffer<_Tp, _Allocator>::operator=(__split_buffer&& __c)
_NOEXCEPT_((__alloc_traits::propagate_on_container_move_assignment::value &&
is_nothrow_move_assignable<allocator_type>::value) ||
!__alloc_traits::propagate_on_container_move_assignment::value)
{
clear();
shrink_to_fit();
__first_ = __c.__first_;
__begin_ = __c.__begin_;
__end_ = __c.__end_;
__end_cap() = __c.__end_cap();
__move_assign_alloc(__c,
integral_constant<bool,
__alloc_traits::propagate_on_container_move_assignment::value>());
__c.__first_ = __c.__begin_ = __c.__end_ = __c.__end_cap() = nullptr;
return *this;
}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::swap(__split_buffer& __x)
_NOEXCEPT_(!__alloc_traits::propagate_on_container_swap::value||
__is_nothrow_swappable<__alloc_rr>::value)
{
_VSTD::swap(__first_, __x.__first_);
_VSTD::swap(__begin_, __x.__begin_);
_VSTD::swap(__end_, __x.__end_);
_VSTD::swap(__end_cap(), __x.__end_cap());
__swap_alloc(__alloc(), __x.__alloc());
}
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::reserve(size_type __n)
{
if (__n < capacity())
{
__split_buffer<value_type, __alloc_rr&> __t(__n, 0, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::shrink_to_fit() _NOEXCEPT
{
if (capacity() > size())
{
#ifndef _LIBCPP_NO_EXCEPTIONS
try
{
#endif // _LIBCPP_NO_EXCEPTIONS
__split_buffer<value_type, __alloc_rr&> __t(size(), 0, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
__t.__end_ = __t.__begin_ + (__end_ - __begin_);
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
#ifndef _LIBCPP_NO_EXCEPTIONS
}
catch (...)
{
}
#endif // _LIBCPP_NO_EXCEPTIONS
}
}
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::push_front(const_reference __x)
{
if (__begin_ == __first_)
{
if (__end_ < __end_cap())
{
difference_type __d = __end_cap() - __end_;
__d = (__d + 1) / 2;
__begin_ = _VSTD::move_backward(__begin_, __end_, __end_ + __d);
__end_ += __d;
}
else
{
size_type __c = max<size_type>(2 * (__end_cap() - __first_), 1);
__split_buffer<value_type, __alloc_rr&> __t(__c, (__c + 3) / 4, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
__alloc_traits::construct(__alloc(), _VSTD::__to_raw_pointer(__begin_-1), __x);
--__begin_;
}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::push_front(value_type&& __x)
{
if (__begin_ == __first_)
{
if (__end_ < __end_cap())
{
difference_type __d = __end_cap() - __end_;
__d = (__d + 1) / 2;
__begin_ = _VSTD::move_backward(__begin_, __end_, __end_ + __d);
__end_ += __d;
}
else
{
size_type __c = max<size_type>(2 * (__end_cap() - __first_), 1);
__split_buffer<value_type, __alloc_rr&> __t(__c, (__c + 3) / 4, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
__alloc_traits::construct(__alloc(), _VSTD::__to_raw_pointer(__begin_-1),
_VSTD::move(__x));
--__begin_;
}
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
__split_buffer<_Tp, _Allocator>::push_back(const_reference __x)
{
if (__end_ == __end_cap())
{
if (__begin_ > __first_)
{
difference_type __d = __begin_ - __first_;
__d = (__d + 1) / 2;
__end_ = _VSTD::move(__begin_, __end_, __begin_ - __d);
__begin_ -= __d;
}
else
{
size_type __c = max<size_type>(2 * (__end_cap() - __first_), 1);
__split_buffer<value_type, __alloc_rr&> __t(__c, __c / 4, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
__alloc_traits::construct(__alloc(), _VSTD::__to_raw_pointer(__end_), __x);
++__end_;
}
#ifndef _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
void
__split_buffer<_Tp, _Allocator>::push_back(value_type&& __x)
{
if (__end_ == __end_cap())
{
if (__begin_ > __first_)
{
difference_type __d = __begin_ - __first_;
__d = (__d + 1) / 2;
__end_ = _VSTD::move(__begin_, __end_, __begin_ - __d);
__begin_ -= __d;
}
else
{
size_type __c = max<size_type>(2 * (__end_cap() - __first_), 1);
__split_buffer<value_type, __alloc_rr&> __t(__c, __c / 4, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
__alloc_traits::construct(__alloc(), _VSTD::__to_raw_pointer(__end_),
_VSTD::move(__x));
++__end_;
}
#ifndef _LIBCPP_HAS_NO_VARIADICS
template <class _Tp, class _Allocator>
template <class... _Args>
void
__split_buffer<_Tp, _Allocator>::emplace_back(_Args&&... __args)
{
if (__end_ == __end_cap())
{
if (__begin_ > __first_)
{
difference_type __d = __begin_ - __first_;
__d = (__d + 1) / 2;
__end_ = _VSTD::move(__begin_, __end_, __begin_ - __d);
__begin_ -= __d;
}
else
{
size_type __c = max<size_type>(2 * (__end_cap() - __first_), 1);
__split_buffer<value_type, __alloc_rr&> __t(__c, __c / 4, __alloc());
__t.__construct_at_end(move_iterator<pointer>(__begin_),
move_iterator<pointer>(__end_));
_VSTD::swap(__first_, __t.__first_);
_VSTD::swap(__begin_, __t.__begin_);
_VSTD::swap(__end_, __t.__end_);
_VSTD::swap(__end_cap(), __t.__end_cap());
}
}
__alloc_traits::construct(__alloc(), _VSTD::__to_raw_pointer(__end_),
_VSTD::forward<_Args>(__args)...);
++__end_;
}
#endif // _LIBCPP_HAS_NO_VARIADICS
#endif // _LIBCPP_HAS_NO_RVALUE_REFERENCES
template <class _Tp, class _Allocator>
_LIBCPP_INLINE_VISIBILITY inline
void
swap(__split_buffer<_Tp, _Allocator>& __x, __split_buffer<_Tp, _Allocator>& __y)
_NOEXCEPT_(_NOEXCEPT_(__x.swap(__y)))
{
__x.swap(__y);
}
_LIBCPP_END_NAMESPACE_STD
#endif // _LIBCPP_SPLIT_BUFFER
| [
"[email protected]"
] | ||
3ee760cc7254a4b123f415182c1dbc0785fff69d | 7740e4a895bfce4567d4ce425bc50158bf91ca09 | /src/system/lua/statemachine.cpp | 38cc6952874188a6ee3ca224c8622c29cbd1176b | [] | no_license | naelstrof/Syme | 193b376d3a01c48a952c8a3ec8d593098085ddf4 | 690651620754d9f5f2741d476635ebcb653e2e18 | refs/heads/master | 2021-01-23T13:49:17.577841 | 2014-04-16T23:03:42 | 2014-04-16T23:03:42 | 14,884,903 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 340 | cpp | #include "statemachine.hpp"
int lua_setState( lua_State* l ) {
std::string statename = lua_tostring( l, -1 );
statemachine->setState( statename );
as::printf( "Switching to state %\n", statename );
return 0;
}
int lua_registerstatemachine( lua_State* l ) {
lua_register( l, "setState", lua_setState );
return 0;
}
| [
"[email protected]"
] | |
e8e6afd72a8672e12b999e0ab347e7ad2d12418f | 183d30ccc4bb09cc89aaacbce9258a73c96d838f | /StandAloneAveDesk/AveInstUnloadLanguage.h | 66e0ccca74615d691d4a7356a8b412e86f1c40b1 | [] | no_license | jackiejohn/AveDesk | 6efaa73d6ccd67845eb6f6954a63f412993edbef | 8f201dc1e14f65ddcfd1f9d281379f347ed22469 | refs/heads/master | 2021-05-27T17:50:41.693612 | 2015-02-21T15:35:43 | 2015-02-21T15:35:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 751 | h | // AveInstUnloadLanguage.h: interface for the CAveInstUnloadLanguage class.
//
//////////////////////////////////////////////////////////////////////
#if !defined(AFX_AVEINSTUNLOADLANGUAGE_H__A5BC7ABA_011B_4421_BE82_1C106C2E0FA8__INCLUDED_)
#define AFX_AVEINSTUNLOADLANGUAGE_H__A5BC7ABA_011B_4421_BE82_1C106C2E0FA8__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include "AveInstAction.h"
class CAveInstUnloadLanguage : public CAveInstAction
{
public:
CAveInstUnloadLanguage();
virtual ~CAveInstUnloadLanguage();
virtual HRESULT LoadFromNode(XMLNode& node);
virtual HRESULT DoAction(CAveInstallerEnvironment& env);
};
#endif // !defined(AFX_AVEINSTUNLOADLANGUAGE_H__A5BC7ABA_011B_4421_BE82_1C106C2E0FA8__INCLUDED_)
| [
"[email protected]"
] | |
7746181a6a4535e832716436c0766ad32abeb766 | e9c4865fc9faf8f64b03aedd7a15fc4563e1148a | /Lolcat.h | cdecc34d52fe964a3cab7be6e21f40bbbff018e6 | [
"MIT"
] | permissive | nifty-site-manager/nsm | 937fa23d06997928ce4a642731206a1565f8252f | 9497b4f3088a5cfae770b24c220ac4a5cc1e2fc0 | refs/heads/master | 2023-07-09T04:00:35.802486 | 2023-07-08T18:17:44 | 2023-07-08T18:17:44 | 33,808,116 | 265 | 23 | MIT | 2022-09-23T07:21:14 | 2015-04-12T07:50:36 | C | UTF-8 | C++ | false | false | 760 | h | #ifndef LOLCAT_H_
#define LOLCAT_H_
#include <cstdio>
#include <iostream>
#include <fstream>
#include <cmath>
#include <math.h>
#include <sstream>
#include <time.h>
#include "FileSystem.h"
#if defined _WIN32 || defined _WIN64
#include <vector>
#include <Windows.h>
//defined in ConsoleColor.h
//const HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
struct WinLolcatColor
{
int col;
WinLolcatColor(const int& Col);
WinLolcatColor(const int& foreground, const int& background);
};
std::ostream& operator<<(std::ostream& os, const WinLolcatColor& cc);
void lolcat_powershell();
#else //*nix
#endif
int lolcat(std::istream& is);
int lolfilter(std::istream &is);
int lolmain(const int& argc, const char* argv[]);
#endif //LOLCAT_H_
| [
"[email protected]"
] | |
11898688055bbbee693b7967edc645edf678fa8a | 9439733c1fa7689ec711b6e71d960e260b30e724 | /utils/dynamic_array.test.cc | 92433a76bf251983e0bfad1218f46329bfac5888 | [] | no_license | bobstine/lang_C | 65a75951b450bee92ca2e411f20be961b660c2e6 | dfe3411ffe5aa4389b6c43baced1bb974de7b995 | refs/heads/master | 2020-05-31T00:09:18.192842 | 2020-04-20T18:21:03 | 2020-04-20T18:21:03 | 190,020,135 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,259 | cc | #include "dynamic_array.h"
#include <iostream>
#include <vector>
int
main()
{
{
int first = 10;
int last = 21;
DynamicArrayBase<double> dab (first, last);
for (int i=first; i<= last; ++i) dab.assign(i, (double)i);
std::cout << "dab[first]=" << dab[first] << " dab[15]=" << dab[15] <<std::endl;
std::cout << dab << std::endl;
}
{
int first = 5;
int last = 21;
DynamicArray<double> da (first, last);
for (int i=first; i<= last; ++i) da.assign(i, (double)i);
std::cout << "da[first]=" << da[first] << " da[15]=" << da[15] <<std::endl;
std::cout << da << std::endl;
}
{
int first = -10;
int last = 14;
DynamicArray<double> da (first, last);
DynamicArray<double> da3 (first, last);
for (int i=first; i<= last; ++i) da.assign(i, (double)i);
{
std::vector< DynamicArray<double> > x;
x.push_back(da);
x.push_back(da3);
x.push_back(da);
std::cout << "TEST: DA after 3 pushed on vector: " << da << std::endl;
}
std::cout << "TEST: DA after vector out of scope: " << da << std::endl;
DynamicArray<double> da2 (da);
std::cout << "TEST: DA2 after copy construct vector: " << da2 << std::endl;
}
return 0;
}
| [
"[email protected]"
] | |
6980f9b3c443f5ea35fa9e48687bea8abd736392 | d1007cc6f2274973f2ce37d08ec0921675019e2a | /cpp/vector_map.cpp | 7e7c34f1e7d2fcd8d2d164da4ccfbfd73410823c | [] | no_license | zhiyu-he/programing_language | deffd214f45669ef6ec57d5a615e6a00c14b38cd | 3e6b309c1d629cf101992a41c4017e498ac392d5 | refs/heads/master | 2021-01-10T01:44:23.620747 | 2019-08-13T06:08:59 | 2019-08-13T06:08:59 | 50,972,834 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 629 | cpp | #include <iostream>
#include <vector>
#include <unordered_map>
int main()
{
std::vector<std::string> v = {"str1", "str2"};
v.push_back("str3");
for(std::string str : v) {
std::cout << str << '\n';
}
std::unordered_map<std::string, std::string> m = {
{"key1", "val1"},
{"key2", "val2"}
};
m["key3"] = "val3";
for(auto& n : m) {
std::cout << "key: [" << n.first << "] Value: [" << n.second << "]\n";
}
auto target = m.find("keyn");
if (target != m.end()) {
std::cout << "Found" << '\n';
} else {
std::cout << "Not Found\n";
}
}
| [
"[email protected]"
] | |
febe939a176813d2a8b24225eaf831d1cca7b499 | 29949244b89ed4eb4a79f228f674c56896b1017f | /牛客-米哈游-字符串正则匹配/Test.cpp | 56f768a2f765849926bd2d1ec2f154d79c9832eb | [] | no_license | SJRLL/niukewang | 8c820be2e42276c3e82ad0185da6cabc863d00dd | 947410803903790f67a018650e7469f7557f1047 | refs/heads/master | 2021-07-22T17:03:45.435420 | 2020-09-19T13:39:43 | 2020-09-19T13:39:43 | 217,432,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,040 | cpp | #include<iostream>
#include<vector>
#include<string>
#include<stdlib.h>
using namespace std;
bool isMatch(string s1, string s2)
{
int ls = s1.size(), lp = s2.size();
vector<vector<int>> dp(ls + 1, vector<int>(lp + 1, 0));
dp[0][0] = 1;
int flag = 1;
for (int j = 0; j<lp; ++j)
{
if (j >= 1 && s2[j - 1] != '*' && s2[j] != '*')
{
flag = 0;
}
if (s2[j] == '*')
{
dp[0][j + 1] = flag;
}
}
for (int i = 0; i<ls; ++i)
{
for (int j = 0; j<lp; ++j)
{
if (s1[i] == s2[j] || s2[j] == '.')
{
dp[i + 1][j + 1] = dp[i][j];
}
else if (s2[j] == '*')
{
if (s2[j - 1] != s1[i] && s2[j - 1] != '.')
{
dp[i + 1][j + 1] = dp[i + 1][j - 1];
}
else
{
dp[i + 1][j + 1] = dp[i + 1][j - 1] || dp[i + 1][j] || dp[i][j + 1];
}
}
}
}
return dp[ls][lp];
}
int main()
{
string s1;
string s2;
cin >> s1;
cin >> s2;
int res;
res = isMatch(s1, s2);
if (res == 1)
{
cout <<"true" << endl;
}
else
{
cout << "false" << endl;
}
system("pause");
return 0;
} | [
"[email protected]"
] | |
b701b386a56632e49a58e529271649bd418aaa65 | 3054ded5d75ec90aac29ca5d601e726cf835f76c | /Contests/CodeChef/June 18/LoC June 18/Chef And Strings.cpp | 900ea512b1e70fd56f6cefd59e5d9cad4aa75085 | [] | no_license | Yefri97/Competitive-Programming | ef8c5806881bee797deeb2ef12416eee83c03add | 2b267ded55d94c819e720281805fb75696bed311 | refs/heads/master | 2022-11-09T20:19:00.983516 | 2022-04-29T21:29:45 | 2022-04-29T21:29:45 | 60,136,956 | 10 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,071 | cpp | #include <bits/stdc++.h>
#define endl '\n'
#define debug(X) cout << #X << " = " << X << endl
#define fori(i,b,e) for (int i = (b); i < (e); ++i)
using namespace std;
typedef long long ll;
typedef vector<int> vi;
typedef pair<int, int> ii;
const int oo = 1e9, MN = 100010;
char ch[MN];
int l[MN], r[MN], p[MN];
int curr[26], freq[26][MN];
bool cmp(int a, int b) { return p[a] < p[b]; }
int main() {
ios_base::sync_with_stdio(false); cin.tie(0);
int n; cin >> n;
vector<string> vs(n);
fori(i, 0, n)
cin >> vs[i];
int m; cin >> m;
fori(i, 0, m)
cin >> l[i] >> r[i] >> p[i] >> ch[i];
vi q(m);
fori(i, 0, m) q[i] = i;
sort(q.begin(), q.end(), cmp);
fori(i, 0, m) p[i]--;
memset(curr, -1, sizeof curr);
vi ans(m);
fori(i, 0, m) {
int x = q[i], c = ch[x] - 'a';
if (curr[c] != p[x]) {
fori(i, 0, n)
freq[c][i + 1] = (p[x] < vs[i].size() && vs[i][p[x]] == ch[x]);
fori(i, 1, n + 1)
freq[c][i] += freq[c][i - 1];
curr[c] = p[x];
}
ans[x] = freq[c][r[x]] - freq[c][l[x] - 1];
}
fori(i, 0, m)
cout << ans[i] << endl;
return 0;
}
| [
"[email protected]"
] | |
cb52f6f906f8dd4ce8da818fb38d1acd33eabff8 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /chrome/browser/extensions/permission_message_combinations_unittest.cc | 2f800e4bcc3b04e4498c6697f44b222a3ac49300 | [
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 40,321 | 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 <memory>
#include "base/command_line.h"
#include "base/macros.h"
#include "base/strings/stringprintf.h"
#include "base/test/values_test_util.h"
#include "chrome/browser/extensions/test_extension_environment.h"
#include "chrome/common/extensions/permissions/chrome_permission_message_provider.h"
#include "components/version_info/version_info.h"
#include "extensions/common/extension.h"
#include "extensions/common/features/feature_channel.h"
#include "extensions/common/features/simple_feature.h"
#include "extensions/common/permissions/permission_message_test_util.h"
#include "extensions/common/permissions/permissions_data.h"
#include "extensions/common/switches.h"
#include "testing/gmock/include/gmock/gmock-matchers.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace extensions {
const char kAllowlistedExtensionID[] = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
// Tests that ChromePermissionMessageProvider produces the expected messages for
// various combinations of app/extension permissions.
class PermissionMessageCombinationsUnittest : public testing::Test {
public:
PermissionMessageCombinationsUnittest()
: message_provider_(new ChromePermissionMessageProvider()),
allowlisted_extension_id_(kAllowlistedExtensionID) {}
~PermissionMessageCombinationsUnittest() override {}
// Overridden from testing::Test:
void SetUp() override {
testing::Test::SetUp();
}
protected:
// Create and install an app or extension with the given manifest JSON string.
// Single-quotes in the string will be replaced with double quotes.
void CreateAndInstall(const std::string& json_manifest) {
std::string json_manifest_with_double_quotes = json_manifest;
std::replace(json_manifest_with_double_quotes.begin(),
json_manifest_with_double_quotes.end(), '\'', '"');
app_ = env_.MakeExtension(
*base::test::ParseJsonDeprecated(json_manifest_with_double_quotes),
kAllowlistedExtensionID);
}
// Checks whether the currently installed app or extension produces the given
// permission messages. Call this after installing an app with the expected
// permission messages. The messages are tested for existence in any order.
testing::AssertionResult CheckManifestProducesPermissions() {
return VerifyNoPermissionMessages(app_->permissions_data());
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1) {
return VerifyOnePermissionMessage(app_->permissions_data(),
expected_message_1);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::string& expected_message_2) {
return VerifyTwoPermissionMessages(app_->permissions_data(),
expected_message_1, expected_message_2,
false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::string& expected_message_2,
const std::string& expected_message_3) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
return VerifyPermissionMessages(app_->permissions_data(), expected_messages,
false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::string& expected_message_2,
const std::string& expected_message_3,
const std::string& expected_message_4) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
expected_messages.push_back(expected_message_4);
return VerifyPermissionMessages(app_->permissions_data(), expected_messages,
false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::string& expected_message_2,
const std::string& expected_message_3,
const std::string& expected_message_4,
const std::string& expected_message_5) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
expected_messages.push_back(expected_message_4);
expected_messages.push_back(expected_message_5);
return VerifyPermissionMessages(app_->permissions_data(), expected_messages,
false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::vector<std::string>& expected_submessages_1) {
return VerifyOnePermissionMessageWithSubmessages(
app_->permissions_data(), expected_message_1, expected_submessages_1);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::vector<std::string>& expected_submessages_1,
const std::string& expected_message_2,
const std::vector<std::string>& expected_submessages_2) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
std::vector<std::vector<std::string>> expected_submessages;
expected_submessages.push_back(expected_submessages_1);
expected_submessages.push_back(expected_submessages_2);
return VerifyPermissionMessagesWithSubmessages(app_->permissions_data(),
expected_messages,
expected_submessages, false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::vector<std::string>& expected_submessages_1,
const std::string& expected_message_2,
const std::vector<std::string>& expected_submessages_2,
const std::string& expected_message_3,
const std::vector<std::string>& expected_submessages_3) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
std::vector<std::vector<std::string>> expected_submessages;
expected_submessages.push_back(expected_submessages_1);
expected_submessages.push_back(expected_submessages_2);
expected_submessages.push_back(expected_submessages_3);
return VerifyPermissionMessagesWithSubmessages(app_->permissions_data(),
expected_messages,
expected_submessages, false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::vector<std::string>& expected_submessages_1,
const std::string& expected_message_2,
const std::vector<std::string>& expected_submessages_2,
const std::string& expected_message_3,
const std::vector<std::string>& expected_submessages_3,
const std::string& expected_message_4,
const std::vector<std::string>& expected_submessages_4) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
expected_messages.push_back(expected_message_4);
std::vector<std::vector<std::string>> expected_submessages;
expected_submessages.push_back(expected_submessages_1);
expected_submessages.push_back(expected_submessages_2);
expected_submessages.push_back(expected_submessages_3);
expected_submessages.push_back(expected_submessages_4);
return VerifyPermissionMessagesWithSubmessages(app_->permissions_data(),
expected_messages,
expected_submessages, false);
}
testing::AssertionResult CheckManifestProducesPermissions(
const std::string& expected_message_1,
const std::vector<std::string>& expected_submessages_1,
const std::string& expected_message_2,
const std::vector<std::string>& expected_submessages_2,
const std::string& expected_message_3,
const std::vector<std::string>& expected_submessages_3,
const std::string& expected_message_4,
const std::vector<std::string>& expected_submessages_4,
const std::string& expected_message_5,
const std::vector<std::string>& expected_submessages_5) {
std::vector<std::string> expected_messages;
expected_messages.push_back(expected_message_1);
expected_messages.push_back(expected_message_2);
expected_messages.push_back(expected_message_3);
expected_messages.push_back(expected_message_4);
expected_messages.push_back(expected_message_5);
std::vector<std::vector<std::string>> expected_submessages;
expected_submessages.push_back(expected_submessages_1);
expected_submessages.push_back(expected_submessages_2);
expected_submessages.push_back(expected_submessages_3);
expected_submessages.push_back(expected_submessages_4);
expected_submessages.push_back(expected_submessages_5);
return VerifyPermissionMessagesWithSubmessages(app_->permissions_data(),
expected_messages,
expected_submessages, false);
}
private:
extensions::TestExtensionEnvironment env_;
std::unique_ptr<ChromePermissionMessageProvider> message_provider_;
scoped_refptr<const Extension> app_;
// Add a known extension id to the explicit allowlist so we can test all
// permissions. This ID will be used for each test app.
SimpleFeature::ScopedThreadUnsafeAllowlistForTest allowlisted_extension_id_;
DISALLOW_COPY_AND_ASSIGN(PermissionMessageCombinationsUnittest);
};
// Test that the USB, Bluetooth and Serial permissions do not coalesce on their
// own, but do coalesce when more than 1 is present.
TEST_F(PermissionMessageCombinationsUnittest, USBSerialBluetoothCoalescing) {
// Test that the USB permission does not coalesce on its own.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': [{ 'vendorId': 123, 'productId': 456 }] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': [{ 'vendorId': 123, 'productId': 456 }] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor"));
// Test that the serial permission does not coalesce on its own.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'serial'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions("Access your serial devices"));
// Test that the bluetooth permission does not coalesce on its own.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'bluetooth': {}"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access information about Bluetooth devices paired with your system and "
"discover nearby Bluetooth devices."));
// Test that the bluetooth permission does not coalesce on its own, even
// when it specifies additional permissions.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'bluetooth': {"
" 'uuids': ['1105', '1106']"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access information about Bluetooth devices paired with your system and "
"discover nearby Bluetooth devices."));
// Test that the USB and Serial permissions coalesce.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': [{ 'vendorId': 123, 'productId': 456 }] },"
" 'serial'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor",
"Access your serial devices"));
// Test that the USB, Serial and Bluetooth permissions coalesce.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': [{ 'vendorId': 123, 'productId': 456 }] },"
" 'serial'"
" ],"
" 'bluetooth': {}"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor",
"Access your Bluetooth and Serial devices"));
// Test that the USB, Serial and Bluetooth permissions coalesce even when
// Bluetooth specifies multiple additional permissions.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': [{ 'vendorId': 123, 'productId': 456 }] },"
" 'serial'"
" ],"
" 'bluetooth': {"
" 'uuids': ['1105', '1106'],"
" 'socket': true,"
" 'low_energy': true"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor",
"Access your Bluetooth and Serial devices"));
}
// Test that the History permission takes precedence over the Tabs permission,
// and that the Sessions permission modifies this final message.
TEST_F(PermissionMessageCombinationsUnittest, TabsHistorySessionsCoalescing) {
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions("Read your browsing history"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs', 'sessions'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read your browsing history on all your signed-in devices"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs', 'history'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your browsing history"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs', 'history', 'sessions'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your browsing history on all your signed-in devices"));
}
// Test that the fileSystem permission produces no messages by itself, unless it
// has both the 'write' and 'directory' additional permissions, in which case it
// displays a message.
TEST_F(PermissionMessageCombinationsUnittest, FileSystemReadWriteCoalescing) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'fileSystem'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'fileSystem', {'fileSystem': ['retainEntries', 'write']}"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'fileSystem', {'fileSystem': ["
" 'retainEntries', 'write', 'directory'"
" ]}"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Write to files and folders that you open in the application"));
}
// Check that host permission messages are generated correctly when URLs are
// entered as permissions.
TEST_F(PermissionMessageCombinationsUnittest, HostsPermissionMessages) {
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://www.blogger.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on www.blogger.com"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://*.google.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all google.com sites"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all google.com sites and "
"www.blogger.com"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all google.com sites, all news.com sites, "
"and www.blogger.com"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" 'http://www.foobar.com/',"
" ]"
"}");
std::vector<std::string> submessages;
submessages.push_back("All google.com sites");
submessages.push_back("All news.com sites");
submessages.push_back("www.blogger.com");
submessages.push_back("www.foobar.com");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on a number of websites", submessages));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" 'http://www.foobar.com/',"
" 'http://*.go.com/',"
" ]"
"}");
submessages.clear();
submessages.push_back("All go.com sites");
submessages.push_back("All google.com sites");
submessages.push_back("All news.com sites");
submessages.push_back("www.blogger.com");
submessages.push_back("www.foobar.com");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on a number of websites", submessages));
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://*.go.com/',"
" 'chrome://favicon/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all go.com sites",
"Read the icons of the websites you visit"));
// Having the 'all sites' permission doesn't change the permission message,
// since its pseudo-granted at runtime.
CreateAndInstall(
"{"
" 'permissions': ["
" 'http://*.go.com/',"
" 'chrome://favicon/',"
" 'http://*.*',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all go.com sites",
"Read the icons of the websites you visit"));
}
// Check that permission messages are generated correctly for
// SocketsManifestPermission, which has host-like permission messages.
TEST_F(PermissionMessageCombinationsUnittest,
SocketsManifestPermissionMessages) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'udp': {'send': '*'},"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'udp': {'send': ':99'},"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcp': {'connect': '127.0.0.1:80'},"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the device named 127.0.0.1"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcp': {'connect': 'www.example.com:23'},"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the device named www.example.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcpServer': {'listen': '127.0.0.1:80'}"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the device named 127.0.0.1"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcpServer': {'listen': ':8080'}"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcpServer': {"
" 'listen': ["
" '127.0.0.1:80',"
" 'www.google.com',"
" 'www.example.com:*',"
" 'www.foo.com:200',"
" 'www.bar.com:200'"
" ]"
" }"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the devices named: 127.0.0.1 www.bar.com "
"www.example.com www.foo.com www.google.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcp': {"
" 'connect': ["
" 'www.abc.com:*',"
" 'www.mywebsite.com:320',"
" 'www.freestuff.com',"
" 'www.foo.com:34',"
" 'www.test.com'"
" ]"
" },"
" 'tcpServer': {"
" 'listen': ["
" '127.0.0.1:80',"
" 'www.google.com',"
" 'www.example.com:*',"
" 'www.foo.com:200',"
" ]"
" }"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the devices named: 127.0.0.1 www.abc.com "
"www.example.com www.foo.com www.freestuff.com www.google.com "
"www.mywebsite.com www.test.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'sockets': {"
" 'tcp': {'send': '*:*'},"
" 'tcpServer': {'listen': '*:*'},"
" }"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
}
// Check that permission messages are generated correctly for
// MediaGalleriesPermission (an API permission with custom messages).
TEST_F(PermissionMessageCombinationsUnittest,
MediaGalleriesPermissionMessages) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'mediaGalleries': ['read'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'mediaGalleries': ['read', 'allAutoDetected'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access photos, music, and other media from your computer"));
// TODO(sashab): Add a test for the
// IDS_EXTENSION_PROMPT_WARNING_MEDIA_GALLERIES_READ_WRITE message (generated
// with the 'read' and 'copyTo' permissions, but not the 'delete' permission),
// if it's possible to get this message. Otherwise, remove it from the code.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'mediaGalleries': ['read', 'delete', 'allAutoDetected'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and delete photos, music, and other media from your computer"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'mediaGalleries':"
" [ 'read', 'delete', 'copyTo', 'allAutoDetected' ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read, change and delete photos, music, and other media from your "
"computer"));
// Without the allAutoDetected permission, there should be no install-time
// permission messages.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'mediaGalleries': ['read', 'delete', 'copyTo'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
}
// TODO(sashab): Add tests for SettingsOverrideAPIPermission (an API permission
// with custom messages).
// Check that permission messages are generated correctly for SocketPermission
// (an API permission with custom messages).
TEST_F(PermissionMessageCombinationsUnittest, SocketPermissionMessages) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ['tcp-connect:*:*'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ["
" 'tcp-connect:*:443',"
" 'tcp-connect:*:50032',"
" 'tcp-connect:*:23',"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ['tcp-connect:foo.example.com:443'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the device named foo.example.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ['tcp-connect:foo.example.com:443', 'udp-send-to'] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ["
" 'tcp-connect:foo.example.com:443',"
" 'udp-send-to:test.ping.com:50032',"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the devices named: foo.example.com test.ping.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ["
" 'tcp-connect:foo.example.com:443',"
" 'udp-send-to:test.ping.com:50032',"
" 'udp-send-to:www.ping.com:50032',"
" 'udp-send-to:test2.ping.com:50032',"
" 'udp-bind:test.ping.com:50032',"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with the devices named: foo.example.com test.ping.com "
"test2.ping.com www.ping.com"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'socket': ["
" 'tcp-connect:foo.example.com:443',"
" 'udp-send-to:test.ping.com:50032',"
" 'tcp-connect:*:23',"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Exchange data with any device on the local network or internet"));
}
// Check that permission messages are generated correctly for
// USBDevicePermission (an API permission with custom messages).
TEST_F(PermissionMessageCombinationsUnittest, USBDevicePermissionMessages) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': ["
" { 'vendorId': 0, 'productId': 0 },"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from an unknown vendor"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': ["
" { 'vendorId': 4179, 'productId': 529 },"
" ] }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access USB devices from Immanuel Electronics Co., Ltd"));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': ["
" { 'vendorId': 6353, 'productId': 8192 },"
" ] }"
" ]"
"}");
ASSERT_TRUE(
CheckManifestProducesPermissions("Access USB devices from Google Inc."));
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" { 'usbDevices': ["
" { 'vendorId': 4179, 'productId': 529 },"
" { 'vendorId': 6353, 'productId': 8192 },"
" ] }"
" ]"
"}");
std::vector<std::string> submessages;
submessages.push_back("unknown devices from Immanuel Electronics Co., Ltd");
submessages.push_back("unknown devices from Google Inc.");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access any of these USB devices", submessages));
// TODO(sashab): Add a test with a valid product/vendor USB device.
}
// Test that hosted apps are not given any messages for host permissions.
TEST_F(PermissionMessageCombinationsUnittest,
PackagedAppsHaveNoHostPermissions) {
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'serial',"
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions("Access your serial devices"));
}
// Test various apps with lots of permissions, including those with no
// permission messages, or those that only apply to apps or extensions even when
// the given manifest is for a different type.
TEST_F(PermissionMessageCombinationsUnittest, PermissionMessageCombos) {
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs',"
" 'bookmarks',"
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'unlimitedStorage',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change your data on all google.com sites and www.blogger.com",
"Read your browsing history", "Read and change your bookmarks"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs',"
" 'sessions',"
" 'bookmarks',"
" 'unlimitedStorage',"
" 'syncFileSystem',"
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" 'http://www.foobar.com/',"
" 'http://*.go.com/',"
" ]"
"}");
std::vector<std::string> submessages;
submessages.push_back("All go.com sites");
submessages.push_back("All google.com sites");
submessages.push_back("All news.com sites");
submessages.push_back("www.blogger.com");
submessages.push_back("www.foobar.com");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read your browsing history on all your signed-in devices",
std::vector<std::string>(), "Read and change your bookmarks",
std::vector<std::string>(),
"Read and change your data on a number of websites", submessages));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs',"
" 'sessions',"
" 'bookmarks',"
" 'accessibilityFeatures.read',"
" 'accessibilityFeatures.modify',"
" 'alarms',"
" 'browsingData',"
" 'cookies',"
" 'desktopCapture',"
" 'gcm',"
" 'topSites',"
" 'storage',"
" 'unlimitedStorage',"
" 'syncFileSystem',"
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" 'http://www.foobar.com/',"
" 'http://*.go.com/',"
" ]"
"}");
submessages.clear();
submessages.push_back("All go.com sites");
submessages.push_back("All google.com sites");
submessages.push_back("All news.com sites");
submessages.push_back("www.blogger.com");
submessages.push_back("www.foobar.com");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read your browsing history on all your signed-in devices",
std::vector<std::string>(), "Capture content of your screen",
std::vector<std::string>(), "Read and change your bookmarks",
std::vector<std::string>(),
"Read and change your data on a number of websites", submessages,
"Read and change your accessibility settings",
std::vector<std::string>()));
// Create an App instead, ensuring that the host permission messages are not
// added.
CreateAndInstall(
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': ["
" 'contextMenus',"
" 'permissions',"
" 'accessibilityFeatures.read',"
" 'accessibilityFeatures.modify',"
" 'alarms',"
" 'power',"
" 'cookies',"
" 'serial',"
" 'usb',"
" 'storage',"
" 'gcm',"
" 'topSites',"
" 'storage',"
" 'unlimitedStorage',"
" 'syncFileSystem',"
" 'http://www.blogger.com/',"
" 'http://*.google.com/',"
" 'http://*.news.com/',"
" 'http://www.foobar.com/',"
" 'http://*.go.com/',"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Access your serial devices", "Store data in your Google Drive account",
"Read and change your accessibility settings"));
}
// Tests that the deprecated 'plugins' manifest key produces no permission.
TEST_F(PermissionMessageCombinationsUnittest, PluginPermission) {
CreateAndInstall(
"{"
" 'plugins': ["
" { 'path': 'extension_plugin.dll' }"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions());
}
TEST_F(PermissionMessageCombinationsUnittest, ClipboardPermissionMessages) {
const char kManifest[] =
"{"
" 'app': {"
" 'background': {"
" 'scripts': ['background.js']"
" }"
" },"
" 'permissions': [%s]"
"}";
CreateAndInstall(base::StringPrintf(kManifest, "'clipboardRead'"));
ASSERT_TRUE(CheckManifestProducesPermissions("Read data you copy and paste"));
CreateAndInstall(
base::StringPrintf(kManifest, "'clipboardRead', 'clipboardWrite'"));
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and modify data you copy and paste"));
CreateAndInstall(base::StringPrintf(kManifest, "'clipboardWrite'"));
ASSERT_TRUE(
CheckManifestProducesPermissions("Modify data you copy and paste"));
}
TEST_F(PermissionMessageCombinationsUnittest, NewTabPagePermissionMessages) {
const char kManifest[] =
"{"
" 'chrome_url_overrides': {"
" 'newtab': 'newtab.html'"
" }"
"}";
CreateAndInstall(kManifest);
ASSERT_TRUE(CheckManifestProducesPermissions(
"Replace the page you see when opening a new tab"));
}
TEST_F(PermissionMessageCombinationsUnittest,
DeclarativeNetRequestFeedbackPermissionMessages) {
// Set the current channel to trunk.
ScopedCurrentChannel scoped_channel(version_info::Channel::UNKNOWN);
CreateAndInstall(
"{"
" 'permissions': ["
" 'declarativeNetRequestFeedback'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions("Read your browsing history"));
CreateAndInstall(
"{"
" 'permissions': ["
" 'tabs', 'declarativeNetRequestFeedback'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions("Read your browsing history"));
CreateAndInstall(
"{"
" 'permissions': ["
" '<all_urls>', 'declarativeNetRequestFeedback'"
" ]"
"}");
ASSERT_TRUE(CheckManifestProducesPermissions(
"Read and change all your data on the websites you visit"));
}
// TODO(sashab): Add a test that checks that messages are generated correctly
// for withheld permissions, when an app is granted the 'all sites' permission.
// TODO(sashab): Add a test that ensures that all permissions that can generate
// a coalesced message can also generate a message on their own (i.e. ensure
// that no permissions only modify other permissions).
// TODO(sashab): Add a test for every permission message combination that can
// generate a message.
// TODO(aboxhall): Add tests for the automation API permission messages.
} // namespace extensions
| [
"[email protected]"
] | |
9a1e432bd7a01d71ec06a3ff01c2a4b7985c1504 | 88483f4ca493e787a35c20669c97cbcf90e39891 | /sender/radio.ino | b263244a1161e30c2a51ac555e0744c54cc88362 | [
"MIT"
] | permissive | samaparicio/arduino-weather-station-lora | 67a4e009316e929740bba96ec3043246c78120f1 | de0b96e2084b8a8e1ec25094fdd6ee517f243914 | refs/heads/master | 2021-09-07T06:53:32.330563 | 2018-02-19T05:06:20 | 2018-02-19T05:06:20 | 115,234,259 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,010 | ino | void waitForAckFromReceiver() {
// Now wait for a reply
uint8_t buf[RH_RF95_MAX_MESSAGE_LEN];
uint8_t len = sizeof(buf);
Serial.println("\nWaiting for reply..."); delay(10);
if (rf95.waitAvailableTimeout(1000))
{
// Should be a reply message for us now
if (rf95.recv(buf, &len))
{
Serial.println("Got reply: ");
Serial.println((char*)buf);
Serial.print("RSSI: ");
Serial.println(rf95.lastRssi(), DEC);
}
else
{
Serial.println("Receive failed");
}
}
else
{
Serial.println("No reply, is gateway up?");
}
}
void sendPacket(String thisPayload) {
unsigned int payloadLength = thisPayload.length() + 1; //+1 is for the null terminator - https://stackoverflow.com/questions/7383606/converting-an-int-or-string-to-a-char-array-on-arduino
char payloadAsChar[payloadLength];
thisPayload.toCharArray(payloadAsChar, payloadLength);
rf95.send((uint8_t *)payloadAsChar, payloadLength);
delay(10);
rf95.waitPacketSent();
}
| [
"[email protected]"
] | |
599a161f0eeb0b305e18f2522e5c223dfeb5cd8a | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir22441/dir22442/dir22443/dir22444/dir22869/dir23624/file23783.cpp | 2ac0dd67bdd324752f55c6725fad43cf5e6a8970 | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file23783
#error "macro file23783 must be defined"
#endif
static const char* file23783String = "file23783"; | [
"[email protected]"
] | |
1e0c2009414eb0024273eb2bc78f3eed9130c9d7 | 4810365d4c281ee3656272189e822d9d14aff504 | /ImagePro/AnisotropyDlg.h | 273feafc807f98cb3ea5108c3f05d1dfe141a328 | [] | no_license | 15831944/GeoReavealLogApp | 869d67b036e7adfe865b0fb89b99c7f009049a6b | 36be9c1d3fea4d55d5e69c8872c2eb1f2c88db8b | refs/heads/main | 2023-03-08T13:28:04.334108 | 2021-02-19T03:59:21 | 2021-02-19T03:59:21 | 478,417,611 | 1 | 1 | null | 2022-04-06T05:37:08 | 2022-04-06T05:37:07 | null | GB18030 | C++ | false | false | 1,342 | h | #ifndef _ANISOTROPYDLG_H__
#define _ANISOTROPYDLG_H__
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// AnisotropyDlg.h : header file
//
/////////////////////////////////////////////////////////////////////////////
// CAnisotropyDlg dialog
#include "WndShadow.h"
class CAnisotropyDlg : public CDialog
{
// Construction
public:
CAnisotropyDlg(CWnd* pParent = NULL); // standard constructor
// Dialog Data
//{{AFX_DATA(CAnisotropyDlg)
enum { IDD = IDD_ANISOTROPYDLG };
float m_AzMax;
float m_RxyMin;
//}}AFX_DATA
float m_fWin; //滑动窗长
float m_fRlev; //滑动步长
float m_NumMin; //样本率
int m_iImage; //图像选择1-静态 2-动态 3-刻度
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CAnisotropyDlg)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
CWndShadow m_Shadow;
// Generated message map functions
//{{AFX_MSG(CAnisotropyDlg)
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_ANISOTROPYDLG_H__67D294E5_F617_45DD_89B1_A2D611FC06D8__INCLUDED_)
| [
"[email protected]"
] | |
78464a05a0b9f8ba055df074e0e53ef8060bf055 | f2e00e5fefe92afe1ec730da6226971a1193b122 | /project/Application/src/App.cpp | cac5b782f144c01ded1a4c08ad6299268db75d8a | [] | no_license | IvanGorshkov/YSPN.Cloud | 0904e67f6728b4f4e5c865dddeaacddf32815c55 | 66433d2f3eb7651884595bcc0a3ce2c2202b4a2c | refs/heads/CodeСarcas | 2023-03-11T06:27:04.607401 | 2020-11-28T13:51:07 | 2020-11-28T13:51:07 | 324,962,809 | 0 | 0 | null | 2021-02-22T15:10:15 | 2020-12-28T09:03:30 | null | UTF-8 | C++ | false | false | 638 | cpp | #include "App.h"
void App::UploadFile() {
}
void App::EditFile() {
}
void App::DeleteFile() {
}
void App::AddFolder() {
}
void App::DeleteFolder() {
}
void App::MoveFile() {
}
void App::SignIn() {
}
void App::SignUp() {
}
void App::ChangePassword() {
}
void App::DeleteAccount() {
}
void App::RenameFile() {
}
void App::ChangeDefaultFolder() {
}
void App::ShowFileHistory() {
}
void App::RollBackFileContent() {
}
void App::DownloadFile() {
}
void App::Refresh() {
}
void App::ExitAccount() {
}
void App::DeleteFileFromComputer() {
}
void App::DeleteFileFromService() {
}
void App::Operation1() {
} | [
"[email protected]"
] | |
e0e28dec3674615ca6cd39c9fe651c354428e7b4 | 412f40fd13e75d7d90cc1bb38e309fb9a9b5c975 | /PrimeMatrix.cpp | 7b09caca367f9bc1a4e154ef8c90345e03b4863a | [] | no_license | ritesh-pandey/codeforces | 7ac0a5779ba5278808ab4a34e45d006bff34591d | 6212daffd2f4907302cdca00c8ddd681c3f2018d | refs/heads/master | 2020-06-02T05:25:39.750099 | 2013-09-01T08:32:17 | 2013-09-01T08:32:17 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 983 | cpp | #include <iostream>
#include <vector>
using namespace std;
int main(){
vector<int> prime(110000,1);
prime[0] = 0;
prime[1] = 0;
for(int i=2; i<110000; i++){
if(prime[i] == 0)
continue;
for(int j=i*2; j<110000; j+=i)
prime[j] = 0;
}
int n,m;
cin>>n>>m;
vector< vector<int> > mat(n, vector<int>(m));
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
cin>>mat[i][j];
long long int minmoves=110000,moves = 0;
for(int i=0; i<n; i++){
moves = 0;
for(int j=0; j<m; j++){
if(prime[mat[i][j]] == 1)
continue;
else{
int k=mat[i][j];
while(prime[k] != 1)
k++;
moves += (k-mat[i][j]);
}
}
if(minmoves > moves)
minmoves = moves;
}
for(int i=0; i<m; i++){
moves = 0;
for(int j=0; j<n; j++){
if(prime[mat[j][i]] == 1)
continue;
else{
int k=mat[j][i];
while(prime[k] != 1)
k++;
moves += (k-mat[j][i]);
}
}
if(minmoves > moves)
minmoves = moves;
}
cout<<minmoves<<"\n";
return 0;
}
| [
"ritesh@ritesh-laptop.(none)"
] | ritesh@ritesh-laptop.(none) |
37b9688ef15fc302428c5bbbccdb313576be5094 | 79dbf3f57788bbd29c6f383655e568daf33b5a8a | /justdel/w32thread-inl.h | ed0bb6d3952edf77bd64310a6a4008aaf21b542e | [
"BSD-2-Clause",
"BSD-3-Clause"
] | permissive | leejeonghun/justdel | 84c65bd504a5220ef63a0898153969f5e8a35707 | 367c1d0a9172b02caac46344784bd3b69af41248 | refs/heads/master | 2021-07-08T21:03:35.535994 | 2018-08-08T02:18:57 | 2018-08-08T02:18:57 | 90,970,918 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,525 | h | // Copyright 2016 jeonghun
#ifndef JUSTDEL_W32THREAD_INL_H_
#define JUSTDEL_W32THREAD_INL_H_
#include "w32thread.h"
#include <cassert>
template <typename T>
w32thread<T>::w32thread(T *obj_ptr, thread_proc_t proc_ptr)
: obj_ptr_(obj_ptr)
, proc_ptr_(proc_ptr) {
assert(obj_ptr != nullptr);
assert(proc_ptr != nullptr);
}
template <typename T>
w32thread<T>::~w32thread() {
close(false);
}
template <typename T>
bool w32thread<T>::create(void *arg_ptr) {
bool succeeded = false;
if (handle_ == NULL) {
arg_ptr_ = arg_ptr;
handle_ = CreateThread(nullptr, 0, [](void *arg_ptr)->DWORD {
DWORD retcode = -1;
self_t* this_ptr = reinterpret_cast<self_t*>(arg_ptr);
if (this_ptr != nullptr) {
this_ptr->run_ = true;
retcode =
((this_ptr->obj_ptr_)->*(this_ptr->proc_ptr_))(this_ptr->arg_ptr_);
this_ptr->run_ = false; // TODO(jeonghun): after deleting an object, a crash will occur.
}
return retcode;
}, this, 0, &id_);
succeeded = handle_ != NULL;
}
return succeeded;
}
template <typename T>
bool w32thread<T>::close(bool wait) {
if (handle_ != NULL) {
if (wait) {
WaitForSingleObject(handle_, INFINITE);
}
CloseHandle(handle_);
handle_ = NULL;
}
return handle_ == NULL;
}
template<typename T>
bool w32thread<T>::post_message(UINT msg, WPARAM wparam, LPARAM lparam) {
return id_ != 0 ?
PostThreadMessage(id_, msg, wparam, lparam) != FALSE : false;
}
#endif // JUSTDEL_W32THREAD_INL_H_
| [
"[email protected]"
] | |
d9a4b2d9e3a94c93ec48a298d503f090cc55edbf | a25e76c90c2347fbe1b6f998a1f0ae8d5d4c54b6 | /engine/material.h | 5729caa3c55479978d7b717f21fa499a949e62f1 | [] | no_license | axh432/Animation-Retargeter-Qt | 6ee84fa847d4758ec71de956a9a212a551c04769 | 4c2ad06fd73333b602c88eb29411d1200f4b8187 | refs/heads/master | 2020-03-26T03:28:42.931791 | 2019-03-26T00:31:22 | 2019-03-26T00:31:22 | 144,457,899 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,299 | h | #ifndef MATERIAL_H
#define MATERIAL_H
#include <QOpenGLTexture>
#include <QOpenGLShaderProgram>
#include <memory>
class Material
{
public:
Material(
QString name,
QString alias,
QString type,
std::unique_ptr<QOpenGLShaderProgram> shader,
std::unique_ptr<QOpenGLTexture> diffuse,
std::unique_ptr<QOpenGLTexture> local,
std::unique_ptr<QOpenGLTexture> height,
std::unique_ptr<QOpenGLTexture> specular
);
inline QString getName(){ return name; }
inline QString getAlias(){ return alias; }
inline QString getType(){ return type; }
inline QOpenGLShaderProgram* getShader(){ return shader.get(); }
inline QOpenGLTexture* getDiffuse(){ return diffuse.get(); }
inline QOpenGLTexture* getLocal(){ return local.get(); }
inline QOpenGLTexture* getHeight(){ return height.get(); }
inline QOpenGLTexture* getSpecular(){ return specular.get(); }
private:
QString name;
QString alias;
QString type;
std::unique_ptr<QOpenGLShaderProgram> shader;
std::unique_ptr<QOpenGLTexture> diffuse;
std::unique_ptr<QOpenGLTexture> local;
std::unique_ptr<QOpenGLTexture> height;
std::unique_ptr<QOpenGLTexture> specular;
};
#endif // MATERIAL_H
| [
"[email protected]"
] | |
be12242b40c826aa7c474ce9d1cc4809772a94ff | d396381414032234ad010285a409ec668fafe56d | /test/test_relu.cpp | 15c1858e514d3224438aa91e58be63cd9079d6e5 | [] | no_license | merdogan10/behlul | 94ef2c81efd31938dea1b3e8a5c8c8a08e4a0d0f | 8dd3e598d51c8efc9989bd63a00a8b761bb73173 | refs/heads/master | 2020-12-07T19:29:19.443722 | 2020-01-09T10:24:48 | 2020-01-09T10:24:48 | 232,781,561 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,458 | cpp | #include "relu.hpp"
#include <catch2/catch.hpp>
#include <eigen3/Eigen/Dense>
#include <iostream>
#include <vector>
using Eigen::MatrixXd;
using namespace std;
TEST_CASE("ReLU Layer Forward pass is tested", "[relu_forward]") {
MatrixXd m0(3, 3), m1(3, 3), m2(3, 3), o0(3, 3), o1(3, 3), o2(3, 3);
m0 << 0.780465, -0.959954, -0.52344, -0.302214, -0.0845965, 0.941268,
-0.871657, -0.873808, 0.804416;
o0 << 0.780465, 0, 0, 0, 0, 0.941268, 0, 0, 0.804416;
m1 << 0.70184, -0.249586, 0.335448, -0.466669, 0.520497, 0.0632129, 0.0795207,
0.0250707, -0.921439;
o1 << 0.70184, 0, 0.335448, 0, 0.520497, 0.0632129, 0.0795207, 0.0250707, 0;
m2 << -0.124725, 0.441905, 0.279958, 0.86367, -0.431413, -0.291903, 0.86162,
0.477069, 0.375723;
o2 << 0, 0.441905, 0.279958, 0.86367, 0, 0, 0.86162, 0.477069, 0.375723;
vector<MatrixXd> input;
input.push_back(m0);
input.push_back(m1);
input.push_back(m2);
ReLU *rl = new ReLU(3, 3, 3);
rl->feed_forward(input);
REQUIRE(rl->output[0].isApprox(o0));
REQUIRE(rl->output[1].isApprox(o1));
REQUIRE(rl->output[2].isApprox(o2));
}
TEST_CASE("ReLU Layer Backward pass is tested", "[relu_backward]") {
MatrixXd m0(3, 3), m1(3, 3), m2(3, 3), o0(3, 3), o1(3, 3), o2(3, 3);
m0 << 0.780465, -0.959954, -0.52344, -0.302214, -0.0845965, 0.941268,
-0.871657, -0.873808, 0.804416;
o0 << 0.780465, 0, 0, 0, 0, 0.941268, 0, 0, 0.804416;
m1 << 0.70184, -0.249586, 0.335448, -0.466669, 0.520497, 0.0632129, 0.0795207,
0.0250707, -0.921439;
o1 << 0.70184, 0, 0.335448, 0, 0.520497, 0.0632129, 0.0795207, 0.0250707, 0;
m2 << -0.124725, 0.441905, 0.279958, 0.86367, -0.431413, -0.291903, 0.86162,
0.477069, 0.375723;
o2 << 0, 0.441905, 0.279958, 0.86367, 0, 0, 0.86162, 0.477069, 0.375723;
vector<MatrixXd> input;
input.push_back(m0);
input.push_back(m1);
input.push_back(m2);
ReLU *rl = new ReLU(3, 3, 3);
rl->feed_forward(input);
MatrixXd g0(3, 3), g1(3, 3), g2(3, 3);
g0 << 1, 0, 0, 0, 0, 1, 0, 0, 1;
g1 << 1, 0, 1, 0, 1, 1, 1, 1, 0;
g2 << 0, 1, 1, 1, 0, 0, 1, 1, 1;
vector<MatrixXd> upstream_gradient;
upstream_gradient.push_back(MatrixXd::Ones(3, 3));
upstream_gradient.push_back(MatrixXd::Ones(3, 3));
upstream_gradient.push_back(MatrixXd::Ones(3, 3));
rl->back_propagation(upstream_gradient);
REQUIRE(rl->gradients[0].isApprox(g0));
REQUIRE(rl->gradients[1].isApprox(g1));
REQUIRE(rl->gradients[2].isApprox(g2));
} | [
"[email protected]"
] | |
20a8357685aff60778de3dab7e49c63af2b5ef44 | 95f7c923592bafc734f8970fa743faafd5226253 | /spoj/IITKWPCN.cpp | 3fa1bb7f57462b6432b8bf341eedec8f44c0f35b | [] | no_license | vishnujayvel/practicecodes | 33132a1afc97e619df9950cd8782951ab183833d | 3849ac44596f56dda95b83d00a38b79a3921c496 | refs/heads/master | 2021-01-06T20:37:49.840924 | 2014-09-09T13:25:36 | 2014-09-09T13:25:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 764 | cpp |
#include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <queue>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cstring>
#include <climits>
#include <stdlib.h>
using namespace std;
#define REP(i,n) for(int i=0; i<n; i++)
#define FOR(i,st,end) for(int i=st;i<end;i++)
#define db(x) cout << (#x) << " = " << x << endl;
#define mp make_pair
#define pb push_back
int main(){
int t;
int w,b;
scanf("%d",&t);
while(t--){
scanf("%d %d",&w,&b);
if(b%2==0)
printf("0.000000\n");
else
printf("1.000000\n");
}
}
| [
"[email protected]"
] | |
5f2b373d0ed9734e5ba07d6956eeb5ef5396278a | 57f63e424c44de3ca672428ea2c02a3f982a7e64 | /ring.cpp | 5cd87d8c9a1a5e500913cef9ebc7b7bacd31a361 | [] | no_license | SuryanarayanaMK/test | e9e66f0e2a0e7d5510486c4d3a924103f8086dbd | 77ff30f8465106a75a6f6b9d01ca68dfd1f5e08e | refs/heads/master | 2021-01-19T02:31:38.918151 | 2016-08-11T13:48:53 | 2016-08-11T13:48:53 | 65,299,617 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 887 | cpp | #include<iostream>
#include<mpi.h>
using namespace std;
int main(int argc,char **argv){
int error = MPI_Init(&argc,&argv);
int myrank,var,var1;
int size;
int ierror;
MPI_Comm_rank(MPI_COMM_WORLD,&myrank);
MPI_Comm_size(MPI_COMM_WORLD,&size);
MPI_Status status;
MPI_Request request;
int other = 1 - myrank;
double start;
int left = (size + myrank - 1)%size;
int right = (myrank + 1)%size;
int sum = 0;
int update_sum = 0;
sum = myrank;
for(int i=1;i<size;i++){
// MPI_Issend(&sum,1,MPI_INT,right,0,MPI_COMM_WORLD,&request);
MPI_Irecv(&update_sum,1,MPI_INT,left,0,MPI_COMM_WORLD,&request);
// MPI_Recv(&update_sum,1,MPI_INT,left,0,MPI_COMM_WORLD,&status);
MPI_Ssend(&sum,1,MPI_INT,right,0,MPI_COMM_WORLD);
MPI_Wait(&request,&status);
sum = update_sum + myrank;
}
if(myrank==0)
cout << sum << endl;
MPI_Finalize();
return 0;
}
| [
"[email protected]"
] | |
6bdd16bba90a509d24a7e962ea301b93d73c6f2b | c2b6bd54bef3c30e53c846e9cf57f1e44f8410df | /Temp/il2cppOutput/il2cppOutput/UnityEngine_UI_UnityEngine_UI_InputField_EditState1111987863.h | 7243fcdfa38b31799febf087b1f3dddc54f710d0 | [] | no_license | PriyeshWani/CrashReproduce-5.4p1 | 549a1f75c848bf9513b2f966f2f500ee6c75ba42 | 03dd84f7f990317fb9026cbcc3873bc110b1051e | refs/heads/master | 2021-01-11T12:04:21.140491 | 2017-01-24T14:01:29 | 2017-01-24T14:01:29 | 79,388,416 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 986 | 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 "UnityEngine_UI_UnityEngine_UI_InputField_EditState1111987863.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// UnityEngine.UI.InputField/EditState
struct EditState_t1111987863
{
public:
// System.Int32 UnityEngine.UI.InputField/EditState::value__
int32_t ___value___1;
public:
inline static int32_t get_offset_of_value___1() { return static_cast<int32_t>(offsetof(EditState_t1111987863, ___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
| [
"[email protected]"
] | |
9a83b0357f721d831496967b029e934c53efb070 | 8bae51ddb3ad34a234dd786f948336ee63132fbd | /SampleCode/StdDriver/USBD_HID_Transfer/WindowsTool/HIDTransferTest/HID.hpp | d8c9805b5072b6c3c0a989d48a37ff5474210d35 | [
"Apache-2.0"
] | permissive | OpenNuvoton/M480BSP | f73192da6e32165c9b8a6b49e3d7853f23e60c07 | 9d28f02603c34d9f96a0fc40428c2f0cd473eb0b | refs/heads/master | 2023-05-14T06:26:55.476021 | 2023-05-08T03:10:41 | 2023-05-08T03:10:41 | 94,418,847 | 41 | 34 | null | 2021-10-20T07:44:36 | 2017-06-15T08:39:17 | HTML | BIG5 | C++ | false | false | 12,859 | hpp | #ifndef INC__HID_HPP__
#define INC__HID_HPP__
#include "stdafx.h"
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
#include <tchar.h>
#include <string.h>
#include "dbt.h"
extern "C" {
#include "setupapi.h"
#include "hidsdi.h"
}
#define HID_MAX_PACKET_SIZE_EP 64
#define V6M_MAX_COMMAND_LENGTH (HID_MAX_PACKET_SIZE_EP - 2)
class CHidIO
{
protected:
HANDLE m_hReadHandle;
HANDLE m_hWriteHandle;
HANDLE m_hReadEvent;
HANDLE m_hWriteEvent;
HANDLE m_hAbordEvent;
public:
CHidIO()
: m_hReadHandle(INVALID_HANDLE_VALUE)
, m_hWriteHandle(INVALID_HANDLE_VALUE)
, m_hAbordEvent(CreateEvent(NULL,TRUE,FALSE,NULL))
, m_hReadEvent(CreateEvent(NULL,TRUE,FALSE,NULL))
, m_hWriteEvent(CreateEvent(NULL,TRUE,FALSE,NULL))
{
}
virtual ~CHidIO()
{
CloseDevice();
CloseHandle(m_hWriteEvent);
CloseHandle(m_hReadEvent);
CloseHandle(m_hAbordEvent);
}
void CloseDevice()
{
if(m_hReadHandle != INVALID_HANDLE_VALUE)
CancelIo(m_hReadHandle);
if(m_hWriteHandle != INVALID_HANDLE_VALUE)
CancelIo(m_hWriteHandle);
if(m_hReadHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hReadHandle);
m_hReadHandle = INVALID_HANDLE_VALUE;
}
if(m_hWriteHandle != INVALID_HANDLE_VALUE)
{
CloseHandle(m_hWriteHandle);
m_hWriteHandle = INVALID_HANDLE_VALUE;
}
}
HIDP_CAPS Capabilities;
BOOL OpenDevice(USHORT usVID, USHORT usPID)
{
DWORD DeviceUsage;
TCHAR MyDevPathName[MAX_PATH];
//Get the Capabilities structure for the device.
PHIDP_PREPARSED_DATA PreparsedData;
//定義一個GUID的結構體HidGuid來保存HID設備的接口類GUID。
GUID HidGuid;
//定義一個DEVINFO的句柄hDevInfoSet來保存獲取到的設備信息集合句柄。
HDEVINFO hDevInfoSet;
//定義MemberIndex,表示當前搜索到第幾個設備,0表示第一個設備。
DWORD MemberIndex;
//DevInterfaceData,用來保存設備的驅動接口信息
SP_DEVICE_INTERFACE_DATA DevInterfaceData;
//定義一個BOOL變量,保存函數調用是否返回成功
BOOL Result;
//定義一個RequiredSize的變量,用來接收需要保存詳細信息的緩衝長度。
DWORD RequiredSize;
//定義一個指向設備詳細信息的結構體指針。
PSP_DEVICE_INTERFACE_DETAIL_DATA pDevDetailData;
//定義一個用來保存打開設備的句柄。
HANDLE hDevHandle;
//定義一個HIDD_ATTRIBUTES的結構體變量,保存設備的屬性。
HIDD_ATTRIBUTES DevAttributes;
//初始化設備未找到
BOOL MyDevFound=FALSE;
//初始化讀、寫句柄為無效句柄。
m_hReadHandle=INVALID_HANDLE_VALUE;
m_hWriteHandle=INVALID_HANDLE_VALUE;
//對DevInterfaceData結構體的cbSize初始化為結構體大小
DevInterfaceData.cbSize=sizeof(DevInterfaceData);
//對DevAttributes結構體的Size初始化為結構體大小
DevAttributes.Size=sizeof(DevAttributes);
//調用HidD_GetHidGuid函數獲取HID設備的GUID,並保存在HidGuid中。
HidD_GetHidGuid(&HidGuid);
//根據HidGuid來獲取設備信息集合。其中Flags參數設置為
//DIGCF_DEVICEINTERFACE|DIGCF_PRESENT,前者表示使用的GUID為
//接口類GUID,後者表示只列舉正在使用的設備,因為我們這裡只
//查找已經連接上的設備。返回的句柄保存在hDevinfo中。注意設備
//信息集合在使用完畢後,要使用函數SetupDiDestroyDeviceInfoList
//銷毀,不然會造成內存洩漏。
hDevInfoSet=SetupDiGetClassDevs(&HidGuid,
NULL,
NULL,
DIGCF_DEVICEINTERFACE|DIGCF_PRESENT);
//AddToInfOut("開始查找設備");
//然後對設備集合中每個設備進行列舉,檢查是否是我們要找的設備
//當找到我們指定的設備,或者設備已經查找完畢時,就退出查找。
//首先指向第一個設備,即將MemberIndex置為0。
MemberIndex=0;
while(1)
{
//調用SetupDiEnumDeviceInterfaces在設備信息集合中獲取編號為
//MemberIndex的設備信息。
Result=SetupDiEnumDeviceInterfaces(hDevInfoSet,
NULL,
&HidGuid,
MemberIndex,
&DevInterfaceData);
//如果獲取信息失敗,則說明設備已經查找完畢,退出循環。
if(Result==FALSE) break;
//將MemberIndex指向下一個設備
MemberIndex++;
//如果獲取信息成功,則繼續獲取該設備的詳細信息。在獲取設備
//詳細信息時,需要先知道保存詳細信息需要多大的緩衝區,這通過
//第一次調用函數SetupDiGetDeviceInterfaceDetail來獲取。這時
//提供緩衝區和長度都為NULL的參數,並提供一個用來保存需要多大
//緩衝區的變量RequiredSize。
Result=SetupDiGetDeviceInterfaceDetail(hDevInfoSet,
&DevInterfaceData,
NULL,
NULL,
&RequiredSize,
NULL);
//然後,分配一個大小為RequiredSize緩衝區,用來保存設備詳細信息。
pDevDetailData=(PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(RequiredSize);
if(pDevDetailData==NULL) //如果內存不足,則直接返回。
{
//MessageBox("內存不足!");
SetupDiDestroyDeviceInfoList(hDevInfoSet);
return FALSE;
}
//並設置pDevDetailData的cbSize為結構體的大小(注意只是結構體大小,
//不包括後面緩衝區)。
pDevDetailData->cbSize=sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);
//然後再次調用SetupDiGetDeviceInterfaceDetail函數來獲取設備的
//詳細信息。這次調用設置使用的緩衝區以及緩衝區大小。
Result=SetupDiGetDeviceInterfaceDetail(hDevInfoSet,
&DevInterfaceData,
pDevDetailData,
RequiredSize,
NULL,
NULL);
//將設備路徑複製出來,然後銷毀剛剛申請的內存。
//MyDevPathName=pDevDetailData->DevicePath;
//_tcscpy(MyDevPathName, pDevDetailData->DevicePath);
wcscpy_s(MyDevPathName, pDevDetailData->DevicePath);
free(pDevDetailData);
//如果調用失敗,則查找下一個設備。
if(Result==FALSE) continue;
//如果調用成功,則使用不帶讀寫訪問的CreateFile函數
//來獲取設備的屬性,包括VID、PID、版本號等。
//對於一些獨佔設備(例如USB鍵盤),使用讀訪問方式是無法打開的,
//而使用不帶讀寫訪問的格式才可以打開這些設備,從而獲取設備的屬性。
hDevHandle=CreateFile(MyDevPathName,
NULL,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
//如果打開成功,則獲取設備屬性。
if(hDevHandle!=INVALID_HANDLE_VALUE)
{
//獲取設備的屬性並保存在DevAttributes結構體中
Result=HidD_GetAttributes(hDevHandle,
&DevAttributes);
//關閉剛剛打開的設備
//CloseHandle(hDevHandle);
//獲取失敗,查找下一個
if(Result==FALSE) continue;
//如果獲取成功,則將屬性中的VID、PID以及設備版本號與我們需要的
//進行比較,如果都一致的話,則說明它就是我們要找的設備。
if(DevAttributes.VendorID == usVID
&& DevAttributes.ProductID == usPID){
// 利用HID Report Descriptor來辨識HID Transfer裝置
HidD_GetPreparsedData(hDevHandle, &PreparsedData);
HidP_GetCaps(PreparsedData, &Capabilities);
HidD_FreePreparsedData(PreparsedData);
DeviceUsage = (Capabilities.UsagePage * 256) + Capabilities.Usage;
if (DeviceUsage != 0xFF0001) // Report Descriptor
continue;
MyDevFound=TRUE; //設置設備已經找到
//AddToInfOut("設備已經找到");
//那麼就是我們要找的設備,分別使用讀寫方式打開之,並保存其句柄
//並且選擇為異步訪問方式。
//讀方式打開設備
m_hReadHandle=CreateFile(MyDevPathName,
GENERIC_READ,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
//FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
FILE_ATTRIBUTE_NORMAL,
NULL);
//if(hReadHandle!=INVALID_HANDLE_VALUE)AddToInfOut("讀訪問打開設備成功");
//else AddToInfOut("讀訪問打開設備失敗");
//寫方式打開設備
m_hWriteHandle=CreateFile(MyDevPathName,
GENERIC_WRITE,
FILE_SHARE_READ|FILE_SHARE_WRITE,
NULL,
OPEN_EXISTING,
//FILE_ATTRIBUTE_NORMAL|FILE_FLAG_OVERLAPPED,
FILE_ATTRIBUTE_NORMAL,
NULL);
//if(hWriteHandle!=INVALID_HANDLE_VALUE)AddToInfOut("寫訪問打開設備成功");
//else AddToInfOut("寫訪問打開設備失敗");
//手動觸發事件,讓讀報告線程恢復運行。因為在這之前並沒有調用
//讀數據的函數,也就不會引起事件的產生,所以需要先手動觸發一
//次事件,讓讀報告線程恢復運行。
//SetEvent(ReadOverlapped.hEvent);
//顯示設備的狀態。
//SetDlgItemText(IDC_DS,"設備已打開");
//找到設備,退出循環。本程序只檢測一個目標設備,查找到後就退出
//查找了。如果你需要將所有的目標設備都列出來的話,可以設置一個
//數組,找到後就保存在數組中,直到所有設備都查找完畢才退出查找
break;
}
}
//如果打開失敗,則查找下一個設備
else //continue;
{
CloseHandle(hDevHandle);
continue;
}
}
//調用SetupDiDestroyDeviceInfoList函數銷毀設備信息集合
SetupDiDestroyDeviceInfoList(hDevInfoSet);
//如果設備已經找到,那麼應該使能各操作按鈕,並同時禁止打開設備按鈕
return MyDevFound;
}
BOOL ReadFile(char *pcBuffer, DWORD szMaxLen, DWORD *pdwLength, DWORD dwMilliseconds)
{
HANDLE events[2] = {m_hAbordEvent, m_hReadEvent};
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = m_hReadEvent;
if(pdwLength != NULL)
*pdwLength = 0;
if(!::ReadFile(m_hReadHandle, pcBuffer, szMaxLen, NULL, &overlapped))
return FALSE;
DWORD dwIndex = WaitForMultipleObjects(2, events, FALSE, dwMilliseconds);
if(dwIndex == WAIT_OBJECT_0
|| dwIndex == WAIT_OBJECT_0 + 1)
{
ResetEvent(events[dwIndex - WAIT_OBJECT_0]);
if(dwIndex == WAIT_OBJECT_0)
return FALSE; //Abort event
else
{
DWORD dwLength = 0;
//Read OK
GetOverlappedResult(m_hReadHandle, &overlapped, &dwLength, TRUE);
if(pdwLength != NULL)
*pdwLength = dwLength;
return TRUE;
}
}
else
return FALSE;
}
BOOL WriteFile(const char *pcBuffer, DWORD szLen, DWORD *pdwLength, DWORD dwMilliseconds)
{
HANDLE events[2] = {m_hAbordEvent, m_hWriteEvent};
OVERLAPPED overlapped;
memset(&overlapped, 0, sizeof(overlapped));
overlapped.hEvent = m_hWriteEvent;
if(pdwLength != NULL)
*pdwLength = 0;
DWORD dwStart2 = GetTickCount();
if(!::WriteFile(m_hWriteHandle, pcBuffer, szLen, NULL, &overlapped))
return FALSE;
DWORD dwIndex = WaitForMultipleObjects(2, events, FALSE, dwMilliseconds);
if(dwIndex == WAIT_OBJECT_0
|| dwIndex == WAIT_OBJECT_0 + 1)
{
ResetEvent(events[dwIndex - WAIT_OBJECT_0]);
if(dwIndex == WAIT_OBJECT_0)
return FALSE; //Abort event
else
{
DWORD dwLength = 0;
//Write OK
GetOverlappedResult(m_hWriteHandle, &overlapped, &dwLength, TRUE);
if(pdwLength != NULL)
*pdwLength = dwLength;
return TRUE;
}
}
else
return FALSE;
}
};
class CHidCmd
{
protected:
CHAR m_acBuffer[HID_MAX_PACKET_SIZE_EP + 1];
CHidIO m_hidIO;
public:
CHidCmd()
: m_hidIO()
{
}
virtual ~CHidCmd()
{
}
void CloseDevice()
{
m_hidIO.CloseDevice();
}
BOOL OpenDevice(USHORT usVID, USHORT usPID)
{
return m_hidIO.OpenDevice(usVID, usPID);
}
BOOL ReadFile(unsigned char *pcBuffer, size_t szMaxLen, DWORD *pdwLength, DWORD dwMilliseconds)
{
BOOL bRet;
bRet = m_hidIO.ReadFile(m_acBuffer, sizeof(m_acBuffer), pdwLength, dwMilliseconds);
(*pdwLength)--;
memcpy(pcBuffer, m_acBuffer+1, *pdwLength);
return bRet;
}
BOOL WriteFile(unsigned char *pcBuffer, DWORD dwLen, DWORD *pdwLength, DWORD dwMilliseconds)
{
/* Set new package index value */
DWORD dwCmdLength = dwLen;
if(dwCmdLength > sizeof(m_acBuffer) - 1)
dwCmdLength = sizeof(m_acBuffer) - 1;
memset(m_acBuffer, 0xCC, sizeof(m_acBuffer));
m_acBuffer[0] = 0x00; //Always 0x00
memcpy(m_acBuffer+1 , pcBuffer, dwCmdLength);
BOOL bRet = m_hidIO.WriteFile(m_acBuffer, 65, pdwLength, dwMilliseconds);
if(bRet)
{
*pdwLength = *pdwLength - 1;
}
return bRet;
}
};
#endif
| [
"[email protected]"
] | |
dc721ee579e4aef206a0e175a6092a13f0d3ffdd | be18dc7b41b872575eade0697bea8ad84c212776 | /Classes/UI/Message/Message.h | eeb21bab6174287c47349456f6d9d5d7113787c2 | [] | no_license | YaumenauPavel/Cocos2d-x-Snake | 4cbe10b365abf34cc7e938258ceffaff834d0e5f | 3c048b63ee6846ac23c14c89f06fc4fb22fba05e | refs/heads/master | 2023-07-09T20:30:51.867670 | 2021-03-18T08:52:34 | 2021-03-18T08:52:34 | 255,822,723 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 551 | h | #pragma once
#include "cocos2d.h"
namespace UI
{
class Message : public cocos2d::Layer
{
public:
bool initWithNode(cocos2d::Node* node, const std::string &msg, const float &time, cocos2d::Vec2 point,
const cocos2d::ccMenuCallback &callback);
Message* createToast(cocos2d::Node* node, const std::string &msg, const float &time, cocos2d::Vec2 point,
const cocos2d::ccMenuCallback &callback);
void onEnter();
void OkClick();
void CancelClick();
private:
CREATE_FUNC(Message);
};
} | [
"[email protected]"
] | |
c5747a01be4f6ef9acf5c3f60692d429d344f13b | 18e669597e963ccbc4041c68ea79c7fa0bec6322 | /MicroEngine_VS2010/MicroEngine/skybox/SkyBoxRenderer.cpp | 8ce456672016a110f4b6d2092d62b4d853336866 | [] | no_license | double-haipi/projects-during-undergraduate | 53a59f75c98aba7e89c7ed9a99a5e94674266293 | 922fb2c0a26348d4cc8abc886b79c716ba744c8b | refs/heads/master | 2021-01-10T13:03:30.533294 | 2015-11-29T10:23:43 | 2015-11-29T10:23:43 | 47,055,770 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 4,820 | cpp | #include "SkyboxRenderer.h"
#include "../GlobalVar.h"
#include "../toolbox/Loader.h"
#include "../models/RawModel.h"
#include "../skybox/SkyboxShader.h"
#include <iostream>
#include <vector>
using namespace std;
SkyboxRenderer::SkyboxRenderer(Loader *loader, Camera *camera)
{
this->camera = camera;
// cube vertices
GLfloat verticesArray[]={
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE,
-GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
GlobalVar::fSkyBox_SIZE, -GlobalVar::fSkyBox_SIZE, GlobalVar::fSkyBox_SIZE,
};
// SkyBox textures (Cube map, 6 textures in total)
const GLchar* textureFiles[] = {
"../res/images/skybox/right.png", "../res/images/skybox/left.png", // x direction
"../res/images/skybox/top.png", "../res/images/skybox/bottom.png", // y direction
"../res/images/skybox/back.png", "../res/images/skybox/front.png", // z direction
};
vector<GLfloat> vertices;
for(GLuint i=0; i<sizeof(verticesArray)/sizeof(GLfloat); ++i){
vertices.push_back(verticesArray[i]);
}
cube = loader->LoadToVAO(vertices, 3);
textureID = loader->LoadCubeMaps(textureFiles);
shader = new SkyBoxShader(GlobalVar::SKYBOX_VERTEX_FILE, GlobalVar::SKYBOX_FRAGMENT_FILE);
shader->Start();
shader->LoadProjectionMatrix(shader->GetUniformLocations("projectionMatrix"));
shader->Stop();
}
void SkyboxRenderer::Render()
{
shader->Start();
shader->LoadViewMatrix(camera);
// Bind VAO
glBindVertexArray(cube->GetvaoID());
glEnableVertexAttribArray(0);
// Bind texture
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_CUBE_MAP, textureID);
// Draw triangle arrays
glDrawArrays(GL_TRIANGLES, 0, cube->GetvertexCount());
// Unbind VAO
glDisableVertexAttribArray(0);
glBindVertexArray(0);
shader->Stop();
}
| [
"[email protected]"
] | |
7bca0172e22f84196d22a05149644ee31d1e626b | 3f96650c88453da8e2837f4c2025c14ed3bf77f5 | /Field/Field.cpp | c2be35cf2f3439aac349cf7e7b7bd06ef6dd5a0b | [] | no_license | yuuurchyk/cpp_tic_tac_toe | c320c598be0c6ca8192ef070280d546df878f86f | c6aff36ada89cd951c8d82a5e1e5d47469ee883d | refs/heads/master | 2021-09-17T18:34:38.958849 | 2018-07-04T12:48:19 | 2018-07-04T12:48:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,468 | cpp | #include <utility>
#include "Field.h"
#include "../Exceptions/FieldExceptions.h"
using namespace TicTacToe;
Field::Field(){}
inline void Field::validate(size_t i, size_t j){
if(i >= kN || j >= kN)
throw FieldOutOfBoundsError();
}
std::ostream& TicTacToe::operator<<(std::ostream &strm, const Field &rhs){
for(size_t i = 0; i < Field::kN; ++i)
{
for(size_t j = 0; j < Field::kN; ++j)
strm << static_cast<char>(rhs(i, j));
strm << ((i == Field::kN - 1) ? "" : "\n");
}
return strm;
}
bool Field::operator==(const Field &rhs) const{
for(size_t i = 0; i < kN; ++i)
for(size_t j = 0; j < kN; ++j)
if(operator()(i, j) == rhs(i, j))
return false;
return true;
}
Field &Field::operator=(const Field &rhs){
for(size_t i = 0; i < kN; ++i)
for(size_t j = 0; j < kN; ++j)
field_[i][j] = rhs(i, j);
freeCellsLeft_ = rhs.freeCellsLeft_;
return *this;
}
Field::Field(const Field &rhs){
operator=(rhs);
}
Player Field::whooseMove() const{
return (freeCellsLeft_ % 2 == (kN * kN) % 2)? Player::X(): Player::O();
}
Field::operator size_t() const{
size_t p{1}, res{0};
for(size_t i = 0; i < kN; ++i)
for(size_t j = 0; j < kN; ++j, p *= Cell::kBase)
res += p * static_cast<size_t>(operator()(i, j));
return res;
}
bool Field::isOccupied(size_t i, size_t j) const{
return at(i, j) != Cell::Empty();
}
void Field::set(size_t i, size_t j, const Player &p){
if(at(i, j) != Cell::Empty())
throw FieldCellOccupiedError(i, j);
if(p != whooseMove())
throw FieldMoveOrderError();
--freeCellsLeft_;
field_[i][j] = static_cast<Cell>(p);
}
const Cell& Field::operator()(size_t i, size_t j) const{
return field_[i][j];
}
const Cell& Field::at(size_t i, size_t j) const{
validate(i, j);
return operator()(i, j);
}
bool Field::isWinner(Player *winner) const{
static const std::array<std::pair<int, int>, 4>
directions{
std::make_pair(1, -1),
std::make_pair(1, 0),
std::make_pair(1, 1),
std::make_pair(0, 1)
};
for(size_t i = 0; i < kN; ++i)
for(size_t j = 0; j < kN; ++j){
Cell current{operator()(i, j)};
if(current == Cell::Empty())
continue;
for(const auto &d :directions){
try{
size_t ti{i}, tj{j};
bool ok = true;
for(size_t t = 0; t < kN; ++t, ti += d.first, tj += d.second)
if(at(ti, tj) != current){
ok = false;
break;
}
if(ok){
if(winner != nullptr)
*winner = static_cast<Player>(current);
return true;
}
}
catch(const FieldOutOfBoundsError &e){
continue;
}
}
}
return false;
}
bool Field::isDraw() const{
return (!isWinner()) && freeCellsLeft_ == 0;
}
std::pair<size_t, size_t> Field::difference(const Field &rhs) const{
for(size_t i = 0; i < kN; ++i)
for(size_t j = 0; j < kN; ++j)
if(operator()(i, j) != rhs(i, j))
return std::make_pair(i, j);
throw FieldDifferenceError();
} | [
"[email protected]"
] | |
235eb2745fcdccf17a71c87429fad2ce3cd48fb6 | 59546681d43cc42cbd14b97c0fccbb43ef312975 | /isCycle.cpp | 4fb8ab37fbd8aebd13f6b0f124a1ddd927afac50 | [] | no_license | sd37/graph_algo | ccc2b3e83c5750e174e65495955c3d104ee46d73 | 212a380e3737b40509620e874621ee39d28354f7 | refs/heads/master | 2020-05-17T09:55:13.421793 | 2013-11-26T22:40:51 | 2013-11-26T22:40:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,255 | cpp | //assume all vertices are numbered from 0 to V - 1
//detect if cycle is present or not
#define present(c,x) ((c).find(x) != (c).end())
#include<iostream>
#include<stdio.h>
#include<list>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<set>
using namespace std;
class Graph
{
unsigned int V;
list<unsigned int> *adj;
bool isCycleUtil(unsigned int v,set<unsigned int>& visited,set<unsigned int>& recStack);
public:
Graph(unsigned int V);
bool isCycle();
void addEdge(unsigned int s,unsigned int d);
};
Graph::Graph(unsigned int V)
{
this->V = V;
this->adj = new list<unsigned int>[V];
}
void Graph::addEdge(unsigned int s, unsigned int d)
{
this->adj[s].push_back(d);
}
bool Graph::isCycleUtil(unsigned int v,set<unsigned int>& visited,set<unsigned int>& recStack)
{
if(!present(visited,v))
return false;
visited.insert(v);
recStack.insert(v);
list<unsigned int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); i++)
{
if(!present(visited,*i) && isCycleUtil(*i, visited, recStack) )
return true;
else if(present(recStack,*i))
return true;
}
set<unsigned int>::iterator it = recStack.find(v);
if(it != recStack.end())
recStack.erase(it);
return false;
}
bool Graph::isCycle()
{
// Returns true if the graph contains a cycle, else false
//Mark all vertices as not visited and not part of recursion
//stack
set<unsigned int> visited;
set<unsigned int> recStack;
//Call recursive helper function to detect cycle in different
//DFS Trees.
for (unsigned int i = 0; i < this->V; i++)
{
if(isCycleUtil(i,visited,recStack))
return true;
}
return false;
}
int main()
{
fflush(stdout);
Graph g(3);
g.addEdge(0,1);
//g.addEdge(2,0);
g.addEdge(1,2);
//g.addEdge(2,1);
/*
Graph g(4);
g.addEdge(0,1);
g.addEdge(0,2);
g.addEdge(1,2);
g.addEdge(2,0);
g.addEdge(2,3);
g.addEdge(3,3);
*/
if(g.isCycle())
printf("yes");
else
printf("no");
printf("\n");
return 0;
}
| [
"spandan@sd37.(none)"
] | spandan@sd37.(none) |
c33fd230a84bff7909c9ba131598914c9d78fbb8 | 1ef0afb6ba04e74cf59c38369f0341899d3635f7 | /Cacades/FileWatcher.cpp | 0a588b5dbf86534fd086ec62f9103a75974cdc86 | [] | no_license | fabi092/Cascades-Shaderprogramming | 57beb4d9b8bfa2d63c8311d3aff37775a4ae5f71 | 22630bd94b988c4212ab238c478d43685d42867c | refs/heads/main | 2023-04-09T13:39:25.891657 | 2021-04-15T06:45:58 | 2021-04-15T06:45:58 | 358,103,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,639 | cpp | #include "FileWatcher.h"
#include <iostream>
FileWatcher::FileWatcher(const char* filePath, const Delegate& delegate, long msCycle) : FileWatcher(&filePath, 1, delegate, msCycle)
{}
FileWatcher::FileWatcher(const char** filePath, int fileCount, const Delegate& delegate, long msCycle) : m_fileCount(fileCount), m_path(new std::experimental::filesystem::path[m_fileCount]), m_lastLoad(new std::chrono::system_clock::time_point[m_fileCount]), m_callBack(delegate), m_msCycle(msCycle), m_stop(false)
{
for (int i = 0; i < m_fileCount; ++i)
{
if (filePath[i] == nullptr)
continue;
m_path[i] = std::experimental::filesystem::path(filePath[i]);
if (!std::experimental::filesystem::exists(m_path[i]))
{
m_path[i] = "";
continue;
}
m_lastLoad[i] = std::chrono::system_clock::now();
}
m_watcherThread = std::thread(&FileWatcher::CheckFile, this);
}
FileWatcher::~FileWatcher()
{
delete[] m_path;
delete[] m_lastLoad;
m_stop = true;
m_watcherThread.join();
}
void FileWatcher::CheckFile() const
{
while (!m_stop)
{
std::this_thread::sleep_for(std::chrono::system_clock::duration(m_msCycle));
for (int i = 0; i < m_fileCount; ++i)
{
if (m_path[i] == "")
continue;
std::chrono::system_clock::time_point modifyStamp;
try
{
modifyStamp = std::experimental::filesystem::last_write_time(m_path[i]);
}
catch (std::exception e)
{
std::cout << "ERROR " << e.what() << " | " << __FILE__ << " (" << __LINE__ << ")" << std::endl;
modifyStamp = m_lastLoad[i];
}
if (modifyStamp > m_lastLoad[i])
{
m_callBack.Invoke();
m_lastLoad[i] = modifyStamp;
}
}
}
}
| [
"[email protected]"
] | |
bc4cacfdf430e4a2c68661140a91bbc26a4ac3ee | 721d70011e3b9447113b0f62d5e6bb00c54b7008 | /windows/mingw/i686-w64-mingw32/lib/gcc/mingw32/4.6.2/include/c++/tr1/regex | e69eb377afefde595786dc4407b25dd6dbc4c45a | [] | no_license | mrmoss/parrot_kinect | d8f3dd477dc6206d54f17266fc618e5e5705fde3 | 5e118c7b5a31bfa999cd3eb8777677f923fa80b0 | refs/heads/master | 2021-01-10T21:06:29.716162 | 2015-11-11T22:11:50 | 2015-11-11T22:11:50 | 8,966,232 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 95,683 | // class template regex -*- C++ -*-
// Copyright (C) 2007, 2009, 2010 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation.
// You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>.
/**
* @file tr1/regex
* @author Stephen M. Webb <[email protected]>
* This is a TR1 C++ Library header.
*/
#ifndef _GLIBCXX_TR1_REGEX
#define _GLIBCXX_TR1_REGEX 1
#pragma GCC system_header
#include <algorithm>
#include <bitset>
#include <iterator>
#include <locale>
#include <stdexcept>
#include <string>
#include <vector>
#include <utility>
#include <sstream>
namespace std _GLIBCXX_VISIBILITY(default)
{
namespace tr1
{
/**
* @defgroup tr1_regex Regular Expressions
* A facility for performing regular expression pattern matching.
*/
//@{
/** @namespace std::regex_constants
* @brief ISO C++ 0x entities sub namespace for regex.
*/
namespace regex_constants
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/**
* @name 5.1 Regular Expression Syntax Options
*/
//@{
enum __syntax_option
{
_S_icase,
_S_nosubs,
_S_optimize,
_S_collate,
_S_ECMAScript,
_S_basic,
_S_extended,
_S_awk,
_S_grep,
_S_egrep,
_S_syntax_last
};
/**
* @brief This is a bitmask type indicating how to interpret the regex.
*
* The @c syntax_option_type is implementation defined but it is valid to
* perform bitwise operations on these values and expect the right thing to
* happen.
*
* A valid value of type syntax_option_type shall have exactly one of the
* elements @c ECMAScript, @c basic, @c extended, @c awk, @c grep, @c egrep
* %set.
*/
typedef unsigned int syntax_option_type;
/**
* Specifies that the matching of regular expressions against a character
* sequence shall be performed without regard to case.
*/
static const syntax_option_type icase = 1 << _S_icase;
/**
* Specifies that when a regular expression is matched against a character
* container sequence, no sub-expression matches are to be stored in the
* supplied match_results structure.
*/
static const syntax_option_type nosubs = 1 << _S_nosubs;
/**
* Specifies that the regular expression engine should pay more attention to
* the speed with which regular expressions are matched, and less to the
* speed with which regular expression objects are constructed. Otherwise
* it has no detectable effect on the program output.
*/
static const syntax_option_type optimize = 1 << _S_optimize;
/**
* Specifies that character ranges of the form [a-b] should be locale
* sensitive.
*/
static const syntax_option_type collate = 1 << _S_collate;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by ECMAScript in ECMA-262 [Ecma International, ECMAScript
* Language Specification, Standard Ecma-262, third edition, 1999], as
* modified in tr1 section [7.13]. This grammar is similar to that defined
* in the PERL scripting language but extended with elements found in the
* POSIX regular expression grammar.
*/
static const syntax_option_type ECMAScript = 1 << _S_ECMAScript;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by POSIX basic regular expressions in IEEE Std 1003.1-2001,
* Portable Operating System Interface (POSIX), Base Definitions and
* Headers, Section 9, Regular Expressions [IEEE, Information Technology --
* Portable Operating System Interface (POSIX), IEEE Standard 1003.1-2001].
*/
static const syntax_option_type basic = 1 << _S_basic;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by POSIX extended regular expressions in IEEE Std 1003.1-2001,
* Portable Operating System Interface (POSIX), Base Definitions and Headers,
* Section 9, Regular Expressions.
*/
static const syntax_option_type extended = 1 << _S_extended;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by POSIX utility awk in IEEE Std 1003.1-2001. This option is
* identical to syntax_option_type extended, except that C-style escape
* sequences are supported. These sequences are:
* \\\\, \\a, \\b, \\f,
* \\n, \\r, \\t , \\v,
* \\', ', and \\ddd
* (where ddd is one, two, or three octal digits).
*/
static const syntax_option_type awk = 1 << _S_awk;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by POSIX utility grep in IEEE Std 1003.1-2001. This option is
* identical to syntax_option_type basic, except that newlines are treated
* as whitespace.
*/
static const syntax_option_type grep = 1 << _S_grep;
/**
* Specifies that the grammar recognized by the regular expression engine is
* that used by POSIX utility grep when given the -E option in
* IEEE Std 1003.1-2001. This option is identical to syntax_option_type
* extended, except that newlines are treated as whitespace.
*/
static const syntax_option_type egrep = 1 << _S_egrep;
//@}
/**
* @name 5.2 Matching Rules
*
* Matching a regular expression against a sequence of characters [first,
* last) proceeds according to the rules of the grammar specified for the
* regular expression object, modified according to the effects listed
* below for any bitmask elements set.
*
*/
//@{
enum __match_flag
{
_S_not_bol,
_S_not_eol,
_S_not_bow,
_S_not_eow,
_S_any,
_S_not_null,
_S_continuous,
_S_prev_avail,
_S_sed,
_S_no_copy,
_S_first_only,
_S_match_flag_last
};
/**
* @brief This is a bitmask type indicating regex matching rules.
*
* The @c match_flag_type is implementation defined but it is valid to
* perform bitwise operations on these values and expect the right thing to
* happen.
*/
typedef std::bitset<_S_match_flag_last> match_flag_type;
/**
* The default matching rules.
*/
static const match_flag_type match_default = 0;
/**
* The first character in the sequence [first, last) is treated as though it
* is not at the beginning of a line, so the character (^) in the regular
* expression shall not match [first, first).
*/
static const match_flag_type match_not_bol = 1 << _S_not_bol;
/**
* The last character in the sequence [first, last) is treated as though it
* is not at the end of a line, so the character ($) in the regular
* expression shall not match [last, last).
*/
static const match_flag_type match_not_eol = 1 << _S_not_eol;
/**
* The expression \\b is not matched against the sub-sequence
* [first,first).
*/
static const match_flag_type match_not_bow = 1 << _S_not_bow;
/**
* The expression \\b should not be matched against the sub-sequence
* [last,last).
*/
static const match_flag_type match_not_eow = 1 << _S_not_eow;
/**
* If more than one match is possible then any match is an acceptable
* result.
*/
static const match_flag_type match_any = 1 << _S_any;
/**
* The expression does not match an empty sequence.
*/
static const match_flag_type match_not_null = 1 << _S_not_null;
/**
* The expression only matches a sub-sequence that begins at first .
*/
static const match_flag_type match_continuous = 1 << _S_continuous;
/**
* --first is a valid iterator position. When this flag is set then the
* flags match_not_bol and match_not_bow are ignored by the regular
* expression algorithms 7.11 and iterators 7.12.
*/
static const match_flag_type match_prev_avail = 1 << _S_prev_avail;
/**
* When a regular expression match is to be replaced by a new string, the
* new string is constructed using the rules used by the ECMAScript replace
* function in ECMA- 262 [Ecma International, ECMAScript Language
* Specification, Standard Ecma-262, third edition, 1999], part 15.5.4.11
* String.prototype.replace. In addition, during search and replace
* operations all non-overlapping occurrences of the regular expression
* are located and replaced, and sections of the input that did not match
* the expression are copied unchanged to the output string.
*
* Format strings (from ECMA-262 [15.5.4.11]):
* @li $$ The dollar-sign itself ($)
* @li $& The matched substring.
* @li $` The portion of @a string that precedes the matched substring.
* This would be match_results::prefix().
* @li $' The portion of @a string that follows the matched substring.
* This would be match_results::suffix().
* @li $n The nth capture, where n is in [1,9] and $n is not followed by a
* decimal digit. If n <= match_results::size() and the nth capture
* is undefined, use the empty string instead. If n >
* match_results::size(), the result is implementation-defined.
* @li $nn The nnth capture, where nn is a two-digit decimal number on
* [01, 99]. If nn <= match_results::size() and the nth capture is
* undefined, use the empty string instead. If
* nn > match_results::size(), the result is implementation-defined.
*/
static const match_flag_type format_default = 0;
/**
* When a regular expression match is to be replaced by a new string, the
* new string is constructed using the rules used by the POSIX sed utility
* in IEEE Std 1003.1- 2001 [IEEE, Information Technology -- Portable
* Operating System Interface (POSIX), IEEE Standard 1003.1-2001].
*/
static const match_flag_type format_sed = 1 << _S_sed;
/**
* During a search and replace operation, sections of the character
* container sequence being searched that do not match the regular
* expression shall not be copied to the output string.
*/
static const match_flag_type format_no_copy = 1 << _S_no_copy;
/**
* When specified during a search and replace operation, only the first
* occurrence of the regular expression shall be replaced.
*/
static const match_flag_type format_first_only = 1 << _S_first_only;
//@}
/**
* @name 5.3 Error Types
*/
//@{
enum error_type
{
_S_error_collate,
_S_error_ctype,
_S_error_escape,
_S_error_backref,
_S_error_brack,
_S_error_paren,
_S_error_brace,
_S_error_badbrace,
_S_error_range,
_S_error_space,
_S_error_badrepeat,
_S_error_complexity,
_S_error_stack,
_S_error_last
};
/** The expression contained an invalid collating element name. */
static const error_type error_collate(_S_error_collate);
/** The expression contained an invalid character class name. */
static const error_type error_ctype(_S_error_ctype);
/**
* The expression contained an invalid escaped character, or a trailing
* escape.
*/
static const error_type error_escape(_S_error_escape);
/** The expression contained an invalid back reference. */
static const error_type error_backref(_S_error_backref);
/** The expression contained mismatched [ and ]. */
static const error_type error_brack(_S_error_brack);
/** The expression contained mismatched ( and ). */
static const error_type error_paren(_S_error_paren);
/** The expression contained mismatched { and } */
static const error_type error_brace(_S_error_brace);
/** The expression contained an invalid range in a {} expression. */
static const error_type error_badbrace(_S_error_badbrace);
/**
* The expression contained an invalid character range,
* such as [b-a] in most encodings.
*/
static const error_type error_range(_S_error_range);
/**
* There was insufficient memory to convert the expression into a
* finite state machine.
*/
static const error_type error_space(_S_error_space);
/**
* One of <em>*?+{</em> was not preceded by a valid regular expression.
*/
static const error_type error_badrepeat(_S_error_badrepeat);
/**
* The complexity of an attempted match against a regular expression
* exceeded a pre-set level.
*/
static const error_type error_complexity(_S_error_complexity);
/**
* There was insufficient memory to determine whether the
* regular expression could match the specified character sequence.
*/
static const error_type error_stack(_S_error_stack);
//@}
_GLIBCXX_END_NAMESPACE_VERSION
}
_GLIBCXX_BEGIN_NAMESPACE_VERSION
// [7.8] Class regex_error
/**
* @brief A regular expression exception class.
* @ingroup exceptions
*
* The regular expression library throws objects of this class on error.
*/
class regex_error
: public std::runtime_error
{
public:
/**
* @brief Constructs a regex_error object.
*
* @param ecode the regex error code.
*/
explicit
regex_error(regex_constants::error_type __ecode)
: std::runtime_error("regex_error"), _M_code(__ecode)
{ }
/**
* @brief Gets the regex error code.
*
* @returns the regex error code.
*/
regex_constants::error_type
code() const
{ return _M_code; }
protected:
regex_constants::error_type _M_code;
};
// [7.7] Class regex_traits
/**
* @brief Describes aspects of a regular expression.
*
* A regular expression traits class that satisfies the requirements of tr1
* section [7.2].
*
* The class %regex is parameterized around a set of related types and
* functions used to complete the definition of its semantics. This class
* satisfies the requirements of such a traits class.
*/
template<typename _Ch_type>
struct regex_traits
{
public:
typedef _Ch_type char_type;
typedef std::basic_string<char_type> string_type;
typedef std::locale locale_type;
typedef std::ctype_base::mask char_class_type;
public:
/**
* @brief Constructs a default traits object.
*/
regex_traits()
{ }
/**
* @brief Gives the length of a C-style string starting at @p __p.
*
* @param __p a pointer to the start of a character sequence.
*
* @returns the number of characters between @p *__p and the first
* default-initialized value of type @p char_type. In other words, uses
* the C-string algorithm for determining the length of a sequence of
* characters.
*/
static std::size_t
length(const char_type* __p)
{ return string_type::traits_type::length(__p); }
/**
* @brief Performs the identity translation.
*
* @param c A character to the locale-specific character set.
*
* @returns c.
*/
char_type
translate(char_type __c) const
{ return __c; }
/**
* @brief Translates a character into a case-insensitive equivalent.
*
* @param c A character to the locale-specific character set.
*
* @returns the locale-specific lower-case equivalent of c.
* @throws std::bad_cast if the imbued locale does not support the ctype
* facet.
*/
char_type
translate_nocase(char_type __c) const
{
using std::ctype;
using std::use_facet;
return use_facet<ctype<char_type> >(_M_locale).tolower(__c);
}
/**
* @brief Gets a sort key for a character sequence.
*
* @param first beginning of the character sequence.
* @param last one-past-the-end of the character sequence.
*
* Returns a sort key for the character sequence designated by the
* iterator range [F1, F2) such that if the character sequence [G1, G2)
* sorts before the character sequence [H1, H2) then
* v.transform(G1, G2) < v.transform(H1, H2).
*
* What this really does is provide a more efficient way to compare a
* string to multiple other strings in locales with fancy collation
* rules and equivalence classes.
*
* @returns a locale-specific sort key equivalent to the input range.
*
* @throws std::bad_cast if the current locale does not have a collate
* facet.
*/
template<typename _Fwd_iter>
string_type
transform(_Fwd_iter __first, _Fwd_iter __last) const
{
using std::collate;
using std::use_facet;
const collate<_Ch_type>& __c(use_facet<
collate<_Ch_type> >(_M_locale));
string_type __s(__first, __last);
return __c.transform(__s.data(), __s.data() + __s.size());
}
/**
* @brief Dunno.
*
* @param first beginning of the character sequence.
* @param last one-past-the-end of the character sequence.
*
* Effects: if typeid(use_facet<collate<_Ch_type> >) ==
* typeid(collate_byname<_Ch_type>) and the form of the sort key
* returned by collate_byname<_Ch_type>::transform(first, last) is known
* and can be converted into a primary sort key then returns that key,
* otherwise returns an empty string. WTF??
*
* @todo Implement this function.
*/
template<typename _Fwd_iter>
string_type
transform_primary(_Fwd_iter __first, _Fwd_iter __last) const;
/**
* @brief Gets a collation element by name.
*
* @param first beginning of the collation element name.
* @param last one-past-the-end of the collation element name.
*
* @returns a sequence of one or more characters that represents the
* collating element consisting of the character sequence designated by
* the iterator range [first, last). Returns an empty string if the
* character sequence is not a valid collating element.
*
* @todo Implement this function.
*/
template<typename _Fwd_iter>
string_type
lookup_collatename(_Fwd_iter __first, _Fwd_iter __last) const;
/**
* @brief Maps one or more characters to a named character
* classification.
*
* @param first beginning of the character sequence.
* @param last one-past-the-end of the character sequence.
*
* @returns an unspecified value that represents the character
* classification named by the character sequence designated by the
* iterator range [first, last). The value returned shall be independent
* of the case of the characters in the character sequence. If the name
* is not recognized then returns a value that compares equal to 0.
*
* At least the following names (or their wide-character equivalent) are
* supported.
* - d
* - w
* - s
* - alnum
* - alpha
* - blank
* - cntrl
* - digit
* - graph
* - lower
* - print
* - punct
* - space
* - upper
* - xdigit
*
* @todo Implement this function.
*/
template<typename _Fwd_iter>
char_class_type
lookup_classname(_Fwd_iter __first, _Fwd_iter __last) const;
/**
* @brief Determines if @p c is a member of an identified class.
*
* @param c a character.
* @param f a class type (as returned from lookup_classname).
*
* @returns true if the character @p c is a member of the classification
* represented by @p f, false otherwise.
*
* @throws std::bad_cast if the current locale does not have a ctype
* facet.
*/
bool
isctype(_Ch_type __c, char_class_type __f) const;
/**
* @brief Converts a digit to an int.
*
* @param ch a character representing a digit.
* @param radix the radix if the numeric conversion (limited to 8, 10,
* or 16).
*
* @returns the value represented by the digit ch in base radix if the
* character ch is a valid digit in base radix; otherwise returns -1.
*/
int
value(_Ch_type __ch, int __radix) const;
/**
* @brief Imbues the regex_traits object with a copy of a new locale.
*
* @param loc A locale.
*
* @returns a copy of the previous locale in use by the regex_traits
* object.
*
* @note Calling imbue with a different locale than the one currently in
* use invalidates all cached data held by *this.
*/
locale_type
imbue(locale_type __loc)
{
std::swap(_M_locale, __loc);
return __loc;
}
/**
* @brief Gets a copy of the current locale in use by the regex_traits
* object.
*/
locale_type
getloc() const
{ return _M_locale; }
protected:
locale_type _M_locale;
};
template<typename _Ch_type>
bool regex_traits<_Ch_type>::
isctype(_Ch_type __c, char_class_type __f) const
{
using std::ctype;
using std::use_facet;
const ctype<_Ch_type>& __ctype(use_facet<
ctype<_Ch_type> >(_M_locale));
if (__ctype.is(__c, __f))
return true;
// special case of underscore in [[:w:]]
if (__c == __ctype.widen('_'))
{
const char* const __wb[] = "w";
char_class_type __wt = this->lookup_classname(__wb,
__wb + sizeof(__wb));
if (__f | __wt)
return true;
}
// special case of [[:space:]] in [[:blank:]]
if (__c == __ctype.isspace(__c))
{
const char* const __bb[] = "blank";
char_class_type __bt = this->lookup_classname(__bb,
__bb + sizeof(__bb));
if (__f | __bt)
return true;
}
return false;
}
template<typename _Ch_type>
int regex_traits<_Ch_type>::
value(_Ch_type __ch, int __radix) const
{
std::basic_istringstream<_Ch_type> __is(string_type(1, __ch));
int __v;
if (__radix == 8)
__is >> std::oct;
else if (__radix == 16)
__is >> std::hex;
__is >> __v;
return __is.fail() ? -1 : __v;
}
// [7.8] Class basic_regex
/**
* Objects of specializations of this class represent regular expressions
* constructed from sequences of character type @p _Ch_type.
*
* Storage for the regular expression is allocated and deallocated as
* necessary by the member functions of this class.
*/
template<typename _Ch_type, typename _Rx_traits = regex_traits<_Ch_type> >
class basic_regex
{
public:
// types:
typedef _Ch_type value_type;
typedef regex_constants::syntax_option_type flag_type;
typedef typename _Rx_traits::locale_type locale_type;
typedef typename _Rx_traits::string_type string_type;
/**
* @name Constants
* tr1 [7.8.1] std [28.8.1]
*/
//@{
static const regex_constants::syntax_option_type icase
= regex_constants::icase;
static const regex_constants::syntax_option_type nosubs
= regex_constants::nosubs;
static const regex_constants::syntax_option_type optimize
= regex_constants::optimize;
static const regex_constants::syntax_option_type collate
= regex_constants::collate;
static const regex_constants::syntax_option_type ECMAScript
= regex_constants::ECMAScript;
static const regex_constants::syntax_option_type basic
= regex_constants::basic;
static const regex_constants::syntax_option_type extended
= regex_constants::extended;
static const regex_constants::syntax_option_type awk
= regex_constants::awk;
static const regex_constants::syntax_option_type grep
= regex_constants::grep;
static const regex_constants::syntax_option_type egrep
= regex_constants::egrep;
//@}
// [7.8.2] construct/copy/destroy
/**
* Constructs a basic regular expression that does not match any
* character sequence.
*/
basic_regex()
: _M_flags(regex_constants::ECMAScript), _M_pattern(), _M_mark_count(0)
{ _M_compile(); }
/**
* @brief Constructs a basic regular expression from the sequence
* [p, p + char_traits<_Ch_type>::length(p)) interpreted according to the
* flags in @p f.
*
* @param p A pointer to the start of a C-style null-terminated string
* containing a regular expression.
* @param f Flags indicating the syntax rules and options.
*
* @throws regex_error if @p p is not a valid regular expression.
*/
explicit
basic_regex(const _Ch_type* __p,
flag_type __f = regex_constants::ECMAScript)
: _M_flags(__f), _M_pattern(__p), _M_mark_count(0)
{ _M_compile(); }
/**
* @brief Constructs a basic regular expression from the sequence
* [p, p + len) interpreted according to the flags in @p f.
*
* @param p A pointer to the start of a string containing a regular
* expression.
* @param len The length of the string containing the regular expression.
* @param f Flags indicating the syntax rules and options.
*
* @throws regex_error if @p p is not a valid regular expression.
*/
basic_regex(const _Ch_type* __p, std::size_t __len, flag_type __f)
: _M_flags(__f) , _M_pattern(__p, __len), _M_mark_count(0)
{ _M_compile(); }
/**
* @brief Copy-constructs a basic regular expression.
*
* @param rhs A @p regex object.
*/
basic_regex(const basic_regex& __rhs)
: _M_flags(__rhs._M_flags), _M_pattern(__rhs._M_pattern),
_M_mark_count(__rhs._M_mark_count)
{ _M_compile(); }
/**
* @brief Constructs a basic regular expression from the string
* @p s interpreted according to the flags in @p f.
*
* @param s A string containing a regular expression.
* @param f Flags indicating the syntax rules and options.
*
* @throws regex_error if @p s is not a valid regular expression.
*/
template<typename _Ch_traits, typename _Ch_alloc>
explicit
basic_regex(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s,
flag_type __f = regex_constants::ECMAScript)
: _M_flags(__f), _M_pattern(__s.begin(), __s.end()), _M_mark_count(0)
{ _M_compile(); }
/**
* @brief Constructs a basic regular expression from the range
* [first, last) interpreted according to the flags in @p f.
*
* @param first The start of a range containing a valid regular
* expression.
* @param last The end of a range containing a valid regular
* expression.
* @param f The format flags of the regular expression.
*
* @throws regex_error if @p [first, last) is not a valid regular
* expression.
*/
template<typename _InputIterator>
basic_regex(_InputIterator __first, _InputIterator __last,
flag_type __f = regex_constants::ECMAScript)
: _M_flags(__f), _M_pattern(__first, __last), _M_mark_count(0)
{ _M_compile(); }
#ifdef _GLIBCXX_INCLUDE_AS_CXX0X
/**
* @brief Constructs a basic regular expression from an initializer list.
*
* @param l The initializer list.
* @param f The format flags of the regular expression.
*
* @throws regex_error if @p l is not a valid regular expression.
*/
basic_regex(initializer_list<_Ch_type> __l,
flag_type __f = regex_constants::ECMAScript)
: _M_flags(__f), _M_pattern(__l.begin(), __l.end()), _M_mark_count(0)
{ _M_compile(); }
#endif
/**
* @brief Destroys a basic regular expression.
*/
~basic_regex()
{ }
/**
* @brief Assigns one regular expression to another.
*/
basic_regex&
operator=(const basic_regex& __rhs)
{ return this->assign(__rhs); }
/**
* @brief Replaces a regular expression with a new one constructed from
* a C-style null-terminated string.
*
* @param A pointer to the start of a null-terminated C-style string
* containing a regular expression.
*/
basic_regex&
operator=(const _Ch_type* __p)
{ return this->assign(__p, flags()); }
/**
* @brief Replaces a regular expression with a new one constructed from
* a string.
*
* @param A pointer to a string containing a regular expression.
*/
template<typename _Ch_typeraits, typename _Allocator>
basic_regex&
operator=(const basic_string<_Ch_type, _Ch_typeraits, _Allocator>& __s)
{ return this->assign(__s, flags()); }
// [7.8.3] assign
/**
* @brief the real assignment operator.
*
* @param that Another regular expression object.
*/
basic_regex&
assign(const basic_regex& __that)
{
basic_regex __tmp(__that);
this->swap(__tmp);
return *this;
}
/**
* @brief Assigns a new regular expression to a regex object from a
* C-style null-terminated string containing a regular expression
* pattern.
*
* @param p A pointer to a C-style null-terminated string containing
* a regular expression pattern.
* @param flags Syntax option flags.
*
* @throws regex_error if p does not contain a valid regular expression
* pattern interpreted according to @p flags. If regex_error is thrown,
* *this remains unchanged.
*/
basic_regex&
assign(const _Ch_type* __p,
flag_type __flags = regex_constants::ECMAScript)
{ return this->assign(string_type(__p), __flags); }
/**
* @brief Assigns a new regular expression to a regex object from a
* C-style string containing a regular expression pattern.
*
* @param p A pointer to a C-style string containing a
* regular expression pattern.
* @param len The length of the regular expression pattern string.
* @param flags Syntax option flags.
*
* @throws regex_error if p does not contain a valid regular expression
* pattern interpreted according to @p flags. If regex_error is thrown,
* *this remains unchanged.
*/
basic_regex&
assign(const _Ch_type* __p, std::size_t __len, flag_type __flags)
{ return this->assign(string_type(__p, __len), __flags); }
/**
* @brief Assigns a new regular expression to a regex object from a
* string containing a regular expression pattern.
*
* @param s A string containing a regular expression pattern.
* @param flags Syntax option flags.
*
* @throws regex_error if p does not contain a valid regular expression
* pattern interpreted according to @p flags. If regex_error is thrown,
* *this remains unchanged.
*/
template<typename _Ch_typeraits, typename _Allocator>
basic_regex&
assign(const basic_string<_Ch_type, _Ch_typeraits, _Allocator>& __s,
flag_type __f = regex_constants::ECMAScript)
{
basic_regex __tmp(__s, __f);
this->swap(__tmp);
return *this;
}
/**
* @brief Assigns a new regular expression to a regex object.
*
* @param first The start of a range containing a valid regular
* expression.
* @param last The end of a range containing a valid regular
* expression.
* @param flags Syntax option flags.
*
* @throws regex_error if p does not contain a valid regular expression
* pattern interpreted according to @p flags. If regex_error is thrown,
* the object remains unchanged.
*/
template<typename _InputIterator>
basic_regex&
assign(_InputIterator __first, _InputIterator __last,
flag_type __flags = regex_constants::ECMAScript)
{ return this->assign(string_type(__first, __last), __flags); }
#ifdef _GLIBCXX_INCLUDE_AS_CXX0X
/**
* @brief Assigns a new regular expression to a regex object.
*
* @param l An initializer list representing a regular expression.
* @param flags Syntax option flags.
*
* @throws regex_error if @p l does not contain a valid regular
* expression pattern interpreted according to @p flags. If regex_error
* is thrown, the object remains unchanged.
*/
basic_regex&
assign(initializer_list<_Ch_type> __l,
flag_type __f = regex_constants::ECMAScript)
{ return this->assign(__l.begin(), __l.end(), __f); }
#endif
// [7.8.4] const operations
/**
* @brief Gets the number of marked subexpressions within the regular
* expression.
*/
unsigned int
mark_count() const
{ return _M_mark_count; }
/**
* @brief Gets the flags used to construct the regular expression
* or in the last call to assign().
*/
flag_type
flags() const
{ return _M_flags; }
// [7.8.5] locale
/**
* @brief Imbues the regular expression object with the given locale.
*
* @param loc A locale.
*/
locale_type
imbue(locale_type __loc)
{ return _M_traits.imbue(__loc); }
/**
* @brief Gets the locale currently imbued in the regular expression
* object.
*/
locale_type
getloc() const
{ return _M_traits.getloc(); }
// [7.8.6] swap
/**
* @brief Swaps the contents of two regular expression objects.
*
* @param rhs Another regular expression object.
*/
void
swap(basic_regex& __rhs)
{
std::swap(_M_flags, __rhs._M_flags);
std::swap(_M_pattern, __rhs._M_pattern);
std::swap(_M_mark_count, __rhs._M_mark_count);
std::swap(_M_traits, __rhs._M_traits);
}
private:
/**
* @brief Compiles a regular expression pattern into a NFA.
* @todo Implement this function.
*/
void _M_compile();
protected:
flag_type _M_flags;
string_type _M_pattern;
unsigned int _M_mark_count;
_Rx_traits _M_traits;
};
/** @brief Standard regular expressions. */
typedef basic_regex<char> regex;
#ifdef _GLIBCXX_USE_WCHAR_T
/** @brief Standard wide-character regular expressions. */
typedef basic_regex<wchar_t> wregex;
#endif
// [7.8.6] basic_regex swap
/**
* @brief Swaps the contents of two regular expression objects.
* @param lhs First regular expression.
* @param rhs Second regular expression.
*/
template<typename _Ch_type, typename _Rx_traits>
inline void
swap(basic_regex<_Ch_type, _Rx_traits>& __lhs,
basic_regex<_Ch_type, _Rx_traits>& __rhs)
{ __lhs.swap(__rhs); }
// [7.9] Class template sub_match
/**
* A sequence of characters matched by a particular marked sub-expression.
*
* An object of this class is essentially a pair of iterators marking a
* matched subexpression within a regular expression pattern match. Such
* objects can be converted to and compared with std::basic_string objects
* of a similar base character type as the pattern matched by the regular
* expression.
*
* The iterators that make up the pair are the usual half-open interval
* referencing the actual original pattern matched.
*/
template<typename _BiIter>
class sub_match : public std::pair<_BiIter, _BiIter>
{
public:
typedef typename iterator_traits<_BiIter>::value_type value_type;
typedef typename iterator_traits<_BiIter>::difference_type
difference_type;
typedef _BiIter iterator;
public:
bool matched;
/**
* Gets the length of the matching sequence.
*/
difference_type
length() const
{ return this->matched ? std::distance(this->first, this->second) : 0; }
/**
* @brief Gets the matching sequence as a string.
*
* @returns the matching sequence as a string.
*
* This is the implicit conversion operator. It is identical to the
* str() member function except that it will want to pop up in
* unexpected places and cause a great deal of confusion and cursing
* from the unwary.
*/
operator basic_string<value_type>() const
{
return this->matched
? std::basic_string<value_type>(this->first, this->second)
: std::basic_string<value_type>();
}
/**
* @brief Gets the matching sequence as a string.
*
* @returns the matching sequence as a string.
*/
basic_string<value_type>
str() const
{
return this->matched
? std::basic_string<value_type>(this->first, this->second)
: std::basic_string<value_type>();
}
/**
* @brief Compares this and another matched sequence.
*
* @param s Another matched sequence to compare to this one.
*
* @retval <0 this matched sequence will collate before @p s.
* @retval =0 this matched sequence is equivalent to @p s.
* @retval <0 this matched sequence will collate after @p s.
*/
int
compare(const sub_match& __s) const
{ return this->str().compare(__s.str()); }
/**
* @brief Compares this sub_match to a string.
*
* @param s A string to compare to this sub_match.
*
* @retval <0 this matched sequence will collate before @p s.
* @retval =0 this matched sequence is equivalent to @p s.
* @retval <0 this matched sequence will collate after @p s.
*/
int
compare(const basic_string<value_type>& __s) const
{ return this->str().compare(__s); }
/**
* @brief Compares this sub_match to a C-style string.
*
* @param s A C-style string to compare to this sub_match.
*
* @retval <0 this matched sequence will collate before @p s.
* @retval =0 this matched sequence is equivalent to @p s.
* @retval <0 this matched sequence will collate after @p s.
*/
int
compare(const value_type* __s) const
{ return this->str().compare(__s); }
};
/** @brief Standard regex submatch over a C-style null-terminated string. */
typedef sub_match<const char*> csub_match;
/** @brief Standard regex submatch over a standard string. */
typedef sub_match<string::const_iterator> ssub_match;
#ifdef _GLIBCXX_USE_WCHAR_T
/** @brief Regex submatch over a C-style null-terminated wide string. */
typedef sub_match<const wchar_t*> wcsub_match;
/** @brief Regex submatch over a standard wide string. */
typedef sub_match<wstring::const_iterator> wssub_match;
#endif
// [7.9.2] sub_match non-member operators
/**
* @brief Tests the equivalence of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator==(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) == 0; }
/**
* @brief Tests the inequivalence of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator!=(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) != 0; }
/**
* @brief Tests the ordering of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator<(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) < 0; }
/**
* @brief Tests the ordering of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator<=(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) <= 0; }
/**
* @brief Tests the ordering of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator>=(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) >= 0; }
/**
* @brief Tests the ordering of two regular expression submatches.
* @param lhs First regular expression submatch.
* @param rhs Second regular expression submatch.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _BiIter>
inline bool
operator>(const sub_match<_BiIter>& __lhs,
const sub_match<_BiIter>& __rhs)
{ return __lhs.compare(__rhs) > 0; }
/**
* @brief Tests the equivalence of a string and a regular expression
* submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator==(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs == __rhs.str(); }
/**
* @brief Tests the inequivalence of a string and a regular expression
* submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator!=(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs)
{ return __lhs != __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator<(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs)
{ return __lhs < __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator>(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs)
{ return __lhs > __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator>=(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs)
{ return __lhs >= __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator<=(const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __lhs, const sub_match<_Bi_iter>& __rhs)
{ return __lhs <= __rhs.str(); }
/**
* @brief Tests the equivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator==(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() == __rhs; }
/**
* @brief Tests the inequivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter, typename _Ch_traits, typename _Ch_alloc>
inline bool
operator!=(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() != __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter, class _Ch_traits, class _Ch_alloc>
inline bool
operator<(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() < __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter, class _Ch_traits, class _Ch_alloc>
inline bool
operator>(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() > __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter, class _Ch_traits, class _Ch_alloc>
inline bool
operator>=(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() >= __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter, class _Ch_traits, class _Ch_alloc>
inline bool
operator<=(const sub_match<_Bi_iter>& __lhs,
const basic_string<
typename iterator_traits<_Bi_iter>::value_type,
_Ch_traits, _Ch_alloc>& __rhs)
{ return __lhs.str() <= __rhs; }
/**
* @brief Tests the equivalence of a C string and a regular expression
* submatch.
* @param lhs A C string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator==(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs == __rhs.str(); }
/**
* @brief Tests the inequivalence of an iterator value and a regular
* expression submatch.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator!=(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs != __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs < __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs > __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>=(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs >= __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<=(typename iterator_traits<_Bi_iter>::value_type const* __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs <= __rhs.str(); }
/**
* @brief Tests the equivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A pointer to a string?
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator==(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() == __rhs; }
/**
* @brief Tests the inequivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A pointer to a string.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator!=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() != __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() < __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() > __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() >= __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A string.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const* __rhs)
{ return __lhs.str() <= __rhs; }
/**
* @brief Tests the equivalence of a string and a regular expression
* submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator==(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs == __rhs.str(); }
/**
* @brief Tests the inequivalence of a string and a regular expression
* submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator!=(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs != __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs < __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs > __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>=(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs >= __rhs.str(); }
/**
* @brief Tests the ordering of a string and a regular expression submatch.
* @param lhs A string.
* @param rhs A regular expression submatch.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<=(typename iterator_traits<_Bi_iter>::value_type const& __lhs,
const sub_match<_Bi_iter>& __rhs)
{ return __lhs <= __rhs.str(); }
/**
* @brief Tests the equivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs is equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator==(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() == __rhs; }
/**
* @brief Tests the inequivalence of a regular expression submatch and a
* string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs is not equivalent to @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator!=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() != __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs precedes @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() < __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs succeeds @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() > __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs does not precede @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator>=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() >= __rhs; }
/**
* @brief Tests the ordering of a regular expression submatch and a string.
* @param lhs A regular expression submatch.
* @param rhs A const string reference.
* @returns true if @a lhs does not succeed @a rhs, false otherwise.
*/
template<typename _Bi_iter>
inline bool
operator<=(const sub_match<_Bi_iter>& __lhs,
typename iterator_traits<_Bi_iter>::value_type const& __rhs)
{ return __lhs.str() <= __rhs; }
/**
* @brief Inserts a matched string into an output stream.
*
* @param os The output stream.
* @param m A submatch string.
*
* @returns the output stream with the submatch string inserted.
*/
template<typename _Ch_type, typename _Ch_traits, typename _Bi_iter>
inline
basic_ostream<_Ch_type, _Ch_traits>&
operator<<(basic_ostream<_Ch_type, _Ch_traits>& __os,
const sub_match<_Bi_iter>& __m)
{ return __os << __m.str(); }
// [7.10] Class template match_results
/**
* @brief The results of a match or search operation.
*
* A collection of character sequences representing the result of a regular
* expression match. Storage for the collection is allocated and freed as
* necessary by the member functions of class template match_results.
*
* This class satisfies the Sequence requirements, with the exception that
* only the operations defined for a const-qualified Sequence are supported.
*
* The sub_match object stored at index 0 represents sub-expression 0, i.e.
* the whole match. In this case the sub_match member matched is always true.
* The sub_match object stored at index n denotes what matched the marked
* sub-expression n within the matched expression. If the sub-expression n
* participated in a regular expression match then the sub_match member
* matched evaluates to true, and members first and second denote the range
* of characters [first, second) which formed that match. Otherwise matched
* is false, and members first and second point to the end of the sequence
* that was searched.
*
* @nosubgrouping
*/
template<typename _Bi_iter,
typename _Allocator = allocator<sub_match<_Bi_iter> > >
class match_results
: private std::vector<std::tr1::sub_match<_Bi_iter>, _Allocator>
{
private:
typedef std::vector<std::tr1::sub_match<_Bi_iter>, _Allocator>
_Base_type;
public:
/**
* @name 10.? Public Types
*/
//@{
typedef sub_match<_Bi_iter> value_type;
typedef typename _Allocator::const_reference const_reference;
typedef const_reference reference;
typedef typename _Base_type::const_iterator const_iterator;
typedef const_iterator iterator;
typedef typename iterator_traits<_Bi_iter>::difference_type
difference_type;
typedef typename _Allocator::size_type size_type;
typedef _Allocator allocator_type;
typedef typename iterator_traits<_Bi_iter>::value_type char_type;
typedef basic_string<char_type> string_type;
//@}
public:
/**
* @name 10.1 Construction, Copying, and Destruction
*/
//@{
/**
* @brief Constructs a default %match_results container.
* @post size() returns 0 and str() returns an empty string.
*/
explicit
match_results(const _Allocator& __a = _Allocator())
: _Base_type(__a), _M_matched(false)
{ }
/**
* @brief Copy constructs a %match_results.
*/
match_results(const match_results& __rhs)
: _Base_type(__rhs), _M_matched(__rhs._M_matched),
_M_prefix(__rhs._M_prefix), _M_suffix(__rhs._M_suffix)
{ }
/**
* @brief Assigns rhs to *this.
*/
match_results&
operator=(const match_results& __rhs)
{
match_results __tmp(__rhs);
this->swap(__tmp);
return *this;
}
/**
* @brief Destroys a %match_results object.
*/
~match_results()
{ }
//@}
/**
* @name 10.2 Size
*/
//@{
/**
* @brief Gets the number of matches and submatches.
*
* The number of matches for a given regular expression will be either 0
* if there was no match or mark_count() + 1 if a match was successful.
* Some matches may be empty.
*
* @returns the number of matches found.
*/
size_type
size() const
{ return _M_matched ? _Base_type::size() + 1 : 0; }
//size_type
//max_size() const;
using _Base_type::max_size;
/**
* @brief Indicates if the %match_results contains no results.
* @retval true The %match_results object is empty.
* @retval false The %match_results object is not empty.
*/
bool
empty() const
{ return size() == 0; }
//@}
/**
* @name 10.3 Element Access
*/
//@{
/**
* @brief Gets the length of the indicated submatch.
* @param sub indicates the submatch.
*
* This function returns the length of the indicated submatch, or the
* length of the entire match if @p sub is zero (the default).
*/
difference_type
length(size_type __sub = 0) const
{ return _M_matched ? this->str(__sub).length() : 0; }
/**
* @brief Gets the offset of the beginning of the indicated submatch.
* @param sub indicates the submatch.
*
* This function returns the offset from the beginning of the target
* sequence to the beginning of the submatch, unless the value of @p sub
* is zero (the default), in which case this function returns the offset
* from the beginning of the target sequence to the beginning of the
* match.
*/
difference_type
position(size_type __sub = 0) const
{
return _M_matched ? std::distance(this->prefix().first,
(*this)[__sub].first) : 0;
}
/**
* @brief Gets the match or submatch converted to a string type.
* @param sub indicates the submatch.
*
* This function gets the submatch (or match, if @p sub is zero) extracted
* from the target range and converted to the associated string type.
*/
string_type
str(size_type __sub = 0) const
{ return _M_matched ? (*this)[__sub].str() : string_type(); }
/**
* @brief Gets a %sub_match reference for the match or submatch.
* @param sub indicates the submatch.
*
* This function gets a reference to the indicated submatch, or the entire
* match if @p sub is zero.
*
* If @p sub >= size() then this function returns a %sub_match with a
* special value indicating no submatch.
*/
const_reference
operator[](size_type __sub) const
{ return _Base_type::operator[](__sub); }
/**
* @brief Gets a %sub_match representing the match prefix.
*
* This function gets a reference to a %sub_match object representing the
* part of the target range between the start of the target range and the
* start of the match.
*/
const_reference
prefix() const
{ return _M_prefix; }
/**
* @brief Gets a %sub_match representing the match suffix.
*
* This function gets a reference to a %sub_match object representing the
* part of the target range between the end of the match and the end of
* the target range.
*/
const_reference
suffix() const
{ return _M_suffix; }
/**
* @brief Gets an iterator to the start of the %sub_match collection.
*/
const_iterator
begin() const
{ return _Base_type::begin(); }
#ifdef _GLIBCXX_INCLUDE_AS_CXX0X
/**
* @brief Gets an iterator to the start of the %sub_match collection.
*/
const_iterator
cbegin() const
{ return _Base_type::begin(); }
#endif
/**
* @brief Gets an iterator to one-past-the-end of the collection.
*/
const_iterator
end() const
{ return _Base_type::end(); }
#ifdef _GLIBCXX_INCLUDE_AS_CXX0X
/**
* @brief Gets an iterator to one-past-the-end of the collection.
*/
const_iterator
cend() const
{ return _Base_type::end(); }
#endif
//@}
/**
* @name 10.4 Formatting
*
* These functions perform formatted substitution of the matched
* character sequences into their target. The format specifiers
* and escape sequences accepted by these functions are
* determined by their @p flags parameter as documented above.
*/
//@{
/**
* @todo Implement this function.
*/
template<typename _Out_iter>
_Out_iter
format(_Out_iter __out, const string_type& __fmt,
regex_constants::match_flag_type __flags
= regex_constants::format_default) const;
/**
* @todo Implement this function.
*/
string_type
format(const string_type& __fmt,
regex_constants::match_flag_type __flags
= regex_constants::format_default) const;
//@}
/**
* @name 10.5 Allocator
*/
//@{
/**
* @brief Gets a copy of the allocator.
*/
//allocator_type
//get_allocator() const;
using _Base_type::get_allocator;
//@}
/**
* @name 10.6 Swap
*/
//@{
/**
* @brief Swaps the contents of two match_results.
*/
void
swap(match_results& __that)
{
_Base_type::swap(__that);
std::swap(_M_matched, __that._M_matched);
std::swap(_M_prefix, __that._M_prefix);
std::swap(_M_suffix, __that._M_suffix);
}
//@}
private:
bool _M_matched;
value_type _M_prefix;
value_type _M_suffix;
};
typedef match_results<const char*> cmatch;
typedef match_results<string::const_iterator> smatch;
#ifdef _GLIBCXX_USE_WCHAR_T
typedef match_results<const wchar_t*> wcmatch;
typedef match_results<wstring::const_iterator> wsmatch;
#endif
// match_results comparisons
/**
* @brief Compares two match_results for equality.
* @returns true if the two objects refer to the same match,
* false otherwise.
* @todo Implement this function.
*/
template<typename _Bi_iter, typename _Allocator>
inline bool
operator==(const match_results<_Bi_iter, _Allocator>& __m1,
const match_results<_Bi_iter, _Allocator>& __m2);
/**
* @brief Compares two match_results for inequality.
* @returns true if the two objects do not refer to the same match,
* false otherwise.
*/
template<typename _Bi_iter, class _Allocator>
inline bool
operator!=(const match_results<_Bi_iter, _Allocator>& __m1,
const match_results<_Bi_iter, _Allocator>& __m2)
{ return !(__m1 == __m2); }
// [7.10.6] match_results swap
/**
* @brief Swaps two match results.
* @param lhs A match result.
* @param rhs A match result.
*
* The contents of the two match_results objects are swapped.
*/
template<typename _Bi_iter, typename _Allocator>
inline void
swap(match_results<_Bi_iter, _Allocator>& __lhs,
match_results<_Bi_iter, _Allocator>& __rhs)
{ __lhs.swap(__rhs); }
// [7.11.2] Function template regex_match
/**
* @name Matching, Searching, and Replacing
*/
//@{
/**
* @brief Determines if there is a match between the regular expression @p e
* and all of the character sequence [first, last).
*
* @param first Beginning of the character sequence to match.
* @param last One-past-the-end of the character sequence to match.
* @param m The match results.
* @param re The regular expression.
* @param flags Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*
* @todo Implement this function.
*/
template<typename _Bi_iter, typename _Allocator,
typename _Ch_type, typename _Rx_traits>
bool
regex_match(_Bi_iter __first, _Bi_iter __last,
match_results<_Bi_iter, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default);
/**
* @brief Indicates if there is a match between the regular expression @p e
* and all of the character sequence [first, last).
*
* @param first Beginning of the character sequence to match.
* @param last One-past-the-end of the character sequence to match.
* @param re The regular expression.
* @param flags Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*/
template<typename _Bi_iter, typename _Ch_type, typename _Rx_traits>
bool
regex_match(_Bi_iter __first, _Bi_iter __last,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{
match_results<_Bi_iter> __what;
return regex_match(__first, __last, __what, __re, __flags);
}
/**
* @brief Determines if there is a match between the regular expression @p e
* and a C-style null-terminated string.
*
* @param s The C-style null-terminated string to match.
* @param m The match results.
* @param re The regular expression.
* @param f Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_type, typename _Allocator, typename _Rx_traits>
inline bool
regex_match(const _Ch_type* __s,
match_results<const _Ch_type*, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __f
= regex_constants::match_default)
{ return regex_match(__s, __s + _Rx_traits::length(__s), __m, __re, __f); }
/**
* @brief Determines if there is a match between the regular expression @p e
* and a string.
*
* @param s The string to match.
* @param m The match results.
* @param re The regular expression.
* @param flags Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_traits, typename _Ch_alloc,
typename _Allocator, typename _Ch_type, typename _Rx_traits>
inline bool
regex_match(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s,
match_results<typename basic_string<_Ch_type,
_Ch_traits, _Ch_alloc>::const_iterator, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{ return regex_match(__s.begin(), __s.end(), __m, __re, __flags); }
/**
* @brief Indicates if there is a match between the regular expression @p e
* and a C-style null-terminated string.
*
* @param s The C-style null-terminated string to match.
* @param re The regular expression.
* @param f Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_type, class _Rx_traits>
inline bool
regex_match(const _Ch_type* __s,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __f
= regex_constants::match_default)
{ return regex_match(__s, __s + _Rx_traits::length(__s), __re, __f); }
/**
* @brief Indicates if there is a match between the regular expression @p e
* and a string.
*
* @param s [IN] The string to match.
* @param re [IN] The regular expression.
* @param flags [IN] Controls how the regular expression is matched.
*
* @retval true A match exists.
* @retval false Otherwise.
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_traits, typename _Str_allocator,
typename _Ch_type, typename _Rx_traits>
inline bool
regex_match(const basic_string<_Ch_type, _Ch_traits, _Str_allocator>& __s,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{ return regex_match(__s.begin(), __s.end(), __re, __flags); }
// [7.11.3] Function template regex_search
/**
* Searches for a regular expression within a range.
* @param first [IN] The start of the string to search.
* @param last [IN] One-past-the-end of the string to search.
* @param m [OUT] The match results.
* @param re [IN] The regular expression to search for.
* @param flags [IN] Search policy flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string, the content of %m is
* undefined.
*
* @throws an exception of type regex_error.
*
* @todo Implement this function.
*/
template<typename _Bi_iter, typename _Allocator,
typename _Ch_type, typename _Rx_traits>
inline bool
regex_search(_Bi_iter __first, _Bi_iter __last,
match_results<_Bi_iter, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default);
/**
* Searches for a regular expression within a range.
* @param first [IN] The start of the string to search.
* @param last [IN] One-past-the-end of the string to search.
* @param re [IN] The regular expression to search for.
* @param flags [IN] Search policy flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string.
* @doctodo
*
* @throws an exception of type regex_error.
*/
template<typename _Bi_iter, typename _Ch_type, typename _Rx_traits>
inline bool
regex_search(_Bi_iter __first, _Bi_iter __last,
const basic_regex<_Ch_type, _Rx_traits>& __re,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{
match_results<_Bi_iter> __what;
return regex_search(__first, __last, __what, __re, __flags);
}
/**
* @brief Searches for a regular expression within a C-string.
* @param s [IN] A C-string to search for the regex.
* @param m [OUT] The set of regex matches.
* @param e [IN] The regex to search for in @p s.
* @param f [IN] The search flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string, the content of %m is
* undefined.
* @doctodo
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_type, class _Allocator, class _Rx_traits>
inline bool
regex_search(const _Ch_type* __s,
match_results<const _Ch_type*, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __e,
regex_constants::match_flag_type __f
= regex_constants::match_default)
{ return regex_search(__s, __s + _Rx_traits::length(__s), __m, __e, __f); }
/**
* @brief Searches for a regular expression within a C-string.
* @param s [IN] The C-string to search.
* @param e [IN] The regular expression to search for.
* @param f [IN] Search policy flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string.
* @doctodo
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_type, typename _Rx_traits>
inline bool
regex_search(const _Ch_type* __s,
const basic_regex<_Ch_type, _Rx_traits>& __e,
regex_constants::match_flag_type __f
= regex_constants::match_default)
{ return regex_search(__s, __s + _Rx_traits::length(__s), __e, __f); }
/**
* @brief Searches for a regular expression within a string.
* @param s [IN] The string to search.
* @param e [IN] The regular expression to search for.
* @param flags [IN] Search policy flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string.
* @doctodo
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_traits, typename _String_allocator,
typename _Ch_type, typename _Rx_traits>
inline bool
regex_search(const basic_string<_Ch_type, _Ch_traits,
_String_allocator>& __s,
const basic_regex<_Ch_type, _Rx_traits>& __e,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{ return regex_search(__s.begin(), __s.end(), __e, __flags); }
/**
* @brief Searches for a regular expression within a string.
* @param s [IN] A C++ string to search for the regex.
* @param m [OUT] The set of regex matches.
* @param e [IN] The regex to search for in @p s.
* @param f [IN] The search flags.
* @retval true A match was found within the string.
* @retval false No match was found within the string, the content of %m is
* undefined.
*
* @throws an exception of type regex_error.
*/
template<typename _Ch_traits, typename _Ch_alloc,
typename _Allocator, typename _Ch_type,
typename _Rx_traits>
inline bool
regex_search(const basic_string<_Ch_type, _Ch_traits, _Ch_alloc>& __s,
match_results<typename basic_string<_Ch_type,
_Ch_traits, _Ch_alloc>::const_iterator, _Allocator>& __m,
const basic_regex<_Ch_type, _Rx_traits>& __e,
regex_constants::match_flag_type __f
= regex_constants::match_default)
{ return regex_search(__s.begin(), __s.end(), __m, __e, __f); }
// tr1 [7.11.4] std [28.11.4] Function template regex_replace
/**
* @doctodo
* @param out
* @param first
* @param last
* @param e
* @param fmt
* @param flags
*
* @returns out
* @throws an exception of type regex_error.
*
* @todo Implement this function.
*/
template<typename _Out_iter, typename _Bi_iter,
typename _Rx_traits, typename _Ch_type>
inline _Out_iter
regex_replace(_Out_iter __out, _Bi_iter __first, _Bi_iter __last,
const basic_regex<_Ch_type, _Rx_traits>& __e,
const basic_string<_Ch_type>& __fmt,
regex_constants::match_flag_type __flags
= regex_constants::match_default);
/**
* @doctodo
* @param s
* @param e
* @param fmt
* @param flags
*
* @returns a copy of string @p s with replacements.
*
* @throws an exception of type regex_error.
*/
template<typename _Rx_traits, typename _Ch_type>
inline basic_string<_Ch_type>
regex_replace(const basic_string<_Ch_type>& __s,
const basic_regex<_Ch_type, _Rx_traits>& __e,
const basic_string<_Ch_type>& __fmt,
regex_constants::match_flag_type __flags
= regex_constants::match_default)
{
std::string __result;
regex_replace(std::back_inserter(__result),
__s.begin(), __s.end(), __e, __fmt, __flags);
return __result;
}
//@}
// tr1 [7.12.1] std [28.12] Class template regex_iterator
/**
* An iterator adaptor that will provide repeated calls of regex_search over
* a range until no more matches remain.
*/
template<typename _Bi_iter,
typename _Ch_type = typename iterator_traits<_Bi_iter>::value_type,
typename _Rx_traits = regex_traits<_Ch_type> >
class regex_iterator
{
public:
typedef basic_regex<_Ch_type, _Rx_traits> regex_type;
typedef match_results<_Bi_iter> value_type;
typedef std::ptrdiff_t difference_type;
typedef const value_type* pointer;
typedef const value_type& reference;
typedef std::forward_iterator_tag iterator_category;
public:
/**
* @brief Provides a singular iterator, useful for indicating
* one-past-the-end of a range.
* @todo Implement this function.
* @doctodo
*/
regex_iterator();
/**
* Constructs a %regex_iterator...
* @param a [IN] The start of a text range to search.
* @param b [IN] One-past-the-end of the text range to search.
* @param re [IN] The regular expression to match.
* @param m [IN] Policy flags for match rules.
* @todo Implement this function.
* @doctodo
*/
regex_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re,
regex_constants::match_flag_type __m
= regex_constants::match_default);
/**
* Copy constructs a %regex_iterator.
* @todo Implement this function.
* @doctodo
*/
regex_iterator(const regex_iterator& __rhs);
/**
* @todo Implement this function.
* @doctodo
*/
regex_iterator&
operator=(const regex_iterator& __rhs);
/**
* @todo Implement this function.
* @doctodo
*/
bool
operator==(const regex_iterator& __rhs);
/**
* @todo Implement this function.
* @doctodo
*/
bool
operator!=(const regex_iterator& __rhs);
/**
* @todo Implement this function.
* @doctodo
*/
const value_type&
operator*();
/**
* @todo Implement this function.
* @doctodo
*/
const value_type*
operator->();
/**
* @todo Implement this function.
* @doctodo
*/
regex_iterator&
operator++();
/**
* @todo Implement this function.
* @doctodo
*/
regex_iterator
operator++(int);
private:
// these members are shown for exposition only:
_Bi_iter begin;
_Bi_iter end;
const regex_type* pregex;
regex_constants::match_flag_type flags;
match_results<_Bi_iter> match;
};
typedef regex_iterator<const char*> cregex_iterator;
typedef regex_iterator<string::const_iterator> sregex_iterator;
#ifdef _GLIBCXX_USE_WCHAR_T
typedef regex_iterator<const wchar_t*> wcregex_iterator;
typedef regex_iterator<wstring::const_iterator> wsregex_iterator;
#endif
// [7.12.2] Class template regex_token_iterator
/**
* Iterates over submatches in a range (or @a splits a text string).
*
* The purpose of this iterator is to enumerate all, or all specified,
* matches of a regular expression within a text range. The dereferenced
* value of an iterator of this class is a std::tr1::sub_match object.
*/
template<typename _Bi_iter,
typename _Ch_type = typename iterator_traits<_Bi_iter>::value_type,
typename _Rx_traits = regex_traits<_Ch_type> >
class regex_token_iterator
{
public:
typedef basic_regex<_Ch_type, _Rx_traits> regex_type;
typedef sub_match<_Bi_iter> value_type;
typedef std::ptrdiff_t difference_type;
typedef const value_type* pointer;
typedef const value_type& reference;
typedef std::forward_iterator_tag iterator_category;
public:
/**
* @brief Default constructs a %regex_token_iterator.
* @todo Implement this function.
*
* A default-constructed %regex_token_iterator is a singular iterator
* that will compare equal to the one-past-the-end value for any
* iterator of the same type.
*/
regex_token_iterator();
/**
* Constructs a %regex_token_iterator...
* @param a [IN] The start of the text to search.
* @param b [IN] One-past-the-end of the text to search.
* @param re [IN] The regular expression to search for.
* @param submatch [IN] Which submatch to return. There are some
* special values for this parameter:
* - -1 each enumerated subexpression does NOT
* match the regular expression (aka field
* splitting)
* - 0 the entire string matching the
* subexpression is returned for each match
* within the text.
* - >0 enumerates only the indicated
* subexpression from a match within the text.
* @param m [IN] Policy flags for match rules.
*
* @todo Implement this function.
* @doctodo
*/
regex_token_iterator(_Bi_iter __a, _Bi_iter __b, const regex_type& __re,
int __submatch = 0,
regex_constants::match_flag_type __m
= regex_constants::match_default);
/**
* Constructs a %regex_token_iterator...
* @param a [IN] The start of the text to search.
* @param b [IN] One-past-the-end of the text to search.
* @param re [IN] The regular expression to search for.
* @param submatches [IN] A list of subexpressions to return for each
* regular expression match within the text.
* @param m [IN] Policy flags for match rules.
*
* @todo Implement this function.
* @doctodo
*/
regex_token_iterator(_Bi_iter __a, _Bi_iter __b,
const regex_type& __re,
const std::vector<int>& __submatches,
regex_constants::match_flag_type __m
= regex_constants::match_default);
/**
* Constructs a %regex_token_iterator...
* @param a [IN] The start of the text to search.
* @param b [IN] One-past-the-end of the text to search.
* @param re [IN] The regular expression to search for.
* @param submatches [IN] A list of subexpressions to return for each
* regular expression match within the text.
* @param m [IN] Policy flags for match rules.
* @todo Implement this function.
* @doctodo
*/
template<std::size_t _Nm>
regex_token_iterator(_Bi_iter __a, _Bi_iter __b,
const regex_type& __re,
const int (&__submatches)[_Nm],
regex_constants::match_flag_type __m
= regex_constants::match_default);
/**
* @brief Copy constructs a %regex_token_iterator.
* @param rhs [IN] A %regex_token_iterator to copy.
* @todo Implement this function.
*/
regex_token_iterator(const regex_token_iterator& __rhs);
/**
* @brief Assigns a %regex_token_iterator to another.
* @param rhs [IN] A %regex_token_iterator to copy.
* @todo Implement this function.
*/
regex_token_iterator&
operator=(const regex_token_iterator& __rhs);
/**
* @brief Compares a %regex_token_iterator to another for equality.
* @todo Implement this function.
*/
bool
operator==(const regex_token_iterator& __rhs);
/**
* @brief Compares a %regex_token_iterator to another for inequality.
* @todo Implement this function.
*/
bool
operator!=(const regex_token_iterator& __rhs);
/**
* @brief Dereferences a %regex_token_iterator.
* @todo Implement this function.
*/
const value_type&
operator*();
/**
* @brief Selects a %regex_token_iterator member.
* @todo Implement this function.
*/
const value_type*
operator->();
/**
* @brief Increments a %regex_token_iterator.
* @todo Implement this function.
*/
regex_token_iterator&
operator++();
/**
* @brief Postincrements a %regex_token_iterator.
* @todo Implement this function.
*/
regex_token_iterator
operator++(int);
private: // data members for exposition only:
typedef regex_iterator<_Bi_iter, _Ch_type, _Rx_traits> position_iterator;
position_iterator __position;
const value_type* __result;
value_type __suffix;
std::size_t __n;
std::vector<int> __subs;
};
/** @brief Token iterator for C-style NULL-terminated strings. */
typedef regex_token_iterator<const char*> cregex_token_iterator;
/** @brief Token iterator for standard strings. */
typedef regex_token_iterator<string::const_iterator> sregex_token_iterator;
#ifdef _GLIBCXX_USE_WCHAR_T
/** @brief Token iterator for C-style NULL-terminated wide strings. */
typedef regex_token_iterator<const wchar_t*> wcregex_token_iterator;
/** @brief Token iterator for standard wide-character strings. */
typedef regex_token_iterator<wstring::const_iterator> wsregex_token_iterator;
#endif
//@}
_GLIBCXX_END_NAMESPACE_VERSION
}
}
#endif // _GLIBCXX_TR1_REGEX
| [
"[email protected]"
] | ||
e7167ff65a1608b58959367ec6a295e7164053de | 831090e5501ceb435aed82106c400166110d0be0 | /TestProject/src/PGkZF3mQ0/Advanced Starter Code/C++/PasswordCracking/main.cpp | 17d32776946c666f6abf9a32a538e01a9f6dff67 | [] | no_license | pforderique/Eclipse-workspace | f8cf825e491baa5cfca8adceb996cb0eb1acda79 | d0bfe1c8321403618644dcd4be16cd90ce94632a | refs/heads/master | 2022-10-09T08:34:30.469950 | 2020-06-06T13:52:01 | 2020-06-06T13:52:01 | 172,536,443 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | cpp | #include <iostream>
using namespace std;
int main(int argc, const char * argv[]) {
int guess; // A five-digit integer.
int lower; // The lower bound.
int upper; // The upper bound.
int answer; // The correct password.
cin >> guess;
cin >> lower;
cin >> upper;
cin >> answer;
// code to solve the problem. You can write and call other functions as well.
return 0;
}
| [
"[email protected]"
] | |
ef7f9ebe321ce97367afd3ffd666d5b185fb135f | e3b0ef6793a4339bc04f2ac49081582722f219c6 | /mySCClient/GlobalFunctions.cpp | 916ce3c8c9b6e8473ef475adf50b797fdf8cdd89 | [] | no_license | CK-Han/TerranWar | faac18d60916f1a0c754a1aee2f28ec6dc466823 | 17281b7da735cf615837b2128741a90b13d13765 | refs/heads/master | 2021-01-22T18:18:20.251349 | 2018-05-08T22:25:52 | 2018-05-08T22:25:52 | 85,074,931 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 8,571 | cpp | #include "GlobalFunctions.h"
#include "stdafx.h"
bool isAnimateObject(int type)
{
if (ANIMATE_OBJECT_START <= type && type <= ANIMATE_OBJECT_END)
return true;
else if (STATIC_OBJECT_START <= type && type <= STATIC_OBJECT_END)
return false;
else
{
cprintf("Invalid Object Type : CScene::isAnimateObject\n");
return false;
}
}
bool isEnemyObject(int type)
{
bool bAnimateObject = isAnimateObject(type);
int my_type = type - ADD_ENEMY_INDEX;
if (bAnimateObject)
{
if (ANIMATE_OBJECT_START <= my_type) //1이 scv니까
return true;
else //0보다 작다 -> 아군 유닛이었다.
return false;
}
else //static
{
if (STATIC_OBJECT_START <= my_type)
return true;
else
return false;
}
}
bool isAirObject(int type)
{
bool bAnimateObject = isAnimateObject(type);
if (bAnimateObject)
{
int my_type = type;
if (isEnemyObject(type))
my_type -= ADD_ENEMY_INDEX;
if (AIR_OBJECT_START <= my_type && my_type <= AIR_OBJECT_END)
return true;
else
return false;
}
else
return false;
}
int getSoundOffsetByType(int type)
{
int my_type = type;
if (isEnemyObject(type))
my_type -= ADD_ENEMY_INDEX;
int retVal;
switch ((OBJECT_TYPE)my_type)
{
case OBJECT_TYPE::Banshee:
retVal = start_offset::banshee; break;
case OBJECT_TYPE::BattleCruiser:
retVal = start_offset::battlecruiser; break;
case OBJECT_TYPE::Ghost:
retVal = start_offset::ghost; break;
case OBJECT_TYPE::Hellion:
retVal = start_offset::hellion; break;
case OBJECT_TYPE::Marauder:
retVal = start_offset::marauder; break;
case OBJECT_TYPE::Marine:
retVal = start_offset::marine; break;
case OBJECT_TYPE::Medivac:
retVal = start_offset::medivac; break;
case OBJECT_TYPE::Mule:
retVal = start_offset::mule; break;
case OBJECT_TYPE::Raven:
retVal = start_offset::raven; break;
case OBJECT_TYPE::Reaper:
retVal = start_offset::reaper; break;
case OBJECT_TYPE::Scv:
retVal = start_offset::scv; break;
case OBJECT_TYPE::Siegetank:
retVal = start_offset::siegetank; break;
case OBJECT_TYPE::Thor:
retVal = start_offset::thor; break;
case OBJECT_TYPE::Viking:
retVal = start_offset::viking; break;
case OBJECT_TYPE::Armory:
retVal = start_offset::armory; break;
case OBJECT_TYPE::Barrack:
retVal = start_offset::barrack; break;
case OBJECT_TYPE::Bunker:
retVal = start_offset::bunker; break;
case OBJECT_TYPE::Commandcenter:
retVal = start_offset::commandcenter; break;
case OBJECT_TYPE::Engineeringbay:
retVal = start_offset::engineeringbay; break;
case OBJECT_TYPE::Factory:
retVal = start_offset::factory; break;
case OBJECT_TYPE::Fusioncore:
retVal = start_offset::fusioncore; break;
case OBJECT_TYPE::Ghostacademy:
retVal = start_offset::ghostacademy; break;
case OBJECT_TYPE::Missileturret:
retVal = start_offset::missileturret; break;
case OBJECT_TYPE::Reactor:
retVal = start_offset::reactor; break;
case OBJECT_TYPE::Refinery:
retVal = start_offset::refinery; break;
case OBJECT_TYPE::Sensortower:
retVal = start_offset::sensortower; break;
case OBJECT_TYPE::Starport:
retVal = start_offset::starport; break;
case OBJECT_TYPE::Supplydepot:
retVal = start_offset::supplydepot; break;
case OBJECT_TYPE::Techlab:
retVal = start_offset::techlab; break;
default: retVal = 3;
}
return retVal;
}
string getNameByType(int type)
{
int my_type = type;
if (isEnemyObject(type))
my_type -= ADD_ENEMY_INDEX;
string retString;
switch ((OBJECT_TYPE)my_type)
{
case OBJECT_TYPE::Banshee:
retString = string("banshee"); break;
case OBJECT_TYPE::BattleCruiser:
retString = string("battlecruiser"); break;
case OBJECT_TYPE::Ghost:
retString = string("ghost"); break;
case OBJECT_TYPE::Hellion:
retString = string("hellion"); break;
case OBJECT_TYPE::Marauder:
retString = string("marauder"); break;
case OBJECT_TYPE::Marine:
retString = string("marine"); break;
case OBJECT_TYPE::Medivac:
retString = string("medivac"); break;
case OBJECT_TYPE::Mule:
retString = string("mule"); break;
case OBJECT_TYPE::Raven:
retString = string("raven"); break;
case OBJECT_TYPE::Reaper:
retString = string("reaper"); break;
case OBJECT_TYPE::Scv:
retString = string("scv"); break;
case OBJECT_TYPE::Siegetank:
retString = string("siegetank"); break;
case OBJECT_TYPE::Thor:
retString = string("thor"); break;
case OBJECT_TYPE::Viking:
retString = string("viking"); break;
case OBJECT_TYPE::Armory:
retString = string("armory"); break;
case OBJECT_TYPE::Barrack:
retString = string("barrack"); break;
case OBJECT_TYPE::Bunker:
retString = string("bunker"); break;
case OBJECT_TYPE::Commandcenter:
retString = string("commandcenter"); break;
case OBJECT_TYPE::Engineeringbay:
retString = string("engineeringbay"); break;
case OBJECT_TYPE::Factory:
retString = string("factory"); break;
case OBJECT_TYPE::Fusioncore:
retString = string("fusioncore"); break;
case OBJECT_TYPE::Ghostacademy:
retString = string("ghostacademy"); break;
case OBJECT_TYPE::Missileturret:
retString = string("missileturret"); break;
case OBJECT_TYPE::Reactor:
retString = string("reactor"); break;
case OBJECT_TYPE::Refinery:
retString = string("refinery"); break;
case OBJECT_TYPE::Sensortower:
retString = string("sensortower"); break;
case OBJECT_TYPE::Starport:
retString = string("starport"); break;
case OBJECT_TYPE::Supplydepot:
retString = string("supplydepot"); break;
case OBJECT_TYPE::Techlab:
retString = string("techlab"); break;
default: retString = string("");
}
return retString;
}
void getNeedResourceForCreate(int type, int& mineral, int& gas)
{
int my_type = type;
if (isEnemyObject(type))
my_type -= ADD_ENEMY_INDEX;
switch ((OBJECT_TYPE)my_type)
{
case OBJECT_TYPE::Banshee:
mineral = 150; gas = 100; break;
case OBJECT_TYPE::BattleCruiser:
mineral = 400; gas = 300; break;
case OBJECT_TYPE::Ghost:
break;
case OBJECT_TYPE::Hellion:
break;
case OBJECT_TYPE::Marauder:
mineral = 100; gas = 25; break;
case OBJECT_TYPE::Marine:
mineral = 50; gas = 0; break;
case OBJECT_TYPE::Medivac:
mineral = 100; gas = 100; break;
case OBJECT_TYPE::Mule:
break;
case OBJECT_TYPE::Raven:
mineral = 100; gas = 200; break;
case OBJECT_TYPE::Reaper:
mineral = 50; gas = 50; break;
case OBJECT_TYPE::Scv:
mineral = 50; gas = 0; break;
case OBJECT_TYPE::Siegetank:
break;
case OBJECT_TYPE::Thor:
mineral = 300; gas = 200; break;
case OBJECT_TYPE::Viking:
mineral = 150; gas = 75; break;
case OBJECT_TYPE::Armory:
mineral = 150; gas = 100; break;
case OBJECT_TYPE::Barrack:
mineral = 150; gas = 0; break;
case OBJECT_TYPE::Bunker:
mineral = 100; gas = 0; break;
case OBJECT_TYPE::Commandcenter:
mineral = 400; gas = 0; break;
case OBJECT_TYPE::Engineeringbay:
mineral = 125; gas = 0; break;
case OBJECT_TYPE::Factory:
mineral = 200; gas = 50; break;
case OBJECT_TYPE::Fusioncore:
mineral = 200; gas = 200; break;
case OBJECT_TYPE::Ghostacademy:
mineral = 150; gas = 50; break;
case OBJECT_TYPE::Missileturret:
mineral = 100; gas = 0; break;
case OBJECT_TYPE::Reactor:
break;
case OBJECT_TYPE::Refinery:
mineral = 75; gas = 0; break;
case OBJECT_TYPE::Sensortower:
mineral = 100; gas = 50; break;
case OBJECT_TYPE::Starport:
mineral = 150; gas = 100; break;
case OBJECT_TYPE::Supplydepot:
mineral = 100; gas = 0; break;
case OBJECT_TYPE::Techlab:
break;
}
}
int gGameMineral = 0;
int gGameGas = 0;
int nPacketCount = 0;
void* gGameCamera = nullptr;
/*
switch ((OBJECT_TYPE)my_type)
{
case OBJECT_TYPE::Banshee:
break;
case OBJECT_TYPE::BattleCruiser:
break;
case OBJECT_TYPE::Ghost:
break;
case OBJECT_TYPE::Hellion:
break;
case OBJECT_TYPE::Marauder:
break;
case OBJECT_TYPE::Marine:
break;
case OBJECT_TYPE::Medivac:
break;
case OBJECT_TYPE::Mule:
break;
case OBJECT_TYPE::Raven:
break;
case OBJECT_TYPE::Reaper:
break;
case OBJECT_TYPE::Scv:
break;
case OBJECT_TYPE::Siegetank:
break;
case OBJECT_TYPE::Thor:
break;
case OBJECT_TYPE::Viking:
break;
case OBJECT_TYPE::Armory:
break;
case OBJECT_TYPE::Barrack:
break;
case OBJECT_TYPE::Bunker:
break;
case OBJECT_TYPE::Commandcenter:
break;
case OBJECT_TYPE::Engineeringbay:
break;
case OBJECT_TYPE::Factory:
break;
case OBJECT_TYPE::Fusioncore:
break;
case OBJECT_TYPE::Ghostacademy:
break;
case OBJECT_TYPE::Missileturret:
break;
case OBJECT_TYPE::Reactor:
break;
case OBJECT_TYPE::Refinery:
break;
case OBJECT_TYPE::Sensortower:
break;
case OBJECT_TYPE::Starport:
break;
case OBJECT_TYPE::Supplydepot:
break;
case OBJECT_TYPE::Techlab:
break;
}
*/ | [
"[email protected]"
] | |
7b0eb9c58a33a073c7f0e6cdf1f6c41442d95054 | 3c22513b9d5415a651444d2c15da1fd175006693 | /Gorski, ULTIMA-P3/MCB.h | 085d2bd7bbebd3f59a1e9c31ee019120580507b6 | [] | no_license | ggorski01/ULTIMA | 4cb845eaabe511364332dade430bdd0b75b7e1f4 | 9fd0cea8af92250f6afe0f6dba05fa2214d87500 | refs/heads/master | 2022-06-19T13:31:00.980069 | 2020-05-06T22:44:57 | 2020-05-06T22:44:57 | 261,894,405 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,582 | h | /*
Filename: MCB.h
Author: Giovanna Gorski
Course: C435 - Operating Systems
Instructor: Dr. Hossein Hakimzadeh
Spring 2020
Purpose: To create a Master Control Block mechanism in which registers
other mechanisms such as IPC, Scheduler, Semaphore...
Furthermore, its registration allows the usage of such mechanisms
without controlling access issues.
*/
#ifndef MCB_H
#define MCB_H
#include <iostream>
#include "Scheduler.h"
#include "Semaphore.h"
#include "Window.h"
class Semaphore;
class Scheduler;
class IPC;
class Window;
class MemoryManager;
class MCB
{
public:
Scheduler *mysch;
Semaphore *mysema;
Semaphore *mysema2;
IPC *myIPC;
Window *mywin;
MemoryManager *mymemo;
MCB(Scheduler *theScheduler, Semaphore *theSemaphore, Semaphore *theSemaphore2, IPC *theIPC, Window *theWIN, MemoryManager *theMemo);
};
//----------------------------------------
//---- M E M B E R F U N C T I O N S ----
//----------------------------------------
//Constructor
MCB::MCB(Scheduler *theScheduler, Semaphore *theSemaphore, Semaphore *theSemaphore2, IPC *theIPC, Window *theWIN, MemoryManager *theMemo)
{
this->myIPC = theIPC;
this->mysch = theScheduler;
this->mysema = theSemaphore;
this->mywin = theWIN;
this->mymemo = theMemo;
this->mysema2 = theSemaphore2;
}
//----------------------------------------
//----------------------------------------
//---- G L O B A L O B J E C T ----
//----------------------------------------
MCB *mcb;
//----------------------------------------
#endif | [
"[email protected]"
] | |
73ad784fd4067f65a997f03d6ace4654571fe119 | 97aab27d4410969e589ae408b2724d0faa5039e2 | /SDK/EXES/INSTALL VISUAL 6 SDK/LEGACY/MSDN/SMPL/SMPL/MSDN/techart/3196/gleasvw.h | c841faa386d2205ca416e9f9c3dd97e963a52250 | [] | no_license | FutureWang123/dreamcast-docs | 82e4226cb1915f8772418373d5cb517713f858e2 | 58027aeb669a80aa783a6d2cdcd2d161fd50d359 | refs/heads/master | 2021-10-26T00:04:25.414629 | 2018-08-10T21:20:37 | 2018-08-10T21:20:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,466 | h | // gleasvw.h : interface of the CGLEasyView class
//
/////////////////////////////////////////////////////////////////////////////
class CGLEasyView : public CView
{
protected: // create from serialization only
CGLEasyView();
DECLARE_DYNCREATE(CGLEasyView)
// Attributes
public:
CGLEasyDoc* GetDocument() { return (CGLEasyDoc*)m_pDocument; }
HGLRC m_hrc ; //OpenGL Rendering Context
CPalette* m_pPal ; //Palette
// Operations
public:
void PrepareScene() ; //OPENGL build display lists
void DrawScene() ; //OPENGL draws OpenGL scene
void OutputGlError(char* label) ; //OPENGL function to display OpenGL errors using TRACE
//
// Rotation support
//
CSize m_angle[4];
BOOL m_bRotate ;
void Tick() ; // See GLEasy.cpp
void Rotate(BOOL bRotate) ;
//
// Multiple object support
//
enum enum_OBJECTS {Box=1, Pyramid=2, Dodec=3} ;
enum_OBJECTS m_RotatingObject ;
//
// Support for generating RGB color palette
//
BOOL CreateRGBPalette(HDC hDC) ;
unsigned char ComponentFromIndex(int i, UINT nbits, UINT shift) ;
static unsigned char m_oneto8[2];
static unsigned char m_twoto8[4];
static unsigned char m_threeto8[8];
static int m_defaultOverride[13];
static PALETTEENTRY m_defaultPalEntry[20];
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CGLEasyView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual void OnInitialUpdate();
protected:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CGLEasyView();
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CGLEasyView)
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnDestroy();
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnRotateStart();
afx_msg void OnUpdateRotateStart(CCmdUI* pCmdUI);
afx_msg void OnRotateStop();
afx_msg void OnUpdateRotateStop(CCmdUI* pCmdUI);
afx_msg void OnRotateBox();
afx_msg void OnUpdateRotateBox(CCmdUI* pCmdUI);
afx_msg void OnRotatePyramid();
afx_msg void OnUpdateRotatePyramid(CCmdUI* pCmdUI);
afx_msg void OnRotateDodec();
afx_msg void OnUpdateRotateDodec(CCmdUI* pCmdUI);
afx_msg void OnPaletteChanged(CWnd* pFocusWnd);
afx_msg BOOL OnQueryNewPalette();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
/////////////////////////////////////////////////////////////////////////////
| [
"[email protected]"
] | |
8832e83f23cb19c37ac6ef34f5f67ac1967bf8b1 | 7be8e3636bf08ebdc6662879dc5afec548705537 | /ios/Pods/Flipper-Folly/folly/detail/AsyncTrace.h | c9bc2dbaf2c13b5553d3aad777aa81c2584b1695 | [
"MIT",
"Apache-2.0"
] | permissive | rdhox/react-native-smooth-picker | 3c7384f1fed0e37f076361cce96071d01b70e209 | ae9316c49512f7ed9824c5a3ad50cdf5e80fffa9 | refs/heads/master | 2023-01-08T16:59:40.709147 | 2021-07-03T14:13:21 | 2021-07-03T14:13:21 | 160,224,312 | 230 | 31 | MIT | 2023-01-06T01:46:04 | 2018-12-03T16:54:10 | TypeScript | UTF-8 | C++ | false | false | 1,336 | h | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* 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.
*/
#pragma once
#include <chrono>
#include <folly/Optional.h>
namespace folly {
class Executor;
class IOExecutor;
namespace async_tracing {
void logSetGlobalCPUExecutor(Executor*) noexcept;
void logSetGlobalCPUExecutorToImmutable() noexcept;
void logGetGlobalCPUExecutor(Executor*) noexcept;
void logGetImmutableCPUExecutor(Executor*) noexcept;
void logSetGlobalIOExecutor(IOExecutor*) noexcept;
void logGetGlobalIOExecutor(IOExecutor*) noexcept;
void logGetImmutableIOExecutor(IOExecutor*) noexcept;
void logSemiFutureVia(Executor*, Executor*) noexcept;
void logFutureVia(Executor*, Executor*) noexcept;
void logBlockingOperation(std::chrono::milliseconds) noexcept;
} // namespace async_tracing
} // namespace folly
| [
"[email protected]"
] |
Subsets and Splits