blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1d966df9d536890fb52dac2ca613e317888d1d05 | c717b260750d9c733b40e668d2841dee92167699 | /software/libs/mctl/ft_sensor_cal.hpp | 2aad94ea629536606217071b13fc275da9c3e267 | [
"Apache-2.0"
] | permissive | hanhanhan-kim/noah_motion_system | b68e3fc6db1a0faea272ead7a22a043dfb80a6c8 | 5bea2750eac638b9f90720b10b5e2516f108c65b | refs/heads/master | 2022-11-06T08:20:49.977792 | 2017-10-06T00:12:05 | 2017-10-06T00:12:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,293 | hpp | #ifndef FT_SENSOR_CAL_HPP
#define FT_SENSOR_CAL_HPP
#include "rtn_status.hpp"
#include "ft_tool_transform.hpp"
#include <memory>
#include <vector>
#include <iostream>
#include <armadillo>
namespace atidaq
{
extern "C"
{
struct Calibration;
}
}
namespace mctl
{
class FT_SensorCal
{
public:
static const std::string DefaultForceUnits;
static const std::string DefaultTorqueUnits;
static const FT_ToolTransform DefaultToolTransform;
static const int FT_VectorSize;
static const int AinVectorSize;
static const int DisplayFloatPrecision;
static const int DisplayMatrixColumnWidth;
FT_SensorCal();
RtnStatus load(std::string filename);
RtnStatus set_force_units(std::string units);
RtnStatus set_torque_units(std::string units);
RtnStatus set_tool_transform(FT_ToolTransform trans);
RtnStatus set_temperature_comp(bool value);
RtnStatus set_bias(std::vector<double> bias_vec);
RtnStatus set_bias(arma::Row<double> bias_vec);
RtnStatus set_bias(double fx, double fy, double fz, double tx, double ty, double tz);
RtnStatus get_units(std::vector<std::string> &units_vec);
RtnStatus get_force_units(std::string &units);
RtnStatus get_torque_units(std::string &units);
RtnStatus get_tool_transform(FT_ToolTransform &tran);
RtnStatus get_filename(std::string &filename);
RtnStatus get_info_string(std::string &info);
RtnStatus has_temperature_comp(bool &value);
void print_info_string();
RtnStatus convert(std::vector<double> ain_vec, std::vector<double> &ft_vec);
RtnStatus convert(arma::Row<double> ain_vec, arma::Row<double> &ft_vec);
RtnStatus convert(arma::Mat<double> ain_mat, arma::Mat<double> &ft_mat);
bool is_initialized();
bool is_initialized(RtnStatus &rtn_status);
protected:
std::string filename_ = std::string("");
std::shared_ptr<atidaq::Calibration> cal_ = nullptr;
RtnStatus check_atidaq_rtn(short rtn_code);
};
}
#endif
| [
"will@iorodeo.com"
] | will@iorodeo.com |
d0779c97dc47d49d93a3454332e4a2f479e30d3e | 841776845974ba2645eff58ff8fabedd873093f0 | /8.最短路径/P2829大逃离.cpp | 278d68a6e0ebfde1361e94ca98674ad04e9183cd | [] | no_license | hello-sources/Coding-Training | f2652c9b8e58d244a172922e56897fa2a3ad52fb | d885ca23676cb712243640169cf2e5bef2d8c70e | refs/heads/master | 2023-01-19T11:17:36.097846 | 2023-01-01T00:49:09 | 2023-01-01T00:49:09 | 246,630,755 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,805 | cpp | /*************************************************************************
> File Name: P2829大逃离.cpp
> Author: ltw
> Mail: 3245849061@qq.com
> Github: https://github.com/hello-sources
> Created Time: Thu 02 Jul 2020 03:31:59 PM CST
************************************************************************/
#include <iostream>
#include <cstring>
#include <queue>
using namespace std;
struct edge {
int from, to, val, next;
};
edge edg[200005];
int n, m, k, edg_cnt, head[5005], ans[5005], ans2[5005], mark[5005], connect[5005];
char edg_mark[5005][5005];
void add_edge(int a, int b, int c) {
edg[edg_cnt].from = a;
edg[edg_cnt].to = b;
edg[edg_cnt].val = c;
edg[edg_cnt].next = head[a];
head[a] = edg_cnt;
edg_cnt++;
}
int main() {
memset(ans, 0x3F, sizeof(ans));
memset(ans2, 0x3F, sizeof(ans2));
memset(head, -1, sizeof(head));
cin >> n >> m >> k;
for (int i = 1; i <= m; i++) {
int a, b, c;
cin >> a >> b >> c;
if (edg_mark[a][b] == 0) {
connect[a]++;
connect[b]++;
}
edg_mark[a][b] = 1;
edg_mark[b][a] = 1;
add_edge(a, b, c);
add_edge(b, a, c);
}
queue<int> que;
que.push(1);
ans[1] = 0;
mark[1] = 1;
while (!que.empty()) {
int t = que.front();
que.pop();
mark[t] = 0;
for (int cnt = head[t]; cnt != -1; cnt = edg[cnt].next) {
if (ans[edg[cnt].to] > ans[t] + edg[cnt].val && (edg[cnt].to == n || connect[edg[cnt].to] >= k)) {
ans[edg[cnt].to] = ans[t] + edg[cnt].val;
if (mark[edg[cnt].to] == 0) {
mark[edg[cnt].to] = 1;
que.push(edg[cnt].to);
}
}
}
}
que.push(n);
ans2[n] = 0;
mark[n] = 1;
while (!que.empty()) {
int t = que.front();
que.pop();
mark[t] = 0;
for (int cnt = head[t]; cnt != -1; cnt = edg[cnt].next) {
if (ans2[edg[cnt].to] > ans2[t] + edg[cnt].val && (edg[cnt].to == 1 || connect[edg[cnt].to] >= k)) {
ans2[edg[cnt].to] = ans2[t] + edg[cnt].val;
if (mark[edg[cnt].to] == 0) {
mark[edg[cnt].to] = 1;
que.push(edg[cnt].to);
}
}
}
}
int fin = 999999999;
for (int i = 0; i < edg_cnt; i++) {
int t = ans[edg[i].from] + ans2[edg[i].to] + edg[i].val;
int a = edg[i].from, b = edg[i].to;
if (fin > t && t != ans[n] && ((connect[a] >= k && connect[b] >= k) || a == 1 || b == 1 || a == n || b == n)) {
fin = t;
}
}
if (fin != 999999999) {
cout << fin << endl;
} else {
cout << -1 << endl;
}
return 0;
}
| [
"3245849061@qq.com"
] | 3245849061@qq.com |
bad3392ec9536a873d23fb973e1f553ca41c6a4e | 8e854323d86b97057ee199e545f508d933d3a5be | /src/privatesend-client.h | adc49bc0ab1737349aae9d95b72cf510718cc85a | [
"MIT"
] | permissive | julivn/.github | 362789f251e73846441028cf4de5a8279fc40f0e | 6d544f99d9ba53d386863cb58e749af163c30294 | refs/heads/master | 2020-04-14T13:18:14.444317 | 2019-01-02T16:31:03 | 2019-01-02T16:31:03 | 163,864,804 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,991 | h | // Copyright (c) 2014-2017 The Dash Core developers
// Copyright (c) 2018 The Bitmonix Core developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef PRIVATESENDCLIENT_H
#define PRIVATESENDCLIENT_H
#include "masternode.h"
#include "privatesend.h"
#include "wallet/wallet.h"
#include "privatesend-util.h"
class CPrivateSendClient;
class CConnman;
static const int DENOMS_COUNT_MAX = 100;
static const int MIN_PRIVATESEND_ROUNDS = 2;
static const int MIN_PRIVATESEND_AMOUNT = 2;
static const int MIN_PRIVATESEND_LIQUIDITY = 0;
static const int MAX_PRIVATESEND_ROUNDS = 16;
static const int MAX_PRIVATESEND_AMOUNT = MAX_MONEY / COIN;
static const int MAX_PRIVATESEND_LIQUIDITY = 100;
static const int DEFAULT_PRIVATESEND_ROUNDS = 2;
static const int DEFAULT_PRIVATESEND_AMOUNT = 1000;
static const int DEFAULT_PRIVATESEND_LIQUIDITY = 0;
static const bool DEFAULT_PRIVATESEND_MULTISESSION = false;
// Warn user if mixing in gui or try to create backup if mixing in daemon mode
// when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_WARNING = 100;
// Stop mixing completely, it's too dangerous to continue when we have only this many keys left
static const int PRIVATESEND_KEYS_THRESHOLD_STOP = 50;
// The main object for accessing mixing
extern CPrivateSendClient privateSendClient;
class CPendingDsaRequest
{
private:
static const int TIMEOUT = 15;
CService addr;
CDarksendAccept dsa;
int64_t nTimeCreated;
public:
CPendingDsaRequest():
addr(CService()),
dsa(CDarksendAccept()),
nTimeCreated(0)
{};
CPendingDsaRequest(const CService& addr_, const CDarksendAccept& dsa_):
addr(addr_),
dsa(dsa_)
{ nTimeCreated = GetTime(); }
CService GetAddr() { return addr; }
CDarksendAccept GetDSA() { return dsa; }
bool IsExpired() { return GetTime() - nTimeCreated > TIMEOUT; }
friend bool operator==(const CPendingDsaRequest& a, const CPendingDsaRequest& b)
{
return a.addr == b.addr && a.dsa == b.dsa;
}
friend bool operator!=(const CPendingDsaRequest& a, const CPendingDsaRequest& b)
{
return !(a == b);
}
explicit operator bool() const
{
return *this != CPendingDsaRequest();
}
};
/** Used to keep track of current status of mixing pool
*/
class CPrivateSendClient : public CPrivateSendBase
{
private:
// Keep track of the used Masternodes
std::vector<COutPoint> vecMasternodesUsed;
std::vector<CAmount> vecDenominationsSkipped;
std::vector<COutPoint> vecOutPointLocked;
int nCachedLastSuccessBlock;
int nMinBlocksToWait; // how many blocks to wait after one successful mixing tx in non-multisession mode
// Keep track of current block height
int nCachedBlockHeight;
int nEntriesCount;
bool fLastEntryAccepted;
std::string strLastMessage;
std::string strAutoDenomResult;
masternode_info_t infoMixingMasternode;
CMutableTransaction txMyCollateral; // client side collateral
CPendingDsaRequest pendingDsaRequest;
CKeyHolderStorage keyHolderStorage; // storage for keys used in PrepareDenominate
/// Check for process
void CheckPool();
void CompletedTransaction(PoolMessage nMessageID);
bool IsDenomSkipped(CAmount nDenomValue);
bool WaitForAnotherBlock();
// Make sure we have enough keys since last backup
bool CheckAutomaticBackup();
bool JoinExistingQueue(CAmount nBalanceNeedsAnonymized, CConnman& connman);
bool StartNewQueue(CAmount nValueMin, CAmount nBalanceNeedsAnonymized, CConnman& connman);
/// Create denominations
bool CreateDenominated(CConnman& connman);
bool CreateDenominated(const CompactTallyItem& tallyItem, bool fCreateMixingCollaterals, CConnman& connman);
/// Split up large inputs or make fee sized inputs
bool MakeCollateralAmounts(CConnman& connman);
bool MakeCollateralAmounts(const CompactTallyItem& tallyItem, bool fTryDenominated, CConnman& connman);
/// As a client, submit part of a future mixing transaction to a Masternode to start the process
bool SubmitDenominate(CConnman& connman);
/// step 1: prepare denominated inputs and outputs
bool PrepareDenominate(int nMinRounds, int nMaxRounds, std::string& strErrorRet, std::vector<CTxDSIn>& vecTxDSInRet, std::vector<CTxOut>& vecTxOutRet);
/// step 2: send denominated inputs and outputs prepared in step 1
bool SendDenominate(const std::vector<CTxDSIn>& vecTxDSIn, const std::vector<CTxOut>& vecTxOut, CConnman& connman);
/// Get Masternode updates about the progress of mixing
bool CheckPoolStateUpdate(PoolState nStateNew, int nEntriesCountNew, PoolStatusUpdate nStatusUpdate, PoolMessage nMessageID, int nSessionIDNew=0);
// Set the 'state' value, with some logging and capturing when the state changed
void SetState(PoolState nStateNew);
/// As a client, check and sign the final transaction
bool SignFinalTransaction(const CTransaction& finalTransactionNew, CNode* pnode, CConnman& connman);
void RelayIn(const CDarkSendEntry& entry, CConnman& connman);
void SetNull();
public:
int nPrivateSendRounds;
int nPrivateSendAmount;
int nLiquidityProvider;
bool fEnablePrivateSend;
bool fPrivateSendMultiSession;
int nCachedNumBlocks; //used for the overview screen
bool fCreateAutoBackups; //builtin support for automatic backups
CPrivateSendClient() :
nCachedLastSuccessBlock(0),
nMinBlocksToWait(1),
txMyCollateral(CMutableTransaction()),
nPrivateSendRounds(DEFAULT_PRIVATESEND_ROUNDS),
nPrivateSendAmount(DEFAULT_PRIVATESEND_AMOUNT),
nLiquidityProvider(DEFAULT_PRIVATESEND_LIQUIDITY),
fEnablePrivateSend(false),
fPrivateSendMultiSession(DEFAULT_PRIVATESEND_MULTISESSION),
nCachedNumBlocks(std::numeric_limits<int>::max()),
fCreateAutoBackups(true) { SetNull(); }
void ProcessMessage(CNode* pfrom, const std::string& strCommand, CDataStream& vRecv, CConnman& connman);
void ClearSkippedDenominations() { vecDenominationsSkipped.clear(); }
void SetMinBlocksToWait(int nMinBlocksToWaitIn) { nMinBlocksToWait = nMinBlocksToWaitIn; }
void ResetPool();
void UnlockCoins();
std::string GetStatus();
bool GetMixingMasternodeInfo(masternode_info_t& mnInfoRet);
bool IsMixingMasternode(const CNode* pnode);
/// Passively run mixing in the background according to the configuration in settings
bool DoAutomaticDenominating(CConnman& connman, bool fDryRun=false);
void ProcessPendingDsaRequest(CConnman& connman);
void CheckTimeout();
void UpdatedBlockTip(const CBlockIndex *pindex);
};
void ThreadCheckPrivateSendClient(CConnman& connman);
#endif
| [
"46324696+julivn@users.noreply.github.com"
] | 46324696+julivn@users.noreply.github.com |
9deda26c98829c6f09c81085d08900cffc1ea5c3 | 3c2217a9e512b0f0cc9158729bf29117673d60fa | /uva 1185 solution.cpp | d774e54a4d5cfed7c5ce0b80ebca095f939f20ff | [] | no_license | tanveerislam/UVASolution | 84b0f443ae435dabe09189ba5ed7a2b550b66415 | 9c03e59fc0a93f319ff17e85a5012823ace16166 | refs/heads/master | 2020-07-22T00:00:41.956658 | 2019-09-07T18:12:57 | 2019-09-07T18:12:57 | 207,007,229 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 441 | cpp | #include<iostream>
#include<cstdio>
using namespace std;
long long a[100000];
int main()
{
long long m,t,i,j,k,l,c;
double n;
cin>>t;
for(i=0;i<t;i++)
{
cin>>a[i];
n=(double)a[i];
c=1;
for(j=n-1;j>0;j--)
{
while(n>=10.0)
{
c++;
n/=10.0;
}
n*=j;
}
cout<<c<<endl;
}
return 0;
}
| [
"tanveerlab10ragshahi@gmail.com"
] | tanveerlab10ragshahi@gmail.com |
62e834969f9caf4ea346d078db2eee2a19074293 | 9008c55d40a55adf6432152fc4fb9bfc71824c42 | /src/Overlook/SystemQueue.cpp | 1e5708c3418448aeb9a5aa2ad3cf19163e36222c | [
"BSD-3-Clause"
] | permissive | IanMadlenya/Overlook | 6a9c46483c5ce651b3f4caac4b41b3e1f1aba8a8 | e62ef353e72d9513f43652d027c546547195a143 | refs/heads/master | 2021-04-25T07:20:49.668491 | 2018-02-19T21:30:50 | 2018-02-19T21:30:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 17,736 | cpp | #include "Overlook.h"
namespace Overlook {
void System::InitRegistry() {
ASSERT(regs.IsEmpty());
ASSERT_(System::GetCoreFactories().GetCount() > 0, "Recompile Overlook.icpp to fix this stupid and weird problem");
// Register factories
for(int i = 0; i < System::GetCoreFactories().GetCount(); i++) {
// unfortunately one object must be created, because IO can't be static and virtual at the same time and it is cleaner to use virtual.
Ptr<Core> core = System::GetCoreFactories()[i].c();
FactoryRegister& reg = regs.Add();
core->IO(reg);
}
// Resize databank
data.SetCount(symbols.GetCount());
for(int i = 0; i < data.GetCount(); i++) {
data[i].SetCount(periods.GetCount());
for(int j = 0; j < periods.GetCount(); j++)
data[i][j].SetCount(regs.GetCount());
}
}
// This function is only a demonstration how to make work queues
void System::GetWorkQueue(Vector<Ptr<CoreItem> >& ci_queue) {
Index<int> sym_ids, tf_ids;
Vector<FactoryDeclaration> indi_ids;
bool all = false;
if (all) {
for(int i = 0; i < symbols.GetCount(); i++)
sym_ids.Add(i);
for(int i = periods.GetCount()-1; i >= 0; i--)
tf_ids.Add(i);
int indi_limit = Find<PeriodicalChange>();
ASSERT(indi_limit != -1);
indi_limit++;
for(int i = 0; i < indi_limit; i++)
indi_ids.Add().Set(i);
} else {
for(int i = 0; i < symbols.GetCount(); i++)
sym_ids.Add(i);
for(int i = periods.GetCount()-1; i >= periods.GetCount()-1; i--)
tf_ids.Add(i);
int indi_limit = Find<MovingAverage>() + 1;
ASSERT(indi_limit != 0);
for(int i = 0; i < indi_limit; i++)
indi_ids.Add().Set(i);
}
GetCoreQueue(ci_queue, sym_ids, tf_ids, indi_ids);
}
int System::GetCoreQueue(Vector<Ptr<CoreItem> >& ci_queue, const Index<int>& sym_ids, const Index<int>& tf_ids, const Vector<FactoryDeclaration>& indi_ids) {
const int tf_count = GetPeriodCount();
Vector<FactoryDeclaration> path;
int total = tf_ids.GetCount() * indi_ids.GetCount() + 2;
int actual = 0;
for (int i = 0; i < tf_ids.GetCount(); i++) {
int tf = tf_ids[i];
ASSERT(tf >= 0 && tf < tf_count);
for(int j = 0; j < indi_ids.GetCount(); j++) {
path.Add(indi_ids[j]);
GetCoreQueue(path, ci_queue, tf, sym_ids);
path.Pop();
WhenProgress(actual++, total);
}
}
// Sort queue by priority
struct PrioritySorter {
bool operator()(const Ptr<CoreItem>& a, const Ptr<CoreItem>& b) const {
if (a->priority == b->priority)
return a->factory < b->factory;
return a->priority < b->priority;
}
};
Sort(ci_queue, PrioritySorter());
WhenProgress(actual++, total);
// Remove duplicates
Vector<int> rem_list;
for(int i = 0; i < ci_queue.GetCount(); i++) {
CoreItem& a = *ci_queue[i];
for(int j = i+1; j < ci_queue.GetCount(); j++) {
CoreItem& b = *ci_queue[j];
if (a.sym == b.sym && a.tf == b.tf && a.factory == b.factory && a.hash == b.hash) {
rem_list.Add(j);
i++;
}
else break;
}
}
ci_queue.Remove(rem_list);
WhenProgress(actual++, total);
for(int i = 0; i < ci_queue.GetCount(); i++) {
CoreItem& ci = *ci_queue[i];
//LOG(Format("%d: sym=%d tf=%d factory=%d hash=%d", i, ci.sym, ci.tf, ci.factory, ci.hash));
}
return 0;
}
int System::GetCoreQueue(Vector<FactoryDeclaration>& path, Vector<Ptr<CoreItem> >& ci_queue, int tf, const Index<int>& sym_ids) {
const int factory = path.Top().factory;
const int tf_count = GetPeriodCount();
const int sym_count = GetTotalSymbolCount();
const int factory_count = GetFactoryCount();
// Loop inputs of the factory
const FactoryRegister& reg = regs[factory];
Vector<Vector<FactoryHash> > input_hashes;
input_hashes.SetCount(reg.in.GetCount());
// Get the unique hash for core item
Vector<int> args;
CombineHash ch;
const FactoryDeclaration& factory_decl = path.Top();
for(int i = 0; i < reg.args.GetCount(); i++) {
const ArgType& arg = reg.args[i];
int value;
ASSERT(factory_decl.arg_count >= 0 && factory_decl.arg_count <= 8);
if (i < factory_decl.arg_count) {
value = factory_decl.args[i];
ASSERT(value >= arg.min && value <= arg.max);
} else {
value = arg.def;
}
args.Add(value);
ch << value << 1;
}
int hash = ch;
// Connect input sources
// Loop all inputs of the custom core-class
for (int l = 0; l < reg.in.GetCount(); l++) {
Index<int> sub_sym_ids, sub_tf_ids;
const RegisterInput& input = reg.in[l];
ASSERT(input.factory >= 0);
FilterFunction fn = (FilterFunction)input.data;
// If equal timeframe is accepted as input
for(int i = 0; i < tf_count; i++) {
if (fn(this, -1, tf, -1, i)) {
sub_tf_ids.Add(i);
}
}
if (!sub_tf_ids.IsEmpty()) {
for(int k = 0; k < sub_tf_ids.GetCount(); k++) {
int used_tf = sub_tf_ids[k];
// Get all symbols what input requires
sub_sym_ids.Clear();
for(int i = 0; i < sym_ids.GetCount(); i++) {
int in_sym = sym_ids[i];
for(int j = 0; j < GetTotalSymbolCount(); j++) {
if (fn(this, in_sym, -1, j, -1))
sub_sym_ids.FindAdd(j);
}
}
if (!sub_sym_ids.IsEmpty()) {
FactoryDeclaration& decl = path.Add();
// Optional: add arguments by calling defined function
decl.Set(input.factory);
if (input.data2)
((ArgsFn)input.data2)(l, decl, args);
int h = GetCoreQueue(path, ci_queue, used_tf, sub_sym_ids);
path.Pop();
input_hashes[l].Add(FactoryHash(input.factory, h));
}
}
}
}
for (int i = 0; i < sym_ids.GetCount(); i++) {
int sym = sym_ids[i];
// Get CoreItem
CoreItem& ci = data[sym][tf][factory].GetAdd(hash);
// Init object if it was just created
if (ci.sym == -1) {
int path_priority = 0;//GetPathPriority(path);
ci.sym = sym;
ci.tf = tf;
if (System::PrioritySlowTf().Find(factory) == -1)
ci.priority = (factory * tf_count + tf) * sym_count + sym;
else
ci.priority = (factory * tf_count + (tf_count - 1 - tf)) * sym_count + sym;
ci.factory = factory;
ci.hash = hash;
ci.input_hashes <<= input_hashes;
ci.args <<= args;
//LOG(Format("%X\tfac=%d\tpath_priority=%d\tprio=%d", (int64)&ci, ci.factory, path_priority, ci.priority));
//DUMPC(args);
// Connect core inputs
ConnectCore(ci);
}
ci_queue.Add(&ci);
}
return hash;
}
int System::GetHash(const Vector<byte>& vec) {
CombineHash ch;
int full_ints = vec.GetCount() / 4;
int int_mod = vec.GetCount() % 4;
int* i = (int*)vec.Begin();
for(int j = 0; j < full_ints; j++) {
ch << *i << 1;
i++;
}
byte* b = (byte*)i;
for(int j = 0; j < int_mod; j++) {
ch << *b << 1;
b++;
}
return ch;
}
void System::ConnectCore(CoreItem& ci) {
const FactoryRegister& part = regs[ci.factory];
Vector<int> enabled_input_factories;
Vector<byte> unique_slot_comb;
// Connect input sources
// Loop all inputs of the custom core-class
ci.inputs.SetCount(part.in.GetCount());
ASSERT(ci.input_hashes.GetCount() == part.in.GetCount());
for (int l = 0; l < part.in.GetCount(); l++) {
const RegisterInput& input = part.in[l];
for(int k = 0; k < ci.input_hashes[l].GetCount(); k++) {
int factory = ci.input_hashes[l][k].a;
int hash = ci.input_hashes[l][k].b;
// Regular inputs
if (input.input_type == REGIN_NORMAL) {
ASSERT(input.factory == factory);
ConnectInput(l, 0, ci, input.factory, hash);
}
// Optional factory inputs
else if (input.input_type == REGIN_OPTIONAL) {
// Skip disabled
if (factory == -1)
continue;
ConnectInput(l, 0, ci, factory, hash);
}
else Panic("Invalid input type");
}
}
}
void System::ConnectInput(int input_id, int output_id, CoreItem& ci, int factory, int hash) {
Vector<int> symlist, tflist;
const RegisterInput& input = regs[ci.factory].in[input_id];
const int sym_count = GetTotalSymbolCount();
const int tf_count = GetPeriodCount();
FilterFunction fn = (FilterFunction)input.data;
if (fn) {
// Filter timeframes
for(int i = 0; i < tf_count; i++) {
if (fn(this, -1, ci.tf, -1, i)) {
tflist.Add(i);
}
}
// Filter symbols
for(int i = 0; i < sym_count; i++) {
if (fn(this, ci.sym, -1, i, -1)) {
symlist.Add(i);
}
}
}
else {
tflist.Add(ci.tf);
symlist.Add(ci.sym);
}
for(int i = 0; i < symlist.GetCount(); i++) {
int sym = symlist[i];
for(int j = 0; j < tflist.GetCount(); j++) {
int tf = tflist[j];
CoreItem& src_ci = data[sym][tf][factory].GetAdd(hash);
ASSERT_(src_ci.sym != -1, "Source CoreItem was not yet initialized");
ASSERT_(src_ci.priority <= ci.priority, "Source didn't have higher priority than current");
// Source found
ci.SetInput(input_id, src_ci.sym, src_ci.tf, src_ci, output_id);
}
}
}
void System::CreateCore(CoreItem& ci) {
ASSERT(ci.core.IsEmpty());
// Create core-object
ci.core = System::GetCoreFactories()[ci.factory].b();
Core& c = *ci.core;
// Set attributes
c.RefreshIO();
c.SetSymbol(ci.sym);
c.SetTimeframe(ci.tf, GetPeriod(ci.tf));
c.SetFactory(ci.factory);
c.SetHash(ci.hash);
// Connect object
int obj_count = c.inputs.GetCount();
int def_count = ci.inputs.GetCount();
ASSERT(obj_count == def_count);
for(int i = 0; i < ci.inputs.GetCount(); i++) {
const VectorMap<int, SourceDef>& src_list = ci.inputs[i];
Input& in = c.inputs[i];
for(int j = 0; j < src_list.GetCount(); j++) {
int key = src_list.GetKey(j);
const SourceDef& src_def = src_list[j];
Source& src_obj = in.Add(key);
CoreItem& src_ci = *src_def.coreitem;
ASSERT_(!src_ci.core.IsEmpty(), "Core object must be created before this point");
src_obj.core = &*src_ci.core;
src_obj.output = &src_obj.core->outputs[src_def.output];
src_obj.sym = src_def.sym;
src_obj.tf = src_def.tf;
}
}
// Set arguments
ArgChanger arg;
arg.SetLoading();
c.IO(arg);
if (ci.args.GetCount() > 0) {
ASSERT(ci.args.GetCount() <= arg.keys.GetCount());
for(int i = 0; i < ci.args.GetCount(); i++)
arg.args[i] = ci.args[i];
arg.SetStoring();
c.IO(arg);
}
// Initialize
c.InitAll();
c.LoadCache();
c.AllowJobs();
}
Core* System::CreateSingle(int factory, int sym, int tf) {
// Enable factory
Vector<FactoryDeclaration> path;
path.Add().Set(factory);
// Enable symbol
ASSERT(sym >= 0 && sym < symbols.GetCount());
Index<int> sym_ids;
sym_ids.Add(sym);
// Enable timeframe
ASSERT(tf >= 0 && tf < periods.GetCount());
// Get working queue
Vector<Ptr<CoreItem> > ci_queue;
GetCoreQueue(path, ci_queue, tf, sym_ids);
// Process job-queue
for(int i = 0; i < ci_queue.GetCount(); i++) {
WhenProgress(i, ci_queue.GetCount());
Process(*ci_queue[i], true);
}
return &*ci_queue.Top()->core;
}
void System::Process(CoreItem& ci, bool store_cache) {
// Load dependencies to the scope
if (ci.core.IsEmpty())
CreateCore(ci);
// Process core-object
ci.core->Refresh();
// Store cache file
if (store_cache)
ci.core->StoreCache();
}
#ifdef flagGUITASK
void System::ProcessJobs() {
bool break_loop = false;
TimeStop ts;
do {
if (job_threads.IsEmpty())
break;
break_loop = ProcessJob(gui_job_thread++);
if (gui_job_thread >= job_threads.GetCount())
gui_job_thread = 0;
}
while (ts.Elapsed() < 200 && !break_loop);
jobs_tc.Set(10, THISBACK(PostProcessJobs));
}
#else
void System::ProcessJobs() {
jobs_stopped = false;
while (jobs_running && !Thread::IsShutdownThreads()) {
LOCK(job_lock) {
int running = 0;
int max_running = GetUsedCpuCores();
for (auto& job : job_threads)
if (!job.IsStopped())
running++;
for(int i = 0; i < job_threads.GetCount() && running < max_running; i++) {
if (job_thread_iter >= job_threads.GetCount())
job_thread_iter = 0;
JobThread& job = job_threads[job_thread_iter++];
if (job.IsStopped()) {
job.Start();
if (!job.IsStopped())
running++;
}
}
}
for(int i = 0; i < 10 && jobs_running; i++)
Sleep(100);
}
LOCK(job_lock) {
for (auto& job : job_threads) job.PutStop(); // Don't wait
for (auto& job : job_threads) job.Stop();
}
jobs_stopped = true;
}
#endif
bool System::ProcessJob(int job_thread) {
return job_threads[job_thread].ProcessJob();
}
bool JobThread::ProcessJob() {
bool r = true;
READLOCK(job_lock) {
if (!jobs.IsEmpty()) {
Job& job = *jobs[job_iter];
if (job.IsFinished()) {
job_iter++;
if (job_iter >= jobs.GetCount()) {
job_iter = 0;
r = false;
}
}
else {
if (job.core->IsInitialized()) {
job.core->EnterJob(&job, this);
bool succ = job.Process();
job.core->LeaveJob();
if (!succ && job.state == Job::INIT)
r = false;
// FIXME: postponing returns false also if (!succ) is_fail = true;
}
// Resist useless fast loop here
else Sleep(100);
}
// Resist useless fast loop here
if (job.state != Job::RUNNING) Sleep(100);
}
else r = false;
}
// Resist useless fast loop here
if (r == false) Sleep(100);
return r;
}
void System::StopJobs() {
#ifndef flagGUITASK
jobs_running = false;
while (!jobs_stopped) Sleep(100);
#endif
StoreJobCores();
}
void System::StoreJobCores() {
Index<Core*> job_cores;
for(int i = 0; i < job_threads.GetCount(); i++) {
JobThread& job_thrd = job_threads[i];
for(int j = 0; j < job_thrd.jobs.GetCount(); j++) {
Job& job = *job_thrd.jobs[j];
Core* core = job.core;
if (!core) continue;
job_cores.FindAdd(core);
}
}
for(int i = 0; i < job_cores.GetCount(); i++)
job_cores[i]->StoreCache();
}
bool Job::Process() {
if (!allow_processing)
return false;
bool r = true;
int begin_state = state;
core->serialization_lock.Enter();
switch (state) {
case INIT: core->RefreshSources();
if ((r=begin()) || !begin) state++; break;
case RUNNING: if ((r=iter()) && actual >= total || !iter) state++; break;
case STOPPING: if ((r=end()) || !end) state++; break;
case INSPECTING: if ((r=inspect()) || !inspect) state++; break;
}
core->serialization_lock.Leave();
if (begin_state < state || ts.Elapsed() >= 5 * 60 * 1000) {
core->StoreCache();
ts.Reset();
}
return r;
}
String Job::GetStateString() const {
switch (state) {
case INIT: return "Init";
case RUNNING: return "Running";
case STOPPING: return "Stopping";
case INSPECTING: return "Inspecting";
case STOPPED: return "Finished";
}
return "";
}
void System::InspectionFailed(const char* file, int line, int symbol, int tf, String msg) {
LOCK(inspection_lock) {
bool found = false;
for(int i = 0; i < inspection_results.GetCount(); i++) {
InspectionResult& r = inspection_results[i];
if (r.file == file &&
r.line == line &&
r.symbol == symbol &&
r.tf == tf &&
r.msg == msg) {
found = true;
break;
}
}
if (!found) {
InspectionResult& r = inspection_results.Add();
r.file = file;
r.line = line;
r.symbol = symbol;
r.tf = tf;
r.msg = msg;
}
}
}
void System::StoreCores() {
for (auto& s : data) {
for (auto& t : s) {
for (auto& f : t) {
for (auto& ci : f) {
if (!ci.core.IsEmpty())
ci.core->StoreCache();
}
}
}
}
}
bool System::RefreshReal() {
Time now = GetUtcTime();
int wday = DayOfWeek(now);
Time after_3hours = now + 3 * 60 * 60;
int wday_after_3hours = DayOfWeek(after_3hours);
now.second = 0;
MetaTrader& mt = GetMetaTrader();
// Skip weekends and first hours of monday
if (wday == 0 || wday == 6 || (wday == 1 && now.hour < 1)) {
LOG("Skipping weekend...");
return true;
}
// Inspect for market closing (weekend and holidays)
else if (wday == 5 && wday_after_3hours == 6) {
WhenInfo("Closing all orders before market break");
for (int i = 0; i < mt.GetSymbolCount(); i++) {
mt.SetSignal(i, 0);
mt.SetSignalFreeze(i, false);
}
mt.SignalOrders(true);
return true;
}
WhenInfo("Updating MetaTrader");
WhenPushTask("Putting latest signals");
// Reset signals
if (realtime_count == 0) {
for (int i = 0; i < mt.GetSymbolCount(); i++)
mt.SetSignal(i, 0);
}
realtime_count++;
try {
mt.Data();
mt.RefreshLimits();
int open_count = 0;
const int MAX_SYMOPEN = 4;
const double FMLEVEL = 0.6;
for (int sym_id = 0; sym_id < GetSymbolCount(); sym_id++) {
int sig = signals[sym_id];
int prev_sig = mt.GetSignal(sym_id);
if (sig == prev_sig && sig != 0)
mt.SetSignalFreeze(sym_id, true);
else {
if ((!prev_sig && sig) || (prev_sig && sig != prev_sig)) {
if (open_count >= MAX_SYMOPEN)
sig = 0;
else
open_count++;
}
mt.SetSignal(sym_id, sig);
mt.SetSignalFreeze(sym_id, false);
}
LOG("Real symbol " << sym_id << " signal " << sig);
}
mt.SetFreeMarginLevel(FMLEVEL);
mt.SetFreeMarginScale(MAX_SYMOPEN);
mt.SignalOrders(true);
}
catch (UserExc e) {
LOG(e);
return false;
}
catch (...) {
return false;
}
WhenRealtimeUpdate();
WhenPopTask();
return true;
}
}
| [
"seppo.pakonen@yandex.com"
] | seppo.pakonen@yandex.com |
f087a53e54beb2bd8e9ef1ce76eb3d5530a6c867 | ece2011fdb20670f76b6b970df54bc818c6b313b | /Sources/Inputs/AxisCompound.cpp | 121c741d5954050f89ad73628f721e636f61926f | [
"MIT"
] | permissive | FirstLoveLife/Acid | eda32711a0cfdcc9f596e547e2880e9edfffda5a | b7ce821a6a2b2d4bc441b724fabe1bbd9b9c6b8d | refs/heads/master | 2020-04-28T04:20:02.863648 | 2019-03-15T19:26:27 | 2019-03-15T19:26:27 | 174,974,067 | 0 | 0 | null | 2019-03-11T10:09:23 | 2019-03-11T10:09:22 | null | UTF-8 | C++ | false | false | 372 | cpp | #include "AxisCompound.hpp"
namespace acid
{
AxisCompound::AxisCompound(const std::vector<IAxis *> &axes)
{
for (const auto &axis : axes)
{
m_axes.emplace_back(axis);
}
}
float AxisCompound::GetAmount() const
{
auto result = 0.0f;
for (const auto &axis : m_axes)
{
result += axis->GetAmount();
}
return std::clamp(result, -1.0f, 1.0f);
}
}
| [
"mattparks5855@gmail.com"
] | mattparks5855@gmail.com |
5091df236918ca918efa34e83268eee3fcc6fdbe | 43a2fbc77f5cea2487c05c7679a30e15db9a3a50 | /Cpp/Internal (Offsets Only)/SDK/AD_ThirdPerson_PlayerPirate_Female_Athletic_classes.h | b64e2dc918f5e7079a5eb84bd930626e57974fdd | [] | no_license | zH4x/SoT-Insider-SDK | 57e2e05ede34ca1fd90fc5904cf7a79f0259085c | 6bff738a1b701c34656546e333b7e59c98c63ad7 | refs/heads/main | 2023-06-09T23:10:32.929216 | 2021-07-07T01:34:27 | 2021-07-07T01:34:27 | 383,638,719 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 901 | h | #pragma once
// Name: SoT-Insider, Version: 1.102.2382.0
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C
// 0x0000 (FullSize[0x0750] - InheritedSize[0x0750])
class UAD_ThirdPerson_PlayerPirate_Female_Athletic_C : public UAD_ThirdPerson_PlayerPirate_Female_Default_C
{
public:
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass AD_ThirdPerson_PlayerPirate_Female_Athletic.AD_ThirdPerson_PlayerPirate_Female_Athletic_C");
return ptr;
}
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"Massimo.linker@gmail.com"
] | Massimo.linker@gmail.com |
39e5fca2873f87f549dc7d7e8a5a8158864f5d8d | e3f4283e488dabbc45cbeeb6309503f8334571e9 | /Wire/Wire.cpp | 881b31bcaa0cefad701933da997fea6b0d75e47d | [] | no_license | igouss/RobotProto | 139a81fe4fc2faa9b3520749bf9bf716c6de3264 | 74833be50b68eb7dc27ec2e60ef9cfa9cb128064 | refs/heads/master | 2021-01-17T06:33:41.452786 | 2011-09-10T01:43:01 | 2011-09-10T01:43:01 | 2,166,120 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,904 | cpp | ///*
// TwoWire.cpp - TWI/I2C library for Wiring & Arduino
// Copyright (c) 2006 Nicholas Zambetti. All right reserved.
//
// 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//*/
//
//extern "C" {
// #include <stdlib.h>
// #include <string.h>
// #include <inttypes.h>
// #include "utility/twi.h"
//}
//
//#include "Wire.h"
//
//// Initialize Class Variables //////////////////////////////////////////////////
//
//uint8_t TwoWire::rxBuffer[BUFFER_LENGTH];
//uint8_t TwoWire::rxBufferIndex = 0;
//uint8_t TwoWire::rxBufferLength = 0;
//
//uint8_t TwoWire::txAddress = 0;
//uint8_t TwoWire::txBuffer[BUFFER_LENGTH];
//uint8_t TwoWire::txBufferIndex = 0;
//uint8_t TwoWire::txBufferLength = 0;
//
//uint8_t TwoWire::transmitting = 0;
//void (*TwoWire::user_onRequest)(void);
//void (*TwoWire::user_onReceive)(int);
//
//// Constructors ////////////////////////////////////////////////////////////////
//
//TwoWire::TwoWire()
//{
//}
//
//// Public Methods //////////////////////////////////////////////////////////////
//
//void TwoWire::begin(void)
//{
// rxBufferIndex = 0;
// rxBufferLength = 0;
//
// txBufferIndex = 0;
// txBufferLength = 0;
//
// twi_init();
//}
//
//void TwoWire::begin(uint8_t address)
//{
// twi_setAddress(address);
// twi_attachSlaveTxEvent(onRequestService);
// twi_attachSlaveRxEvent(onReceiveService);
// begin();
//}
//
//void TwoWire::begin(int address)
//{
// begin((uint8_t)address);
//}
//
//uint8_t TwoWire::requestFrom(uint8_t address, uint8_t quantity)
//{
// // clamp to buffer length
// if(quantity > BUFFER_LENGTH){
// quantity = BUFFER_LENGTH;
// }
// // perform blocking read into buffer
// uint8_t read = twi_readFrom(address, rxBuffer, quantity);
// // set rx buffer iterator vars
// rxBufferIndex = 0;
// rxBufferLength = read;
//
// return read;
//}
//
//uint8_t TwoWire::requestFrom(int address, int quantity)
//{
// return requestFrom((uint8_t)address, (uint8_t)quantity);
//}
//
//void TwoWire::beginTransmission(uint8_t address)
//{
// // indicate that we are transmitting
// transmitting = 1;
// // set address of targeted slave
// txAddress = address;
// // reset tx buffer iterator vars
// txBufferIndex = 0;
// txBufferLength = 0;
//}
//
//void TwoWire::beginTransmission(int address)
//{
// beginTransmission((uint8_t)address);
//}
//
//uint8_t TwoWire::endTransmission(void)
//{
// // transmit buffer (blocking)
// int8_t ret = twi_writeTo(txAddress, txBuffer, txBufferLength, 1);
// // reset tx buffer iterator vars
// txBufferIndex = 0;
// txBufferLength = 0;
// // indicate that we are done transmitting
// transmitting = 0;
// return ret;
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(uint8_t data)
//{
// if(transmitting){
// // in master transmitter mode
// // don't bother if buffer is full
// if(txBufferLength >= BUFFER_LENGTH){
// return;
// }
// // put byte in tx buffer
// txBuffer[txBufferIndex] = data;
// ++txBufferIndex;
// // update amount in buffer
// txBufferLength = txBufferIndex;
// }else{
// // in slave send mode
// // reply to master
// twi_transmit(&data, 1);
// }
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(uint8_t* data, uint8_t quantity)
//{
// if(transmitting){
// // in master transmitter mode
// for(uint8_t i = 0; i < quantity; ++i){
// send(data[i]);
// }
// }else{
// // in slave send mode
// // reply to master
// twi_transmit(data, quantity);
// }
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(char* data)
//{
// send((uint8_t*)data, strlen(data));
//}
//
//// must be called in:
//// slave tx event callback
//// or after beginTransmission(address)
//void TwoWire::send(int data)
//{
// send((uint8_t)data);
//}
//
//// must be called in:
//// slave rx event callback
//// or after requestFrom(address, numBytes)
//uint8_t TwoWire::available(void)
//{
// return rxBufferLength - rxBufferIndex;
//}
//
//// must be called in:
//// slave rx event callback
//// or after requestFrom(address, numBytes)
//uint8_t TwoWire::receive(void)
//{
// // default to returning null char
// // for people using with char strings
// uint8_t value = '\0';
//
// // get each successive byte on each call
// if(rxBufferIndex < rxBufferLength){
// value = rxBuffer[rxBufferIndex];
// ++rxBufferIndex;
// }
//
// return value;
//}
//
//// behind the scenes function that is called when data is received
//void TwoWire::onReceiveService(uint8_t* inBytes, int numBytes)
//{
// // don't bother if user hasn't registered a callback
// if(!user_onReceive){
// return;
// }
// // don't bother if rx buffer is in use by a master requestFrom() op
// // i know this drops data, but it allows for slight stupidity
// // meaning, they may not have read all the master requestFrom() data yet
// if(rxBufferIndex < rxBufferLength){
// return;
// }
// // copy twi rx buffer into local read buffer
// // this enables new reads to happen in parallel
// for(uint8_t i = 0; i < numBytes; ++i){
// rxBuffer[i] = inBytes[i];
// }
// // set rx iterator vars
// rxBufferIndex = 0;
// rxBufferLength = numBytes;
// // alert user program
// user_onReceive(numBytes);
//}
//
//// behind the scenes function that is called when data is requested
//void TwoWire::onRequestService(void)
//{
// // don't bother if user hasn't registered a callback
// if(!user_onRequest){
// return;
// }
// // reset tx buffer iterator vars
// // !!! this will kill any pending pre-master sendTo() activity
// txBufferIndex = 0;
// txBufferLength = 0;
// // alert user program
// user_onRequest();
//}
//
//// sets function called on slave write
//void TwoWire::onReceive( void (*function)(int) )
//{
// user_onReceive = function;
//}
//
//// sets function called on slave read
//void TwoWire::onRequest( void (*function)(void) )
//{
// user_onRequest = function;
//}
//
//// Preinstantiate Objects //////////////////////////////////////////////////////
//
//TwoWire Wire = TwoWire();
| [
"i.gouss@gmail.com"
] | i.gouss@gmail.com |
b96791c7ba47fa615a92e6ab8ca47a7e13e5d7bb | e07e3f41c9774c9684c4700a9772712bf6ac3533 | /app/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_Collections_Generic_Dictionary_2_T2723200652.h | 1e9b71d374786c2e5775168166d7c9f1d70cc086 | [] | no_license | gdesmarais-gsn/inprocess-mobile-skill-client | 0171a0d4aaed13dbbc9cca248aec646ec5020025 | 2499d8ab5149a306001995064852353c33208fc3 | refs/heads/master | 2020-12-03T09:22:52.530033 | 2017-06-27T22:08:38 | 2017-06-27T22:08:38 | 95,603,544 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,148 | h | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.ComponentModel.WeakObjectWrapper
struct WeakObjectWrapper_t2012978780;
// System.Collections.Generic.LinkedList`1<System.ComponentModel.TypeDescriptionProvider>
struct LinkedList_1_t2743332604;
// System.IAsyncResult
struct IAsyncResult_t1999651008;
// System.AsyncCallback
struct AsyncCallback_t163412349;
// System.Object
struct Il2CppObject;
#include "mscorlib_System_MulticastDelegate3201952435.h"
#include "mscorlib_System_Collections_DictionaryEntry3048875398.h"
#ifdef __clang__
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Winvalid-offsetof"
#pragma clang diagnostic ignored "-Wunused-variable"
#endif
// System.Collections.Generic.Dictionary`2/Transform`1<System.ComponentModel.WeakObjectWrapper,System.Collections.Generic.LinkedList`1<System.ComponentModel.TypeDescriptionProvider>,System.Collections.DictionaryEntry>
struct Transform_1_t2723200652 : public MulticastDelegate_t3201952435
{
public:
public:
};
#ifdef __clang__
#pragma clang diagnostic pop
#endif
| [
"gdesmarais@gsngames.com"
] | gdesmarais@gsngames.com |
b730cbb19015ce885de50335d0c25cbd314c5ada | b6ccb7529cd311c953b208e5200f26bdb3cb1d67 | /41.First Missing Positive.cpp | 0e413c0be7a093144f464da6d686b72f9e0745de | [] | no_license | swang109/Leetcode-1 | 2c5b3b6d9a7223c9f791d8972cb0da8c07e33eee | 9243f05ddd1fdcc0de2a6d57148c7df33affc627 | refs/heads/master | 2020-12-01T11:41:23.955464 | 2015-11-08T22:40:40 | 2015-11-08T22:40:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 427 | cpp | #include <iostream>
#include <vector>
using namespace std;
int firstMissingPositive(vector<int>& nums) {
for (int i = 0; i < nums.size(); i++)
while (nums[i] > 0 && nums[i] <= nums.size() && nums[i] != nums[nums[i] - 1])
swap(nums[i], nums[nums[i] - 1]);
for (int i = 0; i < nums.size(); i++)
if (nums[i] != i + 1)
return i + 1;
return nums.size() + 1;
}
int main() {
}
| [
"roddykou@gmail.com"
] | roddykou@gmail.com |
845708b1c6df58776b9b009fbd438edc9b48082f | 56b94ffc8f4dcb39908399201d38b78f4f8c2376 | /tests/parser/030.cpp | c51fafa069c5ce8a8202ee091331561857aea6ac | [] | no_license | helviett/Tiny_C_Compiler | 99f7a5187eea701bf95f090c2efbb34e6326baf9 | 0968c89884e50386911913b3c6703fe4ce31e10f | refs/heads/master | 2021-09-07T06:58:44.035998 | 2018-02-19T05:53:30 | 2018-02-19T05:53:30 | 106,104,684 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 202 | cpp | int main(void)
{
int a, b, c, d, e, f, g[5];
int max = c > d ? c : d;
5 + 12 * 8 <= 5 | 9 << 3 + 1 > 4 ? (123 ^ 7) - d >> 8 << 7 & 12 + ~1 == 9 <= 5 && f + ++g[5] - 15 : 12;
return 0;
} | [
"keltarhelviett@gmail.com"
] | keltarhelviett@gmail.com |
097a2834319794b216c1d29684b8190038ebd097 | 509aa79f8b1054a37c0eaf5786826b140695980a | /Lab/Lab/src/shortestPath2D/ShortestPath.h | afc1937c98f39e56c52fd98b9c94e100312c62ad | [] | no_license | MariKush/MFCG | e5171c0ec38f5fc86819174fb962dfdc30ed0b09 | a2bc141216c6e630c329f346de6041120a3f3506 | refs/heads/master | 2022-07-31T22:01:50.722977 | 2020-05-19T19:31:03 | 2020-05-19T19:31:03 | 262,397,477 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 443 | h | #ifndef SHORTESTPATH2D_SHORTESTPATH_H
#define SHORTESTPATH2D_SHORTESTPATH_H
#include <vector>
#include "Common.h"
#include "Point.h"
#include "Polygon.h"
#include "Path.h"
#include "Graph.h"
namespace shortestPath2D {
class ShortestPath {
struct SPNode {
real distance;
Point point;
Point parent;
};
public:
static Path find(const Point &start, const Point &destination, const Graph<Point> &visibilityGraph);
};
}
#endif
| [
"43176370+MariKush@users.noreply.github.com"
] | 43176370+MariKush@users.noreply.github.com |
747e0748264a21b3471120c028e14041c0c8fb1e | d60c368af917b102962ca4f63fb4f906bf488906 | /CS15 Object-Oriented Programming Methods Workplace/Assignment 5/Assignment 5/Trapezoid.cpp | a56bee3410e1fbc4074eb2520b0cc0ac1cf88d55 | [] | no_license | mahdikhaliki/CS-Classes | f36d3092abf17553bbd75cfe21312edfc403deaf | ef52cc430e3dd778e20c6b59dd6261d193bc59cb | refs/heads/master | 2021-01-15T02:02:59.361191 | 2020-12-11T06:43:14 | 2020-12-11T06:43:14 | 242,841,624 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include "Trapezoid.hpp"
using namespace std;
Trapezoid::Trapezoid() {
_a.setAll(4.0, 0.0);
_b.setAll(0.0, 0.0);
_c.setAll(1.0, 5.0);
_d.setAll(3.0, 5.0);
}
double Trapezoid::area() {
return ((_a.Distance(_b) + _c.Distance(_d)) / 2) * (_c.getY() - _b.getY());
}
double Trapezoid::perimeter() {
return Quadrilateral::perimeter();
}
void Trapezoid::validate() {
Quadrilateral::validate();
if (!Equals(_a.Slope(_b), _d.Slope(_c))) {
cout << "The points do not make a trapezoid." << endl;
_a.setAll(4.0, 0.0);
_b.setAll(0.0, 0.0);
_c.setAll(1.0, 5.0);
_d.setAll(3.0, 5.0);
cout << "New points: " << _a << _b << _c << _d << endl;
}
}
void Trapezoid::read(istream &in) {
in >> _a >> _b >> _c >> _d;
validate();
}
void Trapezoid::print(ostream &out) {
cout << "This is a trapezoid." << endl;
Quadrilateral::print(out);
}
istream &operator >>(istream &in, Trapezoid &p) {
p.read(in);
return in;
}
ostream &operator <<(ostream &out, Trapezoid &p) {
p.print(out);
return out;
}
| [
"mahdi.khaliki@sjsu.edu"
] | mahdi.khaliki@sjsu.edu |
0660949b4c216d61dc21b0c38ee7b2e829bb7cfa | a1a0518781ec8bb41acb853850e115005bdc7c8c | /BOJ/11719_그대로 출력하기 2.cpp | e5a4be9ed311dc99db02c1b2fa516bd6f11b2c78 | [] | no_license | JJungs-lee/problem-solving | e71ccbcab58b6c2444a4b343a138a3082ed09c0c | aa61f2311a7a93fbcb87d2356d15188ea729ee7c | refs/heads/master | 2023-09-03T16:48:31.640762 | 2023-08-31T09:05:39 | 2023-08-31T09:05:39 | 106,645,163 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 141 | cpp | #include <iostream>
using namespace std;
int main(){
char str[101];
while(cin.getline(str, 101)){
cout << str << endl;
}
return 0;
} | [
"loveljhs2@gmail.com"
] | loveljhs2@gmail.com |
358240356f030dfdb855874ba5bc2b9a7efd1b07 | d4acab203c402bc5f8f412b47be13c73f2324b31 | /cdcl/Templates/vbl_smart_ptr+cdcl_feature_with_shape+3--.cxx | af476f679de3973a09e44dcbddee9f77a6f7285f | [
"Apache-2.0"
] | permissive | msofka/LRR | 18b69cb0fd2f98844fa47337e660541c65b7f953 | 8c04ab9d27980c98a201943c1fe46e7e451df367 | refs/heads/master | 2021-05-15T05:35:51.686646 | 2018-01-14T02:36:32 | 2018-01-14T02:36:32 | 116,441,547 | 2 | 0 | Apache-2.0 | 2018-01-06T02:43:14 | 2018-01-06T00:50:29 | C++ | UTF-8 | C++ | false | false | 134 | cxx | #include <vbl/vbl_smart_ptr.txx>
#include <cdcl/cdcl_feature_with_shape.h>
VBL_SMART_PTR_INSTANTIATE( cdcl_feature_with_shape<3> );
| [
"msofka@4catalyzer.com"
] | msofka@4catalyzer.com |
990c74fae962413d962825c19a3658d2853fd003 | 70c1d93fd809d767e7a10611a83425234d1f7a77 | /Study/KOI_Book/KOI/9.cc | 2b3ee01200dcd74e1dbbd5faa873053fefe3c77f | [] | no_license | BlinkingStar7/Problem_Solving | 1e52348d3f013ab1849697894d7e30cf540697f8 | 9f115c831ffb70cd3dfedf6fbee782fba4cfc11a | refs/heads/master | 2021-01-21T04:27:40.184818 | 2016-08-26T09:24:40 | 2016-08-26T09:24:40 | 51,363,595 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,096 | cc | #include <stdio.h>
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
vector<int> Prime;
typedef struct Node {int num, height; vector<Node> child;} Node;
queue <Node*> Q;
int C[4] = {1, 3, 7, 9};
void findPrime(int num) {
for (int i=3; i<num; i+=2) {
bool flag = true;
for (int k=0; k<Prime.size(); ++k)
if (i % Prime[k] == 0) {
flag = false;
break;
}
if (flag) Prime.push_back(i);
}
}
bool isPrime(int num) {
if (num == 1) return false;
for (int i=0; i<Prime.size() && Prime[i]*Prime[i] <= num; ++i) {
if (num % Prime[i] == 0)
return false;
}
return true;
}
int main() {
findPrime (100000);
Node* root = new Node();
root->child.push_back((Node) {2, 1});
Q.push(root); Q.push(&root->child[0]);
while (1) {
Node* cur = Q.front(); Q.pop();
cout << cur->num << endl;
if (cur->height > 10) break;
for (int c=0; c<4; ++c) {
int cand = cur->num * 10 + C[c];
if (isPrime(cand)) {
Node* newNode = &(Node) {cand, cur->height};
cur->child.push_back(*newNode);
Q.push(newNode);
}
}
}
return 0;
}
| [
"steadies@naver.com"
] | steadies@naver.com |
8cbb720c82303474b24892f2f50098f7e228ee7c | 838bc678fc99413b914fdc69b508f77e6c59b66c | /VGP334/17_HelloSkinnedMesh/WinMian.cpp | 8f825318ceb3c1a0986f261fd31cbde8d08dc6ea | [] | no_license | NeilChongSun/SBEngine | 34a6969b1c59226a096986d267265ff2f4479b05 | a2659bb3c40ae7154dfadaeb8c7b1d5fb71fc366 | refs/heads/master | 2023-05-26T06:52:36.933092 | 2021-06-10T23:47:51 | 2021-06-10T23:47:51 | 376,198,320 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 226 | cpp | #include<SB/Inc/SB.h>
#include"GameState.h"
int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int)
{
SB::MainApp().AddState<GameState>("GameState");
SB::MainApp().Run({ "Hello Skinned Mesh", 1280, 720 });
return 0;
} | [
"ImportService@microsoft.com"
] | ImportService@microsoft.com |
927111a3af4e3dd2c7c047d5881697b93de1437e | 62f22ff727b6437362cfdb9d23afb99bed517290 | /libraries/PowerPin/PowerPin.h | d46d073e221c5efa99404b718581f990274d1bd2 | [] | no_license | tezmo/OpenPuzzleBox | 0902c19d7c3f2288b75d03208e044571ddf1d3a6 | a707a0257d7dd13790d1dfc3dc433e7d47ecd3d8 | refs/heads/master | 2016-09-05T10:50:52.258158 | 2015-05-12T17:59:41 | 2015-05-12T17:59:41 | 35,000,074 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 606 | h | /*
PowerPin - Simple Arduino library for powering things, with timeouts.
Juerd Waalboer
*/
#ifndef PowerPin_h
#define PowerPin_h
#include <inttypes.h>
#include <Arduino.h>
class PowerPin {
public:
PowerPin(uint8_t pin, uint8_t off_state = LOW);
void on();
void off();
void on(unsigned int ms);
void off(unsigned int ms);
void toggle();
void check();
private:
void _set(unsigned long end_time, uint8_t state);
uint8_t _pin;
uint8_t _off_state;
unsigned long _end_time;
uint8_t _state;
};
#endif
| [
"jvanderroest@gmail.com"
] | jvanderroest@gmail.com |
b1bc9ea4a932837fe65731fe52349fbafa30c4ed | 7dd9149a4518ac21e3e2ba500f7cdc9823ddaf06 | /T1/CardT1.cpp | fd5f133cf6f9011be375e835ba767906cd671df9 | [
"MIT"
] | permissive | bcspragu/Casino | d34848ae60631cd05de9c249c9f7d7e734375fc3 | eaa106432b6e8ecdd5860d5007f1404e0150e154 | refs/heads/master | 2021-01-21T02:11:13.193473 | 2015-05-05T00:09:29 | 2015-05-05T00:09:29 | 14,091,812 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,652 | cpp | #include <string>
#include "CardT1.h"
using std::string;
CardT1::CardT1(Suit s, Value v){
suit = s;
value = v;
}
CardT1::CardT1(string s){
string su;
string va;
va += s[0];
if(s[0] == '1'){
va += s[1];
}
//Last character
su = *s.rbegin();
if(va == "2"){
value = (Value)0;
}else if(va == "3"){
value = (Value)1;
}else if(va == "4"){
value = (Value)2;
}else if(va == "5"){
value = (Value)3;
}else if(va == "6"){
value = (Value)4;
}else if(va == "7"){
value = (Value)5;
}else if(va == "8"){
value = (Value)6;
}else if(va == "9"){
value = (Value)7;
}else if(va == "10"){
value = (Value)8;
}else if(va == "J"){
value = (Value)9;
}else if(va == "Q"){
value = (Value)10;
}else if(va == "K"){
value = (Value)11;
}else if(va == "A"){
value = (Value)12;
}
if(su == "S"){
suit = (Suit)0;
}else if(su == "D"){
suit = (Suit)1;
}else if(su == "H"){
suit = (Suit)2;
}else if(su == "C"){
suit = (Suit)3;
}
}
CardT1::~CardT1(){}
Suit CardT1::suitFromInt(int i){
Suit s;
switch(i){
case 0:
s = SPADES;
break;
case 1:
s = DIAMONDS;
break;
case 2:
s = HEARTS;
break;
case 3:
s = CLUBS;
break;
}
return s;
}
Value CardT1::valueFromInt(int i){
Value v;
switch(i){
case 0:
v = TWO;
break;
case 1:
v = THREE;
break;
case 2:
v = FOUR;
break;
case 3:
v = FIVE;
break;
case 4:
v = SIX;
break;
case 5:
v = SEVEN;
break;
case 6:
v = EIGHT;
break;
case 7:
v = NINE;
break;
case 8:
v = TEN;
break;
case 9:
v = JACK;
break;
case 10:
v = QUEEN;
break;
case 11:
v = KING;
break;
case 12:
v = ACE;
break;
}
return v;
}
string CardT1::cardString(){
string suitString;
switch(suit){
case HEARTS:
suitString = "Hearts";
break;
case DIAMONDS:
suitString = "Diamonds";
break;
case SPADES:
suitString = "Spades";
break;
case CLUBS:
suitString = "Clubs";
break;
}
string valString;
switch(value){
case TWO:
valString = "2 of";
break;
case THREE:
valString = "3 of";
break;
case FOUR:
valString = "4 of";
break;
case FIVE:
valString = "5 of";
break;
case SIX:
valString = "6 of";
break;
case SEVEN:
valString = "7 of";
break;
case EIGHT:
valString = "8 of";
break;
case NINE:
valString = "9 of";
break;
case TEN:
valString = "10 of";
break;
case JACK:
valString = "Jack of";
break;
case QUEEN:
valString = "Queen of";
break;
case KING:
valString = "King of";
break;
case ACE:
valString = "Ace of";
break;
}
return valString+" "+suitString;
}
//Take the original cardString, and shorten it. ex King of Hearts = KH
string CardT1::shortCardString(){
string cardString = CardT1::cardString();
string shortString;
int spaceCount = 0;
string::iterator itr;
shortString += cardString[0];
if(cardString[0] == '1'){
shortString += cardString[1];
}
for(itr = cardString.begin(); itr < cardString.end(); itr++){
if(spaceCount == 2){
shortString += (*itr);
break;
}
//Character is a space
if((*itr) == ' '){
spaceCount++;
}
}
return shortString;
}
bool CardT1::operator<(const CardT1 &other) const {
return value < other.value;
}
| [
"brandon00sprague@gmail.com"
] | brandon00sprague@gmail.com |
0b0ad3df71d876d345786439f20ae167f28ec32f | 1100c43ab96da22bcfd1003c8472fb568b5b4675 | /examples/src/Core/OverrideFinal/XX_OverrideFinal.cpp | e9923f943784abfe0b4159c8ee30be059a5a1dec | [] | no_license | xcysuccess/CPlusPlus11 | ba6d91655a391d739dc5bd17983d92dc715614fe | 991c71a158777856033414d38bcd3aa2a461aa77 | refs/heads/master | 2020-04-06T09:28:11.683155 | 2018-11-19T13:17:38 | 2018-11-19T13:17:38 | 157,343,810 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 997 | cpp | //
// XX_OverrideFinal.cpp
// XXCPlusPlus
//
// Created by tomxiang on 2018/11/16.
// Copyright © 2018年 tomxiang. All rights reserved.
//
// 1.继承的时候会有无意重写父类方法的问题---
// 2.virtual中如果方法一样,参数类型不同可能会被重复调用---
#include "XX_OverrideFinal.hpp"
#include <XXTiles/XXTiles.h>
//第一种情况----accidentally overrides A::func
class A
{
public:
virtual void func();
};
class B: A{};
class F{};
class D: A, F
{
public:
void func();//meant to declare a new function but
};
//第二种情况----
class G
{
public:
virtual void func(double x){
cout << "G: " << x << endl;
};
};
class H: public G
{
public:
void func(double x) override final{
cout << "H: " << x << endl;
};
};
class Q: public H
{
public:
// void func(double x){
// cout << "H: " << x << endl;
// };
};
void testOverrideFinal(){
H *p=new H;
p->func(5.0);
// p->func(5.0); // calls H::f
}
| [
"tomxiang@tencent.com"
] | tomxiang@tencent.com |
052ec59dc5e0d70b055de852a4c0e9d7992144bd | a1bfdad4489b2ef379330ddb7ce41d279406ea30 | /src/7zipAndroid/CPP/7zip/UI/Console/PercentPrinter.cpp | bce0ba7875b286484b93f6e138d80542d54c1648 | [] | no_license | wcrosmun/simple-7zip-wrapper | 996eb4dafd6255904a411e61707d3e86a970edbf | e14b6bda0af6662905788b88274152d209a4e97b | refs/heads/master | 2021-09-07T01:25:33.889372 | 2018-02-15T00:07:46 | 2018-02-15T00:07:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,470 | cpp | // PercentPrinter.cpp
#include "7zStdAfx.h"
#include "../../../Common/IntToString.h"
#include "PercentPrinter.h"
static const unsigned kPercentsSize = 4;
CPercentPrinter::~CPercentPrinter()
{
ClosePrint(false);
}
void CPercentPrinterState::ClearCurState()
{
Completed = 0;
Total = ((UInt64)(Int64)-1);
Files = 0;
Command.Empty();
FileName.Empty();
}
void CPercentPrinter::ClosePrint(bool needFlush)
{
unsigned num = _printedString.Len();
if (num != 0)
{
unsigned i;
/* '\r' in old MAC OS means "new line".
So we can't use '\r' in some systems */
#ifdef _WIN32
char *start = _temp.GetBuf(num + 2);
char *p = start;
*p++ = '\r';
for (i = 0; i < num; i++) *p++ = ' ';
*p++ = '\r';
#else
char *start = _temp.GetBuf(num * 3);
char *p = start;
for (i = 0; i < num; i++) *p++ = '\b';
for (i = 0; i < num; i++) *p++ = ' ';
for (i = 0; i < num; i++) *p++ = '\b';
#endif
*p = 0;
_temp.ReleaseBuf_SetLen((unsigned)(p - start));
*_so << _temp;
}
if (needFlush)
_so->Flush();
_printedString.Empty();
}
void CPercentPrinter::GetPercents()
{
char s[32];
unsigned size;
{
char c = '%';
UInt64 val = 0;
if (Total == (UInt64)(Int64)-1)
{
val = Completed >> 20;
c = 'M';
}
else if (Total != 0)
val = Completed * 100 / Total;
ConvertUInt64ToString(val, s);
size = (unsigned)strlen(s);
s[size++] = c;
s[size] = 0;
}
while (size < kPercentsSize)
{
_s += ' ';
size++;
}
_s += s;
}
void CPercentPrinter::Print()
{
DWORD tick = 0;
if (_tickStep != 0)
tick = GetTickCount();
bool onlyPercentsChanged = false;
if (!_printedString.IsEmpty())
{
if (_tickStep != 0 && (UInt32)(tick - _prevTick) < _tickStep)
return;
CPercentPrinterState &st = *this;
if (_printedState.Command == st.Command
&& _printedState.FileName == st.FileName
&& _printedState.Files == st.Files)
{
if (_printedState.Total == st.Total
&& _printedState.Completed == st.Completed)
return;
onlyPercentsChanged = true;
}
}
_s.Empty();
GetPercents();
if (onlyPercentsChanged && _s == _printedPercents)
return;
_printedPercents = _s;
if (Files != 0)
{
char s[32];
ConvertUInt64ToString(Files, s);
// unsigned size = (unsigned)strlen(s);
// for (; size < 3; size++) _s += ' ';
_s += ' ';
_s += s;
// _s += "f";
}
if (!Command.IsEmpty())
{
_s += ' ';
_s += Command;
}
if (!FileName.IsEmpty() && _s.Len() < MaxLen)
{
_s += ' ';
StdOut_Convert_UString_to_AString(FileName, _temp);
_temp.Replace('\n', ' ');
if (_s.Len() + _temp.Len() > MaxLen)
{
unsigned len = FileName.Len();
for (; len != 0;)
{
unsigned delta = len / 8;
if (delta == 0)
delta = 1;
len -= delta;
_tempU = FileName;
_tempU.Delete(len / 2, FileName.Len() - len);
_tempU.Insert(len / 2, L" . ");
StdOut_Convert_UString_to_AString(_tempU, _temp);
if (_s.Len() + _temp.Len() <= MaxLen)
break;
}
if (len == 0)
_temp.Empty();
}
_s += _temp;
}
if (_printedString != _s)
{
ClosePrint(false);
*_so << _s;
if (NeedFlush)
_so->Flush();
_printedString = _s;
}
_printedState = *this;
if (_tickStep != 0)
_prevTick = tick;
}
| [
"cryptobees@gmail.com"
] | cryptobees@gmail.com |
8eefc0be7fd82bc76974dd74b77623edb98f4b48 | f13d58b82ab70b42ff017432272e4e9fc3d8d99a | /online-judge/CodeForces/CodeForces 1093C.cpp | 94b28e10eac469fb9c000f7987fb7a0993a35f7b | [] | no_license | WEGFan/Algorithm-Contest-Code | 3586d6edba03165a9e243a10566fedcc6bcf1315 | a5b53605c0ec7161d12d48335171763a2ddf12b0 | refs/heads/master | 2020-11-26T10:33:02.807386 | 2019-12-19T12:05:17 | 2019-12-19T12:05:17 | 229,043,842 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | cpp | #include <iostream>
using namespace std;
long long arr[200007];
long long brr[200007];
int main()
{
int n;
cin >> n;
for (int i = 0; i < n / 2; i++)
{
cin >> brr[i];
}
arr[0] = 0;
arr[n - 1] = brr[0];
for (int i = 1; i < n / 2; i++)
{
long long tmp = arr[n - i];
if (brr[i] - arr[i - 1] <= tmp)
{
arr[i] = arr[i - 1];
arr[n - i - 1] = brr[i] - arr[i - 1];
}
else
{
arr[n - i - 1] = tmp;
arr[i] = brr[i] - tmp;
}
}
for (int i = 0; i < n; i++)
{
cout << arr[i] << ' ';
}
return 0;
} | [
"goofans@qq.com"
] | goofans@qq.com |
0f0a4329caeca28272ba9b782a665fcffba36a76 | 438d9dde1d13a7b49da7ab4599a7ea5a046ccb88 | /Semester5-F/BTP305/Workshop8/Workshop8/w8.cpp | 1701c4586daceeb551c6de5bf8266215b9d7feea | [] | no_license | phanthanhkhai480/school-work | b99e1b11642a9929bbb5a83d3d0e3b6480669d92 | f95831e0d36a461bd0eb00c61946cff526fdbf60 | refs/heads/main | 2023-08-06T00:21:05.091992 | 2021-09-27T02:31:31 | 2021-09-27T02:31:31 | 394,076,848 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,434 | cpp | // Workshop 9 - Smart Pointers
// w9.cpp
#include <iostream>
#include <fstream>
#include <iomanip>
#include <memory>
#include <utility>
#include "Element.h"
#include "List.h"
const int FWC = 5;
const int FWD = 12;
const int FWP = 8;
w9::List<w9::Product> merge(const w9::List<w9::Description>& desc,
const w9::List<w9::Price>& price)
{
w9::List<w9::Product> priceList;
//******* YOUR CODE GOES HERE ***********//
//Part 1
//search for array with common attributes
int desc_size = desc.size();
int price_size = price.size();
for (int a = 0; a < desc_size; a++)
//loop through array of description (code, description)
{
for (int b = 0; b < price_size; b++)
//loop through array price (code,price)
{
if (desc[a].code == price[b].code)
//comparing common attribute
{
//Product(const std::string& str, double p)
//raw pointer
w9::Product* temp = new w9::Product(desc[a].desc, price[b].price);
priceList += temp;
delete temp;
temp = nullptr;
//smart pointer
//std::unique_ptr<w9::Product> same
//( new w9::Product(desc[a].desc, price[b].price) );
//same->validate();
//priceList += std::move(same);
}
}
}
return priceList;
}
int main(int argc, char** argv) {
std::ofstream ofs("Lab8Output.txt");
std::cout << "\nCommand Line : ";
for (int i = 0; i < argc; i++) {
std::cout << argv[i] << ' ';
}
std::cout << std::endl;
if (argc != 3) {
std::cerr << "\n***Incorrect number of arguments***\n";
return 1;
}
try {
w9::List<w9::Description> desc(argv[1]);
ofs << std::endl;
ofs << std::setw(FWC) << "Code" << std::setw(FWD) << "Description" << std::endl;
ofs << desc << std::endl;
w9::List<w9::Price> price(argv[2]);
ofs << std::endl;
ofs << std::setw(FWC) << "Code" << std::setw(FWP) << "Price" << std::endl;
ofs << price << std::endl;
w9::List<w9::Product> priceList = merge(desc, price);
ofs << std::endl;
ofs << std::setw(FWD) << "Description" << std::setw(FWP) << "Price" << std::endl;
ofs << priceList << std::endl;
}
catch (const std::string& msg) {
ofs << msg << std::endl;
}
catch (const char* msg) {
ofs << msg << std::endl;
}
std::cout << "Results can be found in the Lab8Output.txt file\nPress any key to continue ... ";
std::cin.get();
ofs.close();
}
| [
"50007190+phanthanhkhai480@users.noreply.github.com"
] | 50007190+phanthanhkhai480@users.noreply.github.com |
6c3cb6fc5dcdd297386a5fd11b41e311e41218e0 | cc2cd06b8ed582d8363ca0998d5fd1a77e70cd0c | /MFISH.cpp | a03c2a4e9719623f8ef106bbcd37dde219543e98 | [] | no_license | gittyvarshney/DP | 625aaa73ef984fd557db629bdae30c540baa79da | 12798f3211508f8b030671efed6fce85172a74e2 | refs/heads/master | 2022-12-15T01:26:20.591380 | 2020-09-16T14:57:24 | 2020-09-16T14:57:24 | 285,312,858 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,013 | cpp | #include<bits/stdc++.h>
using namespace std;
//Very nice 1D DP Problem of SPOJ
//In original problem their is a constraint that you have to use all the ships but
//if their is no constraint on ships
//you can replace the //with constraint <--between--> //End of constraint With
/*
map<int, int>::reverse_iterator it;
for (it = an.rbegin(); it != an.rend(); it++)
{
//cout << it->first << " ";
for(i=it->first;i<=it->first+it->second-1;i++)
{
if(m[i]==0)
{
m[i] = it->second;
}
}
}
*/
int n;
vector<int>arr_sum(1000000,0);
vector<int>vec(1000000,-1);
map<int,int>m;
int recurr_dp(int i)
{
if(i<=0)
{
//cout << "returning 0\n";
return 0;
}
if(vec[i]!= -1)
{
//cout << "DP Used\n";
return vec[i];
}
int val_1,val_2;
if(m[i]==0)
{
val_1 = recurr_dp(i-1);
vec[i] = val_1;
//cout << "vec[" << i << "]: " << vec[i] << "\n";
return vec[i];
}
if(i-m[i] < 0)
{
val_1 = 0;
}
else
{
val_1 = (arr_sum[i] - arr_sum[i - m[i]]) + recurr_dp(i-m[i]);
}
val_2 = recurr_dp(i-1);
vec[i] = max(val_1,val_2);
//cout << "vec[" << i << "]: " << vec[i] << "\n";
return vec[i];
}
int main()
{
#ifndef ONLINE_JUDGE
freopen("D:\\Project sunrise\\input.txt", "r", stdin);
freopen("D:\\Project sunrise\\output.txt", "w", stdout);
#endif
ios::sync_with_stdio(0);
cin.tie(NULL);
cout.tie(NULL);
cin >> n;
int sum=0;
int fishes;
int i;
for(i=1;i<n+1;i++)
{
cin >> fishes;
arr_sum[i] = fishes+sum;
sum = arr_sum[i];
}
int ships;
int anchor,length;
cin >> ships;
map<int,int>an;
while(ships--)
{
cin >> anchor >> length;
an[anchor] = length;
}
//With constraint
int last = -645;
for(auto it: an)
{
for(i=it.first;i<=it.first+it.second-1;i++)
{
if(i-it.second>=last)
{
m[i] = it.second;
}
else
{
m[i] = 0;
}
}
last = it.first;
}
//End of constraint
cout << recurr_dp(n) << "\n";
}
| [
"pv66645@gmail.com"
] | pv66645@gmail.com |
386fc1cd7d378e4d6d18d62752528d972416fd82 | 9ec67e83200f643f9f55ed90e0b2cae4581ebcb6 | /CppParserLib/PPTokenList.h | 26cf01369c79b1d9f102b0f10cd2339843d503c2 | [] | no_license | andrewpaterson/Codaphela.Library | 465770eaf2839589fc305660725abb38033f8aa2 | 2a4722ba0a4b98a304a297a9d74c9b6811fa4ac5 | refs/heads/master | 2023-05-25T13:01:45.587888 | 2023-05-14T11:46:36 | 2023-05-14T11:46:36 | 3,248,841 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,521 | h | /** ---------------- COPYRIGHT NOTICE, DISCLAIMER, and LICENSE ------------- **
Copyright (c) 2022 Andrew Paterson
This file is part of The Codaphela Project: Codaphela CppParserLib
Codaphela CppParserLib is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Codaphela CppParserLib 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 Codaphela CppParserLib. If not, see <http://www.gnu.org/licenses/>.
** ------------------------------------------------------------------------ **/
#ifndef __P_P_TOKEN_LIST_H__
#define __P_P_TOKEN_LIST_H__
#include "BaseLib/Chars.h"
#include "PPToken.h"
class CPPTokenList
{
protected:
CArrayPPTokenPtrs mcArray;
public:
void Init(void);
void Kill(void);
char* Print(CChars* psz, bool bShowFileAndLine = false);
void Add(CPPToken* ppcToken);
bool Equals(CPPTokenList* pcOther);
void SavageAppend(CChars* psz, int iDepth);
int NumTokens(void);
CPPToken* Get(int iTokenIndex);
void Dump(void);
};
typedef CArrayTemplate<CPPTokenList> CArrayPPTokenLists;
#endif // !__P_P_TOKEN_LIST_H__
| [
"andrew.ian.paterson@gmail.com"
] | andrew.ian.paterson@gmail.com |
9f534a1748b38c981fa29ef589f2293681312296 | 1f171eacac79739625a0500b0097871d40d61a2d | /test/unit/pdf/PdfMappingTest.cpp | f1164040e2ba01583f7f0d97c640f0ba7d309ff1 | [] | no_license | BillyLiggins/oxsx_old | b41a44bf77da859c342843f61d7a5495452089df | 67c23cf2c616a4a637bdda21e3d94e57cc5007b5 | refs/heads/master | 2021-05-02T16:48:47.383871 | 2017-03-02T01:52:36 | 2017-03-02T01:52:36 | 72,468,919 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,171 | cpp | #include <catch.hpp>
#include <PdfMapping.h>
#include <BinnedPdf.h>
TEST_CASE("Check Initialisation of 3x3 -> 3x3"){
AxisCollection ax;
ax.AddAxis(PdfAxis("axis 1", 2.3, 4.5, 90));
ax.AddAxis(PdfAxis("axis 2", 1.3, 4.7, 11));
PdfMapping map;
REQUIRE(map.GetNBins() == 0);
map.SetAxes(ax);
REQUIRE(map.GetNBins() == 90 * 11);
std::vector<double> initalVals;
for(size_t i = 0; i < map.GetNBins(); i++)
for(size_t j = 0; j < map.GetNBins(); j++)
initalVals.push_back(map.GetComponent(i, j));
// should all be initialised to zero
REQUIRE(initalVals == std::vector<double>((90*11) * (90 * 11), 0));
}
TEST_CASE("Identity Matrix Multiplication on 100 long vector"){
AxisCollection axes;
axes.AddAxis(PdfAxis("", 0, 100, 100));
BinnedPdf binnedPdf(axes);
for(size_t i = 0; i < 100; i++)
binnedPdf.SetBinContent(i, 1.1);
PdfMapping map;
map.SetAxes(axes);
for(size_t i = 0; i < 100; i++)
map.SetComponent(i, i, 1);
BinnedPdf mappedPdf = map(binnedPdf);
REQUIRE(mappedPdf.GetBinContents() == std::vector<double> (100, 1.1));
}
| [
"jack.dunger@physics.ox.ax.uk"
] | jack.dunger@physics.ox.ax.uk |
e226e2080c54721f229fa4539455a944904d9488 | 575731c1155e321e7b22d8373ad5876b292b0b2f | /examples/native/ios/Pods/boost-for-react-native/boost/mpl/bitand.hpp | 844cc1a2669f853b0fef30c07dcada5a7f89cf03 | [
"BSL-1.0",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | Nozbe/zacs | 802a84ffd47413a1687a573edda519156ca317c7 | c3d455426bc7dfb83e09fdf20781c2632a205c04 | refs/heads/master | 2023-06-12T20:53:31.482746 | 2023-06-07T07:06:49 | 2023-06-07T07:06:49 | 201,777,469 | 432 | 10 | MIT | 2023-01-24T13:29:34 | 2019-08-11T14:47:50 | JavaScript | UTF-8 | C++ | false | false | 1,191 | hpp |
#ifndef BOOST_MPL_BITAND_HPP_INCLUDED
#define BOOST_MPL_BITAND_HPP_INCLUDED
// Copyright Aleksey Gurtovoy 2000-2009
// Copyright Jaap Suter 2003
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
// agurt, 23/jan/10: workaround a conflict with <iso646.h> header's
// macros, see http://tinyurl.com/ycwdxco; 'defined(bitand)'
// has to be checked in a separate condition, otherwise GCC complains
// about 'bitand' being an alternative token
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(bitand)
# pragma push_macro("bitand")
# undef bitand
# define bitand(x)
#endif
#endif
#endif
#define AUX778076_OP_NAME bitand_
#define AUX778076_OP_PREFIX bitand
#define AUX778076_OP_TOKEN &
#include <boost/mpl/aux_/arithmetic_op.hpp>
#if defined(_MSC_VER) && !defined(__clang__)
#ifndef __GCCXML__
#if defined(bitand)
# pragma pop_macro("bitand")
#endif
#endif
#endif
#endif // BOOST_MPL_BITAND_HPP_INCLUDED
| [
"radexpl@gmail.com"
] | radexpl@gmail.com |
6508690ec1d94a20d85d58f51ac918b4b2aefe18 | 5bee3ec75e44bfc15fc181bb51248e81e6d5e83c | /Currentsensor.h | a45c374fd7af20b41d6220ec8368e062052d03a0 | [] | no_license | Luumo/microgrid-iot-platform | ad9f568d19458bbe0d1726d527200cb23f3611ce | fc727b1ef5d5af53d8e2c94c98285f9eed43b32b | refs/heads/master | 2023-02-21T17:54:11.118478 | 2020-07-03T22:30:15 | 2020-07-03T22:30:15 | 224,829,758 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 648 | h | #ifndef CURRENTSENSOR_H
#define CURRENTSENSOR_H
class CurrentSensor{
public:
CurrentSensor(int pin, float sensitivity);
float readCurrent(); // returns Ampere
float currentValue = 0.000;
private:
int m_pin;
float m_sensitivity; //66mV/A for 30A sensor, 100mV/A for 20A sensor
float m_offsetVoltage = 2500.0; // VIOT 2.5V when no load on ammeter
float m_adcValue = 0.0;
float m_adcVoltage = 0.0;
void calcAdcVoltage(); // helper-function, converts to mV
void getAdcValue(int m_pin); // helper-function, to get raw input value
};
#endif // CURRENTSENSOR_H
| [
"34240620+Luumo@users.noreply.github.com"
] | 34240620+Luumo@users.noreply.github.com |
f0f18c51a1711afe3a6bfe37929757e7ef2167d8 | 7c3705990d82f10c9c5a789c9c8442da51f232f5 | /AmbifluxRobotARNL/AmbifluxRobot/Frame.cpp | 88a1bb6a53a2a93aa56b15e52016af6acdb857aa | [] | no_license | onartz/AmbifluxRobot | 7d30b3c6cbd6364bbf4ec7990cbaf45c9510159d | 7a7331bcf3d81997a073d0abcb8c84a508a266ed | refs/heads/master | 2021-01-21T10:09:08.567781 | 2015-05-28T09:15:06 | 2015-05-28T09:15:06 | 41,915,516 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 102 | cpp | #include "Frame.h"
Frame::Frame(){}
Frame::Frame(char** msg, int nbArgs):msg( msg, msg + nbArgs )
{} | [
"olivier.nartz@univ-lorraine.fr"
] | olivier.nartz@univ-lorraine.fr |
66445abbba295b65d82cfe21ef535dd423fdc7c4 | e104892af303d85c5e661d099b500dc1e35b882d | /Sample12_4/app/src/main/cpp/bndev/MyVulkanManager.cpp | 08bf6e60198a5bdbb2fe66627cb03c2966f6ae67 | [
"Unlicense"
] | permissive | siwangqishiq/Vulkan_Develpment_Samples | 624900dabaca75c9ad21ef5a1ee5af6709dcc9a8 | 409c973e0b37086c854cde07b1e620c3d8d9f15d | refs/heads/master | 2023-08-16T04:13:54.777841 | 2021-10-14T06:53:11 | 2021-10-14T06:53:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 30,672 | cpp | #include <vulkan/vulkan.h>
#include "MatrixState3D.h"
#include "MyVulkanManager.h"
#include "../util/FileUtil.h"
#include "../util/TextureManager.h"
#include "../util/HelpFunction.h"
#include <thread>
#include <iostream>
#include <assert.h>
#include <chrono>
#include "ThreadTask.h"
#include "../util/FPSUtil.h"
#include "FlatData.h"
#include <sys/time.h>
android_app* MyVulkanManager::Android_application;
bool MyVulkanManager::loopDrawFlag=true;
std::vector<const char *> MyVulkanManager::instanceExtensionNames;
VkInstance MyVulkanManager::instance;
uint32_t MyVulkanManager::gpuCount;
std::vector<VkPhysicalDevice> MyVulkanManager::gpus;
uint32_t MyVulkanManager::queueFamilyCount;
std::vector<VkQueueFamilyProperties> MyVulkanManager::queueFamilyprops;
uint32_t MyVulkanManager::queueGraphicsFamilyIndex;
VkQueue MyVulkanManager::queueGraphics;
uint32_t MyVulkanManager::queuePresentFamilyIndex;
std::vector<const char *> MyVulkanManager::deviceExtensionNames;
VkDevice MyVulkanManager::device;
VkCommandPool MyVulkanManager::cmdPool;
VkCommandBuffer MyVulkanManager::cmdBuffer;
VkCommandBufferBeginInfo MyVulkanManager::cmd_buf_info;
VkCommandBuffer MyVulkanManager::cmd_bufs[1];
VkSubmitInfo MyVulkanManager::submit_info[1];
uint32_t MyVulkanManager::screenWidth;
uint32_t MyVulkanManager::screenHeight;
VkSurfaceKHR MyVulkanManager::surface;
std::vector<VkFormat> MyVulkanManager::formats;
VkSurfaceCapabilitiesKHR MyVulkanManager::surfCapabilities;
uint32_t MyVulkanManager::presentModeCount;
std::vector<VkPresentModeKHR> MyVulkanManager::presentModes;
VkExtent2D MyVulkanManager::swapchainExtent;
VkSwapchainKHR MyVulkanManager::swapChain;
uint32_t MyVulkanManager::swapchainImageCount;
std::vector<VkImage> MyVulkanManager::swapchainImages;
std::vector<VkImageView> MyVulkanManager::swapchainImageViews;
VkFormat MyVulkanManager::depthFormat;
VkFormatProperties MyVulkanManager::depthFormatProps;
VkImage MyVulkanManager::depthImage;
VkPhysicalDeviceMemoryProperties MyVulkanManager::memoryroperties;
VkDeviceMemory MyVulkanManager::memDepth;
VkImageView MyVulkanManager::depthImageView;
VkSemaphore MyVulkanManager::imageAcquiredSemaphore;
uint32_t MyVulkanManager::currentBuffer;
VkRenderPass MyVulkanManager::renderPass;
VkClearValue MyVulkanManager::clear_values[2];
VkRenderPassBeginInfo MyVulkanManager::rp_begin;
VkFence MyVulkanManager::taskFinishFence;
VkPresentInfoKHR MyVulkanManager::present;
VkFramebuffer* MyVulkanManager::framebuffers;
ShaderQueueSuit_CommonTex* MyVulkanManager::sqsCT;
ShaderQueueSuit_CommonTexImage* MyVulkanManager::sqsImage;
TexDrawableObject* MyVulkanManager::texTri;
float MyVulkanManager::yAngle=0;
float MyVulkanManager::zAngle=0;
void MyVulkanManager::init_vulkan_instance()
{
AAssetManager* aam=MyVulkanManager::Android_application->activity->assetManager;
FileUtil::setAAssetManager(aam);
if (!vk::loadVulkan())
{
LOGI("加载Vulkan API失败!");
return ;
}
instanceExtensionNames.push_back(VK_KHR_SURFACE_EXTENSION_NAME);
instanceExtensionNames.push_back(VK_KHR_ANDROID_SURFACE_EXTENSION_NAME);
VkApplicationInfo app_info = {};
app_info.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
app_info.pNext = NULL;
app_info.pApplicationName = "HelloVulkan";
app_info.applicationVersion = 1;
app_info.pEngineName = "HelloVulkan";
app_info.engineVersion = 1;
app_info.apiVersion = VK_API_VERSION_1_0;
VkInstanceCreateInfo inst_info = {};
inst_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
inst_info.pNext = NULL;
inst_info.flags = 0;
inst_info.pApplicationInfo = &app_info;
inst_info.enabledExtensionCount = instanceExtensionNames.size();
inst_info.ppEnabledExtensionNames = instanceExtensionNames.data();;
inst_info.enabledLayerCount = 0;
inst_info.ppEnabledLayerNames = NULL;
VkResult result;
result = vk::vkCreateInstance(&inst_info, NULL, &instance);
if(result== VK_SUCCESS)
{
LOGE("Vulkan实例创建成功!");
}
else
{
LOGE("Vulkan实例创建失败!");
}
}
void MyVulkanManager::destroy_vulkan_instance()
{
vk::vkDestroyInstance(instance, NULL);
LOGE("Vulkan实例销毁完毕!");
}
void MyVulkanManager::enumerate_vulkan_phy_devices()
{
gpuCount=0;
VkResult result = vk::vkEnumeratePhysicalDevices(instance, &gpuCount, NULL);
assert(result==VK_SUCCESS);
LOGE("[Vulkan硬件设备数量为%d个]",gpuCount);
gpus.resize(gpuCount);
result = vk::vkEnumeratePhysicalDevices(instance, &gpuCount, gpus.data());
assert(result==VK_SUCCESS);
vk::vkGetPhysicalDeviceMemoryProperties(gpus[0],&memoryroperties);
}
void MyVulkanManager::create_vulkan_devices()
{
vk::vkGetPhysicalDeviceQueueFamilyProperties(gpus[0], &queueFamilyCount, NULL);
LOGE("[Vulkan硬件设备0支持的队列家族数量为%d]",queueFamilyCount);
queueFamilyprops.resize(queueFamilyCount);
vk::vkGetPhysicalDeviceQueueFamilyProperties(gpus[0], &queueFamilyCount, queueFamilyprops.data());
LOGE("[成功获取Vulkan硬件设备0支持的队列家族属性列表]");
VkDeviceQueueCreateInfo queueInfo = {};
bool found = false;
for (unsigned int i = 0; i < queueFamilyCount; i++)
{
if (queueFamilyprops[i].queueFlags & VK_QUEUE_GRAPHICS_BIT)
{
queueInfo.queueFamilyIndex = i;
queueGraphicsFamilyIndex=i;
LOGE("[支持GRAPHICS工作的一个队列家族的索引为%d]",i);
LOGE("[此家族中的实际队列数量是%d]",queueFamilyprops[i].queueCount);
found = true;
break;
}
}
float queue_priorities[1] = {0.0};
queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
queueInfo.pNext = NULL;
queueInfo.queueCount = 1;
queueInfo.pQueuePriorities = queue_priorities;
queueInfo.queueFamilyIndex = queueGraphicsFamilyIndex;
deviceExtensionNames.push_back(VK_KHR_SWAPCHAIN_EXTENSION_NAME);
VkPhysicalDeviceFeatures pdf;
vk::vkGetPhysicalDeviceFeatures(gpus[0],&pdf);
VkDeviceCreateInfo deviceInfo = {};
deviceInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
deviceInfo.pNext = NULL;
deviceInfo.queueCreateInfoCount = 1;
deviceInfo.pQueueCreateInfos = &queueInfo;
deviceInfo.enabledExtensionCount = deviceExtensionNames.size();
deviceInfo.ppEnabledExtensionNames = deviceExtensionNames.data();
deviceInfo.enabledLayerCount = 0;
deviceInfo.ppEnabledLayerNames = NULL;
deviceInfo.pEnabledFeatures = &pdf;
VkResult result = vk::vkCreateDevice(gpus[0], &deviceInfo, NULL, &device);
assert(result==VK_SUCCESS);
}
void MyVulkanManager::destroy_vulkan_devices()
{
vk::vkDestroyDevice(device, NULL);
LOGE("逻辑设备销毁完毕!");
}
void MyVulkanManager::create_vulkan_CommandBuffer()
{
VkCommandPoolCreateInfo cmd_pool_info = {};
cmd_pool_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
cmd_pool_info.pNext = NULL;
cmd_pool_info.queueFamilyIndex = queueGraphicsFamilyIndex;
cmd_pool_info.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
VkResult result = vk::vkCreateCommandPool(device, &cmd_pool_info, NULL, &cmdPool);
assert(result==VK_SUCCESS);
VkCommandBufferAllocateInfo cmdBAI = {};
cmdBAI.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
cmdBAI.pNext = NULL;
cmdBAI.commandPool = cmdPool;
cmdBAI.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
cmdBAI.commandBufferCount = 1;
result = vk::vkAllocateCommandBuffers(device, &cmdBAI, &cmdBuffer);
assert(result==VK_SUCCESS);
cmd_buf_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
cmd_buf_info.pNext = NULL;
cmd_buf_info.flags = 0;
cmd_buf_info.pInheritanceInfo = NULL;
cmd_bufs[0] = cmdBuffer;
VkPipelineStageFlags* pipe_stage_flags = new VkPipelineStageFlags();
*pipe_stage_flags=VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
submit_info[0].pNext = NULL;
submit_info[0].sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
submit_info[0].pWaitDstStageMask = pipe_stage_flags;
submit_info[0].commandBufferCount = 1;
submit_info[0].pCommandBuffers = cmd_bufs;
submit_info[0].signalSemaphoreCount = 0;
submit_info[0].pSignalSemaphores = NULL;
}
void MyVulkanManager::destroy_vulkan_CommandBuffer()
{
VkCommandBuffer cmdBufferArray[1] = {cmdBuffer};
vk::vkFreeCommandBuffers
(
device,
cmdPool,
1,
cmdBufferArray
);
vk::vkDestroyCommandPool(device, cmdPool, NULL);
}
void MyVulkanManager::create_vulkan_swapChain()
{
screenWidth = ANativeWindow_getWidth(Android_application->window);
screenHeight = ANativeWindow_getHeight(Android_application->window);
LOGE("窗体宽度%d 窗体高度%d",screenWidth,screenHeight);
VkAndroidSurfaceCreateInfoKHR createInfo;
createInfo.sType = VK_STRUCTURE_TYPE_ANDROID_SURFACE_CREATE_INFO_KHR;
createInfo.pNext = nullptr;
createInfo.flags = 0;
createInfo.window = Android_application->window;
PFN_vkCreateAndroidSurfaceKHR fpCreateAndroidSurfaceKHR=(PFN_vkCreateAndroidSurfaceKHR)vk::vkGetInstanceProcAddr(instance, "vkCreateAndroidSurfaceKHR");
if (fpCreateAndroidSurfaceKHR == NULL)
{
LOGE( "找不到vkvkCreateAndroidSurfaceKHR扩展函数!" );
}
VkResult result = fpCreateAndroidSurfaceKHR(instance, &createInfo, nullptr, &surface);
assert(result==VK_SUCCESS);
VkBool32 *pSupportsPresent = (VkBool32 *)malloc(queueFamilyCount * sizeof(VkBool32));
for (uint32_t i = 0; i < queueFamilyCount; i++)
{
vk::vkGetPhysicalDeviceSurfaceSupportKHR(gpus[0], i, surface, &pSupportsPresent[i]);
LOGE("队列家族索引=%d %s显示",i,(pSupportsPresent[i]==1?"支持":"不支持"));
}
queueGraphicsFamilyIndex = UINT32_MAX;
queuePresentFamilyIndex = UINT32_MAX;
for (uint32_t i = 0; i <queueFamilyCount; ++i)
{
if ((queueFamilyprops[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) != 0)
{
if (queueGraphicsFamilyIndex== UINT32_MAX) queueGraphicsFamilyIndex = i;
if (pSupportsPresent[i] == VK_TRUE)
{
queueGraphicsFamilyIndex = i;
queuePresentFamilyIndex = i;
LOGE("队列家族索引=%d 同时支持Graphis(图形)和Present(显示)工作",i);
break;
}
}
}
if (queuePresentFamilyIndex == UINT32_MAX)
{
for (size_t i = 0; i < queueFamilyCount; ++i)
{
if (pSupportsPresent[i] == VK_TRUE)
{
queuePresentFamilyIndex= i;
break;
}
}
}
free(pSupportsPresent);
if (queueGraphicsFamilyIndex == UINT32_MAX || queuePresentFamilyIndex == UINT32_MAX)
{
LOGE("没有找到支持Graphis(图形)或Present(显示)工作的队列家族");
assert(false);
}
uint32_t formatCount;
result = vk::vkGetPhysicalDeviceSurfaceFormatsKHR(gpus[0], surface, &formatCount, NULL);
LOGE("支持的格式数量为 %d",formatCount);
VkSurfaceFormatKHR *surfFormats = (VkSurfaceFormatKHR *)malloc(formatCount * sizeof(VkSurfaceFormatKHR));
formats.resize(formatCount);
result = vk::vkGetPhysicalDeviceSurfaceFormatsKHR(gpus[0], surface, &formatCount, surfFormats);
for(int i=0;i<formatCount;i++)
{
formats[i]=surfFormats[i].format;
LOGE("[%d]支持的格式为%d",i,formats[i]);
}
if (formatCount == 1 && surfFormats[0].format == VK_FORMAT_UNDEFINED)
{
formats[0] = VK_FORMAT_B8G8R8A8_UNORM;
}
free(surfFormats);
result = vk::vkGetPhysicalDeviceSurfaceCapabilitiesKHR(gpus[0], surface, &surfCapabilities);
assert(result == VK_SUCCESS);
result = vk::vkGetPhysicalDeviceSurfacePresentModesKHR(gpus[0], surface, &presentModeCount, NULL);
assert(result == VK_SUCCESS);
LOGE("显示模式数量为%d",presentModeCount);
presentModes.resize(presentModeCount);
result = vk::vkGetPhysicalDeviceSurfacePresentModesKHR(gpus[0], surface, &presentModeCount, presentModes.data());
for(int i=0;i<presentModeCount;i++)
{
LOGE("显示模式[%d]编号为%d",i,presentModes[i]);
}
VkPresentModeKHR swapchainPresentMode = VK_PRESENT_MODE_FIFO_KHR;
for (size_t i = 0; i < presentModeCount; i++)
{
if (presentModes[i] == VK_PRESENT_MODE_MAILBOX_KHR)
{
swapchainPresentMode = VK_PRESENT_MODE_MAILBOX_KHR;
break;
}
if ((swapchainPresentMode != VK_PRESENT_MODE_MAILBOX_KHR)&&(presentModes[i] == VK_PRESENT_MODE_IMMEDIATE_KHR))
{
swapchainPresentMode = VK_PRESENT_MODE_IMMEDIATE_KHR;
}
}
if (surfCapabilities.currentExtent.width == 0xFFFFFFFF)
{
swapchainExtent.width = screenWidth;
swapchainExtent.height = screenHeight;
if (swapchainExtent.width < surfCapabilities.minImageExtent.width)
{
swapchainExtent.width = surfCapabilities.minImageExtent.width;
}
else if (swapchainExtent.width > surfCapabilities.maxImageExtent.width)
{
swapchainExtent.width = surfCapabilities.maxImageExtent.width;
}
if (swapchainExtent.height < surfCapabilities.minImageExtent.height)
{
swapchainExtent.height = surfCapabilities.minImageExtent.height;
} else if (swapchainExtent.height > surfCapabilities.maxImageExtent.height)
{
swapchainExtent.height = surfCapabilities.maxImageExtent.height;
}
LOGE("使用自己设置的 宽度 %d 高度 %d",swapchainExtent.width,swapchainExtent.height);
}
else
{
swapchainExtent = surfCapabilities.currentExtent;
LOGE("使用获取的surface能力中的 宽度 %d 高度 %d",swapchainExtent.width,swapchainExtent.height);
}
screenWidth=swapchainExtent.width;
screenHeight=swapchainExtent.height;
uint32_t desiredMinNumberOfSwapChainImages = surfCapabilities.minImageCount+1;
if ((surfCapabilities.maxImageCount > 0) &&(desiredMinNumberOfSwapChainImages > surfCapabilities.maxImageCount))
{
desiredMinNumberOfSwapChainImages = surfCapabilities.maxImageCount;
}
VkSurfaceTransformFlagBitsKHR preTransform;
if (surfCapabilities.supportedTransforms & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
{
preTransform = VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR;
}
else
{
preTransform = surfCapabilities.currentTransform;
}
VkSwapchainCreateInfoKHR swapchain_ci = {};
swapchain_ci.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
swapchain_ci.pNext = NULL;
swapchain_ci.surface = surface;
swapchain_ci.minImageCount = desiredMinNumberOfSwapChainImages;
swapchain_ci.imageFormat = formats[0];
swapchain_ci.imageExtent.width = swapchainExtent.width;
swapchain_ci.imageExtent.height = swapchainExtent.height;
swapchain_ci.preTransform = preTransform;
swapchain_ci.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
swapchain_ci.imageArrayLayers = 1;
swapchain_ci.presentMode = swapchainPresentMode;
swapchain_ci.oldSwapchain = VK_NULL_HANDLE;
swapchain_ci.clipped = true;
swapchain_ci.imageColorSpace = VK_COLORSPACE_SRGB_NONLINEAR_KHR;
swapchain_ci.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
swapchain_ci.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
swapchain_ci.queueFamilyIndexCount = 0;
swapchain_ci.pQueueFamilyIndices = NULL;
if (queueGraphicsFamilyIndex != queuePresentFamilyIndex)
{
swapchain_ci.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
swapchain_ci.queueFamilyIndexCount = 2;
uint32_t queueFamilyIndices[2] = {queueGraphicsFamilyIndex,queuePresentFamilyIndex};
swapchain_ci.pQueueFamilyIndices = queueFamilyIndices;
}
result = vk::vkCreateSwapchainKHR(device, &swapchain_ci, NULL, &swapChain);
assert(result == VK_SUCCESS);
result = vk::vkGetSwapchainImagesKHR(device, swapChain, &swapchainImageCount, NULL);
assert(result == VK_SUCCESS);
LOGE("[SwapChain中的Image数量为%d]",swapchainImageCount);
swapchainImages.resize(swapchainImageCount);
result = vk::vkGetSwapchainImagesKHR(device, swapChain, &swapchainImageCount, swapchainImages.data());
assert(result == VK_SUCCESS);
swapchainImageViews.resize(swapchainImageCount);
for (uint32_t i = 0; i < swapchainImageCount; i++)
{
VkImageViewCreateInfo color_image_view = {};
color_image_view.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
color_image_view.pNext = NULL;
color_image_view.flags = 0;
color_image_view.image = swapchainImages[i];
color_image_view.viewType = VK_IMAGE_VIEW_TYPE_2D;
color_image_view.format = formats[0];
color_image_view.components.r = VK_COMPONENT_SWIZZLE_R;
color_image_view.components.g = VK_COMPONENT_SWIZZLE_G;
color_image_view.components.b = VK_COMPONENT_SWIZZLE_B;
color_image_view.components.a = VK_COMPONENT_SWIZZLE_A;
color_image_view.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
color_image_view.subresourceRange.baseMipLevel = 0;
color_image_view.subresourceRange.levelCount = 1;
color_image_view.subresourceRange.baseArrayLayer = 0;
color_image_view.subresourceRange.layerCount = 1;
result = vk::vkCreateImageView(device, &color_image_view, NULL, &swapchainImageViews[i]);
assert(result == VK_SUCCESS);
}
}
void MyVulkanManager::destroy_vulkan_swapChain()
{
for (uint32_t i = 0; i < swapchainImageCount; i++)
{
vk::vkDestroyImageView(device, swapchainImageViews[i], NULL);
LOGE("[销毁SwapChain ImageView %d 成功]",i);
}
vk::vkDestroySwapchainKHR(device, swapChain, NULL);
LOGE("销毁SwapChain成功!");
}
void MyVulkanManager::create_vulkan_DepthBuffer()
{
depthFormat = VK_FORMAT_D16_UNORM;
VkImageCreateInfo image_info = {};
vk::vkGetPhysicalDeviceFormatProperties(gpus[0], depthFormat, &depthFormatProps);
if (depthFormatProps.linearTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
{
image_info.tiling = VK_IMAGE_TILING_LINEAR;
LOGE("tiling为VK_IMAGE_TILING_LINEAR!");
}
else if (depthFormatProps.optimalTilingFeatures & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT)
{
image_info.tiling = VK_IMAGE_TILING_OPTIMAL;
LOGE("tiling为VK_IMAGE_TILING_OPTIMAL!");
}
else
{
LOGE("不支持VK_FORMAT_D16_UNORM!");
}
image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
image_info.pNext = NULL;
image_info.imageType = VK_IMAGE_TYPE_2D;
image_info.format = depthFormat;
image_info.extent.width = screenWidth;
image_info.extent.height =screenHeight;
image_info.extent.depth = 1;
image_info.mipLevels = 1;
image_info.arrayLayers = 1;
image_info.samples = VK_SAMPLE_COUNT_1_BIT;
image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
image_info.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
image_info.queueFamilyIndexCount = 0;
image_info.pQueueFamilyIndices = NULL;
image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
image_info.flags = 0;
VkMemoryAllocateInfo mem_alloc = {};
mem_alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO;
mem_alloc.pNext = NULL;
mem_alloc.allocationSize = 0;
mem_alloc.memoryTypeIndex = 0;
VkImageViewCreateInfo view_info = {};
view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
view_info.pNext = NULL;
view_info.image = VK_NULL_HANDLE;
view_info.format = depthFormat;
view_info.components.r = VK_COMPONENT_SWIZZLE_R;
view_info.components.g = VK_COMPONENT_SWIZZLE_G;
view_info.components.b = VK_COMPONENT_SWIZZLE_B;
view_info.components.a = VK_COMPONENT_SWIZZLE_A;
view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_DEPTH_BIT;
view_info.subresourceRange.baseMipLevel = 0;
view_info.subresourceRange.levelCount = 1;
view_info.subresourceRange.baseArrayLayer = 0;
view_info.subresourceRange.layerCount = 1;
view_info.viewType = VK_IMAGE_VIEW_TYPE_2D;
view_info.flags = 0;
VkResult result = vk::vkCreateImage(device, &image_info, NULL, &depthImage);
assert(result == VK_SUCCESS);
VkMemoryRequirements mem_reqs;
vk::vkGetImageMemoryRequirements(device, depthImage, &mem_reqs);
mem_alloc.allocationSize = mem_reqs.size;
VkFlags requirements_mask=0;
bool flag=memoryTypeFromProperties(memoryroperties, mem_reqs.memoryTypeBits,requirements_mask,&mem_alloc.memoryTypeIndex);
assert(flag);
LOGE("确定内存类型成功 类型索引为%d",mem_alloc.memoryTypeIndex);
result = vk::vkAllocateMemory(device, &mem_alloc, NULL, &memDepth);
assert(result == VK_SUCCESS);
result = vk::vkBindImageMemory(device, depthImage, memDepth, 0);
assert(result == VK_SUCCESS);
view_info.image = depthImage;
result = vk::vkCreateImageView(device, &view_info, NULL, &depthImageView);
assert(result == VK_SUCCESS);
}
void MyVulkanManager::destroy_vulkan_DepthBuffer()
{
vk::vkDestroyImageView(device, depthImageView, NULL);
vk::vkDestroyImage(device, depthImage, NULL);
vk::vkFreeMemory(device, memDepth, NULL);
LOGE("销毁深度缓冲相关成功!");
}
void MyVulkanManager::create_render_pass()
{
VkSemaphoreCreateInfo imageAcquiredSemaphoreCreateInfo;
imageAcquiredSemaphoreCreateInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
imageAcquiredSemaphoreCreateInfo.pNext = NULL;
imageAcquiredSemaphoreCreateInfo.flags = 0;
VkResult result = vk::vkCreateSemaphore(device, &imageAcquiredSemaphoreCreateInfo, NULL, &imageAcquiredSemaphore);
assert(result == VK_SUCCESS);
VkAttachmentDescription attachments[2];
attachments[0].format = formats[0];
attachments[0].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[0].storeOp = VK_ATTACHMENT_STORE_OP_STORE;
attachments[0].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[0].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[0].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[0].finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
attachments[0].flags = 0;
attachments[1].format = depthFormat;
attachments[1].samples = VK_SAMPLE_COUNT_1_BIT;
attachments[1].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
attachments[1].storeOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
attachments[1].stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
attachments[1].initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
attachments[1].finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
attachments[1].flags = 0;
VkAttachmentReference color_reference = {};
color_reference.attachment = 0;
color_reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
VkAttachmentReference depth_reference = {};
depth_reference.attachment = 1;
depth_reference.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
VkSubpassDescription subpass = {};
subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
subpass.flags = 0;
subpass.inputAttachmentCount = 0;
subpass.pInputAttachments = NULL;
subpass.colorAttachmentCount = 1;
subpass.pColorAttachments = &color_reference;
subpass.pResolveAttachments = NULL;
subpass.pDepthStencilAttachment = &depth_reference;
subpass.preserveAttachmentCount = 0;
subpass.pPreserveAttachments = NULL;
VkRenderPassCreateInfo rp_info = {};
rp_info.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
rp_info.pNext = NULL;
rp_info.attachmentCount = 2;
rp_info.pAttachments = attachments;
rp_info.subpassCount = 1;
rp_info.pSubpasses = &subpass;
rp_info.dependencyCount = 0;
rp_info.pDependencies = NULL;
result = vk::vkCreateRenderPass(device, &rp_info, NULL, &renderPass);
assert(result == VK_SUCCESS);
clear_values[0].color.float32[0] = 0.0f;
clear_values[0].color.float32[1] = 0.0f;
clear_values[0].color.float32[2] = 0.0f;
clear_values[0].color.float32[3] = 0.0f;
clear_values[1].depthStencil.depth = 1.0f;
clear_values[1].depthStencil.stencil = 0;
rp_begin.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
rp_begin.pNext = NULL;
rp_begin.renderPass = renderPass;
rp_begin.renderArea.offset.x = 0;
rp_begin.renderArea.offset.y = 0;
rp_begin.renderArea.extent.width = screenWidth;
rp_begin.renderArea.extent.height = screenHeight;
rp_begin.clearValueCount = 2;
rp_begin.pClearValues = clear_values;
}
void MyVulkanManager::destroy_render_pass()
{
vk::vkDestroyRenderPass(device, renderPass, NULL);
vk::vkDestroySemaphore(device, imageAcquiredSemaphore, NULL);
}
void MyVulkanManager::init_queue()
{
vk::vkGetDeviceQueue(device, queueGraphicsFamilyIndex, 0,&queueGraphics);
}
void MyVulkanManager::create_frame_buffer()
{
VkImageView attachments[2];
attachments[1] = depthImageView;
VkFramebufferCreateInfo fb_info = {};
fb_info.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
fb_info.pNext = NULL;
fb_info.renderPass = renderPass;
fb_info.attachmentCount = 2;
fb_info.pAttachments = attachments;
fb_info.width = screenWidth;
fb_info.height = screenHeight;
fb_info.layers = 1;
uint32_t i;
framebuffers = (VkFramebuffer *)malloc(swapchainImageCount * sizeof(VkFramebuffer));
assert(framebuffers);
for (i = 0; i < swapchainImageCount; i++)
{
attachments[0] = swapchainImageViews[i];
VkResult result = vk::vkCreateFramebuffer(device, &fb_info, NULL, &framebuffers[i]);
assert(result == VK_SUCCESS);
LOGE("[创建帧缓冲%d成功!]",i);
}
}
void MyVulkanManager::destroy_frame_buffer()
{
for (int i = 0; i < swapchainImageCount; i++)
{
vk::vkDestroyFramebuffer(device, framebuffers[i], NULL);
}
free(framebuffers);
LOGE("销毁帧缓冲成功!");
}
void MyVulkanManager::createDrawableObject()
{
FlatData::genVertexData();
texTri=new TexDrawableObject(FlatData::vdata,FlatData::dataByteCount,FlatData::vCount,device, memoryroperties);
}
void MyVulkanManager::destroyDrawableObject()
{
delete texTri;
}
void MyVulkanManager::createFence()
{
VkFenceCreateInfo fenceInfo;
fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
fenceInfo.pNext = NULL;
fenceInfo.flags = 0;
vk::vkCreateFence(device, &fenceInfo, NULL, &taskFinishFence);
}
void MyVulkanManager::destroyFence()
{
vk::vkDestroyFence(device, taskFinishFence, NULL);
}
void MyVulkanManager::initPresentInfo()
{
present.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
present.pNext = NULL;
present.swapchainCount = 1;
present.pSwapchains = &swapChain;
present.pWaitSemaphores = NULL;
present.waitSemaphoreCount = 0;
present.pResults = NULL;
}
void MyVulkanManager::initMatrixAndLight()
{
MatrixState3D::setCamera(0,0,5.5,0,0,0,0,1,0);
MatrixState3D::setInitStack();
float ratio=(float)screenWidth/(float)screenHeight;
MatrixState3D::setProjectFrustum(-ratio,ratio,-1,1,1.5f,1000);
}
void MyVulkanManager::flushUniformBuffer() {
}
void MyVulkanManager::flushTexToDesSet()
{
for(int i=0;i<TextureManager::texNames.size();i++)
{
sqsCT->writes[0].dstSet = sqsCT->descSet[i];
sqsCT->writes[1].dstSet = sqsCT->descSet[i];
sqsCT->writes[1].pImageInfo = &(TextureManager::texImageInfoList[TextureManager::texNames[i]]);
vk::vkUpdateDescriptorSets(device, 2, sqsCT->writes, 0, NULL);
sqsImage->writes[0].dstSet = sqsImage->descSet[i];
sqsImage->writes[1].dstSet = sqsImage->descSet[i];
sqsImage->writes[1].pImageInfo = &(TextureManager::texImageInfoList[TextureManager::texNames[i]]);
vk::vkUpdateDescriptorSets(device, 2, sqsImage->writes, 0, NULL);
}
}
void MyVulkanManager::drawObject()
{
FPSUtil::init();
while(MyVulkanManager::loopDrawFlag)
{
FPSUtil::calFPS();
FPSUtil::before();
VkResult result = vk::vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAcquiredSemaphore, VK_NULL_HANDLE,¤tBuffer);
rp_begin.framebuffer = framebuffers[currentBuffer];
vk::vkResetCommandBuffer(cmdBuffer, 0);
result = vk::vkBeginCommandBuffer(cmdBuffer, &cmd_buf_info);
MyVulkanManager::flushUniformBuffer();
MyVulkanManager::flushTexToDesSet();
vk::vkCmdBeginRenderPass(cmdBuffer, &rp_begin, VK_SUBPASS_CONTENTS_INLINE);
MatrixState3D::pushMatrix();
MatrixState3D::translate(3.3,0,0);//处理后的图像
texTri->drawSelf(cmdBuffer,sqsImage->pipelineLayout,sqsImage->pipeline, &(sqsImage->descSet[TextureManager::getVkDescriptorSetIndex("texture/pm.bntex")]));
MatrixState3D::translate(-6.6,0,0);//正常图像
texTri->drawSelf(cmdBuffer,sqsCT->pipelineLayout,sqsCT->pipeline, &(sqsCT->descSet[TextureManager::getVkDescriptorSetIndex("texture/pm.bntex")]));
MatrixState3D::popMatrix();
vk::vkCmdEndRenderPass(cmdBuffer);
result = vk::vkEndCommandBuffer(cmdBuffer);
submit_info[0].waitSemaphoreCount = 1;
submit_info[0].pWaitSemaphores = &imageAcquiredSemaphore;
result = vk::vkQueueSubmit(queueGraphics, 1, submit_info, taskFinishFence);
do
{
result = vk::vkWaitForFences(device, 1, &taskFinishFence, VK_TRUE, FENCE_TIMEOUT);
}
while (result == VK_TIMEOUT);
vk::vkResetFences(device,1,&taskFinishFence);
present.pImageIndices = ¤tBuffer;
result = vk::vkQueuePresentKHR(queueGraphics, &present);
FPSUtil::after(60);
}
}
void MyVulkanManager::doVulkan()
{
ThreadTask* tt=new ThreadTask();
thread t1(&ThreadTask::doTask,tt);
t1.detach();
}
void MyVulkanManager::init_texture()
{
TextureManager::initTextures(device,gpus[0],memoryroperties,cmdBuffer,queueGraphics);
}
void MyVulkanManager::destroy_textures()
{
TextureManager::deatroyTextures(device);
}
void MyVulkanManager::initPipeline()
{
sqsCT=new ShaderQueueSuit_CommonTex(&device,renderPass,memoryroperties);
sqsImage=new ShaderQueueSuit_CommonTexImage(&device,renderPass,memoryroperties);
}
void MyVulkanManager::destroyPipeline()
{
delete sqsCT;
delete sqsImage;
}
| [
"709165253@qq.com"
] | 709165253@qq.com |
e7c3ad2d7214f48168548eee42907bd0498b6911 | 4121fe2de9aec21141bc70d52b857a8090289a40 | /Interfaz/Prueba/Tools.cpp | c1053a34adccc8fa361888f62fddf5daf330858f | [] | no_license | david-ponc/PDI | 63accf247abbc7d27ea7c92406ee9d61487cca30 | 31473ecb9909f09757cb989deacf9cd46c1e43be | refs/heads/master | 2022-06-19T15:31:24.550421 | 2020-04-19T22:54:21 | 2020-04-19T22:54:21 | 242,806,159 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,726 | cpp | #include "Tools.h"
Image Tools::HistogramRGB(Image img) {
Image histo;
histo.Create(256,256,255, "", "histogramaRGB");
int histoR[256] = {0}, histoG[256] = {0}, histoB[256] = {0};
int maxR = 0, maxG = 0, maxB = 0, max = 0;
for(int i = 0; i < img.height; i++) {
for(int j = 0; j < img.width; j++) {
histoR[img.pixels[i][j].R]++;
histoG[img.pixels[i][j].G]++;
histoB[img.pixels[i][j].B]++;
}
}
for(int i = 0; i < 256; i++) {
if(histoR[i] > maxR) {
maxR = histoR[i];
}
if(histoG[i] > maxG) {
maxG = histoG[i];
}
if(histoB[i] > maxB) {
maxB = histoB[i];
}
}
max = maxR;
if(max < maxG)
max = maxG;
if(max < maxB)
max = maxB;
for(int j = 0; j < histo.width; j++) {
int normalR = (histoR[j] * 100) / max;
normalR = histo.height - ((normalR * histo.height) / 100);
int normalG = (histoG[j] * 100) / max;
normalG = histo.height - ((normalG * histo.height) / 100);
int normalB = (histoB[j] * 100) / max;
normalB = histo.height - ((normalB * histo.height) / 100);
SolidGraph(normalR, histo, "R", j);
SolidGraph(normalG, histo, "G", j);
SolidGraph(normalB, histo, "B", j);
}
return histo;
}
void Tools::SolidGraph(int normal, Image histo, QString channel, int j) {
for(int i = normal; i < histo.height; i++) {
if(channel == "R") {
histo.pixels[i][j].R = 255;
}else if(channel == "G") {
histo.pixels[i][j].G = 255;
}else if(channel == "B") {
histo.pixels[i][j].B = 255;
}
}
}
| [
"buap.david@gmail.com"
] | buap.david@gmail.com |
229fef720611cacd523d8fbc4f2d5853417bc653 | 87b48e7b8d80e11fa8ac762a5327b9877ec5a1ff | /configure/configure_edge/main.cpp | 47f7d8cd35d7e0dc11fc49c80f8577ff0711f1d0 | [] | no_license | junyiliu/innovation-diffusion | 0d5fb38e0ae16f802d223a1f420c22c19bfa330f | d27b0d1689324fb9c3b8cf170e8c0255e64e23b4 | refs/heads/master | 2021-01-10T19:32:58.600105 | 2014-05-10T08:00:46 | 2014-05-10T08:00:46 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,651 | cpp | #include "my_vector.h"
#include "epidemic.h"
#include <cstdio>
#include <iostream>
#include <fstream>
#include <vector>
#include "include/igraph.h"
#include "migraph.h"
#pragma comment(lib,"igraph.lib")
igraph_rng_t *mrng=igraph_rng_default();
extern void gen_graph(igraph_t* res,
const string & name);
int main(int argc,char*argv[])
{
if(argc!=2)
{
cout<<"USAGE:SIS datafile "<<endl;
exit(1);
}
//define the entry
string networkname(argv[1]); //network name
double a=1;
double alpha=0.4;
double beta=0.1;
int game_rounds=500; //MC rounds
int aver_rounds=10; //do average
double delta=1;//delta
string output_name_pre; //the network name
for(int i=0;i!=networkname.size()-4;i++)
{
output_name_pre.push_back(networkname[i]);
}
//random generator
//to initialize the random seed
igraph_rng_init(mrng,&igraph_rngtype_mt19937);
unsigned long idum; // random number seed
idum=(unsigned long)time(NULL);
igraph_rng_seed(mrng,idum);
//construct the graph
igraph_t network;
gen_graph(&network,networkname);
int nwsize=igraph_vcount(&network); //the size of the network
//to generate the name of the output file
//output file name
string resname("res.txt");
string totalname=output_name_pre+resname;
FILE *outfile;
outfile = fopen(totalname.c_str(), "w");
//construct the population
for(a=-6;a<6.1;a+=0.1 )
{
population popu(output_name_pre,&network,delta,0.01,a,1,3*nwsize,3*nwsize);
double res=0;
popu.population_dynamics(&res,alpha,beta,1000);
fprintf(outfile,"%f\t%f\n",a,res/ nwsize);
fflush(outfile);
}
fclose(outfile);
/*
igraph_t network;
int nwsize = igraph_vcount(&network); //the size of the network
igraph_watts_strogatz_game(&network, 1, 500, 4, 0.1, false, false);
string output_name_pre("small_world");
population test(output_name_pre,&network, 1, 0.01, 1, 0, 3 * nwsize, 3 * nwsize);
test.initial_state();
double res = 0;
test.population_dynamics(&res,0.3,0.1,300);
*/
//for (a=-5;a!=5;a+=0.2)
//
//{
// population test(&network,delta,0.01,a,type,3*nwsize,3*nwsize);
// vector<double> average_rres;
// for(int i=0;i!=aver_rounds;++i)
// {
// double rres=0;
// test.initial_state();
// test.population_dynamics(&rres,0.4,0.1,game_rounds);
//// printf("%f\n", rres);
// average_rres.push_back(rres);
// }
// fprintf(outfile,"%f\t%f\n",a,double (accumulate(average_rres.begin(),\
// average_rres.end(),0)/average_rres.size()));
// fflush(outfile);
//}
//fclose(outfile);
igraph_destroy(&network);
return 0;
}
| [
"qikuijun@gmail.com"
] | qikuijun@gmail.com |
663d3de5060c32b3f52419900f2d0b9350ad630c | 384b61b16a703e28093dd07e8d4d74f053e4c582 | /src/Magnum/Trade/imageconverter.cpp | e2d5dce54452e9adeccecc6175e283d70b27e698 | [
"MIT"
] | permissive | fauder/magnum | 6d11a2aa00efbf56a08e41a36ec75b975d5712e0 | f79a9dfecfc042520704f9ad7e563114ee6ed5f7 | refs/heads/master | 2023-07-29T02:29:10.712611 | 2023-07-05T13:19:49 | 2023-07-05T13:24:51 | 264,703,677 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 60,389 | cpp | /*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019,
2020, 2021, 2022, 2023 Vladimír Vondruš <mosra@centrum.cz>
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 <Corrade/Containers/Optional.h>
#include <Corrade/Containers/GrowableArray.h>
#include <Corrade/Containers/Pair.h>
#include <Corrade/Containers/StaticArray.h>
#include <Corrade/Containers/StridedArrayView.h>
#include <Corrade/PluginManager/Manager.h>
#include <Corrade/Utility/Arguments.h>
#include <Corrade/Utility/Algorithms.h>
#include <Corrade/Utility/ConfigurationGroup.h>
#include <Corrade/Utility/DebugStl.h> /** @todo remove once Arguments is std::string-free */
#include <Corrade/Utility/Format.h>
#include <Corrade/Utility/Path.h>
#include "Magnum/ImageView.h"
#include "Magnum/PixelFormat.h"
#include "Magnum/Implementation/converterUtilities.h"
#include "Magnum/Trade/AbstractImporter.h"
#include "Magnum/Trade/AbstractImageConverter.h"
#include "Magnum/Trade/ImageData.h"
#include "Magnum/Trade/Implementation/converterUtilities.h"
namespace Magnum {
/** @page magnum-imageconverter Image conversion utility
@brief Converts images of different formats
@tableofcontents
@m_footernavigation
@m_keywords{magnum-imageconverter imageconverter}
This utility is built if `MAGNUM_WITH_IMAGECONVERTER` is enabled when building
Magnum. To use this utility with CMake, you need to request the
`imageconverter` component of the `Magnum` package and use the
`Magnum::imageconverter` target for example in a custom command:
@code{.cmake}
find_package(Magnum REQUIRED imageconverter)
add_custom_command(OUTPUT ... COMMAND Magnum::imageconverter ...)
@endcode
See @ref building, @ref cmake and the @ref Trade namespace for more
information. There's also a corresponding @ref magnum-sceneconverter "scene conversion utility".
@section magnum-imageconverter-example Example usage
Listing contents of a cubemap DDS file with mipmaps, implicitly using
@relativeref{Trade,AnyImageImporter} that delegates to
@relativeref{Trade,DdsImporter} or
@ref file-formats "any other plugin capable of DDS import" depending on what's
available:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter --info cubemap.dds
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info.ansi
@endparblock
Converting a JPEG file to a PNG, implicitly using
@relativeref{Trade,AnyImageConverter} that delegates to
@relativeref{Trade,PngImageConverter}, @relativeref{Trade,StbImageConverter} or
@ref file-formats "any other plugin capable of PNG export" depending on what's
available:
@code{.sh}
magnum-imageconverter image.jpg image.png
@endcode
Creating a JPEG file with 95% quality from a PNG, by setting a plugin-specific
configuration option that's recognized by both
@ref Trade-JpegImageConverter-configuration "JpegImageConverter" and
@ref Trade-StbImageConverter-configuration "StbImageConverter":
@code{.sh}
magnum-imageconverter image.png image.jpg -c jpegQuality=0.95
@endcode
Extracting raw (uncompressed or block-compressed) data from a DDS file for
manual inspection:
@code{.sh}
magnum-imageconverter image.dds --converter raw data.dat
@endcode
Extracting an arbitrary image from a glTF file. Note that only image formats
are considered by default so you have to explicitly supply a scene importer,
either the generic @relativeref{Trade,AnySceneImporter} or for example directly
the @relativeref{Trade,GltfImporter}. First printing a list of images to choose
from:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter -I GltfImporter --info file.gltf
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info-gltf.ansi
@endparblock
@m_class{m-noindent}
... and then extracting the third image to a PNG file for inspection:
@code{.sh}
magnum-imageconverter -I GltfImporter --image 2 file.gltf image.png
@endcode
Converting a PNG file to a KTX2, resizing it to 512x512 with
@relativeref{Trade,StbResizeImageConverter}, block-compressing its data to BC3
using @relativeref{Trade,StbDxtImageConverter} with high-quality output.
Because the plugin implements image-to-image conversion, the @relativeref{Trade,AnyImageConverter} plugin is implicitly used after it,
proxying to @relativeref{Trade,KtxImageConverter} as the `*.ktx2` extension was
chosen:
@code{.sh}
magnum-imageconverter image.png image.ktx2 \
-C StbResizeImageConverter -c size="512 512" \
-C StbDxtImageConverter -c highQuality
@endcode
Printing features and documented options of a particular image converter
plugin. For debugging convenience the printed configuration file will reflect
also all options specified via `-c`:
@m_class{m-code-figure}
@parblock
@code{.sh}
magnum-imageconverter --info-converter -C StbResizeImageConverter -c size="512 512"
@endcode
<b></b>
@m_class{m-nopad}
@include imageconverter-info-converter.ansi
@endparblock
@subsection magnum-imageconverter-example-levels-layers Dealing with image levels and layers
Converting six 2D images to a 3D cube map file using @relativeref{Trade,OpenExrImageConverter}. Note the `-c envmap-cube` which the
plugin needs to produce an actual cube map file, the `--` is then used to avoid
`-x.exr` and others to be treated as options instead of files. On Unix shells
you could also use `./-x.exr` etc. to circumvent that ambiguity.
@code{.sh}
magnum-imageconverter --layers -c envmap=cube -- \
+x.exr -x.exr +y.exr -y.exr +z.exr -z.exr cube.exr
@endcode
Creating a multi-level OpenEXR cube map file from a set of input files. Note
the use of `-D3` which switches to dealing with 3D images instead of 2D:
@code{.sh}
magnum-imageconverter --levels -c envmap=cube -D3 \
cube-256.exr cube-128.exr cube-64.exr cube-mips.exr
@endcode
Extracting the second level of a +Y face (third layer) of the above cube map
file again:
@code{.sh}
magnum-imageconverter cube-mips.exr --layer 2 --level 1 +x-128.exr
@endcode
@section magnum-imageconverter-usage Full usage documentation
@code{.sh}
magnum-imageconverter [-h|--help] [-I|--importer PLUGIN]
[-C|--converter PLUGIN]... [--plugin-dir DIR] [--map]
[-i|--importer-options key=val,key2=val2,…]
[-c|--converter-options key=val,key2=val2,…]... [-D|--dimensions N]
[--image N] [--level N] [--layer N] [--layers] [--levels] [--in-place]
[--info-importer] [--info-converter] [--info] [--color on|off|auto]
[-v|--verbose] [--profile] [--] input output
@endcode
Arguments:
- `input` --- input image
- `output` --- output image; ignored if `--info` is present, disallowed for
`--in-place`
- `-h`, `--help` --- display this help message and exit
- `-I`, `--importer PLUGIN` --- image importer plugin (default:
@ref Trade::AnyImageImporter "AnyImageImporter")
- `-C`, `--converter PLUGIN` --- image converter plugin (default:
@ref Trade::AnyImageConverter "AnyImageConverter")
- `--plugin-dir DIR` --- override base plugin dir
- `--map` --- memory-map the input for zero-copy import (works only for
standalone files)
- `-i`, `--importer-options key=val,key2=val2,…` --- configuration options to
pass to the importer
- `-c`, `--converter-options key=val,key2=val2,…` --- configuration options
to pass to the converter(s)
- `-D`, `--dimensions N` --- import and convert image of given dimensions
(default: `2`)
- `--image N` --- image to import (default: `0`)
- `--level N` --- import given image level instead of all
- `--layer N` --- extract a layer into an image with one dimension less
- `--layers` --- combine multiple layers into an image with one dimension
more
- `--levels` --- combine multiple image levels into a single file
- `--in-place` --- overwrite the input image with the output
- `--info-importer` --- print info about the importer plugin and exit
- `--info-converter` --- print info about the image converter plugin and exit
- `--info` --- print info about the input file and exit
- `--color` --- colored output for `--info` (default: `auto`)
- `-v`, `--verbose` --- verbose output from importer and converter plugins
- `--profile` --- measure import and conversion time
Specifying `--importer raw:<format>` will treat the input as a raw
tightly-packed square of pixels in given @ref PixelFormat. Specifying `-C` /
`--converter raw` will save raw imported data instead of using a converter
plugin.
If the `--info-importer` or `--info-converter` option is given, the utility
will print information about given plugin specified via the `-I` or `-C`
option, including its configuration options potentially overriden with
`-i` or `-c`. In this case no file is read and no conversion is done and
neither the input nor the output file needs to be specified.
If `--info` is given, the utility will print information about given data,
independently of the `-D` / `--dimensions` option. In this case the input file
is read but no no conversion is done and output file doesn't need to be
specified.
The `-i` / `--importer-options` and `-c` / `--converter-options` arguments
accept a comma-separated list of key/value pairs to set in the importer /
converter plugin configuration. If the `=` character is omitted, it's
equivalent to saying `key=true`; configuration subgroups are delimited with
`/`. Prefix the key with `+` to add new options or multiple options of the same
name.
It's possible to specify the `-C` / `--converter` option (and correspondingly
also `-c` / `--converter-options`) multiple times in order to chain more
converters together. All converters in the chain have to support image-to-image
conversion, the last converter has to be either `raw` or support either
image-to-image or image-to-file conversion. If the last converter doesn't
support conversion to a file, @relativeref{Trade,AnyImageConverter} is used to
save its output; if no `-C` / `--converter` is specified,
@relativeref{Trade,AnyImageConverter} is used.
*/
}
using namespace Magnum;
using namespace Containers::Literals;
namespace {
bool isPluginInfoRequested(const Utility::Arguments& args) {
return args.isSet("info-importer") ||
args.isSet("info-converter");
}
template<UnsignedInt dimensions> bool checkCommonFormatFlags(const Utility::Arguments& args, const Containers::Array<Trade::ImageData<dimensions>>& images) {
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
const bool compressed = images.front().isCompressed();
PixelFormat format{};
CompressedPixelFormat compressedFormat{};
if(!compressed) format = images.front().format();
else compressedFormat = images.front().compressedFormat();
ImageFlags<dimensions> flags = images.front().flags();
for(std::size_t i = 1; i != images.size(); ++i) {
if(images[i].isCompressed() != compressed ||
(!compressed && images[i].format() != format) ||
(compressed && images[i].compressedFormat() != compressedFormat))
{
Error e;
e << "Images have different formats," << args.arrayValue("input", i) << "has";
if(images[i].isCompressed())
e << images[i].compressedFormat();
else
e << images[i].format();
e << Debug::nospace << ", expected";
if(compressed)
e << compressedFormat;
else
e << format;
return false;
}
if(images[i].flags() != flags) {
Error{} << "Images have different flags," << args.arrayValue("input", i) << "has" << images[i].flags() << Debug::nospace << ", expected" << flags;
return false;
}
}
return true;
}
template<UnsignedInt dimensions> bool checkCommonFormatAndSize(const Utility::Arguments& args, const Containers::Array<Trade::ImageData<dimensions>>& images) {
if(!checkCommonFormatFlags(args, images)) return false;
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
Math::Vector<dimensions, Int> size = images.front().size();
for(std::size_t i = 1; i != images.size(); ++i) {
if(images[i].size() != size) {
Error{} << "Images have different sizes," << args.arrayValue("input", i) << "has a size of" << images[i].size() << Debug::nospace << ", expected" << size;
return false;
}
}
return true;
}
template<template<UnsignedInt, class> class View, UnsignedInt dimensions> bool convertOneOrMoreImagesToFile(Trade::AbstractImageConverter& converter, const Containers::Array<Trade::ImageData<dimensions>>& outputImages, const Containers::StringView output) {
Containers::Array<View<dimensions, const char>> views;
arrayReserve(views, outputImages.size());
for(const Trade::ImageData<dimensions>& outputImage: outputImages)
arrayAppend(views, View<dimensions, const char>{outputImage});
return converter.convertToFile(views, output);
}
template<UnsignedInt dimensions> bool convertOneOrMoreImagesToFile(Trade::AbstractImageConverter& converter, const Containers::Array<Trade::ImageData<dimensions>>& outputImages, const Containers::StringView output) {
/* If there's just one image, convert it using the single-level API.
Otherwise the multi-level entrypoint would require the plugin to support
multi-level conversion, and only some file formats have that. */
if(outputImages.size() == 1)
return converter.convertToFile(outputImages.front(), output);
CORRADE_INTERNAL_ASSERT(!outputImages.isEmpty());
if(outputImages.front().isCompressed())
return convertOneOrMoreImagesToFile<CompressedImageView, dimensions>(converter, outputImages, output);
else
return convertOneOrMoreImagesToFile<ImageView, dimensions>(converter, outputImages, output);
}
template<UnsignedInt dimensions> bool convertImages(Trade::AbstractImageConverter& converter, Containers::Array<Trade::ImageData<dimensions>>& images) {
CORRADE_INTERNAL_ASSERT(!images.isEmpty());
for(Trade::ImageData<dimensions>& image: images) {
Containers::Optional<Trade::ImageData<dimensions>> output = converter.convert(image);
if(!output) return false;
image = *std::move(output);
}
return true;
}
}
int main(int argc, char** argv) {
Utility::Arguments args;
args.addArrayArgument("input").setHelp("input", "input image(s)")
.addArgument("output").setHelp("output", "output image; ignored if --info is present, disallowed for --in-place")
.addOption('I', "importer", "AnyImageImporter").setHelp("importer", "image importer plugin", "PLUGIN")
.addArrayOption('C', "converter").setHelp("converter", "image converter plugin(s)", "PLUGIN")
.addOption("plugin-dir").setHelp("plugin-dir", "override base plugin dir", "DIR")
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
.addBooleanOption("map").setHelp("map", "memory-map the input for zero-copy import (works only for standalone files)")
#endif
.addOption('i', "importer-options").setHelp("importer-options", "configuration options to pass to the importer", "key=val,key2=val2,…")
.addArrayOption('c', "converter-options").setHelp("converter-options", "configuration options to pass to the converter(s)", "key=val,key2=val2,…")
.addOption('D', "dimensions", "2").setHelp("dimensions", "import and convert image of given dimensions", "N")
.addOption("image", "0").setHelp("image", "image to import", "N")
.addOption("level").setHelp("level", "import given image level instead of all", "N")
.addOption("layer").setHelp("layer", "extract a layer into an image with one dimension less", "N")
.addBooleanOption("layers").setHelp("layers", "combine multiple layers into an image with one dimension more")
.addBooleanOption("levels").setHelp("layers", "combine multiple image levels into a single file")
.addBooleanOption("in-place").setHelp("in-place", "overwrite the input image with the output")
.addBooleanOption("info-importer").setHelp("info-importer", "print info about the importer plugin and exit")
.addBooleanOption("info-converter").setHelp("info-converter", "print info about the image converter plugin and exit")
.addBooleanOption("info").setHelp("info", "print info about the input file and exit")
.addOption("color", "auto").setHelp("color", "colored output for --info", "on|off|auto")
.addBooleanOption('v', "verbose").setHelp("verbose", "verbose output from importer and converter plugins")
.addBooleanOption("profile").setHelp("profile", "measure import and conversion time")
.setParseErrorCallback([](const Utility::Arguments& args, Utility::Arguments::ParseError error, const std::string& key) {
/* If --info for plugins is passed, we don't need the input */
if(error == Utility::Arguments::ParseError::MissingArgument &&
key == "input" && isPluginInfoRequested(args))
return true;
/* If --in-place or --info for plugins or data is passed, we don't
need the output argument */
if(error == Utility::Arguments::ParseError::MissingArgument &&
key == "output" && (args.isSet("in-place") || isPluginInfoRequested(args) || args.isSet("info")))
return true;
/* Handle all other errors as usual */
return false;
})
.setGlobalHelp(R"(Converts images of different formats.
Specifying --importer raw:<format> will treat the input as a raw tightly-packed
square of pixels in given pixel format. Specifying -C / --converter raw will
save raw imported data instead of using a converter plugin.
If the --info-importer or --info-converter option is given, the utility will
print information about given plugin specified via the -I or -C option,
including its configuration options potentially overriden with -i or -c. In
this case no file is read and no conversion is done and neither the input nor
the output file needs to be specified.
If --info is given, the utility will print information about given data, independently of the -D / --dimensions option. In this case the input file is
read but no conversion is done and output file doesn't need to be specified.
The -i / --importer-options and -c / --converter-options arguments accept a
comma-separated list of key/value pairs to set in the importer / converter
plugin configuration. If the = character is omitted, it's equivalent to saying
key=true; configuration subgroups are delimited with /. Prefix the key with +
to add new options or multiple options of the same name.
It's possible to specify the -C / --converter option (and correspondingly also
-c / --converter-options) multiple times in order to chain more converters
together. All converters in the chain have to support image-to-image
conversion, the last converter has to be either raw or support either
image-to-image or image-to-file conversion. If the last converter doesn't
support conversion to a file, AnyImageConverter is used to save its output; if
no -C / --converter is specified, AnyImageConverter is used.)")
.parse(argc, argv);
/* Colored output. Enable only if a TTY. */
Debug::Flags useColor;
if(args.value("color") == "on")
useColor = Debug::Flags{};
else if(args.value("color") == "off")
useColor = Debug::Flag::DisableColors;
else
useColor = Debug::isTty() ? Debug::Flags{} : Debug::Flag::DisableColors;
/* Generic checks */
if(const std::size_t inputCount = args.arrayValueCount("input")) {
/* Not an error in this case, it should be possible to just append
--info* to existing command line without having to remove anything.
But print a warning at least, it could also be a mistyped option. */
if(isPluginInfoRequested(args)) {
Warning w;
w << "Ignoring input files for --info:";
for(std::size_t i = 0; i != inputCount; ++i)
w << args.arrayValue<Containers::StringView>("input", i);
}
}
if(args.value<Containers::StringView>("output")) {
if(args.isSet("in-place")) {
Error{} << "Output file shouldn't be set for --in-place:" << args.value<Containers::StringView>("output");
return 1;
}
/* Same as above, it should be possible to just append --info* to
existing command line */
if(isPluginInfoRequested(args) || args.isSet("info"))
Warning{} << "Ignoring output file for --info:" << args.value<Containers::StringView>("output");
}
/* Mutually incompatible options */
if(args.isSet("layers") && args.isSet("levels")) {
Error{} << "The --layers and --levels options can't be used together. First combine layers of each level and then all levels in a second step.";
return 1;
}
if((args.isSet("layers") || args.isSet("levels")) && args.isSet("in-place")) {
Error{} << "The --layers / --levels option can't be combined with --in-place";
return 1;
}
if((args.isSet("layers") || args.isSet("levels")) && args.isSet("info")) {
Error{} << "The --layers / --levels option can't be combined with --info";
return 1;
}
/* It can be combined with --levels though. This could potentially be
possible to implement, but I don't see a reason, all it would do is
picking Nth image from the input set and recompress it. OTOH, combining
--levels and --level "works", the --level picks Nth level from each
input image, although the usefulness of that is also doubtful. Why
create multi-level images from images that are already multi-level? */
if(args.isSet("layers") && !args.value("layer").empty()) {
Error{} << "The --layers option can't be combined with --layer.";
return 1;
}
if(args.isSet("levels") && args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw") {
Error{} << "The --levels option can't be combined with raw data output";
return 1;
}
if(!args.isSet("layers") && !args.isSet("levels") && args.arrayValueCount("input") > 1 && !isPluginInfoRequested(args)) {
Error{} << "Multiple input files require the --layers / --levels option to be set";
return 1;
}
/* Importer and converter manager */
PluginManager::Manager<Trade::AbstractImporter> importerManager{
args.value("plugin-dir").empty() ? Containers::String{} :
Utility::Path::join(args.value("plugin-dir"), Utility::Path::split(Trade::AbstractImporter::pluginSearchPaths().back()).second())};
PluginManager::Manager<Trade::AbstractImageConverter> converterManager{
args.value("plugin-dir").empty() ? Containers::String{} :
Utility::Path::join(args.value("plugin-dir"), Utility::Path::split(Trade::AbstractImageConverter::pluginSearchPaths().back()).second())};
/* Print plugin info, if requested */
if(args.isSet("info-importer")) {
Containers::Pointer<Trade::AbstractImporter> importer = importerManager.loadAndInstantiate(args.value("importer"));
if(!importer) {
Debug{} << "Available importer plugins:" << ", "_s.join(importerManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) importer->addFlags(Trade::ImporterFlag::Verbose);
Implementation::setOptions(*importer, "AnyImageImporter", args.value("importer-options"));
Trade::Implementation::printImporterInfo(useColor, *importer);
return 0;
}
if(args.isSet("info-converter")) {
Containers::Pointer<Trade::AbstractImageConverter> converter = converterManager.loadAndInstantiate(args.arrayValueCount("converter") ? args.arrayValue("converter", 0) : "AnyImageConverter");
if(!converter) {
Debug{} << "Available converter plugins:" << ", "_s.join(converterManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) converter->addFlags(Trade::ImageConverterFlag::Verbose);
if(args.arrayValueCount("converter-options"))
Implementation::setOptions(*converter, "AnyImageConverter", args.arrayValue("converter-options", 0));
Trade::Implementation::printImageConverterInfo(useColor, *converter);
return 0;
}
const Int dimensions = args.value<Int>("dimensions");
/** @todo make them array options as well? */
const UnsignedInt image = args.value<UnsignedInt>("image");
Containers::Optional<UnsignedInt> level;
if(!args.value("level").empty()) level = args.value<UnsignedInt>("level");
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
Containers::Array<Containers::Array<const char, Utility::Path::MapDeleter>> mapped;
#endif
Containers::Array<Trade::ImageData1D> images1D;
Containers::Array<Trade::ImageData2D> images2D;
Containers::Array<Trade::ImageData3D> images3D;
/* Wow, C++, you suck. This implicitly initializes to random shit?! */
std::chrono::high_resolution_clock::duration importTime{};
for(std::size_t i = 0, max = args.arrayValueCount("input"); i != max; ++i) {
const Containers::StringView input = args.arrayValue<Containers::StringView>("input", i);
/* Load raw data, if requested; assume it's a tightly-packed square of
given format */
/** @todo implement image slicing and then use `--slice "0 0 w h"` to
specify non-rectangular size (and +x +y to specify padding?) */
if(args.value<Containers::StringView>("importer").hasPrefix("raw:"_s)) {
if(dimensions != 2) {
Error{} << "Raw data inputs can be only used for 2D images";
return 1;
}
/** @todo Any chance to do this without using internal APIs? */
const PixelFormat format = Utility::ConfigurationValue<PixelFormat>::fromString(args.value("importer").substr(4), {});
if(format == PixelFormat{}) {
Error{} << "Invalid raw pixel format" << args.value("importer");
return 4;
}
const UnsignedInt pixelSize = pixelFormatSize(format);
/* Read the file or map it if requested */
Containers::Array<char> data;
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
if(args.isSet("map")) {
arrayAppend(mapped, InPlaceInit);
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<const char, Utility::Path::MapDeleter>> mappedMaybe = Utility::Path::mapRead(input);
if(!mappedMaybe) {
Error() << "Cannot memory-map file" << input;
return 3;
}
/* Fake a mutable array with a non-owning deleter to have the
same type as from Path::read(). The actual memory is owned
by the `mapped` array. */
mapped.back() = *std::move(mappedMaybe);
data = Containers::Array<char>{const_cast<char*>(mapped.back().data()), mapped.back().size(), [](char*, std::size_t){}};
} else
#endif
{
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<char>> dataMaybe = Utility::Path::read(input);
if(!dataMaybe) {
Error{} << "Cannot read file" << input;
return 3;
}
data = *std::move(dataMaybe);
}
auto side = Int(std::sqrt(data.size()/pixelSize));
if(data.size() % pixelSize || side*side*pixelSize != data.size()) {
Error{} << "File of size" << data.size() << "is not a tightly-packed square of" << format;
return 5;
}
/* Print image info, if requested */
if(args.isSet("info")) {
Debug{} << "Image 0:" << format << Vector2i{side};
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds";
}
return 0;
}
arrayAppend(images2D, InPlaceInit, format, Vector2i{side}, std::move(data));
/* Otherwise load it using an importer plugin */
} else {
Containers::Pointer<Trade::AbstractImporter> importer = importerManager.loadAndInstantiate(args.value("importer"));
if(!importer) {
Debug{} << "Available importer plugins:" << ", "_s.join(importerManager.aliasList());
return 1;
}
/* Set options, if passed */
if(args.isSet("verbose")) importer->addFlags(Trade::ImporterFlag::Verbose);
Implementation::setOptions(*importer, "AnyImageImporter", args.value("importer-options"));
/* Open the file or map it if requested */
#if defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT))
if(args.isSet("map")) {
arrayAppend(mapped, InPlaceInit);
Trade::Implementation::Duration d{importTime};
Containers::Optional<Containers::Array<const char, Utility::Path::MapDeleter>> mappedMaybe = Utility::Path::mapRead(input);
if(!mappedMaybe || !importer->openMemory(*mappedMaybe)) {
Error() << "Cannot memory-map file" << input;
return 3;
}
mapped.back() = *std::move(mappedMaybe);
} else
#endif
{
Trade::Implementation::Duration d{importTime};
if(!importer->openFile(input)) {
Error{} << "Cannot open file" << input;
return 3;
}
}
/* Print image info, if requested. This is always done for just one
file, checked above. */
if(args.isSet("info")) {
/* Don't fail when there's no image -- we could be asking for
info on a scene file without images, after all */
if(!importer->image1DCount() && !importer->image2DCount() && !importer->image3DCount()) {
Debug{} << "No images found in" << input;
return 0;
}
/* Parse everything first to avoid errors interleaved with
output */
bool error = false;
Containers::Array<Trade::Implementation::ImageInfo> infos =
Trade::Implementation::imageInfo(*importer, error, importTime);
Trade::Implementation::printImageInfo(useColor, infos, nullptr, nullptr, nullptr);
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds";
}
return error ? 1 : 0;
}
/* Bail early if there's no image whatsoever. More detailed errors
with hints are provided for each dimension below. */
if(!importer->image1DCount() && !importer->image2DCount() && !importer->image3DCount()) {
Error{} << "No images found in" << input;
return 1;
}
bool imported = false;
if(dimensions == 1) {
if(!importer->image1DCount()) {
Error{} << "No 1D images found in" << input << Debug::nospace << ". Specify -D2 or -D3 for 2D or 3D image conversion.";
return 1;
}
if(image >= importer->image1DCount()) {
Error{} << "1D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image1DCount() << "1D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image1DLevelCount(image)) {
Error{} << "1D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image1DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image1DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData1D> image1D = importer->image1D(image, minLevel)) {
/* The --layer option is only for 2D/3D, not checking
any bounds here. If the option is present, the
extraction code below will fail. */
arrayAppend(images1D, std::move(*image1D));
imported = true;
}
}
} else if(dimensions == 2) {
if(!importer->image2DCount()) {
Error{} << "No 2D images found in" << input << Debug::nospace << ". Specify -D1 or -D3 for 1D or 3D image conversion.";
return 1;
}
if(image >= importer->image2DCount()) {
Error{} << "2D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image2DCount() << "2D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image2DLevelCount(image)) {
Error{} << "2D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image2DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image2DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData2D> image2D = importer->image2D(image, minLevel)) {
/* Check bounds for the --layer option here, as we
won't have the filename etc. later */
if(!args.value("layer").empty() && args.value<Int>("layer") >= image2D->size().y()) {
Error{} << "2D image" << image << Debug::nospace << ":" << Debug::nospace << minLevel << "in" << input << "doesn't have a layer number" << args.value<Int>("layer") << Debug::nospace << ", only" << image2D->size().y() << "layers";
return 1;
}
arrayAppend(images2D, std::move(*image2D));
imported = true;
}
}
} else if(dimensions == 3) {
if(!importer->image3DCount()) {
Error{} << "No 3D images found in" << input << Debug::nospace << ". Specify -D1 or -D2 for 1D or 2D image conversion.";
return 1;
}
if(image >= importer->image3DCount()) {
Error{} << "3D image number" << image << "not found in" << input << Debug::nospace << ", the file has only" << importer->image3DCount() << "3D images";
return 1;
}
/* Import all levels of the input or just one if specified */
UnsignedInt minLevel, maxLevel;
if(level) {
minLevel = *level;
maxLevel = *level + 1;
if(*level >= importer->image3DLevelCount(image)) {
Error{} << "3D image" << image << "in" << input << "doesn't have a level number" << level << Debug::nospace << ", only" << importer->image3DLevelCount(image) << "levels";
return 1;
}
} else {
minLevel = 0;
maxLevel = importer->image3DLevelCount(image);
if(maxLevel > 1 && (args.isSet("layers") || args.isSet("levels") || (args.arrayValueCount("converter") && args.arrayValue("converter", args.arrayValueCount("converter") - 1) == "raw"))) {
Error{} << "Cannot use --layers / --levels or raw output with multi-level input images. Specify --level N to extract just one level from each.";
return 1;
}
}
for(; minLevel != maxLevel; ++minLevel) {
if(Containers::Optional<Trade::ImageData3D> image3D = importer->image3D(image, minLevel)) {
/* Check bounds for the --layer option here, as we
won't have the filename etc. later */
if(!args.value("layer").empty() && args.value<Int>("layer") >= image3D->size().z()) {
Error{} << "3D image" << image << Debug::nospace << ":" << Debug::nospace << minLevel << "in" << input << "doesn't have a layer number" << args.value<Int>("layer") << Debug::nospace << ", only" << image3D->size().z() << "layers";
return 1;
}
arrayAppend(images3D, std::move(*image3D));
imported = true;
}
}
} else {
Error{} << "Invalid --dimensions option:" << args.value("dimensions");
return 1;
}
if(!imported) {
Error{} << "Cannot import image" << image << Debug::nospace << ":" << Debug::nospace << level << "from" << input;
return 4;
}
}
}
/* Wow, C++, you suck. This implicitly initializes to random shit?! */
std::chrono::high_resolution_clock::duration conversionTime{};
Containers::StringView output;
if(args.isSet("in-place")) {
/* Should have been checked in a graceful way above */
CORRADE_INTERNAL_ASSERT(args.arrayValueCount("input") == 1);
output = args.arrayValue<Containers::StringView>("input", 0);
} else output = args.value<Containers::StringView>("output");
Int outputDimensions;
Containers::Array<Trade::ImageData1D> outputImages1D;
Containers::Array<Trade::ImageData2D> outputImages2D;
Containers::Array<Trade::ImageData3D> outputImages3D;
/* Combine multiple layers into an image of one dimension more */
if(args.isSet("layers")) {
/* To include allocation + copy costs in the output */
Trade::Implementation::Duration d{conversionTime};
if(dimensions == 1) {
if(!checkCommonFormatAndSize(args, images1D)) return 1;
outputDimensions = 2;
if(!images1D.front().isCompressed()) {
/* Allocate a new image */
/** @todo simplify once ImageData is able to allocate on its
own, including correct padding etc */
const Vector2i size{images1D.front().size()[0], Int(images1D.size())};
arrayAppend(outputImages2D, InPlaceInit,
/* Don't want to bother with row padding, it's temporary
anyway */
PixelStorage{}.setAlignment(1),
images1D.front().format(),
size,
Containers::Array<char>{NoInit, size.product()*images1D.front().pixelSize()}
);
/* Copy the pixel data over */
const Containers::StridedArrayView3D<char> outputPixels = outputImages2D.front().mutablePixels();
for(std::size_t i = 0; i != images1D.size(); ++i)
Utility::copy(images1D[i].pixels(), outputPixels[i]);
} else {
Error{} << "The --layers option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 2) {
if(!checkCommonFormatAndSize(args, images2D)) return 1;
outputDimensions = 3;
if(!images2D.front().isCompressed()) {
/* Allocate a new image */
/** @todo simplify once ImageData is able to allocate on its
own, including correct padding etc */
const Vector3i size{images2D.front().size(), Int(images2D.size())};
arrayAppend(outputImages3D, InPlaceInit,
/* Don't want to bother with row padding, it's temporary
anyway */
PixelStorage{}.setAlignment(1),
images2D.front().format(),
size,
Containers::Array<char>{NoInit, size.product()*images2D.front().pixelSize()}
);
/* Copy the pixel data over */
const Containers::StridedArrayView4D<char> outputPixels = outputImages3D.front().mutablePixels();
for(std::size_t i = 0; i != images2D.size(); ++i)
Utility::copy(images2D[i].pixels(), outputPixels[i]);
} else {
Error{} << "The --layers option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 3) {
Error{} << "The --layers option can be only used with 1D and 2D inputs, not 3D";
return 1;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
/* Extracting a layer, inverse of the above */
} else if(!args.value("layer").empty()) {
const Int layer = args.value<Int>("layer");
if(dimensions == 1) {
Error{} << "The --layer option can be only used with 2D and 3D inputs, not 1D";
return 1;
} else if(dimensions == 2) {
outputDimensions = 1;
/* There can be multiple input levels, and a layer should get
extracted from each level, forming a multi-level image again */
if(!checkCommonFormatFlags(args, images2D)) return 1;
if(!images2D.front().isCompressed()) {
for(std::size_t i = 0; i != images2D.size(); ++i) {
/* Diagnostic printed in the import loop above, as here we
don't have the filename etc. anymore */
CORRADE_INTERNAL_ASSERT(layer < images2D[i].size().y());
/* Copy the layer to a newly alllocated image */
/** @todo if the GL-inspired PixelStorage API wasn't CRAP,
we could just reuse the original memory and slice it.
But because Y skip is ignored for 1D images, it just
won't work. Rework once it's in a better shape. */
Trade::ImageData1D copy{PixelStorage{}.setAlignment(1),
images2D[i].format(), images2D[i].formatExtra(),
images2D[i].pixelSize(), images2D[i].size().x(),
Containers::Array<char>{NoInit, std::size_t(images2D[i].size().x()*images2D[i].pixelSize())}};
Utility::copy(images2D[i].pixels()[layer], copy.mutablePixels());
arrayAppend(outputImages1D, std::move(copy));
}
} else {
Error{} << "The --layer option isn't implemented for compressed images yet.";
return 1;
}
} else if(dimensions == 3) {
outputDimensions = 2;
/* There can be multiple input levels, and a layer should get
extracted from each level, forming a multi-level image again */
if(!checkCommonFormatFlags(args, images3D)) return 1;
if(!images3D.front().isCompressed()) {
for(std::size_t i = 0; i != images3D.size(); ++i) {
/* Diagnostic printed in the import loop above, as here we
don't have the filename etc. anymore */
CORRADE_INTERNAL_ASSERT(layer < images3D[i].size().z());
/* Copy the layer to a newly alllocated image */
/** @todo if the GL-inspired PixelStorage API wasn't CRAP,
we could just reuse the original memory and slice it.
But because Y skip is ignored for 1D images, it just
won't work. Rework once it's in a better shape. */
Trade::ImageData2D copy{PixelStorage{}.setAlignment(1),
images3D[i].format(), images3D[i].formatExtra(),
images3D[i].pixelSize(), images3D[i].size().xy(),
Containers::Array<char>{NoInit, std::size_t(images3D[i].size().xy().product()*images3D[i].pixelSize())}};
Utility::copy(images3D[i].pixels()[layer], copy.mutablePixels());
arrayAppend(outputImages2D, std::move(copy));
}
} else {
Error{} << "The --layer option isn't implemented for compressed images yet.";
return 1;
}
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
/* Single-image (potentially multi-level) conversion, verify that all have
the same format and pass the input through. This happens either if
--levels is set or if the (single) input image is multi-level. */
} else {
if(dimensions == 1) {
if(!checkCommonFormatFlags(args, images1D)) return 1;
outputDimensions = 1;
outputImages1D = std::move(images1D);
} else if(dimensions == 2) {
if(!checkCommonFormatFlags(args, images2D)) return 1;
outputDimensions = 2;
outputImages2D = std::move(images2D);
} else if(dimensions == 3) {
if(!checkCommonFormatFlags(args, images3D)) return 1;
outputDimensions = 3;
outputImages3D = std::move(images3D);
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
}
const bool outputIsMultiLevel =
outputImages1D.size() > 1 ||
outputImages2D.size() > 1 ||
outputImages3D.size() > 1;
/* Assume there's always one passed --converter option less, and the last
is implicitly AnyImageConverter. All converters except the last one are
expected to support ConvertMesh and the mesh is "piped" from one to the
other. If the last converter supports ConvertMeshToFile instead of
ConvertMesh, it's used instead of the last implicit AnySceneConverter. */
for(std::size_t i = 0, converterCount = args.arrayValueCount("converter"); i <= converterCount; ++i) {
const Containers::StringView converterName = i == converterCount ?
"AnyImageConverter"_s : args.arrayValue<Containers::StringView>("converter", i);
const bool outputIsCompressed =
(outputDimensions == 1 && outputImages1D.front().isCompressed()) ||
(outputDimensions == 2 && outputImages2D.front().isCompressed()) ||
(outputDimensions == 3 && outputImages3D.front().isCompressed());
/* Load converter plugin if a raw conversion is not requested */
Containers::Pointer<Trade::AbstractImageConverter> converter;
if(converterName != "raw"_s) {
if(!(converter = converterManager.loadAndInstantiate(converterName))) {
Debug{} << "Available converter plugins:" << ", "_s.join(converterManager.aliasList());
return 2;
}
/* Set options, if passed */
if(args.isSet("verbose")) converter->addFlags(Trade::ImageConverterFlag::Verbose);
if(i < args.arrayValueCount("converter-options"))
Implementation::setOptions(*converter, "AnyImageConverter", args.arrayValue("converter-options", i));
}
/* This is the last --converter (a raw output, a file-capable converter
or the implicit AnyImageConverter at the end), output to a file and
exit the loop */
if(i + 1 >= converterCount && (converterName == "raw"_s || (converter->features() & (
Trade::ImageConverterFeature::Convert1DToFile|
Trade::ImageConverterFeature::Convert2DToFile|
Trade::ImageConverterFeature::Convert3DToFile|
Trade::ImageConverterFeature::ConvertCompressed1DToFile|
Trade::ImageConverterFeature::ConvertCompressed2DToFile|
Trade::ImageConverterFeature::ConvertCompressed3DToFile))))
{
/* Decide what converter feature we should look for for given
dimension count. This has to be redone each iteration, as a
converted could have converted an uncompressed image to a
compressed one and vice versa. */
if(converterName != "raw"_s) {
Trade::ImageConverterFeatures expectedFeatures;
if(outputDimensions == 1) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed1DToFile :
Trade::ImageConverterFeature::Convert1DToFile;
} else if(outputDimensions == 2) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed2DToFile :
Trade::ImageConverterFeature::Convert2DToFile;
} else if(outputDimensions == 3) {
expectedFeatures = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed3DToFile :
Trade::ImageConverterFeature::Convert3DToFile;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(outputIsMultiLevel)
expectedFeatures |= Trade::ImageConverterFeature::Levels;
if(!(converter->features() >= expectedFeatures)) {
Error err;
err << converterName << "doesn't support";
if(outputIsMultiLevel)
err << "multi-level";
if(outputIsCompressed)
err << "compressed";
err << outputDimensions << Debug::nospace << "D image to file conversion, only" << converter->features();
return 6;
}
}
if(args.isSet("verbose")) {
Debug d;
if(converterName == "raw")
d << "Writing raw image data of size";
else
d << "Saving output of size";
d << Debug::packed;
if(outputDimensions == 1) {
d << outputImages1D.front().size();
if(outputImages1D.size() > 1)
d << "(and" << outputImages1D.size() - 1 << "more levels)";
} else if(outputDimensions == 2) {
d << outputImages2D.front().size();
if(outputImages2D.size() > 1)
d << "(and" << outputImages2D.size() - 1 << "more levels)";
} else if(outputDimensions == 3) {
d << outputImages3D.front().size();
if(outputImages3D.size() > 1)
d << "(and" << outputImages3D.size() - 1 << "more levels)";
}
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
d << "and" << (outputIsCompressed ? "compressed format" : "format") << Debug::packed;
if(outputDimensions == 1) {
if(outputImages1D.front().isCompressed())
d << outputImages1D.front().compressedFormat();
else d << outputImages1D.front().format();
} else if(outputDimensions == 2) {
if(outputImages2D.front().isCompressed())
d << outputImages2D.front().compressedFormat();
else d << outputImages2D.front().format();
} else if(outputDimensions == 3) {
if(outputImages3D.front().isCompressed())
d << outputImages3D.front().compressedFormat();
else d << outputImages3D.front().format();
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(converterName != "raw")
d << "with" << converterName;
d << Debug::nospace << "...";
}
/* Save raw data, if requested. Only for single-level images as the
data layout would be messed up otherwise. */
if(converterName == "raw") {
Containers::ArrayView<const char> data;
if(outputDimensions == 1) {
CORRADE_INTERNAL_ASSERT(outputImages1D.size() == 1);
data = outputImages1D.front().data();
} else if(outputDimensions == 2) {
CORRADE_INTERNAL_ASSERT(outputImages2D.size() == 1);
data = outputImages2D.front().data();
} else if(outputDimensions == 3) {
CORRADE_INTERNAL_ASSERT(outputImages3D.size() == 1);
data = outputImages3D.front().data();
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
{
Trade::Implementation::Duration d{conversionTime};
if(!Utility::Path::write(output, data)) return 1;
}
/* Convert to a file */
} else {
bool converted;
Trade::Implementation::Duration d{conversionTime};
if(outputDimensions == 1)
converted = convertOneOrMoreImagesToFile(*converter, outputImages1D, output);
else if(outputDimensions == 2)
converted = convertOneOrMoreImagesToFile(*converter, outputImages2D, output);
else if(outputDimensions == 3)
converted = convertOneOrMoreImagesToFile(*converter, outputImages3D, output);
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!converted) {
Error{} << "Cannot save file" << output;
return 5;
}
}
break;
/* This is not the last converter, expect that it's capable of
image-to-image conversion */
} else {
if(converterName == "raw"_s) {
Error{} << "Only the very last --converter can be raw";
return 1;
}
CORRADE_INTERNAL_ASSERT(i < converterCount);
if(converterCount > 1 && args.isSet("verbose"))
Debug{} << "Processing (" << Debug::nospace << (i+1) << Debug::nospace << "/" << Debug::nospace << converterCount << Debug::nospace << ") with" << converterName << Debug::nospace << "...";
/* Decide what converter feature we should look for for given
dimension count. This has to be redone each iteration, as a
converted could have converted an uncompressed image to a
compressed one and vice versa. */
Trade::ImageConverterFeature expectedFeature;
if(outputDimensions == 1) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed1D :
Trade::ImageConverterFeature::Convert1D;
} else if(outputDimensions == 2) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed2D :
Trade::ImageConverterFeature::Convert2D;
} else if(outputDimensions == 3) {
expectedFeature = outputIsCompressed ?
Trade::ImageConverterFeature::ConvertCompressed3D :
Trade::ImageConverterFeature::Convert3D;
} else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!(converter->features() >= expectedFeature)) {
Error err;
err << converterName << "doesn't support";
if(outputIsCompressed)
err << "compressed";
err << outputDimensions << Debug::nospace << "D image conversion, only" << converter->features();
return 6;
}
bool converted;
Trade::Implementation::Duration d{conversionTime};
if(outputDimensions == 1)
converted = convertImages(*converter, outputImages1D);
else if(outputDimensions == 2)
converted = convertImages(*converter, outputImages2D);
else if(outputDimensions == 3)
converted = convertImages(*converter, outputImages3D);
else CORRADE_INTERNAL_ASSERT_UNREACHABLE();
if(!converted) {
Error{} << converterName << "cannot convert the image";
return 5;
}
}
}
if(args.isSet("profile")) {
Debug{} << "Import took" << UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(importTime).count())/1.0e3f << "seconds, conversion"
<< UnsignedInt(std::chrono::duration_cast<std::chrono::milliseconds>(conversionTime).count())/1.0e3f << "seconds";
}
}
| [
"mosra@centrum.cz"
] | mosra@centrum.cz |
1e531ed1be17a8ef274b456b18740fbd76aaab01 | 03303888daff8e46fac3d333a747adb7a3742d2d | /Core/fun.h | 6d1900949b734f46c5cef30f41b7fb05d1a39ae1 | [
"MIT"
] | permissive | pvmoore/cpp-core | 015c6385c3c2c7428f27cf4816edab85788b22d1 | 6dba63f12415fec5fe2e50dd18c52cac07a14d04 | refs/heads/master | 2021-10-19T13:26:10.372074 | 2019-02-21T11:53:42 | 2019-02-21T11:53:42 | 123,930,155 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 467 | h | #pragma once
namespace core {
template<typename COLLECTION, typename LAMBDA>
void forEach(COLLECTION collection, LAMBDA lambda) {
std::for_each(collection.begin(), collection.end(), lambda);
}
/// Transforms elements of same type within the collection.
template <typename COLLECTION, typename LAMBDA>
COLLECTION map(COLLECTION collection, LAMBDA lambda) {
std::transform(collection.begin(), collection.end(), collection.begin(), lambda);
return collection;
}
} | [
"1926576+pvmoore@users.noreply.github.com"
] | 1926576+pvmoore@users.noreply.github.com |
3d774fefd010ea4393a5da76b5add4841b07913b | a8cd091c684b79676841ef4778fbcc27bdefdfa3 | /Walker/Walker.ino | 583ff65b9856453def67501eb98d9e5fad99adcd | [] | no_license | ericgemnay/Robot | dabaaf6370f1b3c99f509eeff0b78627aa396045 | e12a88ced2bcc9a08ec475457a640c287d286a50 | refs/heads/master | 2021-01-02T08:32:37.179615 | 2015-06-27T00:10:46 | 2015-06-27T00:10:46 | 38,139,893 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,439 | ino |
//including libraries
#include <Servo.h>
#include "Legs.h"
//makes the objects for servos
Servo Coxa1;
Servo Femur1;
Servo Tibia1;
Servo Coxa2;
Servo Femur2; //alt
Servo Tibia2; //alt
Servo Coxa3;
Servo Femur3;
Servo Tibia3;
Servo Coxa4;
Servo Femur4; //alt
Servo Tibia4; //alt
//starting angles
/*
int startingposCoxa = 90;
int startingposTibia = 110;
int startingposFemur = 70;
*/
int startingposCoxa = 90;
int startingposTibia = 110;
int startingposFemur = 70;
int startingposCoxaalt = 180-startingposCoxa;
int startingposTibiaalt = 180-startingposTibia;
int startingposFemuralt = 180-startingposFemur;
//Making an object for each leg
//(Servo Tibia, Servo Coxa, Servo Femur, float tibia, float coxa, float femur, float zoffset, float deflength)
OddLeg FrontLeft = OddLeg(Coxa1, Femur1, Tibia1, 5.468, 6.557, 7.681, 8.2, 8.2);
EvenLeg FrontRight = EvenLeg(Coxa2, Femur2, Tibia2, 5.468, 6.557, 7.681, 8, 8.2);
OddLeg BackRight = OddLeg(Coxa3, Femur3, Tibia3, 5.468, 6.557, 7.681, 8, 8.2);
EvenLeg BackLeft = EvenLeg(Coxa4, Femur4, Tibia4, 5.468, 6.557, 7.681, 8, 8.2);
void setup(){
//only needed for troubleshooting, starting a serial connection
//between the board and the computer
Serial.begin(9600);
//Assings servo objects to pins
Coxa1.attach(2);
Femur1.attach(3);
Tibia1.attach(4);
Coxa2.attach(7);
Femur2.attach(6);
Tibia2.attach(5);
Coxa3.attach(10);
Femur3.attach(8);
Tibia3.attach(9);
Coxa4.attach(13);
Femur4.attach(12);
Tibia4.attach(11);
//Sets the servos to starting positions
Coxa1.write(startingposCoxaalt);
Femur1.write(startingposFemur);
Tibia1.write(startingposTibia);
Coxa2.write(startingposCoxa);
Femur2.write(startingposFemuralt);
Tibia2.write(startingposTibiaalt);
Coxa3.write(startingposCoxaalt);
Femur3.write(startingposFemur);
Tibia3.write(startingposTibia);
Coxa4.write(startingposCoxa);
Femur4.write(startingposFemuralt);
Tibia4.write(startingposTibiaalt);
}
//function that makes the stable tripod for gait
//and causes them to drift backwards
//exception is which leg is not in the tripod
//stride is how far they drift back (use 10 for now)
void drift(int exception, int stride){
//the original stride, the variable is changed by the loop
int ostride = stride;
//the number you enter is the leg that moves forward
switch (exception){
case 1:{
//ostride-stride causes the leg to go in the opposite direction.
//Some even legs need to be inverted because of how they were built mechanically
for (;stride > 0; stride -= 0.5){
FrontLeft.swing(stride); //taking a step
FrontRight.drag(ostride-stride);
BackRight.drag(stride);
BackLeft.drag(stride);
}
//plant causes the leg to go to a low z-level (hopefully makes it touch the ground)
FrontLeft.plant();
break;
}
case 2:{
//calls the drag function with a different stride distance everytime in a for loop
//drag function calculates the angles of the three motors on each leg depending on a stride length
//swing does the same thing but in the other direction
//look in Legs.cpp foir more info
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.swing(stride); //taking a step
BackRight.drag(stride);
BackLeft.drag(stride);
}
FrontRight.plant();
break;
}
case 3:{
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.drag(ostride-stride);
BackRight.swing(ostride-stride); //taking a step
BackLeft.drag(stride);
}
BackRight.plant();
break;
}
case 4:{
for (;stride > 0; stride -= 0.5){
FrontLeft.drag(ostride-stride);
FrontRight.drag(ostride-stride);
BackRight.drag(stride);
BackLeft.swing(ostride-stride); //taking a step
}
BackLeft.plant();
break;
}
}
}
//puts all the motors in their starting positions
void reset(){
FrontLeft.reset();
FrontRight.reset();
BackLeft.reset();
BackRight.reset();
delay(500);
}
void loop(){
drift(1, 10);
delay(1000);
reset();
drift(2, 10);
delay(1000);
reset();
drift(3, 10);
delay(1000);
reset();
drift(4, 10);
delay(1000);
reset();
delay(10000);
}
| [
"egemnay@gmail.com"
] | egemnay@gmail.com |
2208c400bd5400c4ae9d38020c1721a8997deeba | d6752ac9f95da0f1bc04e70a258e9976c9ddacef | /trapfunc.cpp | 4fe330f79df5f6d06290596b1f3cc0662530ad2b | [] | no_license | Justice-/MGSmod | a486119d1d998b2adfcbb9b04f2595fdf41e7fd6 | fcc475aabc1dca04041d1c69aa88af01a3d6ad8a | refs/heads/master | 2021-01-21T08:01:35.964087 | 2013-06-09T07:04:36 | 2013-06-09T07:04:36 | 10,578,456 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 22,148 | cpp | #include "game.h"
#include "trap.h"
#include "rng.h"
void trapfunc::bubble(game *g, int x, int y)
{
g->add_msg("You step on some bubblewrap!");
g->sound(x, y, 18, "Pop!");
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::bubble(game *g, monster *z, int x, int y)
{
g->sound(x, y, 18, "Pop!");
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::cot(game *g, monster *z, int x, int y)
{
g->add_msg("The zombie stumbles over the cot");
z->moves -= 100;
}
void trapfunc::beartrap(game *g, int x, int y)
{
g->add_msg("A bear trap closes on your foot!");
g->sound(x, y, 8, "SNAP!");
g->u.hit(g, bp_legs, rng(0, 1), 10, 16);
g->u.add_disease(DI_BEARTRAP, -1, g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_beartrap], g->turn);
}
void trapfuncm::beartrap(game *g, monster *z, int x, int y)
{
g->sound(x, y, 8, "SNAP!");
if (z->hurt(35)) {
g->kill_mon(g->mon_at(x, y));
g->m.add_item(x, y, g->itypes[itm_beartrap], 0);
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(8, 15));
}
g->m.tr_at(x, y) = tr_null;
item beartrap(g->itypes[itm_beartrap], 0);
z->add_item(beartrap);
}
void trapfunc::board(game *g, int x, int y)
{
g->add_msg("You step on a spiked board!");
g->u.hit(g, bp_feet, 0, 0, rng(6, 10));
g->u.hit(g, bp_feet, 1, 0, rng(6, 10));
}
void trapfuncm::board(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("The %s steps on a spiked board!", z->name().c_str());
if (z->hurt(rng(6, 10)))
g->kill_mon(g->mon_at(x, y));
else
z->moves -= 80;
}
void trapfunc::tripwire(game *g, int x, int y)
{
g->add_msg("You trip over a tripwire!");
std::vector<point> valid;
for (int j = x - 1; j <= x + 1; j++) {
for (int k = y - 1; k <= y + 1; k++) {
if (g->is_empty(j, k)) // No monster, NPC, or player, plus valid for movement
valid.push_back(point(j, k));
}
}
if (valid.size() > 0) {
int index = rng(0, valid.size() - 1);
g->u.posx = valid[index].x;
g->u.posy = valid[index].y;
}
g->u.moves -= 150;
if (rng(5, 20) > g->u.dex_cur)
g->u.hurtall(rng(1, 4));
}
void trapfuncm::tripwire(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("The %s trips over a tripwire!", z->name().c_str());
z->stumble(g, false);
if (rng(0, 10) > z->type->sk_dodge && z->hurt(rng(1, 4)))
g->kill_mon(g->mon_at(z->posx, z->posy));
}
void trapfunc::crossbow(game *g, int x, int y)
{
bool add_bolt = true;
g->add_msg("You trigger a crossbow trap!");
if (!one_in(4) && rng(8, 20) > g->u.dodge(g)) {
body_part hit;
switch (rng(1, 10)) {
case 1: hit = bp_feet; break;
case 2:
case 3:
case 4: hit = bp_legs; break;
case 5:
case 6:
case 7:
case 8:
case 9: hit = bp_torso; break;
case 10: hit = bp_head; break;
}
int side = rng(0, 1);
g->add_msg("Your %s is hit!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, rng(20, 30));
add_bolt = !one_in(10);
} else
g->add_msg("You dodge the shot!");
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_crossbow], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
if (add_bolt)
g->m.add_item(x, y, g->itypes[itm_bolt_steel], 0);
}
void trapfuncm::crossbow(game *g, monster *z, int x, int y)
{
int t;
bool add_bolt = true;
bool seen = g->u_see(z, t);
if (!one_in(4)) {
if (seen)
g->add_msg("A bolt shoots out and hits the %s!", z->name().c_str());
if (z->hurt(rng(20, 30)))
g->kill_mon(g->mon_at(x, y));
add_bolt = !one_in(10);
} else if (seen)
g->add_msg("A bolt shoots out, but misses the %s.", z->name().c_str());
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_crossbow], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
if (add_bolt)
g->m.add_item(x, y, g->itypes[itm_bolt_steel], 0);
}
void trapfunc::shotgun(game *g, int x, int y)
{
g->add_msg("You trigger a shotgun trap!");
int shots = (one_in(8) || one_in(20 - g->u.str_max) ? 2 : 1);
if (g->m.tr_at(x, y) == tr_shotgun_1)
shots = 1;
if (rng(5, 50) > g->u.dodge(g)) {
body_part hit;
switch (rng(1, 10)) {
case 1: hit = bp_feet; break;
case 2:
case 3:
case 4: hit = bp_legs; break;
case 5:
case 6:
case 7:
case 8:
case 9: hit = bp_torso; break;
case 10: hit = bp_head; break;
}
int side = rng(0, 1);
g->add_msg("Your %s is hit!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, rng(40 * shots, 60 * shots));
} else
g->add_msg("You dodge the shot!");
if (shots == 2 || g->m.tr_at(x, y) == tr_shotgun_1) {
g->m.add_item(x, y, g->itypes[itm_shotgun_sawn], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
g->m.tr_at(x, y) = tr_null;
} else
g->m.tr_at(x, y) = tr_shotgun_1;
}
void trapfuncm::shotgun(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
int chance;
switch (z->type->size) {
case MS_TINY: chance = 100; break;
case MS_SMALL: chance = 16; break;
case MS_MEDIUM: chance = 12; break;
case MS_LARGE: chance = 8; break;
case MS_HUGE: chance = 2; break;
}
int shots = (one_in(8) || one_in(chance) ? 2 : 1);
if (g->m.tr_at(x, y) == tr_shotgun_1)
shots = 1;
if (seen)
g->add_msg("A shotgun fires and hits the %s!", z->name().c_str());
if (z->hurt(rng(40 * shots, 60 * shots)))
g->kill_mon(g->mon_at(x, y));
if (shots == 2 || g->m.tr_at(x, y) == tr_shotgun_1) {
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_shotgun_sawn], 0);
g->m.add_item(x, y, g->itypes[itm_string_6], 0);
} else
g->m.tr_at(x, y) = tr_shotgun_1;
}
void trapfunc::blade(game *g, int x, int y)
{
g->add_msg("A blade swings out and hacks your torso!");
g->u.hit(g, bp_torso, 0, 12, 30);
}
void trapfuncm::blade(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(z, t))
g->add_msg("A blade swings out and hacks the %s!", z->name().c_str());
int cutdam = 30 - z->armor_cut();
int bashdam = 12 - z->armor_bash();
if (cutdam < 0)
cutdam = 0;
if (bashdam < 0)
bashdam = 0;
if (z->hurt(bashdam + cutdam))
g->kill_mon(g->mon_at(x, y));
}
void trapfunc::snare_light(game *g, int x, int y)
{
g->sound(x, y, 2, "Snap!");
g->add_msg("A snare closes on your leg.");
g->u.add_disease(DI_LIGHTSNARE, rng(10, 20), g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_string_36], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfuncm::snare_light(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
g->sound(x, y, 2, "Snap!");
switch (z->type->size) {
case MS_TINY:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(10)){
g->kill_mon(g->mon_at(x, y));
} else {
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_SMALL:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(100, 150));
break;
case MS_MEDIUM:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(20, 30));
break;
case MS_LARGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
case MS_HUGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
}
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_string_36], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfunc::snare_heavy(game *g, int x, int y)
{
int side = one_in(2) ? 0 : 1;
body_part hit = bp_legs;
g->sound(x, y, 4, "Snap!");
g->add_msg("A snare closes on your %s.", body_part_name(hit, side).c_str());
g->u.hit(g, bp_legs, side, 15, 20);
g->u.add_disease(DI_HEAVYSNARE, rng(20, 30), g);
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_rope_6], 0);
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
}
void trapfuncm::snare_heavy(game *g, monster *z, int x, int y)
{
int t;
bool seen = g->u_see(z, t);
g->sound(x, y, 4, "Snap!");
switch (z->type->size) {
case MS_TINY:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(20)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_SMALL:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(20)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, -1);
}
break;
case MS_MEDIUM:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
if(z->hurt(10)){
g->kill_mon(g->mon_at(x, y));
} else {
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(100, 150));
}
break;
case MS_LARGE:
if(seen){
g->add_msg("The %s has been snared!", z->name().c_str());
}
z->moves = 0;
z->add_effect(ME_BEARTRAP, rng(20, 30));
break;
case MS_HUGE:
if(seen){
g->add_msg("The snare has no effect on the %s!", z->name().c_str());
}
break;
}
g->m.tr_at(x, y) = tr_null;
g->m.add_item(x, y, g->itypes[itm_snare_trigger], 0);
g->m.add_item(x, y, g->itypes[itm_rope_6], 0);
}
void trapfunc::landmine(game *g, int x, int y)
{
g->add_msg("You trigger a landmine!");
g->explosion(x, y, 10, 8, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::landmine(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(x, y, t))
g->add_msg("The %s steps on a landmine!", z->name().c_str());
g->explosion(x, y, 10, 8, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::boobytrap(game *g, int x, int y)
{
g->add_msg("You trigger a boobytrap!");
g->explosion(x, y, 18, 12, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::boobytrap(game *g, monster *z, int x, int y)
{
int t;
if (g->u_see(x, y, t))
g->add_msg("The %s triggers a boobytrap!", z->name().c_str());
g->explosion(x, y, 18, 12, false);
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::telepad(game *g, int x, int y)
{
g->sound(x, y, 6, "vvrrrRRMM*POP!*");
g->add_msg("The air shimmers around you...");
g->teleport();
}
void trapfuncm::telepad(game *g, monster *z, int x, int y)
{
g->sound(x, y, 6, "vvrrrRRMM*POP!*");
int j;
if (g->u_see(z, j))
g->add_msg("The air shimmers around the %s...", z->name().c_str());
int tries = 0;
int newposx, newposy;
do {
newposx = rng(z->posx - SEEX, z->posx + SEEX);
newposy = rng(z->posy - SEEY, z->posy + SEEY);
tries++;
} while (g->m.move_cost(newposx, newposy) == 0 && tries != 10);
if (tries == 10)
g->explode_mon(g->mon_at(z->posx, z->posy));
else {
int mon_hit = g->mon_at(newposx, newposy), t;
if (mon_hit != -1) {
if (g->u_see(z, t))
g->add_msg("The %s teleports into a %s, killing them both!",
z->name().c_str(), g->z[mon_hit].name().c_str());
g->explode_mon(mon_hit);
} else {
z->posx = newposx;
z->posy = newposy;
}
}
}
void trapfunc::goo(game *g, int x, int y)
{
g->add_msg("You step in a puddle of thick goo.");
g->u.infect(DI_SLIMED, bp_feet, 6, 20, g);
if (one_in(3)) {
g->add_msg("The acidic goo eats away at your feet.");
g->u.hit(g, bp_feet, 0, 0, 5);
g->u.hit(g, bp_feet, 1, 0, 5);
}
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::goo(game *g, monster *z, int x, int y)
{
if (z->type->id == mon_blob) {
z->speed += 15;
z->hp = z->speed;
} else {
z->poly(g->mtypes[mon_blob]);
z->speed -= 15;
z->hp = z->speed;
}
g->m.tr_at(x, y) = tr_null;
}
void trapfunc::dissector(game *g, int x, int y)
{
g->add_msg("Electrical beams emit from the floor and slice your flesh!");
g->sound(x, y, 10, "BRZZZAP!");
g->u.hit(g, bp_head, 0, 0, 15);
g->u.hit(g, bp_torso, 0, 0, 20);
g->u.hit(g, bp_arms, 0, 0, 12);
g->u.hit(g, bp_arms, 1, 0, 12);
g->u.hit(g, bp_hands, 0, 0, 10);
g->u.hit(g, bp_hands, 1, 0, 10);
g->u.hit(g, bp_legs, 0, 0, 12);
g->u.hit(g, bp_legs, 1, 0, 12);
g->u.hit(g, bp_feet, 0, 0, 10);
g->u.hit(g, bp_feet, 1, 0, 10);
}
void trapfuncm::dissector(game *g, monster *z, int x, int y)
{
g->sound(x, y, 10, "BRZZZAP!");
if (z->hurt(60))
g->explode_mon(g->mon_at(x, y));
}
void trapfunc::pit(game *g, int x, int y)
{
g->add_msg("You fall in a pit!");
if (g->u.has_trait(PF_WINGS_BIRD))
g->add_msg("You flap your wings and flutter down gracefully.");
else {
int dodge = g->u.dodge(g);
int damage = rng(10, 20) - rng(dodge, dodge * 5);
if (damage > 0) {
g->add_msg("You hurt yourself!");
g->u.hurtall(rng(int(damage / 2), damage));
g->u.hit(g, bp_legs, 0, damage, 0);
g->u.hit(g, bp_legs, 1, damage, 0);
} else
g->add_msg("You land nimbly.");
}
g->u.add_disease(DI_IN_PIT, -1, g);
}
void trapfuncm::pit(game *g, monster *z, int x, int y)
{
int junk;
if (g->u_see(x, y, junk))
g->add_msg("The %s falls in a pit!", z->name().c_str());
if (z->hurt(rng(10, 20)))
g->kill_mon(g->mon_at(x, y));
else
z->moves = -1000;
}
void trapfunc::pit_spikes(game *g, int x, int y)
{
g->add_msg("You fall in a pit!");
int dodge = g->u.dodge(g);
int damage = rng(20, 50);
if (g->u.has_trait(PF_WINGS_BIRD))
g->add_msg("You flap your wings and flutter down gracefully.");
else if (rng(5, 30) < dodge)
g->add_msg("You avoid the spikes within.");
else {
body_part hit;
switch (rng(1, 10)) {
case 1:
case 2: hit = bp_legs; break;
case 3:
case 4: hit = bp_arms; break;
case 5:
case 6:
case 7:
case 8:
case 9:
case 10: hit = bp_torso; break;
}
int side = rng(0, 1);
g->add_msg("The spikes impale your %s!", body_part_name(hit, side).c_str());
g->u.hit(g, hit, side, 0, damage);
if (one_in(4)) {
g->add_msg("The spears break!");
g->m.ter(x, y) = t_pit;
g->m.tr_at(x, y) = tr_pit;
for (int i = 0; i < 4; i++) { // 4 spears to a pit
if (one_in(3))
g->m.add_item(x, y, g->itypes[itm_spear_wood], g->turn);
}
}
}
g->u.add_disease(DI_IN_PIT, -1, g);
}
void trapfuncm::pit_spikes(game *g, monster *z, int x, int y)
{
int junk;
bool sees = g->u_see(z, junk);
if (sees)
g->add_msg("The %s falls in a spiked pit!", z->name().c_str());
if (z->hurt(rng(20, 50)))
g->kill_mon(g->mon_at(x, y));
else
z->moves = -1000;
if (one_in(4)) {
if (sees)
g->add_msg("The spears break!");
g->m.ter(x, y) = t_pit;
g->m.tr_at(x, y) = tr_pit;
for (int i = 0; i < 4; i++) { // 4 spears to a pit
if (one_in(3))
g->m.add_item(x, y, g->itypes[itm_spear_wood], g->turn);
}
}
}
void trapfunc::lava(game *g, int x, int y)
{
g->add_msg("The %s burns you horribly!", g->m.tername(x, y).c_str());
g->u.hit(g, bp_feet, 0, 0, 20);
g->u.hit(g, bp_feet, 1, 0, 20);
g->u.hit(g, bp_legs, 0, 0, 20);
g->u.hit(g, bp_legs, 1, 0, 20);
}
void trapfuncm::lava(game *g, monster *z, int x, int y)
{
int junk;
bool sees = g->u_see(z, junk);
if (sees)
g->add_msg("The %s burns the %s!", g->m.tername(x, y).c_str(),
z->name().c_str());
int dam = 30;
if (z->made_of(FLESH))
dam = 50;
if (z->made_of(VEGGY))
dam = 80;
if (z->made_of(PAPER) || z->made_of(LIQUID) || z->made_of(POWDER) ||
z->made_of(WOOD) || z->made_of(COTTON) || z->made_of(WOOL))
dam = 200;
if (z->made_of(STONE))
dam = 15;
if (z->made_of(KEVLAR) || z->made_of(STEEL))
dam = 5;
z->hurt(dam);
}
void trapfunc::sinkhole(game *g, int x, int y)
{
g->add_msg("You step into a sinkhole, and start to sink down!");
if (g->u.has_amount(itm_rope_30, 1) &&
query_yn("Throw your rope to try to catch soemthing?")) {
int throwroll = rng(g->u.skillLevel("throw"),
g->u.skillLevel("throw") + g->u.str_cur + g->u.dex_cur);
if (throwroll >= 12) {
g->add_msg("The rope catches something!");
if (rng(g->u.skillLevel("unarmed"),
g->u.skillLevel("unarmed") + g->u.str_cur) > 6) {
// Determine safe places for the character to get pulled to
std::vector<point> safe;
for (int i = g->u.posx - 1; i <= g->u.posx + 1; i++) {
for (int j = g->u.posx - 1; j <= g->u.posx + 1; j++) {
if (g->m.move_cost(i, j) > 0 && g->m.tr_at(i, j) != tr_pit)
safe.push_back(point(i, j));
}
}
if (safe.size() == 0) {
g->add_msg("There's nowhere to pull yourself to, and you sink!");
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
g->vertical_move(-1, true);
} else {
g->add_msg("You pull yourself to safety! The sinkhole collapses.");
int index = rng(0, safe.size() - 1);
g->u.posx = safe[index].x;
g->u.posy = safe[index].y;
g->update_map(g->u.posx, g->u.posy);
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
}
} else {
g->add_msg("You're not strong enough to pull yourself out...");
g->u.moves -= 100;
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
g->vertical_move(-1, true);
}
} else {
g->add_msg("Your throw misses completely, and you sink!");
if (one_in((g->u.str_cur + g->u.dex_cur) / 3)) {
g->u.use_amount(itm_rope_30, 1);
g->m.add_item(g->u.posx + rng(-1, 1), g->u.posy + rng(-1, 1),
g->itypes[itm_rope_30], g->turn);
}
g->m.tr_at(g->u.posx, g->u.posy) = tr_pit;
g->vertical_move(-1, true);
}
} else {
g->add_msg("You sink into the sinkhole!");
g->vertical_move(-1, true);
}
}
void trapfunc::ledge(game *g, int x, int y)
{
g->add_msg("You fall down a level!");
g->vertical_move(-1, true);
}
void trapfunc::airhole(game *g, int x, int y)
{
g->add_msg("You fall down a level!");
g->vertical_move(-1, true);
}
void trapfuncm::ledge(game *g, monster *z, int x, int y)
{
g->add_msg("The %s falls down a level!", z->name().c_str());
g->kill_mon(g->mon_at(x, y));
}
void trapfuncm::airhole(game *g, monster *z, int x, int y)
{
g->add_msg("The %s falls down a level!", z->name().c_str());
g->kill_mon(g->mon_at(x, y));
}
void trapfunc::temple_flood(game *g, int x, int y)
{
g->add_msg("You step on a loose tile, and water starts to flood the room!");
for (int i = 0; i < SEEX * MAPSIZE; i++) {
for (int j = 0; j < SEEY * MAPSIZE; j++) {
if (g->m.tr_at(i, j) == tr_temple_flood)
g->m.tr_at(i, j) = tr_null;
}
}
g->add_event(EVENT_TEMPLE_FLOOD, g->turn + 3);
}
void trapfunc::temple_toggle(game *g, int x, int y)
{
g->add_msg("You hear the grinding of shifting rock.");
ter_id type = g->m.ter(x, y);
for (int i = 0; i < SEEX * MAPSIZE; i++) {
for (int j = 0; j < SEEY * MAPSIZE; j++) {
switch (type) {
case t_floor_red:
if (g->m.ter(i, j) == t_rock_green)
g->m.ter(i, j) = t_floor_green;
else if (g->m.ter(i, j) == t_floor_green)
g->m.ter(i, j) = t_rock_green;
break;
case t_floor_green:
if (g->m.ter(i, j) == t_rock_blue)
g->m.ter(i, j) = t_floor_blue;
else if (g->m.ter(i, j) == t_floor_blue)
g->m.ter(i, j) = t_rock_blue;
break;
case t_floor_blue:
if (g->m.ter(i, j) == t_rock_red)
g->m.ter(i, j) = t_floor_red;
else if (g->m.ter(i, j) == t_floor_red)
g->m.ter(i, j) = t_rock_red;
break;
}
}
}
}
void trapfunc::glow(game *g, int x, int y)
{
if (one_in(3)) {
g->add_msg("You're bathed in radiation!");
g->u.radiation += rng(10, 30);
} else if (one_in(4)) {
g->add_msg("A blinding flash strikes you!");
g->flashbang(g->u.posx, g->u.posy);
} else
g->add_msg("Small flashes surround you.");
}
void trapfuncm::glow(game *g, monster *z, int x, int y)
{
if (one_in(3)) {
z->hurt( rng(5, 10) );
z->speed *= .9;
}
}
void trapfunc::hum(game *g, int x, int y)
{
int volume = rng(1, 200);
std::string sfx;
if (volume <= 10)
sfx = "hrm";
else if (volume <= 50)
sfx = "hrmmm";
else if (volume <= 100)
sfx = "HRMMM";
else
sfx = "VRMMMMMM";
g->sound(x, y, volume, sfx);
}
void trapfuncm::hum(game *g, monster *z, int x, int y)
{
int volume = rng(1, 200);
std::string sfx;
if (volume <= 10)
sfx = "hrm";
else if (volume <= 50)
sfx = "hrmmm";
else if (volume <= 100)
sfx = "HRMMM";
else
sfx = "VRMMMMMM";
if (volume >= 150)
z->add_effect(ME_DEAF, volume - 140);
g->sound(x, y, volume, sfx);
}
void trapfunc::shadow(game *g, int x, int y)
{
monster spawned(g->mtypes[mon_shadow]);
int tries = 0, monx, mony, junk;
do {
if (one_in(2)) {
monx = rng(g->u.posx - 5, g->u.posx + 5);
mony = (one_in(2) ? g->u.posy - 5 : g->u.posy + 5);
} else {
monx = (one_in(2) ? g->u.posx - 5 : g->u.posx + 5);
mony = rng(g->u.posy - 5, g->u.posy + 5);
}
} while (tries < 5 && !g->is_empty(monx, mony) &&
!g->m.sees(monx, mony, g->u.posx, g->u.posy, 10, junk));
if (tries < 5) {
g->add_msg("A shadow forms nearby.");
spawned.sp_timeout = rng(2, 10);
spawned.spawn(monx, mony);
g->z.push_back(spawned);
g->m.tr_at(x, y) = tr_null;
}
}
void trapfunc::drain(game *g, int x, int y)
{
g->add_msg("You feel your life force sapping away.");
g->u.hurtall(1);
}
void trapfuncm::drain(game *g, monster *z, int x, int y)
{
z->hurt(1);
}
void trapfunc::snake(game *g, int x, int y)
{
if (one_in(3)) {
monster spawned(g->mtypes[mon_shadow_snake]);
int tries = 0, monx, mony, junk;
do {
if (one_in(2)) {
monx = rng(g->u.posx - 5, g->u.posx + 5);
mony = (one_in(2) ? g->u.posy - 5 : g->u.posy + 5);
} else {
monx = (one_in(2) ? g->u.posx - 5 : g->u.posx + 5);
mony = rng(g->u.posy - 5, g->u.posy + 5);
}
} while (tries < 5 && !g->is_empty(monx, mony) &&
!g->m.sees(monx, mony, g->u.posx, g->u.posy, 10, junk));
if (tries < 5) {
g->add_msg("A shadowy snake forms nearby.");
spawned.spawn(monx, mony);
g->z.push_back(spawned);
g->m.tr_at(x, y) = tr_null;
return;
}
}
g->sound(x, y, 10, "ssssssss");
if (one_in(6))
g->m.tr_at(x, y) = tr_null;
}
void trapfuncm::snake(game *g, monster *z, int x, int y)
{
g->sound(x, y, 10, "ssssssss");
if (one_in(6))
g->m.tr_at(x, y) = tr_null;
}
bool trap::is_benign()
{
if (id == tr_rollmat || id == tr_cot)
return true;
else
return false;
}
| [
"codepublic@charter.net"
] | codepublic@charter.net |
9f794de3c23a5ccd76aa5e785aa032e3d73841c7 | 617296ef3936724a88be5a2e6023aa363cb93d1d | /backup/新建文件夹/word.cpp | 59b50bfb2c9eab3a55a95ca380251f05d2793291 | [] | no_license | Melos17/Lex | d2fc204fb383a9677c72cd380e410f4adc2c0a9a | 89f1e63ddee89063373cdf10744a170b57ea63a9 | refs/heads/master | 2023-01-06T03:21:10.782944 | 2020-11-03T11:51:01 | 2020-11-03T11:51:01 | 309,675,249 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,115 | cpp | #include "word.h"
enum TOKEN_TYPE {
Unknown = -1,
Parenthese_Left = '(', Parenthese_Right = ')',
Bracket_Left = '[', Bracket_Right = ']',
Star = '*',
Plus = '+',
Question = '?',
VerticalLine = '|',
Dot = '.',
Hyphen = '-',
Caret = '^',
Normal_Character = 128,
Escape_Character,
// no support currently.
Brace_Left, Brace_Right, // {}
Dollar, // $
Comma, // ,
Number, // 0-9
};
int RegexWord::runRelativeCode(int type) {
switch( type ) {
case 0:
{ return(Parenthese_Left); }
break;
case 1:
{ return(Parenthese_Right); }
break;
case 2:
{ return(Bracket_Left); }
break;
case 3:
{ return(Bracket_Right); }
break;
case 4:
{ return(Star); }
break;
case 5:
{ return(Plus); }
break;
case 6:
{ return(Question); }
break;
case 7:
{ return(VerticalLine); }
break;
case 8:
{ return(Dot); }
break;
case 9:
{ return(Hyphen); }
break;
case 10:
{ return(Caret); }
break;
case 11:
{ return(Normal_Character); }
break;
case 12:
{ return(Escape_Character); }
break;
}
return -1;
}
| [
"melos17@qq.com"
] | melos17@qq.com |
5b02a691bbd1bcc8d62c2854283ca13dba56fe5e | 63a1e65a9c66c0de59673ddd6e54367da2da12a3 | /字节跳动/5. 最长回文子串.cpp | c4ed290c68eb9b0954403021007d0f86fb23d77f | [] | no_license | Maserhe/Algorithm_practise | 58df28ce1e6ab7bd10943c022264662c2a7bbf19 | f06dc4395e1089b5d3076e3c463b59d1483f324a | refs/heads/master | 2023-03-22T10:14:27.381659 | 2021-03-15T14:44:43 | 2021-03-15T14:44:43 | 230,616,496 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 671 | cpp | class Solution {
public:
int getStr(int l, int r, string& s) {
while (l >= 0 && r < s.size() && s[l] == s[r]) {
l -- ;
r ++ ;
}
return r - l - 1;
}
string longestPalindrome(string s) {
int max = 0, start = 0;
for (int i = 0; i < s.size(); i ++ ) {
int curMax = std::max(getStr(i, i, s), getStr(i, i + 1, s));
if (curMax > max) {
max = curMax;
start = i - ((curMax - 1) / 2);
}
}
string ans;
for (int i = 0; i < max; i ++ ) ans += s[start + i];
return ans;
}
}; | [
"982289931@qq.com"
] | 982289931@qq.com |
7e7252a91c740f5331c75770749578c5432d499c | f622e20ed72dcc6a11b6de365dc7f62d34af4995 | /TP.h | c13b1947c144c082d55a5cbb64e523cf716edc0e | [] | no_license | MarcosRolando/tp2taller | d637ac425127d14cf0518eb896c11de181f323ee | b7bdf6e9113d5f0f3917d2a817aaf7e8ffac43f6 | refs/heads/master | 2022-07-13T01:35:36.088076 | 2020-05-13T13:57:36 | 2020-05-13T13:57:36 | 262,163,479 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | h | //
// Created by marcos on 12/5/20.
//
#ifndef TP2TALLER_TP_H
#define TP2TALLER_TP_H
#include "King.h"
#include "FileException.h"
class TP {
public:
static int run(int argc, char** argv);
private:
static bool _validInput(int argc);
};
#endif //TP2TALLER_TP_H
| [
"marcosrolando.mr@gmail.com"
] | marcosrolando.mr@gmail.com |
e7f2363bcc2c2146d2426d119017f54bddb31722 | 5c6d2151717fcca45406321895b59505a681f25e | /examples/cli_single.cpp | 54dcde55d346bcaff5d9bd5a2720fbcf03c533ce | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | DonRazor2/libsolace | fd29266a166b8249578e7368638c6bf9305795cd | d7501d2e83b30064a0aa938e03509b4822b3b2b0 | refs/heads/master | 2020-03-23T10:01:16.064131 | 2018-07-16T14:50:32 | 2018-07-16T14:50:32 | 141,421,486 | 0 | 0 | null | 2018-07-18T10:47:33 | 2018-07-18T10:47:33 | null | UTF-8 | C++ | false | false | 1,690 | cpp | /*
* Copyright 2016 Ivan Ryabov
*
* 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.
*/
/**
* An example of command line argument parser for a single action CLI.
*/
#include <solace/cli/parser.hpp>
#include <iostream>
using namespace Solace;
static constexpr StringLiteral kAppName = "cli_single";
static const Version kAppVersion = Version(0, 0, 1, "dev");
int main(int argc, const char **argv) {
int intValue = 0;
float32 floatValue = 0.0f;
StringView userName(getenv("USER"));
const auto res = cli::Parser("Solace cli single action example", {
cli::Parser::printHelp(),
cli::Parser::printVersion(kAppName, kAppVersion),
{{"i", "intOption"}, "Some useless parameter for the demo", &intValue},
{{"fOption"}, "Foating point value for the demo", &floatValue},
{{"u", "name"}, "Greet user name", &userName}
})
.parse(argc, argv);
if (res) {
std::cout << "Hello '" << userName << "'" << std::endl;
return EXIT_SUCCESS;
} else {
std::cerr << res.getError().toString();
return EXIT_FAILURE;
}
}
| [
"abbyssoul@gmail.com"
] | abbyssoul@gmail.com |
b0f1b2bd9dff725c9e5f2d0e38b76742874b32b1 | 827405b8f9a56632db9f78ea6709efb137738b9d | /CodingWebsites/WHU_OJ/Volume1/P1050.cpp | b04b93db762767ad04efb30d1c828beb9f77f6cd | [] | no_license | MingzhenY/code-warehouse | 2ae037a671f952201cf9ca13992e58718d11a704 | d87f0baa6529f76e41a448b8056e1f7ca0ab3fe7 | refs/heads/master | 2020-03-17T14:59:30.425939 | 2019-02-10T17:12:36 | 2019-02-10T17:12:36 | 133,694,119 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,147 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
int D[100][100];
int F[100];
void Init(int n){for(int i=0;i<n;++i) F[i]=i;}
int Find(int x){return x==F[x]?x:Find(F[x]);}
struct Arc{
int from,to,dist;
Arc(){}
Arc(int from,int to,int dist):from(from),to(to),dist(dist){}
bool operator < (const Arc &B)const{return dist < B.dist;}
}Arcs[10000];
int main(){
freopen("P1050.txt","r",stdin);
int t,n;
scanf("%d",&t);
while(t-->0){
scanf("%d",&n);
for(int i=0;i<n;++i){
for(int j=0;j<n;++j){
scanf("%d",&D[i][j]);
}
}
Init(n);
int An = 0,Dist = 0;
for(int i=0;i<n;++i){
for(int j=i+1;j<n;++j){
Arcs[An++] = Arc(i,j,D[i][j]);
}
}
sort(Arcs,Arcs+An);
for(int i=0;i<An;++i){
int Fa=Find(Arcs[i].from),Fb=Find(Arcs[i].to);
if(Fa!=Fb){
F[Fa]=Fb;
Dist += Arcs[i].dist;
}
}
printf("%d\n",Dist);
}
return 0;
}
| [
"mingzhenyan@yahoo.com"
] | mingzhenyan@yahoo.com |
73d390b2855ecd39f3140f85c2e73c56bb4f384f | 454c964ab7dd6a8258632bdf3ab9e6eeafd71872 | /source/TouchButton.cpp | ab08450c01cb0382783b1ec88953488c72b749f6 | [] | no_license | fizzyfrosty/FuzzyCubesUniversalHD | bebc023769173a5debd6299acd733f6477d355bf | 1d8b95f6687be5b9fad1b8cc0941ebcbca2818d6 | refs/heads/master | 2020-05-29T14:32:12.210893 | 2014-04-04T02:18:40 | 2014-04-04T02:18:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,305 | cpp | #include "TouchButton.h"
TouchButton::TouchButton(void)
{
pressed = false;
initialPressed = false;
enabled = true;
x = 0;
y = 0;
}
TouchButton::~TouchButton(void)
{
}
bool TouchButton::isPressed( int16 x, int16 y )
{
if( enabled == true )
{
// sets the hitbox for the button, determines if it's pressed
if( x > this->x - hitboxWidth/2 && x < this->x + hitboxWidth/2 && y > this->y - hitboxHeight/2 && y < this->y + hitboxHeight/2 )
return true;
else
return false;
}
else
{
return false; // set as not touched if false
}
}
void TouchButton::Render()
{
if( enabled == true ) // only render if the button is enabled
{
if( pressed == false )
{
unpressedSprite.setPosition( x, y );
unpressedSprite.Render();
}
else if( pressed == true )
{
pressedSprite.setPosition( x, y );
pressedSprite.Render();
}
}
}
void TouchButton::setLocation( int16 x, int16 y )
{
this->x = x;
this->y = y;
}
void TouchButton::setTouchSize( int16 w, int16 h )
{
hitboxWidth = w;
hitboxHeight = h;
}
void TouchButton::setRenderSize( int16 w, int16 h )
{
pressedSprite.setSize( w, h );
unpressedSprite.setSize( w, h );
}
void TouchButton::setUnpressedSprite( Sprite s )
{
unpressedSprite = s;
}
void TouchButton::setPressedSprite( Sprite s )
{
pressedSprite = s;
} | [
"fizzyfrosty@yahoo.com"
] | fizzyfrosty@yahoo.com |
0ea10fbfc307cc922163b390ac51401eee098b88 | 5565952688dd8a0619c71bfe4fdf36b333fb94de | /server/Main.cpp | 8a7bed0e0d45e2783db9d42504dafc88c77f7b73 | [] | no_license | huykaiba/YgoProServer | 131b89d2e35e2c2eba606788475e69725ad144f8 | 3ff281f2285bafb7662dc5942bd02838966dea62 | refs/heads/master | 2021-03-27T12:18:16.884009 | 2016-07-16T04:50:50 | 2016-07-16T04:50:50 | 63,411,406 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 476 | cpp | #include "Config.h"
#include <string>
#include "GameserversManager.h"
using namespace ygo;
using namespace std;
volatile bool needReboot = false;
volatile bool isFather = true;
int sfd; //server fd
int main(int argc, char**argv)
{
Config* config = Config::getInstance();
if(config->parseCommandLine(argc,argv))
return EXIT_SUCCESS;
config->LoadConfig();
GameserversManager gsm;
gsm.StartServer(config->serverport);
return 0;
}
| [
"huykaiba@gmail.com"
] | huykaiba@gmail.com |
e206cf05236021f2c5e9eaca259134ecc1e7a4be | 58a0ba5ee99ec7a0bba36748ba96a557eb798023 | /Olympiad Solutions/SPOJ/CNTPRIME.cpp | 13a2af59f950396eff9ceb9c2813c86af182aca2 | [
"MIT"
] | permissive | adityanjr/code-DS-ALGO | 5bdd503fb5f70d459c8e9b8e58690f9da159dd53 | 1c104c33d2f56fe671d586b702528a559925f875 | refs/heads/master | 2022-10-22T21:22:09.640237 | 2022-10-18T15:38:46 | 2022-10-18T15:38:46 | 217,567,198 | 40 | 54 | MIT | 2022-10-18T15:38:47 | 2019-10-25T15:50:28 | C++ | UTF-8 | C++ | false | false | 2,164 | cpp | // Ivan Carvalho
// Solution to https://www.spoj.com/problems/CNTPRIME/
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int MAXN = 1e4 + 1;
const int MAXP = 1e6 + 1;
const int MAXS = 1e3 + 1;
int arvore[4*MAXN],lazy[4*MAXN],vetor[MAXN],n,m,TC;
int crivo[MAXP];
void build(int pos,int left,int right){
lazy[pos] = -1;
if(left == right){
arvore[pos] = !crivo[vetor[left]];
return;
}
int mid = (left+right)/2;
build(2*pos,left,mid);
build(2*pos+1,mid+1,right);
arvore[pos] = arvore[2*pos] + arvore[2*pos+1];
}
void update(int pos,int left,int right,int i,int j,int val){
if(lazy[pos] != -1){
arvore[pos] = (right - left + 1)*lazy[pos];
if(left != right){
lazy[2*pos] = lazy[pos];
lazy[2*pos+1] = lazy[pos];
}
lazy[pos] = -1;
}
if(left > right || left > j || right < i) return;
if(left >= i && right <= j){
arvore[pos] = (right - left + 1)*val;
if(left != right){
lazy[2*pos] = val;
lazy[2*pos+1] = val;
}
return;
}
int mid = (left+right)/2;
update(2*pos,left,mid,i,j,val);
update(2*pos+1,mid+1,right,i,j,val);
arvore[pos] = arvore[2*pos] + arvore[2*pos+1];
}
int query(int pos,int left,int right,int i,int j){
if(lazy[pos] != -1){
arvore[pos] = (right - left + 1)*lazy[pos];
if(left != right){
lazy[2*pos] = lazy[pos];
lazy[2*pos+1] = lazy[pos];
}
lazy[pos] = -1;
}
if(left > right || left > j || right < i) return 0;
if(left >= i && right <= j){
return arvore[pos];
}
int mid = (left+right)/2;
return query(2*pos,left,mid,i,j) + query(2*pos+1,mid+1,right,i,j);
}
int main(){
crivo[0] = crivo[1] = 1;
for(int i=2;i<MAXP;i++){
if(!crivo[i]){
if(i > MAXS) continue;
for(int j = i*i;j<MAXP;j += i){
crivo[j] = 1;
}
}
}
scanf("%d",&TC);
for(int tc=1;tc<=TC;tc++){
printf("Case %d:\n",tc);
scanf("%d %d",&n,&m);
for(int i=1;i<=n;i++){
scanf("%d",&vetor[i]);
}
build(1,1,n);
while(m--){
int op;
scanf("%d",&op);
if(op == 0){
int x,y,v;
scanf("%d %d %d",&x,&y,&v);
update(1,1,n,x,y,!crivo[v]);
}
else{
int x,y;
scanf("%d %d",&x,&y);
printf("%d\n",query(1,1,n,x,y));
}
}
}
return 0;
} | [
"samant04aditya@gmail.com"
] | samant04aditya@gmail.com |
945cc14ae145165a5fbfbefcf79808b84a99ddca | 38a724327679ba89a9a5383b79523476264c69b2 | /3 term/mipt-concurrency-course/task4/striped_hash_set/striped_hash_set.cpp | a5d64e9a87847b36b4e9f43e54555907314cd4dd | [] | no_license | alexeyqu/mipt-alexeyqu | 3f0af5534a142082d8f9b10b36bbc9ae82daf6fe | 1059b0e9a95855a95d0bc6c7da564799dfc7c449 | refs/heads/master | 2021-01-21T04:39:39.719665 | 2017-10-11T16:28:20 | 2017-10-11T16:28:20 | 51,085,003 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 589 | cpp | #include "striped_hash_set.h"
#include <thread>
const int MAX_TEST = 50000;
int main()
{
std::cin.get();
striped_hash_set<int, std::hash<int>> my_hash_set(1);
std::thread([&my_hash_set]()
{
for (int i = 0; i < MAX_TEST; ++i)
{
std::cerr << i << std::endl;
my_hash_set.contains(i);
my_hash_set.add(i);
if(!my_hash_set.contains(i)) throw;
my_hash_set.remove(i);
if(my_hash_set.contains(i)) throw;
my_hash_set.add(i);
if(!my_hash_set.contains(i)) throw;
}
}
).join();
return 0;
}
| [
"alexeyqu@gmail.com"
] | alexeyqu@gmail.com |
a5b9510b4de68fd3c47d873b87711b0b58882282 | 2c22ee6d774b40d147263ed3891f2dcf700ff9bd | /Type.cpp | 17e9664a25a54a991a7f8780af606f3206a1edfd | [] | no_license | dogilla/CompiladoresC | 9fbfa2a0bc643d06bdff361672e79ea9e611d403 | e8d6ea804a62fc4ed50a665a57aee54cc5383c97 | refs/heads/main | 2023-07-09T16:23:12.277225 | 2021-08-16T21:55:27 | 2021-08-16T21:55:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 963 | cpp | #include "Type.h"
#include "Table.h"
C0::Type::Type(){
}
C0::Type::Type(string name, int baseType, int numItems, int tam){
this->name = name;
this->baseType =baseType;
this->numItems = numItems;
this->tamBytes = tam;
}
C0::Type::Type(string name, int bytes){
this->name = name;
this->tamBytes = bytes;
}
C0::Type::~Type(){
}
int C0::Type::getBaseType(){
return baseType;
}
int C0::Type::getNumItems(){
return numItems;
}
int C0::Type::getTamBytes(){
return tamBytes;
}
string C0::Type::getName(){
return name;
}
// TODO(4) Programar la función setBase que recibe a base:*Table
void C0::Type::setBase(C0::Table* base){
this->base = base;
}
// TODO(5) Programar la función getBase que retorna a base
C0::Table* C0::Type::getBase(){
return base;
}
string C0::Type::toString(){
string cadena = name+" "+to_string(numItems)+" "+to_string(tamBytes)+" "+to_string(baseType)+"\n";
return cadena;
}
| [
"ferbpp@ciencias.unam.mx"
] | ferbpp@ciencias.unam.mx |
908e2a75ce7a78d04b275b5372592b592f326cdb | 55cd0ea9846924b0abd1d6ae6c5d0889b2689fdb | /cny70/cny-test/cny-test.ino | 96933288d8996f70fac33754a50bf36cd678c869 | [] | no_license | rezacode01/CPS-Real-time-Embedded-Systems | 68cbaa429728f0e6b6133186e7324f1e209e52c1 | cac43967723c6b781d7f22aa3266c6eee8aa7340 | refs/heads/master | 2020-03-18T15:25:27.410866 | 2018-06-10T12:11:56 | 2018-06-10T12:11:56 | 134,906,644 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 272 | ino | int a = -1;
void setup() {
// put your setup code here, to run once:
pinMode(2, INPUT);
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
a = digitalRead(2);
Serial.print("input is");
Serial.println(a);
delay(500);
}
| [
"rezacode01@gmail.com"
] | rezacode01@gmail.com |
0838ee9d06acf6b82889badd386b9ca10346c4bd | 6d5db68fe2e912f7f18dfddcf73955a042f32475 | /project1-1403225/codebase/rbf/rbftest8b.cc | 04d508a8001ffab144b5a8fa27d6549f1984b943 | [] | no_license | DanielThurau/Database-System-II | 9d33341d37f71324bd63b29571a1b53e12346af1 | 42ab3c9d84cc100a7606d099924dcfb9c32bb8dc | refs/heads/master | 2020-03-09T21:07:59.720033 | 2018-06-12T18:44:10 | 2018-06-12T18:44:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,621 | cc | #include <iostream>
#include <string>
#include <cassert>
#include <sys/stat.h>
#include <stdlib.h>
#include <string.h>
#include <stdexcept>
#include <stdio.h>
#include "pfm.h"
#include "rbfm.h"
#include "test_util.h"
using namespace std;
int RBFTest_8b(RecordBasedFileManager *rbfm) {
// Functions tested
// 1. Create Record-Based File
// 2. Open Record-Based File
// 3. Insert Record - NULL
// 4. Read Record
// 5. Close Record-Based File
// 6. Destroy Record-Based File
cout << endl << "***** In RBF Test Case 8b *****" << endl;
RC rc;
string fileName = "test8b";
// Create a file named "test8b"
rc = rbfm->createFile(fileName);
assert(rc == success && "Creating the file should not fail.");
rc = createFileShouldSucceed(fileName);
assert(rc == success && "Creating the file failed.");
// Open the file "test8b"
FileHandle fileHandle;
rc = rbfm->openFile(fileName, fileHandle);
assert(rc == success && "Opening the file should not fail.");
RID rid;
int recordSize = 0;
void *record = malloc(100);
void *returnedData = malloc(100);
vector<Attribute> recordDescriptor;
createRecordDescriptor(recordDescriptor);
// NULL field indicator
int nullFieldsIndicatorActualSize = getActualByteForNullsIndicator(recordDescriptor.size());
unsigned char *nullsIndicator = (unsigned char *) malloc(nullFieldsIndicatorActualSize);
memset(nullsIndicator, 0, nullFieldsIndicatorActualSize);
// Setting the salary field value as null
nullsIndicator[0] = 16; // 00010000
// Insert a record into a file
prepareRecord(recordDescriptor.size(), nullsIndicator, 8, "UCSCSlug", 24, 170.1, NULL, record, &recordSize);
cout << endl << "Inserting Data:" << endl;
rbfm->printRecord(recordDescriptor, record);
rc = rbfm->insertRecord(fileHandle, recordDescriptor, record, rid);
assert(rc == success && "Inserting a record should not fail.");
// Given the rid, read the record from file
rc = rbfm->readRecord(fileHandle, recordDescriptor, rid, returnedData);
assert(rc == success && "Reading a record should not fail.");
// The salary field should not be printed
cout << endl << "Returned Data:" << endl;
rbfm->printRecord(recordDescriptor, returnedData);
// Compare whether the two memory blocks are the same
if(memcmp(record, returnedData, recordSize) != 0)
{
cout << "[FAIL] Test Case 8b Failed!" << endl << endl;
free(record);
free(returnedData);
return -1;
}
cout << endl;
// Close the file "test8b"
rc = rbfm->closeFile(fileHandle);
assert(rc == success && "Closing the file should not fail.");
// Destroy File
rc = rbfm->destroyFile(fileName);
assert(rc == success && "Destroying the file should not fail.");
rc = destroyFileShouldSucceed(fileName);
assert(rc == success && "Destroying the file should not fail.");
free(record);
free(returnedData);
cout << "RBF Test Case 8b Finished! The result will be examined." << endl << endl;
return 0;
}
int main()
{
// To test the functionality of the paged file manager
// PagedFileManager *pfm = PagedFileManager::instance();
// To test the functionality of the record-based file manager
RecordBasedFileManager *rbfm = RecordBasedFileManager::instance();
remove("test8b");
RC rcmain = RBFTest_8b(rbfm);
return rcmain;
}
| [
"pefbass@gmail.com"
] | pefbass@gmail.com |
5621aa78d51d80d8839919a31aec4946a8b92f5e | 92ebaf7ce3022a38f8ae6bb57f6f8ee4ce6d267c | /tek2/object_prog/arcade/graphical/sdl2/Menu.hpp | d09f4b81d05f47994ff92c35f92ee692d0af1731 | [] | no_license | CyrilGrosjean/Epitech | d69d6c448214c9ea17c9837fb03e0e166a73afc4 | dde6bc229dcef73d66c422e98bd300cee6d19502 | refs/heads/master | 2023-04-28T17:32:08.333950 | 2021-05-20T00:12:33 | 2021-05-20T00:12:33 | 228,628,449 | 0 | 0 | null | 2023-04-14T17:18:22 | 2019-12-17T13:59:00 | C++ | UTF-8 | C++ | false | false | 570 | hpp | /*
** EPITECH PROJECT, 2021
** B-OOP-400-MPL-4-1-arcade-cyril.grosjean
** File description:
** Menu
*/
#ifndef MENU_HPP_
#define MENU_HPP_
#include <iostream>
#include <fstream>
#include "../../includes/Vector.hpp"
#include <vector>
namespace sdl
{
class Menu
{
public:
Menu();
~Menu();
size_t _gameIdx;
size_t _graphicalIdx;
std::string _username;
void set_libraries(std::vector<std::string> games, std::vector<std::string> graphicals);
void set_highscore(void);
};
}
#endif /* !MENU_HPP_ */
| [
"cyril.grosjean@epitech.eu"
] | cyril.grosjean@epitech.eu |
1b5bc9a069318c1a7938372630886282b2dbed28 | ef7eabdd5f9573050ef11d8c68055ab6cdb5da44 | /eolimp/page27/q2619/Main.cpp | c462ba7d1f9960b7a332275f7b58a7c3b97e9e1f | [
"WTFPL"
] | permissive | gauravsingh58/algo | cdbf68e28019ba7c3e4832e373d32c71902c9c0d | 397859a53429e7a585e5f6964ad24146c6261326 | refs/heads/master | 2022-12-28T01:08:32.333111 | 2020-09-30T19:37:53 | 2020-09-30T19:37:53 | 300,037,652 | 1 | 1 | WTFPL | 2020-10-15T09:26:32 | 2020-09-30T19:29:29 | Java | UTF-8 | C++ | false | false | 453 | cpp | #include <cstdio>
int main() {
int n, ns[1000000], sum1 = 0, sum2 = 0;
scanf("%d", &n);
for(int i=0; i<n; i++) {
scanf("%d", &ns[i]);
sum1 += ns[i];
}
if(sum1%2 == 0) {
for(int i=0; i<n; i++) {
sum1 -= ns[i];
sum2 += ns[i];
if(sum1 == sum2) {
printf("%d\n", i+1);
break;
} else if(sum1 < sum2) {
printf("%d\n", -1);
break;
}
}
} else
printf("%d\n", -1);
}
| [
"elmas.ferhat@gmail.com"
] | elmas.ferhat@gmail.com |
0b17591b5f274b89f38d222f9f63924b4d44b383 | b30a7be97defa312346391099b3d2eae0fb6f7ce | /src/qt/addresstablemodel.cpp | eee2a1bddfe1ffbe118039c23bd65e6265f23b14 | [
"MIT"
] | permissive | chavezcoin-project/arepacoin-pivx | 5a3b6000834417f295aba719c5b66283cd5df63f | e51b95c8a733f98a71e0e2b4fc8d8dbc43fc2bae | refs/heads/master | 2021-07-10T15:24:35.549002 | 2017-10-03T16:36:11 | 2017-10-03T16:36:11 | 105,044,698 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 14,043 | cpp | // Copyright (c) 2011-2014 The Bitcoin developers
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addresstablemodel.h"
#include "guiutil.h"
#include "walletmodel.h"
#include "base58.h"
#include "wallet.h"
#include <QDebug>
#include <QFont>
const QString AddressTableModel::Send = "S";
const QString AddressTableModel::Receive = "R";
struct AddressTableEntry {
enum Type {
Sending,
Receiving,
Hidden /* QSortFilterProxyModel will filter these out */
};
Type type;
QString label;
QString address;
AddressTableEntry() {}
AddressTableEntry(Type type, const QString& label, const QString& address) : type(type), label(label), address(address) {}
};
struct AddressTableEntryLessThan {
bool operator()(const AddressTableEntry& a, const AddressTableEntry& b) const
{
return a.address < b.address;
}
bool operator()(const AddressTableEntry& a, const QString& b) const
{
return a.address < b;
}
bool operator()(const QString& a, const AddressTableEntry& b) const
{
return a < b.address;
}
};
/* Determine address type from address purpose */
static AddressTableEntry::Type translateTransactionType(const QString& strPurpose, bool isMine)
{
AddressTableEntry::Type addressType = AddressTableEntry::Hidden;
// "refund" addresses aren't shown, and change addresses aren't in mapAddressBook at all.
if (strPurpose == "send")
addressType = AddressTableEntry::Sending;
else if (strPurpose == "receive")
addressType = AddressTableEntry::Receiving;
else if (strPurpose == "unknown" || strPurpose == "") // if purpose not set, guess
addressType = (isMine ? AddressTableEntry::Receiving : AddressTableEntry::Sending);
return addressType;
}
// Private implementation
class AddressTablePriv
{
public:
CWallet* wallet;
QList<AddressTableEntry> cachedAddressTable;
AddressTableModel* parent;
AddressTablePriv(CWallet* wallet, AddressTableModel* parent) : wallet(wallet), parent(parent) {}
void refreshAddressTable()
{
cachedAddressTable.clear();
{
LOCK(wallet->cs_wallet);
BOOST_FOREACH (const PAIRTYPE(CTxDestination, CAddressBookData) & item, wallet->mapAddressBook) {
const CBitcoinAddress& address = item.first;
bool fMine = IsMine(*wallet, address.Get());
AddressTableEntry::Type addressType = translateTransactionType(
QString::fromStdString(item.second.purpose), fMine);
const std::string& strName = item.second.name;
cachedAddressTable.append(AddressTableEntry(addressType,
QString::fromStdString(strName),
QString::fromStdString(address.ToString())));
}
}
// qLowerBound() and qUpperBound() require our cachedAddressTable list to be sorted in asc order
// Even though the map is already sorted this re-sorting step is needed because the originating map
// is sorted by binary address, not by base58() address.
qSort(cachedAddressTable.begin(), cachedAddressTable.end(), AddressTableEntryLessThan());
}
void updateEntry(const QString& address, const QString& label, bool isMine, const QString& purpose, int status)
{
// Find address / label in model
QList<AddressTableEntry>::iterator lower = qLowerBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
QList<AddressTableEntry>::iterator upper = qUpperBound(
cachedAddressTable.begin(), cachedAddressTable.end(), address, AddressTableEntryLessThan());
int lowerIndex = (lower - cachedAddressTable.begin());
int upperIndex = (upper - cachedAddressTable.begin());
bool inModel = (lower != upper);
AddressTableEntry::Type newEntryType = translateTransactionType(purpose, isMine);
switch (status) {
case CT_NEW:
if (inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_NEW, but entry is already in model";
break;
}
parent->beginInsertRows(QModelIndex(), lowerIndex, lowerIndex);
cachedAddressTable.insert(lowerIndex, AddressTableEntry(newEntryType, label, address));
parent->endInsertRows();
break;
case CT_UPDATED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_UPDATED, but entry is not in model";
break;
}
lower->type = newEntryType;
lower->label = label;
parent->emitDataChanged(lowerIndex);
break;
case CT_DELETED:
if (!inModel) {
qWarning() << "AddressTablePriv::updateEntry : Warning: Got CT_DELETED, but entry is not in model";
break;
}
parent->beginRemoveRows(QModelIndex(), lowerIndex, upperIndex - 1);
cachedAddressTable.erase(lower, upper);
parent->endRemoveRows();
break;
}
}
int size()
{
return cachedAddressTable.size();
}
AddressTableEntry* index(int idx)
{
if (idx >= 0 && idx < cachedAddressTable.size()) {
return &cachedAddressTable[idx];
} else {
return 0;
}
}
};
AddressTableModel::AddressTableModel(CWallet* wallet, WalletModel* parent) : QAbstractTableModel(parent), walletModel(parent), wallet(wallet), priv(0)
{
columns << tr("Label") << tr("Address");
priv = new AddressTablePriv(wallet, this);
priv->refreshAddressTable();
}
AddressTableModel::~AddressTableModel()
{
delete priv;
}
int AddressTableModel::rowCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return priv->size();
}
int AddressTableModel::columnCount(const QModelIndex& parent) const
{
Q_UNUSED(parent);
return columns.length();
}
QVariant AddressTableModel::data(const QModelIndex& index, int role) const
{
if (!index.isValid())
return QVariant();
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
if (role == Qt::DisplayRole || role == Qt::EditRole) {
switch (index.column()) {
case Label:
if (rec->label.isEmpty() && role == Qt::DisplayRole) {
return tr("(no label)");
} else {
return rec->label;
}
case Address:
return rec->address;
}
} else if (role == Qt::FontRole) {
QFont font;
if (index.column() == Address) {
font = GUIUtil::bitcoinAddressFont();
}
return font;
} else if (role == TypeRole) {
switch (rec->type) {
case AddressTableEntry::Sending:
return Send;
case AddressTableEntry::Receiving:
return Receive;
default:
break;
}
}
return QVariant();
}
bool AddressTableModel::setData(const QModelIndex& index, const QVariant& value, int role)
{
if (!index.isValid())
return false;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
std::string strPurpose = (rec->type == AddressTableEntry::Sending ? "send" : "receive");
editStatus = OK;
if (role == Qt::EditRole) {
LOCK(wallet->cs_wallet); /* For SetAddressBook / DelAddressBook */
CTxDestination curAddress = CBitcoinAddress(rec->address.toStdString()).Get();
if (index.column() == Label) {
// Do nothing, if old label == new label
if (rec->label == value.toString()) {
editStatus = NO_CHANGES;
return false;
}
wallet->SetAddressBook(curAddress, value.toString().toStdString(), strPurpose);
} else if (index.column() == Address) {
CTxDestination newAddress = CBitcoinAddress(value.toString().toStdString()).Get();
// Refuse to set invalid address, set error status and return false
if (boost::get<CNoDestination>(&newAddress)) {
editStatus = INVALID_ADDRESS;
return false;
}
// Do nothing, if old address == new address
else if (newAddress == curAddress) {
editStatus = NO_CHANGES;
return false;
}
// Check for duplicate addresses to prevent accidental deletion of addresses, if you try
// to paste an existing address over another address (with a different label)
else if (wallet->mapAddressBook.count(newAddress)) {
editStatus = DUPLICATE_ADDRESS;
return false;
}
// Double-check that we're not overwriting a receiving address
else if (rec->type == AddressTableEntry::Sending) {
// Remove old entry
wallet->DelAddressBook(curAddress);
// Add new entry with new address
wallet->SetAddressBook(newAddress, rec->label.toStdString(), strPurpose);
}
}
return true;
}
return false;
}
QVariant AddressTableModel::headerData(int section, Qt::Orientation orientation, int role) const
{
if (orientation == Qt::Horizontal) {
if (role == Qt::DisplayRole && section < columns.size()) {
return columns[section];
}
}
return QVariant();
}
Qt::ItemFlags AddressTableModel::flags(const QModelIndex& index) const
{
if (!index.isValid())
return 0;
AddressTableEntry* rec = static_cast<AddressTableEntry*>(index.internalPointer());
Qt::ItemFlags retval = Qt::ItemIsSelectable | Qt::ItemIsEnabled;
// Can edit address and label for sending addresses,
// and only label for receiving addresses.
if (rec->type == AddressTableEntry::Sending ||
(rec->type == AddressTableEntry::Receiving && index.column() == Label)) {
retval |= Qt::ItemIsEditable;
}
return retval;
}
QModelIndex AddressTableModel::index(int row, int column, const QModelIndex& parent) const
{
Q_UNUSED(parent);
AddressTableEntry* data = priv->index(row);
if (data) {
return createIndex(row, column, priv->index(row));
} else {
return QModelIndex();
}
}
void AddressTableModel::updateEntry(const QString& address,
const QString& label,
bool isMine,
const QString& purpose,
int status)
{
// Update address book model from Arepacoin core
priv->updateEntry(address, label, isMine, purpose, status);
}
QString AddressTableModel::addRow(const QString& type, const QString& label, const QString& address)
{
std::string strLabel = label.toStdString();
std::string strAddress = address.toStdString();
editStatus = OK;
if (type == Send) {
if (!walletModel->validateAddress(address)) {
editStatus = INVALID_ADDRESS;
return QString();
}
// Check for duplicate addresses
{
LOCK(wallet->cs_wallet);
if (wallet->mapAddressBook.count(CBitcoinAddress(strAddress).Get())) {
editStatus = DUPLICATE_ADDRESS;
return QString();
}
}
} else if (type == Receive) {
// Generate a new address to associate with given label
CPubKey newKey;
if (!wallet->GetKeyFromPool(newKey)) {
WalletModel::UnlockContext ctx(walletModel->requestUnlock(true));
if (!ctx.isValid()) {
// Unlock wallet failed or was cancelled
editStatus = WALLET_UNLOCK_FAILURE;
return QString();
}
if (!wallet->GetKeyFromPool(newKey)) {
editStatus = KEY_GENERATION_FAILURE;
return QString();
}
}
strAddress = CBitcoinAddress(newKey.GetID()).ToString();
} else {
return QString();
}
// Add entry
{
LOCK(wallet->cs_wallet);
wallet->SetAddressBook(CBitcoinAddress(strAddress).Get(), strLabel,
(type == Send ? "send" : "receive"));
}
return QString::fromStdString(strAddress);
}
bool AddressTableModel::removeRows(int row, int count, const QModelIndex& parent)
{
Q_UNUSED(parent);
AddressTableEntry* rec = priv->index(row);
if (count != 1 || !rec || rec->type == AddressTableEntry::Receiving) {
// Can only remove one row at a time, and cannot remove rows not in model.
// Also refuse to remove receiving addresses.
return false;
}
{
LOCK(wallet->cs_wallet);
wallet->DelAddressBook(CBitcoinAddress(rec->address.toStdString()).Get());
}
return true;
}
/* Look up label for address in address book, if not found return empty string.
*/
QString AddressTableModel::labelForAddress(const QString& address) const
{
{
LOCK(wallet->cs_wallet);
CBitcoinAddress address_parsed(address.toStdString());
std::map<CTxDestination, CAddressBookData>::iterator mi = wallet->mapAddressBook.find(address_parsed.Get());
if (mi != wallet->mapAddressBook.end()) {
return QString::fromStdString(mi->second.name);
}
}
return QString();
}
int AddressTableModel::lookupAddress(const QString& address) const
{
QModelIndexList lst = match(index(0, Address, QModelIndex()),
Qt::EditRole, address, 1, Qt::MatchExactly);
if (lst.isEmpty()) {
return -1;
} else {
return lst.at(0).row();
}
}
void AddressTableModel::emitDataChanged(int idx)
{
emit dataChanged(index(idx, 0, QModelIndex()), index(idx, columns.length() - 1, QModelIndex()));
}
| [
"loldlm1@gmail.com"
] | loldlm1@gmail.com |
b0807aa9e4bae0c3134a47e57130f077d11f6fd8 | 8ad84e8c9ff528394cfaa36120a1f8a37a16f558 | /boost/shared_ptr/payload.cxx | 3fdce173d90eca0d1b0ce30f6acdaf30c4969b44 | [] | no_license | cellist/dev | 30378d031cbf2cc4ca23d8bdcd831679d6417786 | 3b59f54cafb2cfe97ff90caf127e165d866b9280 | refs/heads/master | 2023-08-19T03:43:30.494172 | 2023-08-12T14:43:46 | 2023-08-12T14:43:46 | 1,159,225 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 386 | cxx | #include <iostream>
#include "payload.h"
Payload::Payload() {
std::cout << "Payload(): "
<< this->reference.use_count() << std::endl;
}
Payload::~Payload() {
std::cout << "~Payload(): "
<< this->reference.use_count() << std::endl;
}
void Payload::inject(const PayloadPtr& ref) {
std::cout << "Payload::inject: "
<< this->reference.use_count() << std::endl;
}
| [
"cellist@squizzy.de"
] | cellist@squizzy.de |
a446699439d3e6312cbfcfd14bd677d7b1513b2b | 883dc584a7df35efc9dbc52ffea8b7078c6e231d | /UVA兩顆星/Blowing Fuses.cpp | 2b8dc5617fe866397ef47597eb0a25469a9fd448 | [] | no_license | gigilin7/Program-solving | 5ef048c24fa9ff0f2ea738c0d9361eb340c50152 | ac4402b2635b2af2f41c83764bcc9bfce02a0f89 | refs/heads/main | 2023-03-12T17:59:33.905088 | 2021-02-22T11:22:23 | 2021-02-22T11:22:23 | 341,097,168 | 1 | 0 | null | null | null | null | BIG5 | C++ | false | false | 811 | cpp | //題目:http://javauva.blogspot.com/2016/01/c094-00661-blowing-fuses.html
#include <iostream>
using namespace std;
int main()
{
int n,m,c,count=1;//電器用品數,開關次數,上限
while(cin>>n>>m>>c&&n)
{ //turn=0是關,turn=1是開
int I[20]={0},turn[100]={0},sum=0,max=0;
for(int i=1;i<=n;i++)
{
cin>>I[i];//每個電器的電流
}
for(int i=0;i<m;i++)
{
int num;
cin>>num;//哪個電器要開關
if(turn[num]==0)
{
turn[num]=1;
sum=sum+I[num];
if(sum>max)
max=sum;
}
else
{
turn[num]=0;
sum=sum-I[num];
}
}
cout<<"Sequence "<<count++<<'\n';
if(sum>c)
cout<<"Fuse was blown.\n";
else
{
cout<<"Fuse was not blown.\n";
cout<<"Maximal power consumption was "<<max<<" amperes.\n";
}
cout<<'\n';
}
}
| [
"gigilinqoo@gmail.com"
] | gigilinqoo@gmail.com |
4443686ae5356bfe45dcf193765788f50aa50797 | bcfe3b540106599630acbfd811c48a5ce283d4ef | /RPS.cpp | 0ca1da0bde24c499a1aa38e10046bc7fd9fdbe03 | [] | no_license | Kevin-Escobedo/RPS | 14e374fa90e0ed470568bab62f40b37b5537cf85 | 90257b1240275734a1452c7466ad4b3da1dbeaa7 | refs/heads/master | 2023-03-09T04:29:52.056508 | 2021-02-19T21:35:17 | 2021-02-19T21:35:17 | 340,464,192 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,061 | cpp | #include "RPS.h"
RPS::RPS()
:result(0), lastPlayerMove()
{
srand(time(nullptr));
}
RPS::RPS(const RPS& rps)
:result(rps.result), lastPlayerMove(rps.lastPlayerMove)
{
srand(time(nullptr));
}
RPS& RPS::operator =(const RPS& rps)
{
result = rps.result;
lastPlayerMove = rps.lastPlayerMove;
return *this;
}
RPS::~RPS()
{
}
std::string RPS::getUserInput()
{
std::string playerMove;
while(true)
{
std::cout<<"Enter Move: ";
std::getline(std::cin, playerMove);
if(playerMove == "Rock" || playerMove == "Paper" || playerMove == "Scissors")
{
break;
}
}
return playerMove;
}
void RPS::play(const int trials)
{
for(int i = 0; i < trials; i++)
{
std::string cpuMove = makeMove();
std::string humanMove = getUserInput();
lastPlayerMove = humanMove;
if(cpuMove == humanMove)
{
result = 0;
}
//TODO: Optimize
if(cpuMove == "Rock")
{
if(humanMove == "Paper")
{
result = -1;
}
if(humanMove == "Scissors")
{
result = 1;
}
}
if(cpuMove == "Paper")
{
if(humanMove == "Rock")
{
result = 1;
}
if(humanMove == "Scissors")
{
result = -1;
}
}
if(cpuMove == "Scissors")
{
if(humanMove == "Rock")
{
result = -1;
}
if(humanMove == "Paper")
{
result = 1;
}
}
showResult();
}
}
void RPS::showResult()
{
switch(result)
{
case -1:
std::cout<<"Player Win!"<<std::endl;
break;
case 0:
std::cout<<"Draw!"<<std::endl;
break;
case 1:
std::cout<<"Computer Win!"<<std::endl;
break;
default:
std::cout<<"ERROR"<<std::endl;
}
}
std::string RPS::makeMove()
{
const int move = rand() % 3;
switch(result)
{
case -1: //Play what wasn't played
if(lastPlayerMove == "Rock")
{
return "Paper";
}
if(lastPlayerMove == "Paper")
{
return "Scissors";
}
if(lastPlayerMove == "Scissors")
{
return "Rock";
}
break;
case 0: //Random move
switch(move)
{
case 0:
return "Rock";
case 1:
return "Paper";
case 2:
return "Scissors";
default:
return "ERROR";
}
break;
case 1: //Play what they played
return lastPlayerMove;
default:
return "ERROR";
}
return "ERROR";
} | [
"escobedo001@gmail.com"
] | escobedo001@gmail.com |
d7cebdf9af46425513763dd91c011de1c2be5a41 | e59b51f7aa3abd84607879c5d8a360c62e3c3f96 | /include/leveldb/table_builder.h | 74a3aaa1d08c620ffe2da244ee7015fe6ce5a9c8 | [
"BSD-3-Clause"
] | permissive | bigtreetree/leveldb2 | b4421b4fe327d12b074a123816138c0a85793376 | 6d058a0672854e76e526b94d52571ef4782d614c | refs/heads/master | 2021-01-10T14:04:56.506997 | 2015-11-03T13:04:57 | 2015-11-03T13:04:57 | 43,273,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,452 | h | // Copyright (c) 2011 The LevelDB Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file. See the AUTHORS file for names of contributors.
//
// TableBuilder provides the interface used to build a Table
// (an immutable and sorted map from keys to values).
//
// Multiple threads can invoke const methods on a TableBuilder without
// external synchronization, but if any of the threads may call a
// non-const method, all threads accessing the same TableBuilder must use
// external synchronization.
#ifndef STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_
#define STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_
#include <stdint.h>
#include "leveldb/options.h"
#include "leveldb/status.h"
namespace leveldb {
class BlockBuilder;
class BlockHandle;
class WritableFile;
/*
* 类 名:TableBuilder
* 功 能:构建sst文件
*/
class TableBuilder {
public:
// Create a builder that will store the contents of the table it is
// building in *file. Does not close the file. It is up to the
// caller to close the file after calling Finish().
TableBuilder(const Options& options, WritableFile* file);
// REQUIRES: Either Finish() or Abandon() has been called.
~TableBuilder();
// Change the options used by this builder. Note: only some of the
// option fields can be changed after construction. If a field is
// not allowed to change dynamically and its value in the structure
// passed to the constructor is different from its value in the
// structure passed to this method, this method will return an error
// without changing any fields.
Status ChangeOptions(const Options& options);
// Add key,value to the table being constructed.
// REQUIRES: key is after any previously added key according to comparator.
// REQUIRES: Finish(), Abandon() have not been called
void Add(const Slice& key, const Slice& value);
// Advanced operation: flush any buffered key/value pairs to file.
// Can be used to ensure that two adjacent entries never live in
// the same data block. Most clients should not need to use this method.
// REQUIRES: Finish(), Abandon() have not been called
void Flush();
// Return non-ok iff some error has been detected.
Status status() const;
// Finish building the table. Stops using the file passed to the
// constructor after this function returns.
// REQUIRES: Finish(), Abandon() have not been called
Status Finish();
// Indicate that the contents of this builder should be abandoned. Stops
// using the file passed to the constructor after this function returns.
// If the caller is not going to call Finish(), it must call Abandon()
// before destroying this builder.
// REQUIRES: Finish(), Abandon() have not been called
void Abandon();
// Number of calls to Add() so far.
uint64_t NumEntries() const;
// Size of the file generated so far. If invoked after a successful
// Finish() call, returns the size of the final generated file.
uint64_t FileSize() const;
private:
bool ok() const { return status().ok(); }
void WriteBlock(BlockBuilder* block, BlockHandle* handle);
void WriteRawBlock(const Slice& data, CompressionType, BlockHandle* handle);
struct Rep;
Rep* rep_;
// No copying allowed
TableBuilder(const TableBuilder&);
void operator=(const TableBuilder&);
};
} // namespace leveldb
#endif // STORAGE_LEVELDB_INCLUDE_TABLE_BUILDER_H_
| [
"chengshaoyuan@daoke.me"
] | chengshaoyuan@daoke.me |
33efc59050ea54141be8ef3066911d753e9d41d6 | e42c57e2cbcc6193bb0f623e67931e084b828c8b | /Libraries/BetterStepper/BetterStepper.cpp | ecf25eb50baaab654dfb27fdaf187190e8b458c3 | [] | no_license | CautelaTech/BluetoothRCCar | 8df89e54ec3aea3a34093c35bd1ceeb40f8db3dd | 35fe38c1913774a507418c1e3b92224de3f87551 | refs/heads/master | 2021-01-25T05:23:17.462100 | 2014-12-30T21:22:40 | 2014-12-30T21:22:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 8,023 | cpp | /*
BetterStepper.cpp - - BetterStepper library for Wiring/Arduino - Version 0.4
Original library (0.1) by Tom Igoe.
Two-wire modifications (0.2) by Sebastian Gassner
Combination version (0.3) by Tom Igoe and David Mellis
Bug fix for four-wire (0.4) by Tom Igoe, bug fix from Noah Shibley
Drives a unipolar or bipolar stepper motor using 2 wires or 4 wires
When wiring multiple stepper motors to a microcontroller,
you quickly run out of output pins, with each motor requiring 4 connections.
By making use of the fact that at any time two of the four motor
coils are the inverse of the other two, the number of
control connections can be reduced from 4 to 2.
A slightly modified circuit around a Darlington transistor array or an L293 H-bridge
connects to only 2 microcontroler pins, inverts the signals received,
and delivers the 4 (2 plus 2 inverted ones) output signals required
for driving a stepper motor.
The sequence of control signals for 4 control wires is as follows:
Step C0 C1 C2 C3
1 1 0 1 0
2 0 1 1 0
3 0 1 0 1
4 1 0 0 1
The sequence of controls signals for 2 control wires is as follows
(columns C1 and C2 from above):
Step C0 C1
1 0 1
2 1 1
3 1 0
4 0 0
The circuits can be found at
http://www.arduino.cc/en/Tutorial/BetterStepper
*/
#include <Arduino.h>
#include "BetterStepper.h"
/*
* two-wire constructor.
* Sets which wires should control the motor.
*/
BetterStepper::BetterStepper(int number_of_steps, int motor_pin_1, int motor_pin_2)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
// When there are only 2 pins, set the other two to 0:
this->motor_pin_3 = 0;
this->motor_pin_4 = 0;
// pin_count is used by the stepMotor() method:
this->pin_count = 2;
}
/*
* constructor for four-pin version
* Sets which wires should control the motor.
*/
BetterStepper::BetterStepper(int number_of_steps, int motor_pin_1, int motor_pin_2, int motor_pin_3, int motor_pin_4)
{
this->step_number = 0; // which step the motor is on
this->speed = 0; // the motor speed, in revolutions per minute
this->direction = 0; // motor direction
this->last_step_time = 0; // time stamp in ms of the last step taken
this->number_of_steps = number_of_steps; // total number of steps for this motor
// Arduino pins for the motor control connection:
this->motor_pin_1 = motor_pin_1;
this->motor_pin_2 = motor_pin_2;
this->motor_pin_3 = motor_pin_3;
this->motor_pin_4 = motor_pin_4;
// setup the pins on the microcontroller:
pinMode(this->motor_pin_1, OUTPUT);
pinMode(this->motor_pin_2, OUTPUT);
pinMode(this->motor_pin_3, OUTPUT);
pinMode(this->motor_pin_4, OUTPUT);
// pin_count is used by the stepMotor() method:
this->pin_count = 4;
}
/*
Sets the speed in revs per minute
*/
void BetterStepper::setSpeed(long rpm_start, long rpm_max)
{
this->delay_max_speed = 60L * 1000L *1000L / this->number_of_steps / rpm_max;
this->delay_start_speed = 60L * 1000L * 1000L/ this->number_of_steps / rpm_start;
}
/*
Moves the motor steps_to_move steps. If the number is negative,
the motor moves in the reverse direction.
*/
#define SPD_BUFF_STEPS 100
void BetterStepper::step(int steps_to_move)
{
int steps_left = abs(steps_to_move); // how many steps to take
int steps_orig = steps_left;
int steps_buffer = SPD_BUFF_STEPS;
if (steps_orig < steps_buffer*2)
steps_buffer = steps_left/2;
float delays = this->delay_start_speed;
float delay_minus = (delays - this->delay_max_speed)/SPD_BUFF_STEPS;
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
delayMicroseconds(delays);
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
if ((steps_orig - steps_left) <= steps_buffer)
delays -= delay_minus;
else if (steps_left <= steps_buffer)
delays += delay_minus;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
}
}
void BetterStepper::step(int steps_to_move, int (*fun)())
{
int steps_left = abs(steps_to_move); // how many steps to take
int steps_orig = steps_left;
int steps_buffer = SPD_BUFF_STEPS;
if (steps_orig < steps_buffer*2)
steps_buffer = steps_left/2;
float delays = this->delay_start_speed;
float delay_minus = (delays - this->delay_max_speed)/SPD_BUFF_STEPS;
// determine direction based on whether steps_to_mode is + or -:
if (steps_to_move > 0) {this->direction = 1;}
if (steps_to_move < 0) {this->direction = 0;}
// decrement the number of steps, moving one step each time:
while(steps_left > 0) {
delayMicroseconds(delays);
if (this->direction == 1) {
this->step_number++;
if (this->step_number == this->number_of_steps) {
this->step_number = 0;
}
}
else {
if (this->step_number == 0) {
this->step_number = this->number_of_steps;
}
this->step_number--;
}
// decrement the steps left:
steps_left--;
if ((steps_orig - steps_left) <= steps_buffer)
delays -= delay_minus;
else if (steps_left <= steps_buffer)
delays += delay_minus;
// step the motor to step number 0, 1, 2, or 3:
stepMotor(this->step_number % 4);
if(fun())return; // exit
}
}
/*
* Moves the motor forward or backwards.
*/
void BetterStepper::stepMotor(int thisStep)
{
if (this->pin_count == 2) {
switch (thisStep) {
case 0: /* 01 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
break;
case 1: /* 11 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, HIGH);
break;
case 2: /* 10 */
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
break;
case 3: /* 00 */
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, LOW);
break;
}
}
if (this->pin_count == 4) {
switch (thisStep) {
case 0: // 1010
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 1: // 0110
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, HIGH);
digitalWrite(motor_pin_4, LOW);
break;
case 2: //0101
digitalWrite(motor_pin_1, LOW);
digitalWrite(motor_pin_2, HIGH);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
case 3: //1001
digitalWrite(motor_pin_1, HIGH);
digitalWrite(motor_pin_2, LOW);
digitalWrite(motor_pin_3, LOW);
digitalWrite(motor_pin_4, HIGH);
break;
}
}
}
/*
version() returns the version of the library:
*/
int BetterStepper::version(void)
{
return 4;
}
| [
"ncoursey@brownjordan.com"
] | ncoursey@brownjordan.com |
5d1741e362d0165ad09e1bdb76ac79cbd6784100 | 9556ebced20e46c57e9827f671d6026b180e02bd | /ioComponents/DRAMsim/DRAM_config.cc | cc245f3c1c5b616bde3380dd6c50f3345700977a | [] | no_license | lebiednik/PhoenixSim | fedb066194da5edb4a351608e34ac536ddfab228 | c4254118cbdb07c6ff91b5bc0da7b43bd0b84a2e | refs/heads/master | 2021-01-12T04:00:43.153824 | 2017-01-26T15:27:25 | 2017-01-26T15:27:25 | 77,463,750 | 5 | 3 | null | null | null | null | UTF-8 | C++ | false | false | 26,592 | cc | #include "DRAM_config.h"
#include "TransactionQueue.h"
DRAM_config::DRAM_config(){
dram_power_config = NULL;
init_dram_system_configuration();
}
void DRAM_config::init_dram_system_configuration(){
int i;
set_dram_type(SDRAM); /* explicitly initialize the variables */
set_dram_frequency(100); /* explicitly initialize the variables */
set_memory_frequency(100); /* explicitly initialize the variables */
set_dram_channel_count(1); /* single channel of memory */
set_dram_channel_width(8); /* 8 byte wide data bus */
set_pa_mapping_policy(SDRAM_BASE_MAP); /* generic mapping policy */
set_dram_transaction_granularity(64); /* 64 bytes long cachelines */
set_dram_row_buffer_management_policy(OPEN_PAGE);
set_cpu_memory_frequency_ratio();
set_transaction_selection_policy(FCFS);
strict_ordering_flag = FALSE;
packet_count = MAX(1,(cacheline_size / (channel_width * 8 )));
t_burst = cacheline_size / (channel_width);
auto_refresh_enabled = TRUE;
refresh_policy = REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK;
refresh_issue_policy = REFRESH_OPPORTUNISTIC;
refresh_time = 100;
refresh_cycle_count = 10000;
dram_debug_flag = FALSE;
addr_debug_flag = FALSE;
wave_debug_flag = FALSE;
wave_cas_debug_flag = FALSE;
issue_debug_flag = FALSE;
var_latency_flag = FALSE;
watch_refresh = FALSE;
memory2dram_freq_ratio = 1;
arrival_threshold = 1500;
/** Just setup the default types for FBD stuff too **/
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
drive_cmd_count = 1;
num_thread_sets = 1;
thread_sets[0] = 32;
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
single_rank = true;
t_cmd = 0;
bus_queue_depth = 0;
set_independent_threads();
}
/* Dumps the DRAM configuration. */
void DRAM_config::dump_config(FILE *stream)
{
fprintf(stream, "===================== DRAM config ======================\n");
print_dram_type( dram_type, stream );
fprintf(stream, " dram_frequency: %d MHz\n", dram_type != FBD_DDR2 ? memory_frequency : dram_frequency );
fprintf(stream, " memory_frequency: %d MHz\n", memory_frequency);
fprintf(stream, " cpu_frequency: %d MHz\n", get_cpu_frequency());
fprintf(stream, " dram_clock_granularity: %d\n", dram_clock_granularity);
fprintf(stream, " memfreq2cpufreq ration: %f \n", (float)mem2cpu_clock_ratio);
fprintf(stream, " memfreq2dramfreq ration: %f \n", memory2dram_freq_ratio);
fprintf(stream, " critical_word_first_flag: %d\n", critical_word_first_flag);
print_pa_mapping_policy( physical_address_mapping_policy, stream);
print_row_policy( row_buffer_management_policy, stream);
print_trans_policy( get_transaction_selection_policy(), stream);
fprintf(stream, " cacheline_size: %d\n", cacheline_size);
fprintf(stream, " chan_count: %d\n", channel_count);
fprintf(stream, " rank_count: %d\n", rank_count);
fprintf(stream, " bank_count: %d\n", bank_count);
fprintf(stream, " row_count: %d\n", row_count);
fprintf(stream, " col_count: %d\n", col_count);
fprintf(stream, " buffer count: %d\n", up_buffer_cnt);
fprintf(stream, " t_rcd: %d\n", t_rcd);
fprintf(stream, " t_cac: %d\n", t_cac);
fprintf(stream, " t_cas: %d\n", t_cas);
fprintf(stream, " t_ras: %d\n", t_ras);
fprintf(stream, " t_rp: %d\n", t_rp);
fprintf(stream, " t_cwd: %d\n", t_cwd);
fprintf(stream, " t_rtr: %d\n", t_rtr);
fprintf(stream, " t_burst: %d\n", t_burst);
fprintf(stream, " t_rc: %d\n", t_rc);
fprintf(stream, " t_rfc: %d\n", t_rfc);
fprintf(stream, " t_al: %d\n", t_al);
fprintf(stream, " t_wr: %d\n", t_wr);
fprintf(stream, " t_rtp: %d\n", t_rtp);
fprintf(stream, " t_dqs: %d\n", t_dqs);
// FBDIMM RELATED
fprintf(stream, " t_amb_up: %d\n", t_amb_up);
fprintf(stream, " t_amb_down: %d\n", t_amb_down);
fprintf(stream, " t_bundle: %d\n", t_bundle);
fprintf(stream, " t_bus: %d\n", t_bus);
fprintf(stream, " posted_cas: %d\n", posted_cas_flag);
fprintf(stream, " row_command_duration: %d\n", row_command_duration);
fprintf(stream, " col_command_duration: %d\n", col_command_duration);
// REFRESH POLICY
fprintf(stream, " auto_refresh_enabled: %d\n", auto_refresh_enabled);
fprintf(stream, " auto_refresh_policy: %d\n", refresh_policy);
fprintf(stream, " refresh_time: %f\n", refresh_time);
fprintf(stream, " refresh_cycle_count: %d\n", refresh_cycle_count);
fprintf(stream, " strict_ordering_flag: %d\n", strict_ordering_flag);
// DEBUG
fprintf(stream, " dram_debug: %d\n", dram_debug_flag);
fprintf(stream, " addr_debug: %d\n", addr_debug_flag);
fprintf(stream, " wave_debug: %d\n", wave_debug_flag);
fprintf(stream, "========================================================\n\n\n");
}
/**
* All cycles in the config file are in terms of dram cycles.
* This converts everything in terms of memory controller cycles.
*/
void DRAM_config::convert_config_dram_cycles_to_mem_cycles(){
// Not sure wher to put this -> but it needs to be done
t_cac = t_cas - col_command_duration;
t_ras*=(int)memory2dram_freq_ratio; /* interval between ACT and PRECHARGE to same bank */
t_rcd*=(int)memory2dram_freq_ratio; /* RAS to CAS delay of same bank */
t_cas*=(int)memory2dram_freq_ratio; /* delay between start of CAS command and start of data burst */
t_cac*=(int)memory2dram_freq_ratio; /* delay between end of CAS command and start of data burst*/
t_rp*=(int)memory2dram_freq_ratio; /* interval between PRECHARGE and ACT to same bank */
/* t_rc is simply t_ras + t_rp */
t_rc*=(int)memory2dram_freq_ratio;
t_rfc*=(int)memory2dram_freq_ratio;
t_cwd*=(int)memory2dram_freq_ratio; /* delay between end of CAS Write command and start of data packet */
t_rtr*=(int)memory2dram_freq_ratio; /* delay between start of CAS Write command and start of write retirement command*/
t_burst*=(int)memory2dram_freq_ratio; /* number of cycles utilized per cacheline burst */
t_al*=(int)memory2dram_freq_ratio; /* additive latency = t_rcd - 2 (ddr half cycles) */
t_rl*=(int)memory2dram_freq_ratio; /* read latency = t_al + t_cas */
t_wr*=(int)memory2dram_freq_ratio; /* write recovery time latency, time to restore data o cells */
t_rtp*=(int)memory2dram_freq_ratio; /* write recovery time latency, time to restore data o cells */
//t_bus*=(int)memory2dram_freq_ratio; /* FBDIMM - bus delay */
t_amb_up*=(int)memory2dram_freq_ratio; /* FBDIMM - Amb up delay */
t_amb_down*=(int)memory2dram_freq_ratio; /* FBDIMM - Amb down delay */
//t_bundle*=(int)memory2dram_freq_ratio; /* FBDIMM number of cycles utilized to transmit a bundle */
row_command_duration*=(int)memory2dram_freq_ratio; // originally 2 -> goest to 12
col_command_duration*=(int)memory2dram_freq_ratio;
t_dqs*=(int)memory2dram_freq_ratio; /* rank hand off penalty. 0 for SDRAM, 2 for DDR, */
refresh_cycle_count*=(int)memory2dram_freq_ratio;
return;
}
/*
* set configurations for specific DRAM Systems.
*
* We set the init here so we can use 16 256Mbit parts to get 512MB of total memory
*/
void DRAM_config::set_dram_type(int type){ /* SDRAM, DDR RDRAM etc */
dram_type = type;
if (dram_type == SDRAM){ /* PC100 SDRAM -75 chips. nominal timing assumed */
channel_width = 8; /* bytes */
set_dram_frequency(100);
row_command_duration = 1; /* cycles */
col_command_duration = 1; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
/* Micron 256 Mbit SDRAM chip data sheet -75 specs used */
bank_count = 4; /* per rank */
row_count = 8*1024;
col_count = 512;
t_ras = 5; /* actually 44ns, so that's 5 cycles */
t_rp = 2; /* actually 20ns, so that's 2 cycles */
t_rcd = 2; /* actually 20 ns, so that's only 2 cycles */
t_cas = 2; /* this is CAS, use 2 */
t_al = 0;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = -1; /* SDRAM has no write delay . -1 cycles between end of CASW command and data placement on data bus*/
t_rtr = 0; /* SDRAM has no write delay, no need for retire packet */
t_dqs = 0;
t_rc = t_ras + t_rp;
t_rfc = t_rc;
t_wr = 2;
t_rtp = 1;
posted_cas_flag = 0;
up_buffer_cnt = 0;
t_amb_up = 0;
t_amb_down = 0;
t_bundle = 0;
t_bus = 0;
tq_delay = 2; /* 2 DRAM ticks of delay @ 100 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 1;
} else if (dram_type == DDRSDRAM){
channel_width = 8;
set_dram_frequency(200);
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank */
row_count = 8*1024;
col_count = 512;
t_ras = 5 * 2;
t_rp = 2 * 2;
t_al = 0;
t_rcd = 2 * 2;
t_cas = 2 * 2;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = 0 * 2; /* not really write delay, but it's the DQS delay */
t_rtr = 0;
t_dqs = 2;
t_rc = t_ras + t_rp;
t_rfc = t_rc;
t_wr = 2; /* FIXME */
t_rtp = 2;
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 2; /* DDR clock granularity */
} else if (dram_type == DDR2 || dram_type == DDR3 ){
channel_width = 8; /* bytes */
set_dram_frequency(400);
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank , 8 banks in near future.*/
row_count = 8*1024;
col_count = 512;
t_ras = 9 * 2; /* 45ns @ 400 mbps is 18 cycles */
t_rp = 3 * 2; /* 15ns @ 400 mpbs is 6 cycles */
t_rcd = 3 * 2;
t_cas = 3 * 2;
t_al = 0;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = t_cac;
t_rtr = 0;
t_dqs = 1 * 2;
t_rc = t_ras + t_rp;
t_rfc = 51; // 127.5 ns
t_wr = 2; /* FIXME */
t_rtp = 6;
t_rl = t_al + t_cas;
t_rrd = 0;
t_faw = 0;
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= TRUE;
dram_clock_granularity = 2; /* DDR clock granularity */
cas_with_prec = true;
} else if (dram_type == FBD_DDR2) {
up_channel_width = 10; /* bits */
down_channel_width = 14; /* bits */
set_dram_channel_width(8); /* 8 byte wide data bus */
set_memory_frequency(1600);
set_dram_frequency(400);
memory2dram_freq_ratio = memory_frequency/dram_frequency;
row_command_duration = 1 * 2; /* cycles */
col_command_duration = 1 * 2; /* cycles */
rank_count = 4; /* for SDRAM and DDR SDRAM, rank_count is DIMM-bank count */
bank_count = 4; /* per rank , 8 banks in near future.*/
row_count = 8*1024;
col_count = 512;
t_ras = 9 * 2; /* 45ns @ 400 mbps is 18 cycles */
t_rp = 3 * 2; /* 15ns @ 400 mpbs is 6 cycles */
t_rcd = 3 * 2;
t_cas = 3 * 2;
t_cac = t_cas - col_command_duration; /* delay in between CAS command and start of read data burst */
t_cwd = t_cac;
t_al = 0;
t_rtr = 0;
t_dqs = 0;
t_rc = t_ras + t_rp;
t_rfc = 51; // 127.5 ns
t_wr = 12; /* FIXME */
t_rtp = 8;
t_amb_up = 6; /*** Arbitrary Value FIXME **/
t_amb_down = 6; /*** Arbitrary Value FIXME **/
up_buffer_cnt = 4; /** Set to as many up buffers as ther are banks in the rank **/
down_buffer_cnt = 4; /** Set to as many up buffers as ther are banks in the rank **/
tq_delay =2*2; /* 4 DRAM ticks of delay @ 200 MHz = 20ns */
max_tq_size = MAX_TRANSACTION_QUEUE_DEPTH;
critical_word_first_flag= FALSE;
dram_clock_granularity = 2; /* DDR clock granularity */
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
drive_cmd_count = 1;
//refresh_policy = REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK;
refresh_time = 100;
refresh_cycle_count = 10000;
cas_with_prec = true;
}
else {
fprintf(stdout,"Unknown memory type %d\n",dram_type);
exit(3);
}
}
int DRAM_config::get_dram_type(){ /* SDRAM, DDR RDRAM etc */
return dram_type;
}
void DRAM_config::set_chipset_delay(int delay){
tq_delay = MAX(1,delay);
}
/*******************************************
* FBDIMM - This is the frequency of the DRAM
* For all other configurations the frequency of the
* DRAM is the freq of the memory controller.
* *****************************************/
void DRAM_config::set_dram_frequency(int freq){
if (dram_type != FBD_DDR2) {
if(freq < MIN_DRAM_FREQUENCY){
memory_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
memory_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
memory_frequency = freq;
}
dram_frequency = memory_frequency;
}
else if(freq < MIN_DRAM_FREQUENCY){
dram_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
dram_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
dram_frequency = freq;
}
memory2dram_freq_ratio = (float)memory_frequency/dram_frequency;
if(dram_power_config != NULL)
dram_power_config->update(freq);
}
void DRAM_config::set_posted_cas(bool flag){
posted_cas_flag = flag;
}
int DRAM_config::get_dram_frequency(){
return dram_frequency;
}
int DRAM_config::get_memory_frequency(){
return memory_frequency;
}
void DRAM_config::set_memory_frequency(int freq) { /* FBD-DIMM only*/
if(freq < MIN_DRAM_FREQUENCY){
memory_frequency = MIN_DRAM_FREQUENCY; /* MIN DRAM freq */
} else if (freq > MAX_DRAM_FREQUENCY){
memory_frequency = MAX_DRAM_FREQUENCY; /* MAX DRAM freq */
} else {
memory_frequency = freq;
}
set_cpu_memory_frequency_ratio( );
}
int DRAM_config::get_dram_channel_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return channel_count;
}
void DRAM_config::set_dram_channel_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
channel_count = MIN(MAX(1,count),MAX_CHANNEL_COUNT);
}
int DRAM_config::get_dram_rank_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return rank_count;
}
void DRAM_config::set_dram_rank_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
rank_count = MIN(MAX(1,count),MAX_RANK_COUNT);
}
void DRAM_config::set_dram_bank_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
bank_count = count;
}
int DRAM_config::get_dram_bank_count(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return bank_count;
}
int DRAM_config::get_dram_row_buffer_management_policy(){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
return row_buffer_management_policy;
}
void DRAM_config::set_dram_row_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
row_count = count;
}
void DRAM_config::set_dram_buffer_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
up_buffer_cnt= MIN(MAX(1,count),MAX_AMB_BUFFER_COUNT);
down_buffer_cnt= MIN(MAX(1,count),MAX_AMB_BUFFER_COUNT);
}
int DRAM_config::get_dram_row_count(){
return row_count;
}
int DRAM_config::get_dram_col_count(){
return col_count;
}
void DRAM_config::set_dram_col_count(int count){ /* set 1 <= channel_count <= MAX_CHANNEL_COUNT */
col_count = count;
}
void DRAM_config::set_dram_channel_width(int width){
channel_width = MAX(MIN_CHANNEL_WIDTH,width); /* smallest width is 2 bytes */
t_burst = MAX(1,cacheline_size / channel_width);
}
void DRAM_config::set_dram_transaction_granularity(int size){
cacheline_size = MAX(MIN_CACHE_LINE_SIZE,size); /*bytes */
t_burst = MAX(1,cacheline_size / channel_width);
data_cmd_count = MAX(1,cacheline_size/DATA_BYTES_PER_WRITE_BUNDLE);
}
void DRAM_config::set_pa_mapping_policy(int policy){
physical_address_mapping_policy = policy;
}
void DRAM_config::set_dram_row_buffer_management_policy(int policy){
row_buffer_management_policy = policy;
}
void DRAM_config::set_dram_refresh_policy(int policy){
refresh_policy = policy;
refresh_cycle_count = (tick_t)((refresh_time/row_count)*dram_frequency);
/* Time between each refresh command */
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
else if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count);
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
}
void DRAM_config::set_dram_refresh_time(int time){
refresh_time = time;
refresh_cycle_count = (refresh_time/row_count)*dram_frequency;
/* Time between each refresh command */
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count );
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
}
/* oppourtunistic vs highest priority */
void DRAM_config::set_dram_refresh_issue_policy(int policy){
refresh_issue_policy = policy;
}
void DRAM_config::set_fbd_var_latency_flag(int value) {
if (value) {
var_latency_flag = true;
}else {
var_latency_flag = false;
}
}
void DRAM_config::set_dram_debug(int debug_status){
dram_debug_flag = debug_status;
}
void DRAM_config::set_issue_debug(int debug_status){
issue_debug_flag = debug_status;
}
void DRAM_config::set_addr_debug(int debug_status){
addr_debug_flag = debug_status;
}
void DRAM_config::set_wave_debug(int debug_status){
wave_debug_flag = debug_status;
}
void DRAM_config::set_wave_cas_debug(int debug_status){
wave_cas_debug_flag = debug_status;
}
void DRAM_config::set_bundle_debug(int debug_status){
bundle_debug_flag = debug_status;
}
void DRAM_config::set_amb_buffer_debug(int debug_status){
amb_buffer_debug_flag = debug_status;
}
/** FB-DIMM : set methods **/
void DRAM_config::set_dram_up_channel_width(int width) {
up_channel_width = width;
/** FIXME : Add code to set t_burst i.e. transmission time for data
* packets*/
}
void DRAM_config::set_dram_down_channel_width(int width) {
down_channel_width = width;
/** FIXME : Add code to set t_burst i.e. transmission time for data
* packets*/
}
void DRAM_config::set_t_bundle(int bundle) {
t_bundle = bundle;
}
void DRAM_config::set_t_bus(int bus) {
t_bus = bus;
}
/* This has to be enabled late */
void DRAM_config::enable_auto_refresh(int flag, int refresh_time_ms){
if(flag == TRUE){
auto_refresh_enabled = TRUE;
refresh_time = refresh_time_ms * 1000.0; /* input is in milliseconds, keep here in microseconds */
refresh_cycle_count = (int) (refresh_time * dram_frequency/row_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count * bank_count);
if (refresh_policy == REFRESH_ONE_CHAN_ONE_RANK_ALL_BANK)
refresh_cycle_count = refresh_cycle_count/(rank_count );
else if (refresh_policy == REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK)
refresh_cycle_count = refresh_cycle_count/(bank_count);
} else {
auto_refresh_enabled = FALSE;
}
}
void DRAM_config::set_independent_threads(){
int i;
int j;
int num_threads = 0;
for (i=0;i<num_thread_sets;i++) {
for (j=0;j<thread_sets[i];j++) {
thread_set_map[num_threads++] = i;
}
}
}
int DRAM_config::addr_debug(){
return (addr_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::dram_debug(){
return (dram_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::wave_debug(){
return (wave_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::cas_wave_debug(){
return (wave_cas_debug_flag);
}
int DRAM_config::bundle_debug(){
return (bundle_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
int DRAM_config::amb_buffer_debug(){
return (amb_buffer_debug_flag &&
(tq_info.transaction_id_ctr >= tq_info.debug_tran_id_threshold));
}
void DRAM_config::set_strict_ordering(int flag){
strict_ordering_flag = flag;
}
void DRAM_config::set_transaction_debug(int debug_status){
tq_info.debug_flag = debug_status;
}
void DRAM_config::set_debug_tran_id_threshold(uint64_t dtit){
tq_info.debug_tran_id_threshold = dtit;
}
void DRAM_config::set_tran_watch(uint64_t tran_id){
tq_info.tran_watch_flag = TRUE;
tq_info.tran_watch_id = tran_id;
}
int DRAM_config::get_tran_watch(uint64_t tran_id) {
return tq_info.tran_watch_flag &&
tq_info.tran_watch_id == tran_id;
}
void DRAM_config::set_ref_tran_watch(uint64_t tran_id){
watch_refresh = TRUE;
ref_tran_id = tran_id;
}
int DRAM_config::get_ref_tran_watch(uint64_t tran_id) {
return watch_refresh &&
ref_tran_id == tran_id;
}
void DRAM_config::print_dram_type( int dram_type, FILE *stream ) {
fprintf(stream, " dram_type: ");
switch( dram_type ) {
case SDRAM: fprintf(stream, "sdram\n");
break;
case DDRSDRAM: fprintf(stream, "ddrsdram\n");
break;
case DDR2: fprintf(stream, "ddr2\n");
break;
case DDR3: fprintf(stream, "ddr3\n");
break;
case FBD_DDR2: fprintf(stream, "fbd_ddr2\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_pa_mapping_policy( int papolicy, FILE *stream ) {
fprintf(stream, " physical address mapping_policy: ");
switch( papolicy ) {
case BURGER_BASE_MAP: fprintf(stream, "burger_base_map\n");
break;
case BURGER_ALT_MAP: fprintf(stream, "burger_alt_map\n");
break;
case SDRAM_BASE_MAP: fprintf(stream, "sdram_base_map\n");
break;
case SDRAM_HIPERF_MAP: fprintf(stream, "sdram_hiperf_map\n");
break;
case INTEL845G_MAP: fprintf(stream, "intel845g_map\n");
break;
case SDRAM_CLOSE_PAGE_MAP: fprintf(stream, "sdram_close_page_map\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_row_policy( int rowpolicy, FILE *stream ) {
fprintf(stream, " row_buffer_management_policy: ");
switch( rowpolicy ) {
case OPEN_PAGE: fprintf(stream, "open_page\n");
break;
case CLOSE_PAGE: fprintf(stream, "close_page\n");
break;
case PERFECT_PAGE: fprintf(stream, "perfect_page\n");
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_refresh_policy( int refreshpolicy, FILE *stream ) {
fprintf(stream, " row_buffer_management_policy: ");
switch( refreshpolicy ) {
case REFRESH_ONE_CHAN_ALL_RANK_ALL_BANK: fprintf(stream, "refresh_one_chan_all_rank_all_bank\n");
break;
case REFRESH_ONE_CHAN_ALL_RANK_ONE_BANK: fprintf(stream, "refresh_one_chan_all_rank_one_bank\n");
break;
case REFRESH_ONE_CHAN_ONE_RANK_ONE_BANK: fprintf(stream, "refresh_one_chan_one_rank_one_bank\n");
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::print_trans_policy( int policy, FILE *stream ) {
fprintf(stream, " transaction_selection_policy: ");
switch( policy ) {
case WANG: fprintf(stream, "wang\n");
break;
case LEAST_PENDING: fprintf(stream, "least pending\n");
break;
case MOST_PENDING: fprintf(stream, "most pending\n");
break;
case OBF: fprintf(stream, "open bank first\n");
break;
case RIFF: fprintf(stream, "Read Instruction Fetch First\n");
break;
case FCFS: fprintf(stream, "First Come first Serve\n");
break;
case GREEDY: fprintf(stream, "greedy\n");
break;
default: fprintf(stream, "unknown\n");
break;
}
}
void DRAM_config::set_cpu_frequency( int freq){
if(freq < MIN_CPU_FREQUENCY){
cpu_frequency = MIN_CPU_FREQUENCY;
fprintf(stdout,"\n\n\n\n\n\n\n\nWARNING: CPU frequency set to minimum allowed frequency [%d] MHz\n\n\n\n\n\n",cpu_frequency);
} else if (freq > MAX_CPU_FREQUENCY){
cpu_frequency = MAX_CPU_FREQUENCY;
fprintf(stdout,"\n\n\n\n\n\n\n\nWARNING: CPU frequency set to maximum allowed frequency [%d] MHz\n\n\n\n\n\n",cpu_frequency);
} else {
cpu_frequency = freq;
}
set_cpu_memory_frequency_ratio( );
}
int DRAM_config::get_cpu_frequency(){
return cpu_frequency;
}
/***
* This function sets the raito of the cpu 2 memory controller frequency
* Note in FBDIMM only is the memory controller freq diff from the dram freq
* Old function in Daves original code set_cpu_dram_frequency_ratio
* **/
void DRAM_config::set_cpu_memory_frequency_ratio( ){
mem2cpu_clock_ratio = (double) memory_frequency / (double) cpu_frequency;
cpu2mem_clock_ratio = (double) cpu_frequency / (double) memory_frequency;
}
void DRAM_config::set_transaction_selection_policy( int policy){
transaction_selection_policy = policy;
}
int DRAM_config::get_transaction_selection_policy(){
return transaction_selection_policy;
}
int DRAM_config::get_num_ifetch() {
return tq_info.num_ifetch_tran;
}
int DRAM_config::get_num_prefetch() {
return tq_info.num_prefetch_tran;
}
int DRAM_config::get_num_read() {
return tq_info.num_read_tran;
}
int DRAM_config::get_num_write() {
return tq_info.num_write_tran;
}
int DRAM_config::get_biu_queue_depth (){
return bus_queue_depth;
}
void DRAM_config::set_biu_depth(int depth){
bus_queue_depth = MAX(1,depth);
}
| [
"brian.lebiednik@gmail.com"
] | brian.lebiednik@gmail.com |
4a843629d5d1c73fecc2da0187c9769d79d265aa | 98998787f7d2fe79e4438ffc3c01b049824bedbc | /Data Structures/Graph C++/graph.h | 8a947f2a90ada1d3981790434a8769a5dd68882a | [] | no_license | Niangmodou/Cpp-DataStructures-Algorithms | 41f15377bfbb28828db8426aa75be5401578a2f1 | fbff402cafa94ffccb3ef34edbe072382e6f1eb6 | refs/heads/master | 2022-04-14T05:14:56.013694 | 2020-04-06T01:56:09 | 2020-04-06T01:56:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 501 | h | #include <iostream>
#include <vector>
#include <set>
struct Node{
Node(int data = 0);
int data;
std::vector<Node*>;
};
class Graph{
private:
size_t numVerticies;
std::set<int> verticies;
std::vector< std::vector<Node*>> adjacenyList;
public:
Graph();
~Graph();
Graph& operator=(const Graph&);
Graph(const Graph&);
size_t size();
//checks if a number is already in our set of verticies
bool inGraph(int) const;
Node* findNode(int) const;
void addEdge(int,int);
printGraph();
} | [
"niangmodou100@gmail.com"
] | niangmodou100@gmail.com |
0f1d1fdb9351d125b48a756d9f3a897a2d55f011 | 806fdce612d3753d219e7b3474c52a419e382fb1 | /Renderer/RendererBackend/Direct3D11Renderer/include/Direct3D11Renderer/RootSignature.h | 1011490a154f67d81bded029952ab074887e1a68 | [
"MIT"
] | permissive | whaison/unrimp | 4ca650ac69e4e8fd09b35d9caa198fe05a0246a3 | 8fb5dfb80a3818b0b12e474160602cded4972d11 | refs/heads/master | 2021-01-11T15:19:21.726753 | 2017-01-25T19:55:54 | 2017-01-25T21:55:34 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,888 | h | /*********************************************************\
* Copyright (c) 2012-2017 The Unrimp Team
*
* 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.
\*********************************************************/
//[-------------------------------------------------------]
//[ Header guard ]
//[-------------------------------------------------------]
#pragma once
//[-------------------------------------------------------]
//[ Includes ]
//[-------------------------------------------------------]
#include <Renderer/IRootSignature.h>
#include <Renderer/RootSignatureTypes.h>
//[-------------------------------------------------------]
//[ Forward declarations ]
//[-------------------------------------------------------]
namespace Direct3D11Renderer
{
class Direct3D11Renderer;
}
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
namespace Direct3D11Renderer
{
//[-------------------------------------------------------]
//[ Classes ]
//[-------------------------------------------------------]
/**
* @brief
* Direct3D 11 root signature ("pipeline layout" in Vulkan terminology) class
*/
class RootSignature : public Renderer::IRootSignature
{
//[-------------------------------------------------------]
//[ Public methods ]
//[-------------------------------------------------------]
public:
/**
* @brief
* Constructor
*
* @param[in] direct3D11Renderer
* Owner Direct3D 11 renderer instance
* @param[in] rootSignature
* Root signature to use
*/
RootSignature(Direct3D11Renderer &direct3D11Renderer, const Renderer::RootSignature &rootSignature);
/**
* @brief
* Destructor
*/
virtual ~RootSignature();
/**
* @brief
* Return the root signature data
*
* @return
* The root signature data
*/
inline const Renderer::RootSignature& getRootSignature() const;
//[-------------------------------------------------------]
//[ Private data ]
//[-------------------------------------------------------]
private:
Renderer::RootSignature mRootSignature;
};
//[-------------------------------------------------------]
//[ Namespace ]
//[-------------------------------------------------------]
} // Direct3D11Renderer
//[-------------------------------------------------------]
//[ Implementation ]
//[-------------------------------------------------------]
#include "Direct3D11Renderer/RootSignature.inl"
| [
"cofenberg@gmail.com"
] | cofenberg@gmail.com |
0ac3a1da96544775e71947d71648ef12b20d9950 | 1dd825971ed4ec0193445dc9ed72d10618715106 | /examples/extended/hadronic/Hadr02/include/G4UrQMD1_3Model.hh | b508864984d593e3a0977dcbacf5f07cc4d010b4 | [] | no_license | gfh16/Geant4 | 4d442e5946eefc855436f4df444c245af7d3aa81 | d4cc6c37106ff519a77df16f8574b2fe4ad9d607 | refs/heads/master | 2021-06-25T22:32:21.104339 | 2020-11-02T13:12:01 | 2020-11-02T13:12:01 | 158,790,658 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,179 | hh | //
// ********************************************************************
// * License and Disclaimer *
// * *
// * The Geant4 software is copyright of the Copyright Holders of *
// * the Geant4 Collaboration. It is provided under the terms and *
// * conditions of the Geant4 Software License, included in the file *
// * LICENSE and available at http://cern.ch/geant4/license . These *
// * include a list of copyright holders. *
// * *
// * Neither the authors of this software system, nor their employing *
// * institutes,nor the agencies providing financial support for this *
// * work make any representation or warranty, express or implied, *
// * regarding this software system or assume any liability for its *
// * use. Please see the license in the file LICENSE and URL above *
// * for the full disclaimer and the limitation of liability. *
// * *
// * This code implementation is the result of the scientific and *
// * technical work of the GEANT4 collaboration. *
// * *
// * Parts of this code which have been developed by Abdel-Waged *
// * et al under contract (31-465) to the King Abdul-Aziz City for *
// * Science and Technology (KACST), the National Centre of *
// * Mathematics and Physics (NCMP), Saudi Arabia. *
// * *
// * By using, copying, modifying or distributing the software (or *
// * any work based on the software) you agree to acknowledge its *
// * use in resulting scientific publications, and indicate your *
// * acceptance of all terms of the Geant4 Software license. *
// ********************************************************************
//
/// \file hadronic/Hadr02/include/G4UrQMD1_3Model.hh
/// \brief Definition of the G4UrQMD1_3Model class
//
// $Id$
//
#ifndef G4UrQMD1_3Model_hh
#define G4UrQMD1_3Model_hh
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// MODULE: G4UrQMD1_3Model.hh
//
// Version: 0.B
// Date: 20/10/12
// Author: Kh. Abdel-Waged and Nuha Felemban
// Revised by: V.V. Uzhinskii
// SPONSERED BY
// Customer: KAUST/NCMP
// Contract: 31-465
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
//
// Class Description
//
//
// Class Description - End
//
// %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
///////////////////////////////////////////////////////////////////////////////
#include "G4Nucleon.hh"
#include "G4Nucleus.hh"
#include "G4VIntraNuclearTransportModel.hh"
#include "G4KineticTrackVector.hh"
#include "G4FragmentVector.hh"
#include "G4ParticleChange.hh"
#include "G4ReactionProductVector.hh"
#include "G4ReactionProduct.hh"
#include "G4IntraNucleiCascader.hh"
#include "G4Track.hh"
#include <fstream>
#include <string>
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
class G4UrQMD1_3Model : public G4VIntraNuclearTransportModel {
public:
G4UrQMD1_3Model(const G4String& name = "UrQMD1_3");
virtual ~G4UrQMD1_3Model ();
G4ReactionProductVector* Propagate(G4KineticTrackVector*
theSecondaries,
G4V3DNucleus* theTarget);
virtual G4HadFinalState* ApplyYourself(const G4HadProjectile&,
G4Nucleus&);
private:
G4int operator==(G4UrQMD1_3Model& right);
G4int operator!=(G4UrQMD1_3Model& right);
void InitialiseDataTables();
void WelcomeMessage () const;
G4int CurrentEvent;
G4int verbose;
G4HadFinalState theResult;
};
#endif
| [
"gfh16@mails.tsinghua.edu.cn"
] | gfh16@mails.tsinghua.edu.cn |
0c8bef0e31c3ae8be762f14676a19c8c7f02b391 | fe7519308d99558da2ba14a8a5235166039496bb | /src/Models/Embedded/AchievedCommands/AchievedCommands.cpp | da923043c7353adcf8678d7a65f4e74f71fea24b | [] | no_license | SwaggyTyrion/MissileSim | c1953b1c1bd275d4d1ae4642bd75ecb13757c9d5 | c49088247f34c7fbfb1d86fe73261d6735321a88 | refs/heads/master | 2020-06-15T13:09:29.841446 | 2016-12-28T18:30:01 | 2016-12-28T18:30:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,844 | cpp | //
// AchievedCommands.cpp
// MissileSim
//
// Created by Christian J Howard on 9/30/16.
// Copyright © 2016 Christian Howard. All rights reserved.
//
#include "AchievedCommands.hpp"
#include "MissileModel.hpp"
#include "ProNav.hpp"
#include "CoordTransforms.hpp"
#include "Gravity84.hpp"
#include <math.h>
#include "TargetModel.hpp"
AchievedCommands::AchievedCommands():missile(0) {
}
void AchievedCommands::setMissile( MissileModel & missile_ ) {
missile = &missile_;
}
void AchievedCommands::getForce( double time, vec3 & outForceBody ) {
LatLongAlt null;
const TargetModel & targ = *missile->target;
const LatLongAlt & start = missile->eom.getCurrentCoord();
const quat & q = missile->eom.getAttitude();
quat P;
vec3 accelENU;
pronav::R = CoordTransforms::getRelativeENU(start, targ.eom.getCurrentCoord()) ;
mat3 ecef2enu = CoordTransforms::ECEFtoENU_Matrix(start);
pronav::V = ecef2enu * (targ.eom.getVel() - missile->eom.getVel());
pronav::computeCommandedAccel(accelENU);
vec3 g( 0, 0, -Earth::Gravity84::obtainGravityWithCoordinate(start) );
accelENU = (accelENU + g)*missile->getMass();
P.setVectorPart( CoordTransforms::ENUtoNED(accelENU) );
outForceBody = (q.getInverse() * P * q).getVectorPart();
const double G = 9.81;
const double MAX_FORCE = 5.0*G*missile->getMass();
outForceBody[0] = sign(outForceBody[0])*std::min(MAX_FORCE, fabs(outForceBody[0]));
outForceBody[1] = sign(outForceBody[1])*std::min(MAX_FORCE, fabs(outForceBody[1]));
outForceBody[2] = sign(outForceBody[2])*std::min(MAX_FORCE, fabs(outForceBody[2]));
}
void AchievedCommands::getMoment( double time, vec3 & outMomentBody ) {
}
void AchievedCommands::getLocation( double time, vec3 & locBody ) {
locBody[0] = locBody[1] = locBody[2] = 0.0;
}
| [
"choward1491@gmail.com"
] | choward1491@gmail.com |
c8b944e4911a3201c02cb369db7a2b946a910873 | 8a2f29a448f953a757e3421a1494bd575b6d324f | /orig/HeadCoupledPerspective/CPUT/CPUT/CPUTEventHandler.h | e31aaf6378f4be466901a369f42bd69bf60a6faa | [] | no_license | SRP2504/clap_project | 5c203e0b36632b29ec66b7974e0630177678910d | c5d0e11a24484e89991a38574e0b9866526bc276 | refs/heads/master | 2016-09-05T20:08:48.528622 | 2014-03-16T16:48:54 | 2014-03-16T16:48:54 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,738 | h | //--------------------------------------------------------------------------------------
// Copyright 2011 Intel Corporation
// All Rights Reserved
//
// Permission is granted to use, copy, distribute and prepare derivative works of this
// software for any purpose and without fee, provided, that the above copyright notice
// and this statement appear in all copies. Intel makes no representations about the
// suitability of this software for any purpose. THIS SOFTWARE IS PROVIDED "AS IS."
// INTEL SPECIFICALLY DISCLAIMS ALL WARRANTIES, EXPRESS OR IMPLIED, AND ALL LIABILITY,
// INCLUDING CONSEQUENTIAL AND OTHER INDIRECT DAMAGES, FOR THE USE OF THIS SOFTWARE,
// INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PROPRIETARY RIGHTS, AND INCLUDING THE
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. Intel does not
// assume any responsibility for any errors which may appear in this software nor any
// responsibility to update it.
//--------------------------------------------------------------------------------------
#ifndef __CPUTEVENTHANDLER_H__
#define __CPUTEVENTHANDLER_H__
#include <stdio.h>
// event handling enums
//-----------------------------------------------------------------------------
enum CPUTKey
{
KEY_NONE,
// caps keys
KEY_A,
KEY_B,
KEY_C,
KEY_D,
KEY_E,
KEY_F,
KEY_G,
KEY_H,
KEY_I,
KEY_J,
KEY_K,
KEY_L,
KEY_M,
KEY_N,
KEY_O,
KEY_P,
KEY_Q,
KEY_R,
KEY_S,
KEY_T,
KEY_U,
KEY_V,
KEY_W,
KEY_X,
KEY_Y,
KEY_Z,
// number keys
KEY_1,
KEY_2,
KEY_3,
KEY_4,
KEY_5,
KEY_6,
KEY_7,
KEY_8,
KEY_9,
KEY_0,
// symbols
KEY_SPACE,
KEY_BACKQUOTE,
KEY_TILDE,
KEY_EXCLAMATION,
KEY_AT,
KEY_HASH,
KEY_$,
KEY_PERCENT,
KEY_CARROT,
KEY_ANDSIGN,
KEY_STAR,
KEY_OPENPAREN,
KEY_CLOSEPARN,
KEY__,
KEY_MINUS,
KEY_PLUS,
KEY_OPENBRACKET,
KEY_CLOSEBRACKET,
KEY_OPENBRACE,
KEY_CLOSEBRACE,
KEY_BACKSLASH,
KEY_PIPE,
KEY_SEMICOLON,
KEY_COLON,
KEY_SINGLEQUOTE,
KEY_QUOTE,
KEY_COMMA,
KEY_PERIOD,
KEY_SLASH,
KEY_LESS,
KEY_GREATER,
KEY_QUESTION,
// function keys
KEY_F1,
KEY_F2,
KEY_F3,
KEY_F4,
KEY_F5,
KEY_F6,
KEY_F7,
KEY_F8,
KEY_F9,
KEY_F10,
KEY_F11,
KEY_F12,
// special keys
KEY_HOME,
KEY_END,
KEY_INSERT,
KEY_DELETE,
KEY_PAGEUP,
KEY_PAGEDOWN,
KEY_UP,
KEY_DOWN,
KEY_LEFT,
KEY_RIGHT,
KEY_BACKSPACE,
KEY_ENTER,
KEY_TAB,
KEY_PAUSE,
KEY_CAPSLOCK,
KEY_ESCAPE,
// control keys
KEY_LEFT_SHIFT,
KEY_RIGHT_SHIFT,
KEY_LEFT_CTRL,
KEY_RIGHT_CTRL,
KEY_LEFT_ALT,
KEY_RIGHT_ALT,
};
// these must be unique because we bitwise && them to get multiple states
enum CPUTMouseState
{
CPUT_MOUSE_NONE = 0,
CPUT_MOUSE_LEFT_DOWN = 1,
CPUT_MOUSE_RIGHT_DOWN = 2,
CPUT_MOUSE_MIDDLE_DOWN = 4,
CPUT_MOUSE_CTRL_DOWN = 8,
CPUT_MOUSE_SHIFT_DOWN = 16,
CPUT_MOUSE_WHEEL = 32,
};
enum CPUTEventHandledCode
{
CPUT_EVENT_HANDLED = 0,
CPUT_EVENT_UNHANDLED = 1,
CPUT_EVENT_PASSTHROUGH = 2,
};
// Event handler interface - used by numerous classes in the system
class CPUTEventHandler
{
public:
virtual CPUTEventHandledCode HandleKeyboardEvent(CPUTKey key)=0;
virtual CPUTEventHandledCode HandleMouseEvent(int x, int y, int wheel, CPUTMouseState state)=0;
};
#endif //#ifndef __CPUTEVENTHANDLER_H__ | [
"srp201201051@gmail.com"
] | srp201201051@gmail.com |
fa429d4690761c57ce37e41ef32069cff2afa378 | 6393b2fffc38998362aa4510c502186bcbac937c | /src/KOPSMsg_m.cc | 2dc2fe863239a5a0f2a4b8f7555249f96617a14c | [] | no_license | rodneyamanor/BLE-Link | 1412c308c0bdc69291803435e55661cb37036f3e | 39d43823e385308ca10826be145758ebc4a56d95 | refs/heads/main | 2023-02-07T19:35:14.211980 | 2021-01-03T04:05:57 | 2021-01-03T04:05:57 | 326,323,161 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 118,889 | cc | //
// Generated file, do not edit! Created by nedtool 5.4 from KOPSMsg.msg.
//
// Disable warnings about unused variables, empty switch stmts, etc:
#ifdef _MSC_VER
# pragma warning(disable:4101)
# pragma warning(disable:4065)
#endif
#if defined(__clang__)
# pragma clang diagnostic ignored "-Wshadow"
# pragma clang diagnostic ignored "-Wconversion"
# pragma clang diagnostic ignored "-Wunused-parameter"
# pragma clang diagnostic ignored "-Wc++98-compat"
# pragma clang diagnostic ignored "-Wunreachable-code-break"
# pragma clang diagnostic ignored "-Wold-style-cast"
#elif defined(__GNUC__)
# pragma GCC diagnostic ignored "-Wshadow"
# pragma GCC diagnostic ignored "-Wconversion"
# pragma GCC diagnostic ignored "-Wunused-parameter"
# pragma GCC diagnostic ignored "-Wold-style-cast"
# pragma GCC diagnostic ignored "-Wsuggest-attribute=noreturn"
# pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
#include <iostream>
#include <sstream>
#include "KOPSMsg_m.h"
namespace omnetpp {
// Template pack/unpack rules. They are declared *after* a1l type-specific pack functions for multiple reasons.
// They are in the omnetpp namespace, to allow them to be found by argument-dependent lookup via the cCommBuffer argument
// Packing/unpacking an std::vector
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::vector<T,A>& v)
{
int n = v.size();
doParsimPacking(buffer, n);
for (int i = 0; i < n; i++)
doParsimPacking(buffer, v[i]);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::vector<T,A>& v)
{
int n;
doParsimUnpacking(buffer, n);
v.resize(n);
for (int i = 0; i < n; i++)
doParsimUnpacking(buffer, v[i]);
}
// Packing/unpacking an std::list
template<typename T, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::list<T,A>& l)
{
doParsimPacking(buffer, (int)l.size());
for (typename std::list<T,A>::const_iterator it = l.begin(); it != l.end(); ++it)
doParsimPacking(buffer, (T&)*it);
}
template<typename T, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::list<T,A>& l)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
l.push_back(T());
doParsimUnpacking(buffer, l.back());
}
}
// Packing/unpacking an std::set
template<typename T, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::set<T,Tr,A>& s)
{
doParsimPacking(buffer, (int)s.size());
for (typename std::set<T,Tr,A>::const_iterator it = s.begin(); it != s.end(); ++it)
doParsimPacking(buffer, *it);
}
template<typename T, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::set<T,Tr,A>& s)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
T x;
doParsimUnpacking(buffer, x);
s.insert(x);
}
}
// Packing/unpacking an std::map
template<typename K, typename V, typename Tr, typename A>
void doParsimPacking(omnetpp::cCommBuffer *buffer, const std::map<K,V,Tr,A>& m)
{
doParsimPacking(buffer, (int)m.size());
for (typename std::map<K,V,Tr,A>::const_iterator it = m.begin(); it != m.end(); ++it) {
doParsimPacking(buffer, it->first);
doParsimPacking(buffer, it->second);
}
}
template<typename K, typename V, typename Tr, typename A>
void doParsimUnpacking(omnetpp::cCommBuffer *buffer, std::map<K,V,Tr,A>& m)
{
int n;
doParsimUnpacking(buffer, n);
for (int i=0; i<n; i++) {
K k; V v;
doParsimUnpacking(buffer, k);
doParsimUnpacking(buffer, v);
m[k] = v;
}
}
// Default pack/unpack function for arrays
template<typename T>
void doParsimArrayPacking(omnetpp::cCommBuffer *b, const T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimPacking(b, t[i]);
}
template<typename T>
void doParsimArrayUnpacking(omnetpp::cCommBuffer *b, T *t, int n)
{
for (int i = 0; i < n; i++)
doParsimUnpacking(b, t[i]);
}
// Default rule to prevent compiler from choosing base class' doParsimPacking() function
template<typename T>
void doParsimPacking(omnetpp::cCommBuffer *, const T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimPacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
template<typename T>
void doParsimUnpacking(omnetpp::cCommBuffer *, T& t)
{
throw omnetpp::cRuntimeError("Parsim error: No doParsimUnpacking() function for type %s", omnetpp::opp_typename(typeid(t)));
}
} // namespace omnetpp
// forward
template<typename T, typename A>
std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec);
// Template rule which fires if a struct or class doesn't have operator<<
template<typename T>
inline std::ostream& operator<<(std::ostream& out,const T&) {return out;}
// operator<< for std::vector<T>
template<typename T, typename A>
inline std::ostream& operator<<(std::ostream& out, const std::vector<T,A>& vec)
{
out.put('{');
for(typename std::vector<T,A>::const_iterator it = vec.begin(); it != vec.end(); ++it)
{
if (it != vec.begin()) {
out.put(','); out.put(' ');
}
out << *it;
}
out.put('}');
char buf[32];
sprintf(buf, " (size=%u)", (unsigned int)vec.size());
out.write(buf, strlen(buf));
return out;
}
Register_Class(KDataMsg)
KDataMsg::KDataMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->msgType = 0;
this->validUntilTime = 0;
this->msgUniqueID = 0;
this->initialInjectionTime = 0;
this->realPayloadSize = 0;
this->realPacketSize = 0;
this->hopsTravelled = 0;
this->destinationOriented = false;
this->goodnessValue = 50;
this->hopCount = 255;
this->duplicates = 0;
}
KDataMsg::KDataMsg(const KDataMsg& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
KDataMsg::~KDataMsg()
{
}
KDataMsg& KDataMsg::operator=(const KDataMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KDataMsg::copy(const KDataMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->dataName = other.dataName;
this->dummyPayloadContent = other.dummyPayloadContent;
this->msgType = other.msgType;
this->validUntilTime = other.validUntilTime;
this->msgUniqueID = other.msgUniqueID;
this->initialInjectionTime = other.initialInjectionTime;
this->realPayloadSize = other.realPayloadSize;
this->realPacketSize = other.realPacketSize;
this->hopsTravelled = other.hopsTravelled;
this->initialOriginatorAddress = other.initialOriginatorAddress;
this->finalDestinationAddress = other.finalDestinationAddress;
this->destinationOriented = other.destinationOriented;
this->goodnessValue = other.goodnessValue;
this->messageID = other.messageID;
this->hopCount = other.hopCount;
this->duplicates = other.duplicates;
}
void KDataMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->dataName);
doParsimPacking(b,this->dummyPayloadContent);
doParsimPacking(b,this->msgType);
doParsimPacking(b,this->validUntilTime);
doParsimPacking(b,this->msgUniqueID);
doParsimPacking(b,this->initialInjectionTime);
doParsimPacking(b,this->realPayloadSize);
doParsimPacking(b,this->realPacketSize);
doParsimPacking(b,this->hopsTravelled);
doParsimPacking(b,this->initialOriginatorAddress);
doParsimPacking(b,this->finalDestinationAddress);
doParsimPacking(b,this->destinationOriented);
doParsimPacking(b,this->goodnessValue);
doParsimPacking(b,this->messageID);
doParsimPacking(b,this->hopCount);
doParsimPacking(b,this->duplicates);
}
void KDataMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->dataName);
doParsimUnpacking(b,this->dummyPayloadContent);
doParsimUnpacking(b,this->msgType);
doParsimUnpacking(b,this->validUntilTime);
doParsimUnpacking(b,this->msgUniqueID);
doParsimUnpacking(b,this->initialInjectionTime);
doParsimUnpacking(b,this->realPayloadSize);
doParsimUnpacking(b,this->realPacketSize);
doParsimUnpacking(b,this->hopsTravelled);
doParsimUnpacking(b,this->initialOriginatorAddress);
doParsimUnpacking(b,this->finalDestinationAddress);
doParsimUnpacking(b,this->destinationOriented);
doParsimUnpacking(b,this->goodnessValue);
doParsimUnpacking(b,this->messageID);
doParsimUnpacking(b,this->hopCount);
doParsimUnpacking(b,this->duplicates);
}
const char * KDataMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KDataMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KDataMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KDataMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
const char * KDataMsg::getDataName() const
{
return this->dataName.c_str();
}
void KDataMsg::setDataName(const char * dataName)
{
this->dataName = dataName;
}
const char * KDataMsg::getDummyPayloadContent() const
{
return this->dummyPayloadContent.c_str();
}
void KDataMsg::setDummyPayloadContent(const char * dummyPayloadContent)
{
this->dummyPayloadContent = dummyPayloadContent;
}
int KDataMsg::getMsgType() const
{
return this->msgType;
}
void KDataMsg::setMsgType(int msgType)
{
this->msgType = msgType;
}
::omnetpp::simtime_t KDataMsg::getValidUntilTime() const
{
return this->validUntilTime;
}
void KDataMsg::setValidUntilTime(::omnetpp::simtime_t validUntilTime)
{
this->validUntilTime = validUntilTime;
}
int KDataMsg::getMsgUniqueID() const
{
return this->msgUniqueID;
}
void KDataMsg::setMsgUniqueID(int msgUniqueID)
{
this->msgUniqueID = msgUniqueID;
}
::omnetpp::simtime_t KDataMsg::getInitialInjectionTime() const
{
return this->initialInjectionTime;
}
void KDataMsg::setInitialInjectionTime(::omnetpp::simtime_t initialInjectionTime)
{
this->initialInjectionTime = initialInjectionTime;
}
int KDataMsg::getRealPayloadSize() const
{
return this->realPayloadSize;
}
void KDataMsg::setRealPayloadSize(int realPayloadSize)
{
this->realPayloadSize = realPayloadSize;
}
int KDataMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KDataMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
int KDataMsg::getHopsTravelled() const
{
return this->hopsTravelled;
}
void KDataMsg::setHopsTravelled(int hopsTravelled)
{
this->hopsTravelled = hopsTravelled;
}
const char * KDataMsg::getInitialOriginatorAddress() const
{
return this->initialOriginatorAddress.c_str();
}
void KDataMsg::setInitialOriginatorAddress(const char * initialOriginatorAddress)
{
this->initialOriginatorAddress = initialOriginatorAddress;
}
const char * KDataMsg::getFinalDestinationAddress() const
{
return this->finalDestinationAddress.c_str();
}
void KDataMsg::setFinalDestinationAddress(const char * finalDestinationAddress)
{
this->finalDestinationAddress = finalDestinationAddress;
}
bool KDataMsg::getDestinationOriented() const
{
return this->destinationOriented;
}
void KDataMsg::setDestinationOriented(bool destinationOriented)
{
this->destinationOriented = destinationOriented;
}
int KDataMsg::getGoodnessValue() const
{
return this->goodnessValue;
}
void KDataMsg::setGoodnessValue(int goodnessValue)
{
this->goodnessValue = goodnessValue;
}
const char * KDataMsg::getMessageID() const
{
return this->messageID.c_str();
}
void KDataMsg::setMessageID(const char * messageID)
{
this->messageID = messageID;
}
int KDataMsg::getHopCount() const
{
return this->hopCount;
}
void KDataMsg::setHopCount(int hopCount)
{
this->hopCount = hopCount;
}
int KDataMsg::getDuplicates() const
{
return this->duplicates;
}
void KDataMsg::setDuplicates(int duplicates)
{
this->duplicates = duplicates;
}
class KDataMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KDataMsgDescriptor();
virtual ~KDataMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KDataMsgDescriptor)
KDataMsgDescriptor::KDataMsgDescriptor() : omnetpp::cClassDescriptor("KDataMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KDataMsgDescriptor::~KDataMsgDescriptor()
{
delete[] propertynames;
}
bool KDataMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KDataMsg *>(obj)!=nullptr;
}
const char **KDataMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KDataMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KDataMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 18+basedesc->getFieldCount() : 18;
}
unsigned int KDataMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<18) ? fieldTypeFlags[field] : 0;
}
const char *KDataMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"dataName",
"dummyPayloadContent",
"msgType",
"validUntilTime",
"msgUniqueID",
"initialInjectionTime",
"realPayloadSize",
"realPacketSize",
"hopsTravelled",
"initialOriginatorAddress",
"finalDestinationAddress",
"destinationOriented",
"goodnessValue",
"messageID",
"hopCount",
"duplicates",
};
return (field>=0 && field<18) ? fieldNames[field] : nullptr;
}
int KDataMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2;
if (fieldName[0]=='d' && strcmp(fieldName, "dummyPayloadContent")==0) return base+3;
if (fieldName[0]=='m' && strcmp(fieldName, "msgType")==0) return base+4;
if (fieldName[0]=='v' && strcmp(fieldName, "validUntilTime")==0) return base+5;
if (fieldName[0]=='m' && strcmp(fieldName, "msgUniqueID")==0) return base+6;
if (fieldName[0]=='i' && strcmp(fieldName, "initialInjectionTime")==0) return base+7;
if (fieldName[0]=='r' && strcmp(fieldName, "realPayloadSize")==0) return base+8;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+9;
if (fieldName[0]=='h' && strcmp(fieldName, "hopsTravelled")==0) return base+10;
if (fieldName[0]=='i' && strcmp(fieldName, "initialOriginatorAddress")==0) return base+11;
if (fieldName[0]=='f' && strcmp(fieldName, "finalDestinationAddress")==0) return base+12;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationOriented")==0) return base+13;
if (fieldName[0]=='g' && strcmp(fieldName, "goodnessValue")==0) return base+14;
if (fieldName[0]=='m' && strcmp(fieldName, "messageID")==0) return base+15;
if (fieldName[0]=='h' && strcmp(fieldName, "hopCount")==0) return base+16;
if (fieldName[0]=='d' && strcmp(fieldName, "duplicates")==0) return base+17;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KDataMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"string",
"string",
"int",
"simtime_t",
"int",
"simtime_t",
"int",
"int",
"int",
"string",
"string",
"bool",
"int",
"string",
"int",
"int",
};
return (field>=0 && field<18) ? fieldTypeStrings[field] : nullptr;
}
const char **KDataMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KDataMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KDataMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KDataMsg *pp = (KDataMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *KDataMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KDataMsg *pp = (KDataMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KDataMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KDataMsg *pp = (KDataMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return oppstring2string(pp->getDataName());
case 3: return oppstring2string(pp->getDummyPayloadContent());
case 4: return long2string(pp->getMsgType());
case 5: return simtime2string(pp->getValidUntilTime());
case 6: return long2string(pp->getMsgUniqueID());
case 7: return simtime2string(pp->getInitialInjectionTime());
case 8: return long2string(pp->getRealPayloadSize());
case 9: return long2string(pp->getRealPacketSize());
case 10: return long2string(pp->getHopsTravelled());
case 11: return oppstring2string(pp->getInitialOriginatorAddress());
case 12: return oppstring2string(pp->getFinalDestinationAddress());
case 13: return bool2string(pp->getDestinationOriented());
case 14: return long2string(pp->getGoodnessValue());
case 15: return oppstring2string(pp->getMessageID());
case 16: return long2string(pp->getHopCount());
case 17: return long2string(pp->getDuplicates());
default: return "";
}
}
bool KDataMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KDataMsg *pp = (KDataMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setDataName((value)); return true;
case 3: pp->setDummyPayloadContent((value)); return true;
case 4: pp->setMsgType(string2long(value)); return true;
case 5: pp->setValidUntilTime(string2simtime(value)); return true;
case 6: pp->setMsgUniqueID(string2long(value)); return true;
case 7: pp->setInitialInjectionTime(string2simtime(value)); return true;
case 8: pp->setRealPayloadSize(string2long(value)); return true;
case 9: pp->setRealPacketSize(string2long(value)); return true;
case 10: pp->setHopsTravelled(string2long(value)); return true;
case 11: pp->setInitialOriginatorAddress((value)); return true;
case 12: pp->setFinalDestinationAddress((value)); return true;
case 13: pp->setDestinationOriented(string2bool(value)); return true;
case 14: pp->setGoodnessValue(string2long(value)); return true;
case 15: pp->setMessageID((value)); return true;
case 16: pp->setHopCount(string2long(value)); return true;
case 17: pp->setDuplicates(string2long(value)); return true;
default: return false;
}
}
const char *KDataMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KDataMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KDataMsg *pp = (KDataMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
Register_Class(KFeedbackMsg)
KFeedbackMsg::KFeedbackMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->realPacketSize = 0;
this->goodnessValue = 0;
this->feedbackType = 0;
}
KFeedbackMsg::KFeedbackMsg(const KFeedbackMsg& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
KFeedbackMsg::~KFeedbackMsg()
{
}
KFeedbackMsg& KFeedbackMsg::operator=(const KFeedbackMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KFeedbackMsg::copy(const KFeedbackMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->dataName = other.dataName;
this->realPacketSize = other.realPacketSize;
this->goodnessValue = other.goodnessValue;
this->feedbackType = other.feedbackType;
}
void KFeedbackMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->dataName);
doParsimPacking(b,this->realPacketSize);
doParsimPacking(b,this->goodnessValue);
doParsimPacking(b,this->feedbackType);
}
void KFeedbackMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->dataName);
doParsimUnpacking(b,this->realPacketSize);
doParsimUnpacking(b,this->goodnessValue);
doParsimUnpacking(b,this->feedbackType);
}
const char * KFeedbackMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KFeedbackMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KFeedbackMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KFeedbackMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
const char * KFeedbackMsg::getDataName() const
{
return this->dataName.c_str();
}
void KFeedbackMsg::setDataName(const char * dataName)
{
this->dataName = dataName;
}
int KFeedbackMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KFeedbackMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
int KFeedbackMsg::getGoodnessValue() const
{
return this->goodnessValue;
}
void KFeedbackMsg::setGoodnessValue(int goodnessValue)
{
this->goodnessValue = goodnessValue;
}
int KFeedbackMsg::getFeedbackType() const
{
return this->feedbackType;
}
void KFeedbackMsg::setFeedbackType(int feedbackType)
{
this->feedbackType = feedbackType;
}
class KFeedbackMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KFeedbackMsgDescriptor();
virtual ~KFeedbackMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KFeedbackMsgDescriptor)
KFeedbackMsgDescriptor::KFeedbackMsgDescriptor() : omnetpp::cClassDescriptor("KFeedbackMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KFeedbackMsgDescriptor::~KFeedbackMsgDescriptor()
{
delete[] propertynames;
}
bool KFeedbackMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KFeedbackMsg *>(obj)!=nullptr;
}
const char **KFeedbackMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KFeedbackMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KFeedbackMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 6+basedesc->getFieldCount() : 6;
}
unsigned int KFeedbackMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<6) ? fieldTypeFlags[field] : 0;
}
const char *KFeedbackMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"dataName",
"realPacketSize",
"goodnessValue",
"feedbackType",
};
return (field>=0 && field<6) ? fieldNames[field] : nullptr;
}
int KFeedbackMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+3;
if (fieldName[0]=='g' && strcmp(fieldName, "goodnessValue")==0) return base+4;
if (fieldName[0]=='f' && strcmp(fieldName, "feedbackType")==0) return base+5;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KFeedbackMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"string",
"int",
"int",
"int",
};
return (field>=0 && field<6) ? fieldTypeStrings[field] : nullptr;
}
const char **KFeedbackMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KFeedbackMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KFeedbackMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *KFeedbackMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KFeedbackMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return oppstring2string(pp->getDataName());
case 3: return long2string(pp->getRealPacketSize());
case 4: return long2string(pp->getGoodnessValue());
case 5: return long2string(pp->getFeedbackType());
default: return "";
}
}
bool KFeedbackMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setDataName((value)); return true;
case 3: pp->setRealPacketSize(string2long(value)); return true;
case 4: pp->setGoodnessValue(string2long(value)); return true;
case 5: pp->setFeedbackType(string2long(value)); return true;
default: return false;
}
}
const char *KFeedbackMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KFeedbackMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KFeedbackMsg *pp = (KFeedbackMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
Register_Class(KSummaryVectorMsg)
KSummaryVectorMsg::KSummaryVectorMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->realPacketSize = 0;
messageIDHashVector_arraysize = 0;
this->messageIDHashVector = 0;
}
KSummaryVectorMsg::KSummaryVectorMsg(const KSummaryVectorMsg& other) : ::omnetpp::cPacket(other)
{
messageIDHashVector_arraysize = 0;
this->messageIDHashVector = 0;
copy(other);
}
KSummaryVectorMsg::~KSummaryVectorMsg()
{
delete [] this->messageIDHashVector;
}
KSummaryVectorMsg& KSummaryVectorMsg::operator=(const KSummaryVectorMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KSummaryVectorMsg::copy(const KSummaryVectorMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->realPacketSize = other.realPacketSize;
delete [] this->messageIDHashVector;
this->messageIDHashVector = (other.messageIDHashVector_arraysize==0) ? nullptr : new ::omnetpp::opp_string[other.messageIDHashVector_arraysize];
messageIDHashVector_arraysize = other.messageIDHashVector_arraysize;
for (unsigned int i=0; i<messageIDHashVector_arraysize; i++)
this->messageIDHashVector[i] = other.messageIDHashVector[i];
}
void KSummaryVectorMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->realPacketSize);
b->pack(messageIDHashVector_arraysize);
doParsimArrayPacking(b,this->messageIDHashVector,messageIDHashVector_arraysize);
}
void KSummaryVectorMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->realPacketSize);
delete [] this->messageIDHashVector;
b->unpack(messageIDHashVector_arraysize);
if (messageIDHashVector_arraysize==0) {
this->messageIDHashVector = 0;
} else {
this->messageIDHashVector = new ::omnetpp::opp_string[messageIDHashVector_arraysize];
doParsimArrayUnpacking(b,this->messageIDHashVector,messageIDHashVector_arraysize);
}
}
const char * KSummaryVectorMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KSummaryVectorMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KSummaryVectorMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KSummaryVectorMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
int KSummaryVectorMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KSummaryVectorMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
void KSummaryVectorMsg::setMessageIDHashVectorArraySize(unsigned int size)
{
::omnetpp::opp_string *messageIDHashVector2 = (size==0) ? nullptr : new ::omnetpp::opp_string[size];
unsigned int sz = messageIDHashVector_arraysize < size ? messageIDHashVector_arraysize : size;
for (unsigned int i=0; i<sz; i++)
messageIDHashVector2[i] = this->messageIDHashVector[i];
for (unsigned int i=sz; i<size; i++)
messageIDHashVector2[i] = 0;
messageIDHashVector_arraysize = size;
delete [] this->messageIDHashVector;
this->messageIDHashVector = messageIDHashVector2;
}
unsigned int KSummaryVectorMsg::getMessageIDHashVectorArraySize() const
{
return messageIDHashVector_arraysize;
}
const char * KSummaryVectorMsg::getMessageIDHashVector(unsigned int k) const
{
if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k);
return this->messageIDHashVector[k].c_str();
}
void KSummaryVectorMsg::setMessageIDHashVector(unsigned int k, const char * messageIDHashVector)
{
if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k);
this->messageIDHashVector[k] = messageIDHashVector;
}
class KSummaryVectorMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KSummaryVectorMsgDescriptor();
virtual ~KSummaryVectorMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KSummaryVectorMsgDescriptor)
KSummaryVectorMsgDescriptor::KSummaryVectorMsgDescriptor() : omnetpp::cClassDescriptor("KSummaryVectorMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KSummaryVectorMsgDescriptor::~KSummaryVectorMsgDescriptor()
{
delete[] propertynames;
}
bool KSummaryVectorMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KSummaryVectorMsg *>(obj)!=nullptr;
}
const char **KSummaryVectorMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KSummaryVectorMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KSummaryVectorMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount() : 4;
}
unsigned int KSummaryVectorMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISARRAY | FD_ISEDITABLE,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *KSummaryVectorMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"realPacketSize",
"messageIDHashVector",
};
return (field>=0 && field<4) ? fieldNames[field] : nullptr;
}
int KSummaryVectorMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2;
if (fieldName[0]=='m' && strcmp(fieldName, "messageIDHashVector")==0) return base+3;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KSummaryVectorMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"int",
"string",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr;
}
const char **KSummaryVectorMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KSummaryVectorMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KSummaryVectorMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp;
switch (field) {
case 3: return pp->getMessageIDHashVectorArraySize();
default: return 0;
}
}
const char *KSummaryVectorMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KSummaryVectorMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return long2string(pp->getRealPacketSize());
case 3: return oppstring2string(pp->getMessageIDHashVector(i));
default: return "";
}
}
bool KSummaryVectorMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setRealPacketSize(string2long(value)); return true;
case 3: pp->setMessageIDHashVector(i,(value)); return true;
default: return false;
}
}
const char *KSummaryVectorMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KSummaryVectorMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KSummaryVectorMsg *pp = (KSummaryVectorMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
Register_Class(KDataRequestMsg)
KDataRequestMsg::KDataRequestMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->realPacketSize = 0;
messageIDHashVector_arraysize = 0;
this->messageIDHashVector = 0;
}
KDataRequestMsg::KDataRequestMsg(const KDataRequestMsg& other) : ::omnetpp::cPacket(other)
{
messageIDHashVector_arraysize = 0;
this->messageIDHashVector = 0;
copy(other);
}
KDataRequestMsg::~KDataRequestMsg()
{
delete [] this->messageIDHashVector;
}
KDataRequestMsg& KDataRequestMsg::operator=(const KDataRequestMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KDataRequestMsg::copy(const KDataRequestMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->realPacketSize = other.realPacketSize;
delete [] this->messageIDHashVector;
this->messageIDHashVector = (other.messageIDHashVector_arraysize==0) ? nullptr : new ::omnetpp::opp_string[other.messageIDHashVector_arraysize];
messageIDHashVector_arraysize = other.messageIDHashVector_arraysize;
for (unsigned int i=0; i<messageIDHashVector_arraysize; i++)
this->messageIDHashVector[i] = other.messageIDHashVector[i];
this->initialOriginatorAddress = other.initialOriginatorAddress;
}
void KDataRequestMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->realPacketSize);
b->pack(messageIDHashVector_arraysize);
doParsimArrayPacking(b,this->messageIDHashVector,messageIDHashVector_arraysize);
doParsimPacking(b,this->initialOriginatorAddress);
}
void KDataRequestMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->realPacketSize);
delete [] this->messageIDHashVector;
b->unpack(messageIDHashVector_arraysize);
if (messageIDHashVector_arraysize==0) {
this->messageIDHashVector = 0;
} else {
this->messageIDHashVector = new ::omnetpp::opp_string[messageIDHashVector_arraysize];
doParsimArrayUnpacking(b,this->messageIDHashVector,messageIDHashVector_arraysize);
}
doParsimUnpacking(b,this->initialOriginatorAddress);
}
const char * KDataRequestMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KDataRequestMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KDataRequestMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KDataRequestMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
int KDataRequestMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KDataRequestMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
void KDataRequestMsg::setMessageIDHashVectorArraySize(unsigned int size)
{
::omnetpp::opp_string *messageIDHashVector2 = (size==0) ? nullptr : new ::omnetpp::opp_string[size];
unsigned int sz = messageIDHashVector_arraysize < size ? messageIDHashVector_arraysize : size;
for (unsigned int i=0; i<sz; i++)
messageIDHashVector2[i] = this->messageIDHashVector[i];
for (unsigned int i=sz; i<size; i++)
messageIDHashVector2[i] = 0;
messageIDHashVector_arraysize = size;
delete [] this->messageIDHashVector;
this->messageIDHashVector = messageIDHashVector2;
}
unsigned int KDataRequestMsg::getMessageIDHashVectorArraySize() const
{
return messageIDHashVector_arraysize;
}
const char * KDataRequestMsg::getMessageIDHashVector(unsigned int k) const
{
if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k);
return this->messageIDHashVector[k].c_str();
}
void KDataRequestMsg::setMessageIDHashVector(unsigned int k, const char * messageIDHashVector)
{
if (k>=messageIDHashVector_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", messageIDHashVector_arraysize, k);
this->messageIDHashVector[k] = messageIDHashVector;
}
const char * KDataRequestMsg::getInitialOriginatorAddress() const
{
return this->initialOriginatorAddress.c_str();
}
void KDataRequestMsg::setInitialOriginatorAddress(const char * initialOriginatorAddress)
{
this->initialOriginatorAddress = initialOriginatorAddress;
}
class KDataRequestMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KDataRequestMsgDescriptor();
virtual ~KDataRequestMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KDataRequestMsgDescriptor)
KDataRequestMsgDescriptor::KDataRequestMsgDescriptor() : omnetpp::cClassDescriptor("KDataRequestMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KDataRequestMsgDescriptor::~KDataRequestMsgDescriptor()
{
delete[] propertynames;
}
bool KDataRequestMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KDataRequestMsg *>(obj)!=nullptr;
}
const char **KDataRequestMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KDataRequestMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KDataRequestMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 5+basedesc->getFieldCount() : 5;
}
unsigned int KDataRequestMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISARRAY | FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<5) ? fieldTypeFlags[field] : 0;
}
const char *KDataRequestMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"realPacketSize",
"messageIDHashVector",
"initialOriginatorAddress",
};
return (field>=0 && field<5) ? fieldNames[field] : nullptr;
}
int KDataRequestMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2;
if (fieldName[0]=='m' && strcmp(fieldName, "messageIDHashVector")==0) return base+3;
if (fieldName[0]=='i' && strcmp(fieldName, "initialOriginatorAddress")==0) return base+4;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KDataRequestMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"int",
"string",
"string",
};
return (field>=0 && field<5) ? fieldTypeStrings[field] : nullptr;
}
const char **KDataRequestMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KDataRequestMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KDataRequestMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp;
switch (field) {
case 3: return pp->getMessageIDHashVectorArraySize();
default: return 0;
}
}
const char *KDataRequestMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KDataRequestMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return long2string(pp->getRealPacketSize());
case 3: return oppstring2string(pp->getMessageIDHashVector(i));
case 4: return oppstring2string(pp->getInitialOriginatorAddress());
default: return "";
}
}
bool KDataRequestMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setRealPacketSize(string2long(value)); return true;
case 3: pp->setMessageIDHashVector(i,(value)); return true;
case 4: pp->setInitialOriginatorAddress((value)); return true;
default: return false;
}
}
const char *KDataRequestMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KDataRequestMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KDataRequestMsg *pp = (KDataRequestMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
EXECUTE_ON_STARTUP(
omnetpp::cEnum *e = omnetpp::cEnum::find("reactionType");
if (!e) omnetpp::enums.getInstance()->add(e = new omnetpp::cEnum("reactionType"));
e->insert(ignore, "ignore");
e->insert(comment, "comment");
e->insert(save, "save");
)
Register_Class(KReactionMsg)
KReactionMsg::KReactionMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->reaction = 0;
}
KReactionMsg::KReactionMsg(const KReactionMsg& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
KReactionMsg::~KReactionMsg()
{
}
KReactionMsg& KReactionMsg::operator=(const KReactionMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KReactionMsg::copy(const KReactionMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->dataName = other.dataName;
this->reaction = other.reaction;
}
void KReactionMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->dataName);
doParsimPacking(b,this->reaction);
}
void KReactionMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->dataName);
doParsimUnpacking(b,this->reaction);
}
const char * KReactionMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KReactionMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KReactionMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KReactionMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
const char * KReactionMsg::getDataName() const
{
return this->dataName.c_str();
}
void KReactionMsg::setDataName(const char * dataName)
{
this->dataName = dataName;
}
int KReactionMsg::getReaction() const
{
return this->reaction;
}
void KReactionMsg::setReaction(int reaction)
{
this->reaction = reaction;
}
class KReactionMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KReactionMsgDescriptor();
virtual ~KReactionMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KReactionMsgDescriptor)
KReactionMsgDescriptor::KReactionMsgDescriptor() : omnetpp::cClassDescriptor("KReactionMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KReactionMsgDescriptor::~KReactionMsgDescriptor()
{
delete[] propertynames;
}
bool KReactionMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KReactionMsg *>(obj)!=nullptr;
}
const char **KReactionMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KReactionMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KReactionMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount() : 4;
}
unsigned int KReactionMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *KReactionMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"dataName",
"reaction",
};
return (field>=0 && field<4) ? fieldNames[field] : nullptr;
}
int KReactionMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "dataName")==0) return base+2;
if (fieldName[0]=='r' && strcmp(fieldName, "reaction")==0) return base+3;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KReactionMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"string",
"int",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr;
}
const char **KReactionMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 3: {
static const char *names[] = { "enum", nullptr };
return names;
}
default: return nullptr;
}
}
const char *KReactionMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
case 3:
if (!strcmp(propertyname,"enum")) return "reactionType";
return nullptr;
default: return nullptr;
}
}
int KReactionMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KReactionMsg *pp = (KReactionMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *KReactionMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KReactionMsg *pp = (KReactionMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KReactionMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KReactionMsg *pp = (KReactionMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return oppstring2string(pp->getDataName());
case 3: return enum2string(pp->getReaction(), "reactionType");
default: return "";
}
}
bool KReactionMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KReactionMsg *pp = (KReactionMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setDataName((value)); return true;
case 3: pp->setReaction((reactionType)string2enum(value, "reactionType")); return true;
default: return false;
}
}
const char *KReactionMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KReactionMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KReactionMsg *pp = (KReactionMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
Register_Class(KDPtableRequestMsg)
KDPtableRequestMsg::KDPtableRequestMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->realPacketSize = 0;
}
KDPtableRequestMsg::KDPtableRequestMsg(const KDPtableRequestMsg& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
KDPtableRequestMsg::~KDPtableRequestMsg()
{
}
KDPtableRequestMsg& KDPtableRequestMsg::operator=(const KDPtableRequestMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KDPtableRequestMsg::copy(const KDPtableRequestMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
this->realPacketSize = other.realPacketSize;
}
void KDPtableRequestMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
doParsimPacking(b,this->realPacketSize);
}
void KDPtableRequestMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
doParsimUnpacking(b,this->realPacketSize);
}
const char * KDPtableRequestMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KDPtableRequestMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KDPtableRequestMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KDPtableRequestMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
int KDPtableRequestMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KDPtableRequestMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
class KDPtableRequestMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KDPtableRequestMsgDescriptor();
virtual ~KDPtableRequestMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KDPtableRequestMsgDescriptor)
KDPtableRequestMsgDescriptor::KDPtableRequestMsgDescriptor() : omnetpp::cClassDescriptor("KDPtableRequestMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KDPtableRequestMsgDescriptor::~KDPtableRequestMsgDescriptor()
{
delete[] propertynames;
}
bool KDPtableRequestMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KDPtableRequestMsg *>(obj)!=nullptr;
}
const char **KDPtableRequestMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KDPtableRequestMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KDPtableRequestMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount() : 3;
}
unsigned int KDPtableRequestMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *KDPtableRequestMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"realPacketSize",
};
return (field>=0 && field<3) ? fieldNames[field] : nullptr;
}
int KDPtableRequestMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+2;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KDPtableRequestMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"int",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr;
}
const char **KDPtableRequestMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KDPtableRequestMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KDPtableRequestMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *KDPtableRequestMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KDPtableRequestMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: return long2string(pp->getRealPacketSize());
default: return "";
}
}
bool KDPtableRequestMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 2: pp->setRealPacketSize(string2long(value)); return true;
default: return false;
}
}
const char *KDPtableRequestMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KDPtableRequestMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KDPtableRequestMsg *pp = (KDPtableRequestMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
MsgDelivPredictability::MsgDelivPredictability()
{
this->nodeDP = 0;
}
void __doPacking(omnetpp::cCommBuffer *b, const MsgDelivPredictability& a)
{
doParsimPacking(b,a.nodeMACAddress);
doParsimPacking(b,a.nodeDP);
}
void __doUnpacking(omnetpp::cCommBuffer *b, MsgDelivPredictability& a)
{
doParsimUnpacking(b,a.nodeMACAddress);
doParsimUnpacking(b,a.nodeDP);
}
class MsgDelivPredictabilityDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
MsgDelivPredictabilityDescriptor();
virtual ~MsgDelivPredictabilityDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(MsgDelivPredictabilityDescriptor)
MsgDelivPredictabilityDescriptor::MsgDelivPredictabilityDescriptor() : omnetpp::cClassDescriptor("MsgDelivPredictability", "")
{
propertynames = nullptr;
}
MsgDelivPredictabilityDescriptor::~MsgDelivPredictabilityDescriptor()
{
delete[] propertynames;
}
bool MsgDelivPredictabilityDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<MsgDelivPredictability *>(obj)!=nullptr;
}
const char **MsgDelivPredictabilityDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *MsgDelivPredictabilityDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int MsgDelivPredictabilityDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 2+basedesc->getFieldCount() : 2;
}
unsigned int MsgDelivPredictabilityDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<2) ? fieldTypeFlags[field] : 0;
}
const char *MsgDelivPredictabilityDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"nodeMACAddress",
"nodeDP",
};
return (field>=0 && field<2) ? fieldNames[field] : nullptr;
}
int MsgDelivPredictabilityDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='n' && strcmp(fieldName, "nodeMACAddress")==0) return base+0;
if (fieldName[0]=='n' && strcmp(fieldName, "nodeDP")==0) return base+1;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *MsgDelivPredictabilityDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"double",
};
return (field>=0 && field<2) ? fieldTypeStrings[field] : nullptr;
}
const char **MsgDelivPredictabilityDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *MsgDelivPredictabilityDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int MsgDelivPredictabilityDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *MsgDelivPredictabilityDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string MsgDelivPredictabilityDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->nodeMACAddress);
case 1: return double2string(pp->nodeDP);
default: return "";
}
}
bool MsgDelivPredictabilityDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp;
switch (field) {
case 0: pp->nodeMACAddress = (value); return true;
case 1: pp->nodeDP = string2double(value); return true;
default: return false;
}
}
const char *MsgDelivPredictabilityDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *MsgDelivPredictabilityDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
MsgDelivPredictability *pp = (MsgDelivPredictability *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
Register_Class(KDPtableDataMsg)
KDPtableDataMsg::KDPtableDataMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
dpList_arraysize = 0;
this->dpList = 0;
this->realPacketSize = 0;
}
KDPtableDataMsg::KDPtableDataMsg(const KDPtableDataMsg& other) : ::omnetpp::cPacket(other)
{
dpList_arraysize = 0;
this->dpList = 0;
copy(other);
}
KDPtableDataMsg::~KDPtableDataMsg()
{
delete [] this->dpList;
}
KDPtableDataMsg& KDPtableDataMsg::operator=(const KDPtableDataMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KDPtableDataMsg::copy(const KDPtableDataMsg& other)
{
this->sourceAddress = other.sourceAddress;
this->destinationAddress = other.destinationAddress;
delete [] this->dpList;
this->dpList = (other.dpList_arraysize==0) ? nullptr : new MsgDelivPredictability[other.dpList_arraysize];
dpList_arraysize = other.dpList_arraysize;
for (unsigned int i=0; i<dpList_arraysize; i++)
this->dpList[i] = other.dpList[i];
this->realPacketSize = other.realPacketSize;
}
void KDPtableDataMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->sourceAddress);
doParsimPacking(b,this->destinationAddress);
b->pack(dpList_arraysize);
doParsimArrayPacking(b,this->dpList,dpList_arraysize);
doParsimPacking(b,this->realPacketSize);
}
void KDPtableDataMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->sourceAddress);
doParsimUnpacking(b,this->destinationAddress);
delete [] this->dpList;
b->unpack(dpList_arraysize);
if (dpList_arraysize==0) {
this->dpList = 0;
} else {
this->dpList = new MsgDelivPredictability[dpList_arraysize];
doParsimArrayUnpacking(b,this->dpList,dpList_arraysize);
}
doParsimUnpacking(b,this->realPacketSize);
}
const char * KDPtableDataMsg::getSourceAddress() const
{
return this->sourceAddress.c_str();
}
void KDPtableDataMsg::setSourceAddress(const char * sourceAddress)
{
this->sourceAddress = sourceAddress;
}
const char * KDPtableDataMsg::getDestinationAddress() const
{
return this->destinationAddress.c_str();
}
void KDPtableDataMsg::setDestinationAddress(const char * destinationAddress)
{
this->destinationAddress = destinationAddress;
}
void KDPtableDataMsg::setDpListArraySize(unsigned int size)
{
MsgDelivPredictability *dpList2 = (size==0) ? nullptr : new MsgDelivPredictability[size];
unsigned int sz = dpList_arraysize < size ? dpList_arraysize : size;
for (unsigned int i=0; i<sz; i++)
dpList2[i] = this->dpList[i];
dpList_arraysize = size;
delete [] this->dpList;
this->dpList = dpList2;
}
unsigned int KDPtableDataMsg::getDpListArraySize() const
{
return dpList_arraysize;
}
MsgDelivPredictability& KDPtableDataMsg::getDpList(unsigned int k)
{
if (k>=dpList_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", dpList_arraysize, k);
return this->dpList[k];
}
void KDPtableDataMsg::setDpList(unsigned int k, const MsgDelivPredictability& dpList)
{
if (k>=dpList_arraysize) throw omnetpp::cRuntimeError("Array of size %d indexed by %d", dpList_arraysize, k);
this->dpList[k] = dpList;
}
int KDPtableDataMsg::getRealPacketSize() const
{
return this->realPacketSize;
}
void KDPtableDataMsg::setRealPacketSize(int realPacketSize)
{
this->realPacketSize = realPacketSize;
}
class KDPtableDataMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KDPtableDataMsgDescriptor();
virtual ~KDPtableDataMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KDPtableDataMsgDescriptor)
KDPtableDataMsgDescriptor::KDPtableDataMsgDescriptor() : omnetpp::cClassDescriptor("KDPtableDataMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KDPtableDataMsgDescriptor::~KDPtableDataMsgDescriptor()
{
delete[] propertynames;
}
bool KDPtableDataMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KDPtableDataMsg *>(obj)!=nullptr;
}
const char **KDPtableDataMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KDPtableDataMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KDPtableDataMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 4+basedesc->getFieldCount() : 4;
}
unsigned int KDPtableDataMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISARRAY | FD_ISCOMPOUND,
FD_ISEDITABLE,
};
return (field>=0 && field<4) ? fieldTypeFlags[field] : 0;
}
const char *KDPtableDataMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"sourceAddress",
"destinationAddress",
"dpList",
"realPacketSize",
};
return (field>=0 && field<4) ? fieldNames[field] : nullptr;
}
int KDPtableDataMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='s' && strcmp(fieldName, "sourceAddress")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "destinationAddress")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "dpList")==0) return base+2;
if (fieldName[0]=='r' && strcmp(fieldName, "realPacketSize")==0) return base+3;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KDPtableDataMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"string",
"string",
"MsgDelivPredictability",
"int",
};
return (field>=0 && field<4) ? fieldTypeStrings[field] : nullptr;
}
const char **KDPtableDataMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KDPtableDataMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KDPtableDataMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp;
switch (field) {
case 2: return pp->getDpListArraySize();
default: return 0;
}
}
const char *KDPtableDataMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KDPtableDataMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp;
switch (field) {
case 0: return oppstring2string(pp->getSourceAddress());
case 1: return oppstring2string(pp->getDestinationAddress());
case 2: {std::stringstream out; out << pp->getDpList(i); return out.str();}
case 3: return long2string(pp->getRealPacketSize());
default: return "";
}
}
bool KDPtableDataMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp;
switch (field) {
case 0: pp->setSourceAddress((value)); return true;
case 1: pp->setDestinationAddress((value)); return true;
case 3: pp->setRealPacketSize(string2long(value)); return true;
default: return false;
}
}
const char *KDPtableDataMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
case 2: return omnetpp::opp_typename(typeid(MsgDelivPredictability));
default: return nullptr;
};
}
void *KDPtableDataMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KDPtableDataMsg *pp = (KDPtableDataMsg *)object; (void)pp;
switch (field) {
case 2: return (void *)(&pp->getDpList(i)); break;
default: return nullptr;
}
}
Register_Class(KStatisticsMsg)
KStatisticsMsg::KStatisticsMsg(const char *name, short kind) : ::omnetpp::cPacket(name,kind)
{
this->likedData = false;
this->dataCountReceivable = 0;
this->dataBytesReceivable = 0;
}
KStatisticsMsg::KStatisticsMsg(const KStatisticsMsg& other) : ::omnetpp::cPacket(other)
{
copy(other);
}
KStatisticsMsg::~KStatisticsMsg()
{
}
KStatisticsMsg& KStatisticsMsg::operator=(const KStatisticsMsg& other)
{
if (this==&other) return *this;
::omnetpp::cPacket::operator=(other);
copy(other);
return *this;
}
void KStatisticsMsg::copy(const KStatisticsMsg& other)
{
this->likedData = other.likedData;
this->dataCountReceivable = other.dataCountReceivable;
this->dataBytesReceivable = other.dataBytesReceivable;
}
void KStatisticsMsg::parsimPack(omnetpp::cCommBuffer *b) const
{
::omnetpp::cPacket::parsimPack(b);
doParsimPacking(b,this->likedData);
doParsimPacking(b,this->dataCountReceivable);
doParsimPacking(b,this->dataBytesReceivable);
}
void KStatisticsMsg::parsimUnpack(omnetpp::cCommBuffer *b)
{
::omnetpp::cPacket::parsimUnpack(b);
doParsimUnpacking(b,this->likedData);
doParsimUnpacking(b,this->dataCountReceivable);
doParsimUnpacking(b,this->dataBytesReceivable);
}
bool KStatisticsMsg::getLikedData() const
{
return this->likedData;
}
void KStatisticsMsg::setLikedData(bool likedData)
{
this->likedData = likedData;
}
int KStatisticsMsg::getDataCountReceivable() const
{
return this->dataCountReceivable;
}
void KStatisticsMsg::setDataCountReceivable(int dataCountReceivable)
{
this->dataCountReceivable = dataCountReceivable;
}
int KStatisticsMsg::getDataBytesReceivable() const
{
return this->dataBytesReceivable;
}
void KStatisticsMsg::setDataBytesReceivable(int dataBytesReceivable)
{
this->dataBytesReceivable = dataBytesReceivable;
}
class KStatisticsMsgDescriptor : public omnetpp::cClassDescriptor
{
private:
mutable const char **propertynames;
public:
KStatisticsMsgDescriptor();
virtual ~KStatisticsMsgDescriptor();
virtual bool doesSupport(omnetpp::cObject *obj) const override;
virtual const char **getPropertyNames() const override;
virtual const char *getProperty(const char *propertyname) const override;
virtual int getFieldCount() const override;
virtual const char *getFieldName(int field) const override;
virtual int findField(const char *fieldName) const override;
virtual unsigned int getFieldTypeFlags(int field) const override;
virtual const char *getFieldTypeString(int field) const override;
virtual const char **getFieldPropertyNames(int field) const override;
virtual const char *getFieldProperty(int field, const char *propertyname) const override;
virtual int getFieldArraySize(void *object, int field) const override;
virtual const char *getFieldDynamicTypeString(void *object, int field, int i) const override;
virtual std::string getFieldValueAsString(void *object, int field, int i) const override;
virtual bool setFieldValueAsString(void *object, int field, int i, const char *value) const override;
virtual const char *getFieldStructName(int field) const override;
virtual void *getFieldStructValuePointer(void *object, int field, int i) const override;
};
Register_ClassDescriptor(KStatisticsMsgDescriptor)
KStatisticsMsgDescriptor::KStatisticsMsgDescriptor() : omnetpp::cClassDescriptor("KStatisticsMsg", "omnetpp::cPacket")
{
propertynames = nullptr;
}
KStatisticsMsgDescriptor::~KStatisticsMsgDescriptor()
{
delete[] propertynames;
}
bool KStatisticsMsgDescriptor::doesSupport(omnetpp::cObject *obj) const
{
return dynamic_cast<KStatisticsMsg *>(obj)!=nullptr;
}
const char **KStatisticsMsgDescriptor::getPropertyNames() const
{
if (!propertynames) {
static const char *names[] = { nullptr };
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
const char **basenames = basedesc ? basedesc->getPropertyNames() : nullptr;
propertynames = mergeLists(basenames, names);
}
return propertynames;
}
const char *KStatisticsMsgDescriptor::getProperty(const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? basedesc->getProperty(propertyname) : nullptr;
}
int KStatisticsMsgDescriptor::getFieldCount() const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
return basedesc ? 3+basedesc->getFieldCount() : 3;
}
unsigned int KStatisticsMsgDescriptor::getFieldTypeFlags(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeFlags(field);
field -= basedesc->getFieldCount();
}
static unsigned int fieldTypeFlags[] = {
FD_ISEDITABLE,
FD_ISEDITABLE,
FD_ISEDITABLE,
};
return (field>=0 && field<3) ? fieldTypeFlags[field] : 0;
}
const char *KStatisticsMsgDescriptor::getFieldName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldName(field);
field -= basedesc->getFieldCount();
}
static const char *fieldNames[] = {
"likedData",
"dataCountReceivable",
"dataBytesReceivable",
};
return (field>=0 && field<3) ? fieldNames[field] : nullptr;
}
int KStatisticsMsgDescriptor::findField(const char *fieldName) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
int base = basedesc ? basedesc->getFieldCount() : 0;
if (fieldName[0]=='l' && strcmp(fieldName, "likedData")==0) return base+0;
if (fieldName[0]=='d' && strcmp(fieldName, "dataCountReceivable")==0) return base+1;
if (fieldName[0]=='d' && strcmp(fieldName, "dataBytesReceivable")==0) return base+2;
return basedesc ? basedesc->findField(fieldName) : -1;
}
const char *KStatisticsMsgDescriptor::getFieldTypeString(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldTypeString(field);
field -= basedesc->getFieldCount();
}
static const char *fieldTypeStrings[] = {
"bool",
"int",
"int",
};
return (field>=0 && field<3) ? fieldTypeStrings[field] : nullptr;
}
const char **KStatisticsMsgDescriptor::getFieldPropertyNames(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldPropertyNames(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
const char *KStatisticsMsgDescriptor::getFieldProperty(int field, const char *propertyname) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldProperty(field, propertyname);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
}
}
int KStatisticsMsgDescriptor::getFieldArraySize(void *object, int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldArraySize(object, field);
field -= basedesc->getFieldCount();
}
KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp;
switch (field) {
default: return 0;
}
}
const char *KStatisticsMsgDescriptor::getFieldDynamicTypeString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldDynamicTypeString(object,field,i);
field -= basedesc->getFieldCount();
}
KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
std::string KStatisticsMsgDescriptor::getFieldValueAsString(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldValueAsString(object,field,i);
field -= basedesc->getFieldCount();
}
KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp;
switch (field) {
case 0: return bool2string(pp->getLikedData());
case 1: return long2string(pp->getDataCountReceivable());
case 2: return long2string(pp->getDataBytesReceivable());
default: return "";
}
}
bool KStatisticsMsgDescriptor::setFieldValueAsString(void *object, int field, int i, const char *value) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->setFieldValueAsString(object,field,i,value);
field -= basedesc->getFieldCount();
}
KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp;
switch (field) {
case 0: pp->setLikedData(string2bool(value)); return true;
case 1: pp->setDataCountReceivable(string2long(value)); return true;
case 2: pp->setDataBytesReceivable(string2long(value)); return true;
default: return false;
}
}
const char *KStatisticsMsgDescriptor::getFieldStructName(int field) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructName(field);
field -= basedesc->getFieldCount();
}
switch (field) {
default: return nullptr;
};
}
void *KStatisticsMsgDescriptor::getFieldStructValuePointer(void *object, int field, int i) const
{
omnetpp::cClassDescriptor *basedesc = getBaseClassDescriptor();
if (basedesc) {
if (field < basedesc->getFieldCount())
return basedesc->getFieldStructValuePointer(object, field, i);
field -= basedesc->getFieldCount();
}
KStatisticsMsg *pp = (KStatisticsMsg *)object; (void)pp;
switch (field) {
default: return nullptr;
}
}
| [
"rodney@massalia.comnets.uni-bremen.de"
] | rodney@massalia.comnets.uni-bremen.de |
22b51dc8b515c62e99ddbf4ef9a8bbe9c6acf361 | 434ff801f9f28918c9e572bb752d0fc5a181edb2 | /face_practice question/stage2/Electricity_bill.cpp | 5858714446e530f65e0c3f7e969b86f3fdce0c8a | [] | no_license | ayushikhandelwal99/C_basic_to_adv | bdf63dd202a9ef287f558a959a82a04e157f8a76 | 9cfcc20c10a2b1c19e3e32f5c8e3a49c581df1fa | refs/heads/master | 2022-12-26T00:52:48.973577 | 2020-10-15T05:31:03 | 2020-10-15T05:31:03 | 279,268,546 | 0 | 1 | null | 2020-10-15T05:31:04 | 2020-07-13T10:15:51 | C++ | UTF-8 | C++ | false | false | 320 | cpp | #include<iostream>
using namespace std;
int main()
{
int units;
int cost=0;
cin>>units;
if(units<=200)
cost=units*0.5;
else if(units<=400)
cost=units*0.65+100;
else if(units<=600)
cost=units*0.80+200;
else
cost=units*1.25+425;
cout<<"Rs."<<cost;
return 0;
//Type your code here.
}
| [
"ayushikhandelwal9919@yahoo.com"
] | ayushikhandelwal9919@yahoo.com |
8e045e40a75c60d6dc79d3a739864a9588517d05 | 1490a424c1916dfa42ae67e7c64326c10cfb115a | /SEAL/native/examples/7_performance.cpp | 82aa68a90ac7697fbff4b8642546f96e33eba9c8 | [
"MIT",
"CC0-1.0",
"BSD-3-Clause"
] | permissive | WeidanJi/seal_expansion | d858b05f5dba2e4aefded6b0f6d1ec1f0ced2bda | f4cd34f31fb43d3511cdca62206e0f764d460abc | refs/heads/master | 2023-05-06T11:43:50.011827 | 2021-05-26T05:39:12 | 2021-05-26T05:39:12 | 351,049,890 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 33,053 | cpp | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
#include "examples.h"
using namespace std;
using namespace seal;
void bfv_performance_test(SEALContext context)
{
chrono::high_resolution_clock::time_point time_start, time_end;
print_parameters(context);
cout << endl;
auto &parms = context.first_context_data()->parms();
auto &plain_modulus = parms.plain_modulus();
size_t poly_modulus_degree = parms.poly_modulus_degree();
cout << "Generating secret/public keys: ";
KeyGenerator keygen(context);
cout << "Done" << endl;
auto secret_key = keygen.secret_key();
PublicKey public_key;
keygen.create_public_key(public_key);
RelinKeys relin_keys;
GaloisKeys gal_keys;
chrono::microseconds time_diff;
if (context.using_keyswitching())
{
/*
Generate relinearization keys.
*/
cout << "Generating relinearization keys: ";
time_start = chrono::high_resolution_clock::now();
keygen.create_relin_keys(relin_keys);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
cout << "Done [" << time_diff.count() << " microseconds]" << endl;
if (!context.key_context_data()->qualifiers().using_batching)
{
cout << "Given encryption parameters do not support batching." << endl;
return;
}
/*
Generate Galois keys. In larger examples the Galois keys can use a lot of
memory, which can be a problem in constrained systems. The user should
try some of the larger runs of the test and observe their effect on the
memory pool allocation size. The key generation can also take a long time,
as can be observed from the print-out.
*/
cout << "Generating Galois keys: ";
time_start = chrono::high_resolution_clock::now();
keygen.create_galois_keys(gal_keys);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
cout << "Done [" << time_diff.count() << " microseconds]" << endl;
}
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
BatchEncoder batch_encoder(context);
/*
These will hold the total times used by each operation.
*/
chrono::microseconds time_batch_sum(0);
chrono::microseconds time_unbatch_sum(0);
chrono::microseconds time_encrypt_sum(0);
chrono::microseconds time_decrypt_sum(0);
chrono::microseconds time_add_sum(0);
chrono::microseconds time_multiply_sum(0);
chrono::microseconds time_multiply_plain_sum(0);
chrono::microseconds time_square_sum(0);
chrono::microseconds time_relinearize_sum(0);
chrono::microseconds time_rotate_rows_one_step_sum(0);
chrono::microseconds time_rotate_rows_random_sum(0);
chrono::microseconds time_rotate_columns_sum(0);
chrono::microseconds time_serialize_sum(0);
#ifdef SEAL_USE_ZLIB
chrono::microseconds time_serialize_zlib_sum(0);
#endif
#ifdef SEAL_USE_ZSTD
chrono::microseconds time_serialize_zstd_sum(0);
#endif
/*
How many times to run the test?
*/
long long count = 10;
/*
Populate a vector of values to batch.
*/
size_t slot_count = batch_encoder.slot_count();
vector<uint64_t> pod_vector;
random_device rd;
for (size_t i = 0; i < slot_count; i++)
{
pod_vector.push_back(plain_modulus.reduce(rd()));
}
cout << "Running tests ";
for (size_t i = 0; i < static_cast<size_t>(count); i++)
{
/*
[Batching]
There is nothing unusual here. We batch our random plaintext matrix
into the polynomial. Note how the plaintext we create is of the exactly
right size so unnecessary reallocations are avoided.
*/
Plaintext plain(poly_modulus_degree, 0);
Plaintext plain1(poly_modulus_degree, 0);
Plaintext plain2(poly_modulus_degree, 0);
time_start = chrono::high_resolution_clock::now();
batch_encoder.encode(pod_vector, plain);
time_end = chrono::high_resolution_clock::now();
time_batch_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Unbatching]
We unbatch what we just batched.
*/
vector<uint64_t> pod_vector2(slot_count);
time_start = chrono::high_resolution_clock::now();
batch_encoder.decode(plain, pod_vector2);
time_end = chrono::high_resolution_clock::now();
time_unbatch_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
if (pod_vector2 != pod_vector)
{
throw runtime_error("Batch/unbatch failed. Something is wrong.");
}
/*
[Encryption]
We make sure our ciphertext is already allocated and large enough
to hold the encryption with these encryption parameters. We encrypt
our random batched matrix here.
*/
Ciphertext encrypted(context);
time_start = chrono::high_resolution_clock::now();
encryptor.encrypt(plain, encrypted);
time_end = chrono::high_resolution_clock::now();
time_encrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Decryption]
We decrypt what we just encrypted.
*/
time_start = chrono::high_resolution_clock::now();
decryptor.decrypt(encrypted, plain2);
time_end = chrono::high_resolution_clock::now();
time_decrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
if (plain2 != plain)
{
throw runtime_error("Encrypt/decrypt failed. Something is wrong.");
}
/*
[Add]
We create two ciphertexts and perform a few additions with them.
*/
Ciphertext encrypted1(context);
batch_encoder.encode(vector<uint64_t>(slot_count, i), plain1);
encryptor.encrypt(plain1, encrypted1);
Ciphertext encrypted2(context);
batch_encoder.encode(vector<uint64_t>(slot_count, i + 1), plain2);
encryptor.encrypt(plain2, encrypted2);
time_start = chrono::high_resolution_clock::now();
evaluator.add_inplace(encrypted1, encrypted1);
evaluator.add_inplace(encrypted2, encrypted2);
evaluator.add_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_add_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Multiply]
We multiply two ciphertexts. Since the size of the result will be 3,
and will overwrite the first argument, we reserve first enough memory
to avoid reallocating during multiplication.
*/
encrypted1.reserve(3);
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_multiply_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Multiply Plain]
We multiply a ciphertext with a random plaintext. Recall that
multiply_plain does not change the size of the ciphertext so we use
encrypted2 here.
*/
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_plain_inplace(encrypted2, plain);
time_end = chrono::high_resolution_clock::now();
time_multiply_plain_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Square]
We continue to use encrypted2. Now we square it; this should be
faster than generic homomorphic multiplication.
*/
time_start = chrono::high_resolution_clock::now();
evaluator.square_inplace(encrypted2);
time_end = chrono::high_resolution_clock::now();
time_square_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
if (context.using_keyswitching())
{
/*
[Relinearize]
Time to get back to encrypted1. We now relinearize it back
to size 2. Since the allocation is currently big enough to
contain a ciphertext of size 3, no costly reallocations are
needed in the process.
*/
time_start = chrono::high_resolution_clock::now();
evaluator.relinearize_inplace(encrypted1, relin_keys);
time_end = chrono::high_resolution_clock::now();
time_relinearize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Rotate Rows One Step]
We rotate matrix rows by one step left and measure the time.
*/
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_rows_inplace(encrypted, 1, gal_keys);
evaluator.rotate_rows_inplace(encrypted, -1, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_rows_one_step_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
;
/*
[Rotate Rows Random]
We rotate matrix rows by a random number of steps. This is much more
expensive than rotating by just one step.
*/
size_t row_size = batch_encoder.slot_count() / 2;
// row_size is always a power of 2
int random_rotation = static_cast<int>(rd() & (row_size - 1));
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_rows_inplace(encrypted, random_rotation, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_rows_random_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Rotate Columns]
Nothing surprising here.
*/
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_columns_inplace(encrypted, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_columns_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
}
/*
[Serialize Ciphertext]
*/
size_t buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::none));
vector<seal_byte> buf(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::none);
time_end = chrono::high_resolution_clock::now();
time_serialize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#ifdef SEAL_USE_ZLIB
/*
[Serialize Ciphertext (ZLIB)]
*/
buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zlib));
buf.resize(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::zlib);
time_end = chrono::high_resolution_clock::now();
time_serialize_zlib_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#endif
#ifdef SEAL_USE_ZSTD
/*
[Serialize Ciphertext (Zstandard)]
*/
buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zstd));
buf.resize(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::zstd);
time_end = chrono::high_resolution_clock::now();
time_serialize_zstd_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#endif
/*
Print a dot to indicate progress.
*/
cout << ".";
cout.flush();
}
cout << " Done" << endl << endl;
cout.flush();
auto avg_batch = time_batch_sum.count() / count;
auto avg_unbatch = time_unbatch_sum.count() / count;
auto avg_encrypt = time_encrypt_sum.count() / count;
auto avg_decrypt = time_decrypt_sum.count() / count;
auto avg_add = time_add_sum.count() / (3 * count);
auto avg_multiply = time_multiply_sum.count() / count;
auto avg_multiply_plain = time_multiply_plain_sum.count() / count;
auto avg_square = time_square_sum.count() / count;
auto avg_relinearize = time_relinearize_sum.count() / count;
auto avg_rotate_rows_one_step = time_rotate_rows_one_step_sum.count() / (2 * count);
auto avg_rotate_rows_random = time_rotate_rows_random_sum.count() / count;
auto avg_rotate_columns = time_rotate_columns_sum.count() / count;
auto avg_serialize = time_serialize_sum.count() / count;
#ifdef SEAL_USE_ZLIB
auto avg_serialize_zlib = time_serialize_zlib_sum.count() / count;
#endif
#ifdef SEAL_USE_ZSTD
auto avg_serialize_zstd = time_serialize_zstd_sum.count() / count;
#endif
cout << "Average batch: " << avg_batch << " microseconds" << endl;
cout << "Average unbatch: " << avg_unbatch << " microseconds" << endl;
cout << "Average encrypt: " << avg_encrypt << " microseconds" << endl;
cout << "Average decrypt: " << avg_decrypt << " microseconds" << endl;
cout << "Average add: " << avg_add << " microseconds" << endl;
cout << "Average multiply: " << avg_multiply << " microseconds" << endl;
cout << "Average multiply plain: " << avg_multiply_plain << " microseconds" << endl;
cout << "Average square: " << avg_square << " microseconds" << endl;
if (context.using_keyswitching())
{
cout << "Average relinearize: " << avg_relinearize << " microseconds" << endl;
cout << "Average rotate rows one step: " << avg_rotate_rows_one_step << " microseconds" << endl;
cout << "Average rotate rows random: " << avg_rotate_rows_random << " microseconds" << endl;
cout << "Average rotate columns: " << avg_rotate_columns << " microseconds" << endl;
}
cout << "Average serialize ciphertext: " << avg_serialize << " microseconds" << endl;
#ifdef SEAL_USE_ZLIB
cout << "Average compressed (ZLIB) serialize ciphertext: " << avg_serialize_zlib << " microseconds" << endl;
#endif
#ifdef SEAL_USE_ZSTD
cout << "Average compressed (Zstandard) serialize ciphertext: " << avg_serialize_zstd << " microseconds" << endl;
#endif
cout.flush();
}
void ckks_performance_test(SEALContext context)
{
chrono::high_resolution_clock::time_point time_start, time_end;
print_parameters(context);
cout << endl;
auto &parms = context.first_context_data()->parms();
size_t poly_modulus_degree = parms.poly_modulus_degree();
cout << "Generating secret/public keys: ";
KeyGenerator keygen(context);
cout << "Done" << endl;
auto secret_key = keygen.secret_key();
PublicKey public_key;
keygen.create_public_key(public_key);
RelinKeys relin_keys;
GaloisKeys gal_keys;
chrono::microseconds time_diff;
if (context.using_keyswitching())
{
cout << "Generating relinearization keys: ";
time_start = chrono::high_resolution_clock::now();
keygen.create_relin_keys(relin_keys);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
cout << "Done [" << time_diff.count() << " microseconds]" << endl;
if (!context.first_context_data()->qualifiers().using_batching)
{
cout << "Given encryption parameters do not support batching." << endl;
return;
}
cout << "Generating Galois keys: ";
time_start = chrono::high_resolution_clock::now();
keygen.create_galois_keys(gal_keys);
time_end = chrono::high_resolution_clock::now();
time_diff = chrono::duration_cast<chrono::microseconds>(time_end - time_start);
cout << "Done [" << time_diff.count() << " microseconds]" << endl;
}
Encryptor encryptor(context, public_key);
Decryptor decryptor(context, secret_key);
Evaluator evaluator(context);
CKKSEncoder ckks_encoder(context);
chrono::microseconds time_encode_sum(0);
chrono::microseconds time_decode_sum(0);
chrono::microseconds time_encrypt_sum(0);
chrono::microseconds time_decrypt_sum(0);
chrono::microseconds time_add_sum(0);
chrono::microseconds time_multiply_sum(0);
chrono::microseconds time_multiply_plain_sum(0);
chrono::microseconds time_square_sum(0);
chrono::microseconds time_relinearize_sum(0);
chrono::microseconds time_rescale_sum(0);
chrono::microseconds time_rotate_one_step_sum(0);
chrono::microseconds time_rotate_random_sum(0);
chrono::microseconds time_conjugate_sum(0);
chrono::microseconds time_serialize_sum(0);
#ifdef SEAL_USE_ZLIB
chrono::microseconds time_serialize_zlib_sum(0);
#endif
#ifdef SEAL_USE_ZSTD
chrono::microseconds time_serialize_zstd_sum(0);
#endif
/*
How many times to run the test?
*/
long long count = 10;
/*
Populate a vector of floating-point values to batch.
*/
vector<double> pod_vector;
random_device rd;
for (size_t i = 0; i < ckks_encoder.slot_count(); i++)
{
pod_vector.push_back(1.001 * static_cast<double>(i));
}
cout << "Running tests ";
for (long long i = 0; i < count; i++)
{
/*
[Encoding]
For scale we use the square root of the last coeff_modulus prime
from parms.
*/
Plaintext plain(parms.poly_modulus_degree() * parms.coeff_modulus().size(), 0);
/*
*/
double scale = sqrt(static_cast<double>(parms.coeff_modulus().back().value()));
time_start = chrono::high_resolution_clock::now();
ckks_encoder.encode(pod_vector, scale, plain);
time_end = chrono::high_resolution_clock::now();
time_encode_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Decoding]
*/
vector<double> pod_vector2(ckks_encoder.slot_count());
time_start = chrono::high_resolution_clock::now();
ckks_encoder.decode(plain, pod_vector2);
time_end = chrono::high_resolution_clock::now();
time_decode_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Encryption]
*/
Ciphertext encrypted(context);
time_start = chrono::high_resolution_clock::now();
encryptor.encrypt(plain, encrypted);
time_end = chrono::high_resolution_clock::now();
time_encrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Decryption]
*/
Plaintext plain2(poly_modulus_degree, 0);
time_start = chrono::high_resolution_clock::now();
decryptor.decrypt(encrypted, plain2);
time_end = chrono::high_resolution_clock::now();
time_decrypt_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Add]
*/
Ciphertext encrypted1(context);
ckks_encoder.encode(i + 1, plain);
encryptor.encrypt(plain, encrypted1);
Ciphertext encrypted2(context);
ckks_encoder.encode(i + 1, plain2);
encryptor.encrypt(plain2, encrypted2);
time_start = chrono::high_resolution_clock::now();
evaluator.add_inplace(encrypted1, encrypted1);
evaluator.add_inplace(encrypted2, encrypted2);
evaluator.add_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_add_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Multiply]
*/
encrypted1.reserve(3);
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_inplace(encrypted1, encrypted2);
time_end = chrono::high_resolution_clock::now();
time_multiply_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Multiply Plain]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.multiply_plain_inplace(encrypted2, plain);
time_end = chrono::high_resolution_clock::now();
time_multiply_plain_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Square]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.square_inplace(encrypted2);
time_end = chrono::high_resolution_clock::now();
time_square_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
if (context.using_keyswitching())
{
/*
[Relinearize]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.relinearize_inplace(encrypted1, relin_keys);
time_end = chrono::high_resolution_clock::now();
time_relinearize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Rescale]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.rescale_to_next_inplace(encrypted1);
time_end = chrono::high_resolution_clock::now();
time_rescale_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Rotate Vector]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_vector_inplace(encrypted, 1, gal_keys);
evaluator.rotate_vector_inplace(encrypted, -1, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_one_step_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Rotate Vector Random]
*/
// ckks_encoder.slot_count() is always a power of 2.
int random_rotation = static_cast<int>(rd() & (ckks_encoder.slot_count() - 1));
time_start = chrono::high_resolution_clock::now();
evaluator.rotate_vector_inplace(encrypted, random_rotation, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_rotate_random_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
/*
[Complex Conjugate]
*/
time_start = chrono::high_resolution_clock::now();
evaluator.complex_conjugate_inplace(encrypted, gal_keys);
time_end = chrono::high_resolution_clock::now();
time_conjugate_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
}
/*
[Serialize Ciphertext]
*/
size_t buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::none));
vector<seal_byte> buf(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::none);
time_end = chrono::high_resolution_clock::now();
time_serialize_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#ifdef SEAL_USE_ZLIB
/*
[Serialize Ciphertext (ZLIB)]
*/
buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zlib));
buf.resize(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::zlib);
time_end = chrono::high_resolution_clock::now();
time_serialize_zlib_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#endif
#ifdef SEAL_USE_ZSTD
/*
[Serialize Ciphertext (Zstandard)]
*/
buf_size = static_cast<size_t>(encrypted.save_size(compr_mode_type::zstd));
buf.resize(buf_size);
time_start = chrono::high_resolution_clock::now();
encrypted.save(buf.data(), buf_size, compr_mode_type::zstd);
time_end = chrono::high_resolution_clock::now();
time_serialize_zstd_sum += chrono::duration_cast<chrono::microseconds>(time_end - time_start);
#endif
/*
Print a dot to indicate progress.
*/
cout << ".";
cout.flush();
}
cout << " Done" << endl << endl;
cout.flush();
auto avg_encode = time_encode_sum.count() / count;
auto avg_decode = time_decode_sum.count() / count;
auto avg_encrypt = time_encrypt_sum.count() / count;
auto avg_decrypt = time_decrypt_sum.count() / count;
auto avg_add = time_add_sum.count() / (3 * count);
auto avg_multiply = time_multiply_sum.count() / count;
auto avg_multiply_plain = time_multiply_plain_sum.count() / count;
auto avg_square = time_square_sum.count() / count;
auto avg_relinearize = time_relinearize_sum.count() / count;
auto avg_rescale = time_rescale_sum.count() / count;
auto avg_rotate_one_step = time_rotate_one_step_sum.count() / (2 * count);
auto avg_rotate_random = time_rotate_random_sum.count() / count;
auto avg_conjugate = time_conjugate_sum.count() / count;
auto avg_serialize = time_serialize_sum.count() / count;
#ifdef SEAL_USE_ZLIB
auto avg_serialize_zlib = time_serialize_zlib_sum.count() / count;
#endif
#ifdef SEAL_USE_ZSTD
auto avg_serialize_zstd = time_serialize_zstd_sum.count() / count;
#endif
cout << "Average encode: " << avg_encode << " microseconds" << endl;
cout << "Average decode: " << avg_decode << " microseconds" << endl;
cout << "Average encrypt: " << avg_encrypt << " microseconds" << endl;
cout << "Average decrypt: " << avg_decrypt << " microseconds" << endl;
cout << "Average add: " << avg_add << " microseconds" << endl;
cout << "Average multiply: " << avg_multiply << " microseconds" << endl;
cout << "Average multiply plain: " << avg_multiply_plain << " microseconds" << endl;
cout << "Average square: " << avg_square << " microseconds" << endl;
if (context.using_keyswitching())
{
cout << "Average relinearize: " << avg_relinearize << " microseconds" << endl;
cout << "Average rescale: " << avg_rescale << " microseconds" << endl;
cout << "Average rotate vector one step: " << avg_rotate_one_step << " microseconds" << endl;
cout << "Average rotate vector random: " << avg_rotate_random << " microseconds" << endl;
cout << "Average complex conjugate: " << avg_conjugate << " microseconds" << endl;
}
cout << "Average serialize ciphertext: " << avg_serialize << " microseconds" << endl;
#ifdef SEAL_USE_ZLIB
cout << "Average compressed (ZLIB) serialize ciphertext: " << avg_serialize_zlib << " microseconds" << endl;
#endif
#ifdef SEAL_USE_ZSTD
cout << "Average compressed (Zstandard) serialize ciphertext: " << avg_serialize_zstd << " microseconds" << endl;
#endif
cout.flush();
}
void example_bfv_performance_default()
{
print_example_banner("BFV Performance Test with Degrees: 4096, 8192, and 16384");
EncryptionParameters parms(scheme_type::bfv);
size_t poly_modulus_degree = 4096;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
parms.set_plain_modulus(786433);
bfv_performance_test(parms);
cout << endl;
poly_modulus_degree = 8192;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
parms.set_plain_modulus(786433);
bfv_performance_test(parms);
cout << endl;
poly_modulus_degree = 16384;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
parms.set_plain_modulus(786433);
bfv_performance_test(parms);
/*
Comment out the following to run the biggest example.
*/
// cout << endl;
// poly_modulus_degree = 32768;
// parms.set_poly_modulus_degree(poly_modulus_degree);
// parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
// parms.set_plain_modulus(786433);
// bfv_performance_test(parms);
}
void example_bfv_performance_custom()
{
size_t poly_modulus_degree = 0;
cout << endl << "Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): ";
if (!(cin >> poly_modulus_degree))
{
cout << "Invalid option." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return;
}
if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 ||
(poly_modulus_degree & (poly_modulus_degree - 1)) != 0)
{
cout << "Invalid option." << endl;
return;
}
string banner = "BFV Performance Test with Degree: ";
print_example_banner(banner + to_string(poly_modulus_degree));
EncryptionParameters parms(scheme_type::bfv);
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
if (poly_modulus_degree == 1024)
{
parms.set_plain_modulus(12289);
}
else
{
parms.set_plain_modulus(786433);
}
bfv_performance_test(parms);
}
void example_ckks_performance_default()
{
print_example_banner("CKKS Performance Test with Degrees: 4096, 8192, and 16384");
// It is not recommended to use BFVDefault primes in CKKS. However, for performance
// test, BFVDefault primes are good enough.
EncryptionParameters parms(scheme_type::ckks);
size_t poly_modulus_degree = 4096;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
ckks_performance_test(parms);
cout << endl;
poly_modulus_degree = 8192;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
ckks_performance_test(parms);
cout << endl;
poly_modulus_degree = 16384;
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
ckks_performance_test(parms);
/*
Comment out the following to run the biggest example.
*/
// cout << endl;
// poly_modulus_degree = 32768;
// parms.set_poly_modulus_degree(poly_modulus_degree);
// parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
// ckks_performance_test(parms);
}
void example_ckks_performance_custom()
{
size_t poly_modulus_degree = 0;
cout << endl << "Set poly_modulus_degree (1024, 2048, 4096, 8192, 16384, or 32768): ";
if (!(cin >> poly_modulus_degree))
{
cout << "Invalid option." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
return;
}
if (poly_modulus_degree < 1024 || poly_modulus_degree > 32768 ||
(poly_modulus_degree & (poly_modulus_degree - 1)) != 0)
{
cout << "Invalid option." << endl;
return;
}
string banner = "CKKS Performance Test with Degree: ";
print_example_banner(banner + to_string(poly_modulus_degree));
EncryptionParameters parms(scheme_type::ckks);
parms.set_poly_modulus_degree(poly_modulus_degree);
parms.set_coeff_modulus(CoeffModulus::BFVDefault(poly_modulus_degree));
ckks_performance_test(parms);
}
/*
Prints a sub-menu to select the performance test.
*/
void example_performance_test()
{
print_example_banner("Example: Performance Test");
while (true)
{
cout << endl;
cout << "Select a scheme (and optionally poly_modulus_degree):" << endl;
cout << " 1. BFV with default degrees" << endl;
cout << " 2. BFV with a custom degree" << endl;
cout << " 3. CKKS with default degrees" << endl;
cout << " 4. CKKS with a custom degree" << endl;
cout << " 0. Back to main menu" << endl;
int selection = 0;
cout << endl << "> Run performance test (1 ~ 4) or go back (0): ";
if (!(cin >> selection))
{
cout << "Invalid option." << endl;
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(), '\n');
continue;
}
switch (selection)
{
case 1:
example_bfv_performance_default();
break;
case 2:
example_bfv_performance_custom();
break;
case 3:
example_ckks_performance_default();
break;
case 4:
example_ckks_performance_custom();
break;
case 0:
cout << endl;
return;
default:
cout << "Invalid option." << endl;
}
}
}
| [
"weidan.ji@basebit.ai"
] | weidan.ji@basebit.ai |
59ecec546b2544c44b9f34af59509db93abc0776 | b9f1e77d86ad07110fae422c6212184d92cb558a | /Item.h | 73f1ab6b89fd323477f12c45b6785645fead43e6 | [] | no_license | calvinlf/BORK | 7c6a05ee1f8b8acdbc6f191a03a609af6aa6ab28 | 08c1ae4de853252127a204cafbfe9ececd9742f8 | refs/heads/master | 2020-04-09T19:46:25.441131 | 2018-12-09T03:00:38 | 2018-12-09T03:00:38 | 160,552,945 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 795 | h | //
// Created by CalPC on 11/27/2018.
//
#ifndef BORK_ITEM_H
#define BORK_ITEM_H
#include <string>
#include <vector>
#include <functional>
using namespace std;
class Item {
public:
Item();
Item(vector<string> names, string description, string use, vector<string> usePhrases);
Item(vector<string> names, string description, string use, vector<string> usePhrases, int weight);
bool hasName(string name);
string getName();
string getDescription();
string getUse();
virtual void useItem();
bool hasUsePhrase(string phrase);
int getWeight() {return weight;}
protected:
void addTheToNames(vector<string> names);
vector<string> names;
vector<string> usePhrases;
string description;
string use;
int weight = 1;
};
#endif //BORK_ITEM_H
| [
"calvin.l.fischer@gmail.com"
] | calvin.l.fischer@gmail.com |
1c14897dcc8eb2daa13d030ad237dd83fc2712cd | eef01cebbf69c1d5132793432578d931a40ce77c | /IF/Classes/scene/battle/BattleManager.cpp | 8f48dfc283d1ffe2a9f1bcbc2191026a1c9dd700 | [] | no_license | atom-chen/zltx | 0b2e78dd97fc94fa0448ba9832da148217f1a77d | 8ead8fdddecd64b7737776c03417d73a82a6ff32 | refs/heads/master | 2022-12-03T05:02:45.624200 | 2017-03-29T02:58:10 | 2017-03-29T02:58:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 35,809 | cpp | //
// BattleManager.cpp
// IF
//
// Created by ganxiaohua on 13-9-17.
//
//
#include "BattleManager.h"
#include "UIComponent.h"
#include "GeneralInfo.h"
#include "CCFloatingText.h"
#include "GeneralManager.h"
#include "MailFightReportCommand.h"
#include <spine/Json.h>
using namespace cocos2d;
CCPoint postion[11][3] =
{
{ ccp(-380, -300), ccp(-132, -300), ccp(100, -300), },//0
{ ccp(-370, -130), ccp(-132, -130), ccp(100, -130), },//1
{ ccp(-360, 0), ccp(-132, 0), ccp(100, 0), },
{ ccp(-350, 105), ccp(-132, 105), ccp(100, 105), },
{ ccp(-350, 200), ccp(-132, 200), ccp(90, 200), },
{ ccp(-350, 285), ccp(-132, 285), ccp(85, 285), },
{ ccp(-350, 370), ccp(-132, 370), ccp(85, 370), },
{ ccp(-340, 450), ccp(-132, 450), ccp(85, 450), },
{ ccp(-340, 515), ccp(-132, 515), ccp(85, 515), },
{ ccp(-340, 570), ccp(-132, 570), ccp(85, 570), },//9
{ ccp(-340, 620), ccp(-132, 620), ccp(85, 620), },//10
};
BattleManager* BattleManager::instance = NULL;
BattleManager* BattleManager::shared()
{
if( NULL == instance )
{
instance = new BattleManager();
instance->isDuringRequestingBattleInfo = false;
}
return instance;
}
void BattleManager::requestBattleInfo(int cityId,int checkpointId,int cost){
m_checkpointId = checkpointId;
m_cityId = cityId;
GlobalData::shared()->lordInfo.energy = GlobalData::shared()->lordInfo.energy - cost;
// UIComponent::getInstance()->onCityEnergyUpdate(NULL);
UIComponent::getInstance()->UIHide();
m_lastSence = SceneController::getInstance()->currentSceneId;
// BattleReportCommand* cmd = new BattleReportCommand(cityId,cost);
// cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL));
// cmd->sendAndRelease();
this->parseBattleReport(NULL);
goToBattle(NULL);
}
void BattleManager::mailFightReport(std::string reportUid){
if(GlobalData::shared()->playerInfo.gmFlag==1){
MailFightReportCommand* cmd = new MailFightReportCommand(reportUid);
cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL));
cmd->sendAndRelease();
}
}
void BattleManager::goToBattle(CCObject* p){
// BattleReportCommand* cmd = new BattleReportCommand(0,0);
// cmd->setSuccessCallback(CCCallFuncO::create(this, callfuncO_selector(BattleManager::goToBattle), NULL));
// cmd->sendAndRelease();
// return ;
// GameController::getInstance()->removeWaitInterface();
// SceneController::getInstance()->gotoScene(SCENE_ID_BATTLE,false,true,1);
// CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_TRANSITION_FINISHED);
}
std::string BattleManager::getWalkDirect(std::string direct){
std::string changeDirect = "N";
if(direct=="NE"){
changeDirect = "NW";
}else if(direct=="SE"){
changeDirect = "SW";
}else if(direct=="E"){
changeDirect = "W";
}else{
changeDirect = direct;
}
return changeDirect;
}
void BattleManager::parseBattleReport(CCObject* report){
// if(report!=NULL){
// m_report = _dict(report)->valueForKey("report")->getCString();
// }
// if(m_report==""){
// CCLOG("battle report is NULL");//
// //return;
// }
// CCLOG("result=%s",m_report.c_str());//
// //107310
// std::string strReport1 = "{\"battlereport\":{\"winside\":0,\"battleType\":3,\"report\":\"2_1_3|gj|1_1_1|0|0|0|sh|0;2_1_4|gj|1_1_1|0|0|0|sh|0;xj|4|107920|1_1_1|sh|0;xj|4|107900|1_1_1|sh|0;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;2_1_1|gj|1_1_1|6|0|0|sh|0;1_1_1|gj|2_1_1|6|1|938|sh|938;1_1_1|mv|0|80|2_1_2|7|1;2_1_2|mv|0|80|1_1_1|1|7;2_1_2|gj|1_1_1|8|0|0|sh|0;1_1_1|gj|2_1_2|8|0|711|sh|711\",\"maxRound\":8},\"attacker\":{\"member\":\"1|107009|41100|41100|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|6\"},\"defender\":{\"member\":\"1|107002|285|285|0|100;2|107301|102|102|0|110;3|107800|1|1|-30|130;4|107800|1|1|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"}}";
//
// std::string strReport2 = "{\"battlereport\":{\"winside\":1,\"battleType\":3,\"report\":\"2_1_4|mv|0|110|1_1_1|1|3;xj|4|107900|1_1_1|sh|5;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;2_1_2|mv|0|70|1_1_1|1|7;2_1_3|mv|0|70|1_1_1|1|9;xj|10|107900|1_1_1|sh|5;xj|16|107900|1_1_1|sh|5;1_1_1|gj|2_1_1|6|12|3|sh|0|sh|1|sh|0|sh|1|sh|0|sh|1|sh|0;2_1_1|gj|1_1_1|6|12|4|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|1;2_1_2|gj|1_1_1|8|10|37|sh|6|sh|6|sh|6|sh|6|sh|6|sh|7;2_1_3|gj|1_1_1|10|8|15|sh|3|sh|3|sh|3|sh|3|sh|3;2_1_4|gj|1_1_1|4|14|17|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3;2_1_5|gj|1_1_1|2|16|23|sh|2|sh|2|sh|3|sh|3|sh|2|sh|2|sh|3|sh|3|sh|3\",\"maxRound\":18},\"attacker\":{\"member\":\"1|107000|110|110|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|2\"},\"defender\":{\"member\":\"1|107000|97|97|0|100;2|107002|140|140|0|110;3|107100|160|160|0|120;4|107200|110|110|0|130;5|107300|20|20|0|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|5\"}}";
//
// std::string strReport3 = "{\"battlereport\":{\"winside\":1,\"battleType\":3,\"report\":\"2_1_9|gj|1_1_1|0|0|2|sh|2;2_1_10|gj|1_1_1|0|0|2|sh|2;1_1_5|mv|0|10|2_1_1|1|1;2_1_7|mv|0|150|1_1_1|1|1;1_1_3|mv|0|30|2_1_1|1|3;1_1_4|mv|0|30|2_1_1|1|3;2_1_6|mv|0|140|1_1_1|1|3;2_1_8|mv|0|160|1_1_1|1|3;xj|4|107900|1_1_1|sh|2;xj|4|107901|1_1_1|sh|15;xj|4|107911|1_1_1|sh|18;1_1_1|mv|0|70|2_1_1|1|5;2_1_1|mv|0|70|1_1_1|1|5;1_1_2|mv|0|70|2_1_1|1|7;2_1_2|mv|0|70|1_1_1|1|7;2_1_3|mv|0|70|1_1_1|1|9;xj|10|107900|1_1_1|sh|2;xj|10|107901|1_1_1|sh|15;xj|10|107911|1_1_1|sh|19;2_1_4|mv|0|70|1_1_1|1|11;2_1_5|mv|0|70|1_1_1|1|13;xj|16|107900|1_1_1|sh|2;xj|16|107901|1_1_1|sh|17;xj|16|107911|1_1_1|sh|20;2_1_9|gj|1_1_1|18|0|3|sh|3;2_1_10|gj|1_1_1|18|0|3|sh|3;1_1_1|gj|2_1_1|6|16|12|sh|2|sh|2|sh|2|sh|2|sh|1|sh|1|sh|1|sh|1|sh|0;xj|22|107900|1_1_1|sh|0;xj|22|107901|1_1_1|sh|0;xj|22|107911|1_1_1|sh|0;2_1_1|gj|1_1_1|6|18|176|sh|19|sh|19|sh|19|sh|19|sh|19|sh|19|sh|19|sh|21|sh|22;2_1_2|gj|1_1_1|8|16|157|sh|18|sh|19|sh|19|sh|19|sh|20|sh|20|sh|20|sh|22;2_1_3|gj|1_1_1|10|14|25|sh|3|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4;2_1_4|gj|1_1_1|12|12|37|sh|6|sh|6|sh|5|sh|6|sh|7|sh|7;2_1_5|gj|1_1_1|14|10|101|sh|19|sh|20|sh|20|sh|20|sh|22;2_1_6|gj|1_1_1|4|20|226|sh|22|sh|21|sh|22|sh|22|sh|22|sh|22|sh|23|sh|23|sh|24|sh|25;2_1_7|gj|1_1_1|2|22|105|sh|9|sh|9|sh|9|sh|9|sh|9|sh|9|sh|10|sh|9|sh|10|sh|11|sh|11;2_1_8|gj|1_1_1|4|20|284|sh|27|sh|27|sh|27|sh|28|sh|28|sh|28|sh|29|sh|29|sh|29|sh|32;xj|28|107900|1_1_1|sh|0;xj|28|107901|1_1_1|sh|0;xj|28|107911|1_1_1|sh|0;xj|34|107900|1_1_1|sh|0;xj|34|107901|1_1_1|sh|0;xj|34|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|36|0|0|sh|0;2_1_10|gj|1_1_1|36|0|0|sh|0;xj|40|107900|1_1_1|sh|0;xj|40|107901|1_1_1|sh|0;xj|40|107911|1_1_1|sh|0;xj|46|107900|1_1_1|sh|0;xj|46|107901|1_1_1|sh|0;xj|46|107911|1_1_1|sh|0;xj|52|107900|1_1_1|sh|0;xj|52|107901|1_1_1|sh|0;xj|52|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|54|0|0|sh|0;2_1_10|gj|1_1_1|54|0|0|sh|0;xj|58|107900|1_1_1|sh|0;xj|58|107901|1_1_1|sh|0;xj|58|107911|1_1_1|sh|0;xj|64|107900|1_1_1|sh|0;xj|64|107901|1_1_1|sh|0;xj|64|107911|1_1_1|sh|0;xj|70|107900|1_1_1|sh|0;xj|70|107901|1_1_1|sh|0;xj|70|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|72|0|0|sh|0;2_1_10|gj|1_1_1|72|0|0|sh|0;xj|76|107900|1_1_1|sh|0;xj|76|107901|1_1_1|sh|0;xj|76|107911|1_1_1|sh|0;xj|82|107900|1_1_1|sh|0;xj|82|107901|1_1_1|sh|0;xj|82|107911|1_1_1|sh|0;xj|88|107900|1_1_1|sh|0;xj|88|107901|1_1_1|sh|0;xj|88|107911|1_1_1|sh|0;2_1_9|gj|1_1_1|90|0|0|sh|0;2_1_10|gj|1_1_1|90|0|0|sh|0;xj|94|107900|1_1_1|sh|0;xj|94|107901|1_1_1|sh|0;xj|94|107911|1_1_1|sh|0;2_1_1|gj|1_1_2|24|76|513|sh|12|sh|13|sh|13|sh|13|sh|12|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|14|sh|13|sh|13|sh|13|sh|13|sh|14|sh|14|sh|14|sh|13|sh|13|sh|13|sh|14|sh|13|sh|14|sh|14|sh|14;1_1_2|gj|2_1_1|8|92|25|sh|1|sh|1|sh|0|sh|1|sh|1|sh|1|sh|0|sh|1|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0;2_1_2|gj|1_1_2|24|76|432|sh|11|sh|11|sh|11|sh|11|sh|11|sh|10|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|10|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|11|sh|12|sh|11|sh|11|sh|11|sh|11|sh|12|sh|11|sh|12|sh|11|sh|12|sh|12|sh|11|sh|11;1_1_3|gj|2_1_1|4|96|16|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|0|sh|1|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|1|sh|1|sh|1|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0|sh|0;2_1_3|gj|1_1_2|24|76|82|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3;1_1_4|gj|2_1_1|4|96|72|sh|1|sh|2|sh|2|sh|1|sh|1|sh|2|sh|1|sh|2|sh|1|sh|2|sh|1|sh|1|sh|2|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|1|sh|1|sh|1|sh|2|sh|2|sh|2|sh|2|sh|1|sh|1|sh|1|sh|1|sh|1|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2;2_1_4|gj|1_1_2|24|76|135|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4|sh|3|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4|sh|3|sh|3|sh|3|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3;1_1_5|gj|2_1_1|2|98|182|sh|3|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|4|sh|4|sh|3|sh|3|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|3|sh|4|sh|4|sh|4|sh|4|sh|3|sh|3|sh|3|sh|4|sh|4|sh|4|sh|4|sh|4|sh|4|sh|3|sh|3|sh|3|sh|3|sh|3|sh|4;2_1_5|gj|1_1_2|24|76|529|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|13|sh|14|sh|13|sh|14|sh|14|sh|14|sh|13|sh|14|sh|13|sh|13|sh|14|sh|13|sh|13|sh|14|sh|14|sh|14|sh|14|sh|14|sh|13|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|14|sh|15;1_1_6|gj|2_1_1|2|98|111|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|2|sh|3|sh|3|sh|3|sh|2;2_1_6|gj|1_1_2|24|76|603|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|16|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|15|sh|16|sh|15|sh|16|sh|16|sh|15|sh|16|sh|16|sh|15|sh|15|sh|15|sh|16|sh|16|sh|16|sh|15|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16|sh|16;2_1_7|gj|1_1_2|24|76|250|sh|6|sh|6|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|6|sh|7|sh|6|sh|6|sh|6|sh|6|sh|6|sh|6|sh|6|sh|7|sh|6|sh|6|sh|7|sh|7|sh|7|sh|6|sh|6|sh|7|sh|7|sh|6|sh|6|sh|7|sh|6|sh|7|sh|7|sh|7|sh|7|sh|7;2_1_8|gj|1_1_2|24|76|780|sh|19|sh|19|sh|19|sh|20|sh|19|sh|19|sh|19|sh|19|sh|20|sh|20|sh|19|sh|20|sh|19|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|20|sh|21|sh|20|sh|20|sh|20|sh|21|sh|21|sh|21|sh|21|sh|21|sh|20|sh|21|sh|21|sh|21\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107102|1170|1170|0|40;2|107301|4991|4991|0|30;3|107200|1315|1315|0|20;4|107201|4137|4137|0|10;5|107202|5773|5773|0|0;6|107300|2863|2863|0|-10\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"},\"defender\":{\"member\":\"1|107003|22147|22147|0|100;2|107002|2808|2808|0|110;3|107100|724|724|0|120;4|107101|606|606|0|130;5|107102|7384|7384|0|140;6|107202|4010|4010|0|150;7|107300|907|907|0|160;8|107302|1860|1860|0|170;9|107801|1|1|-30|130;10|107801|1|1|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|12\"}}";
//
// std::string strReport4 = "{\"battlereport\":{\"winside\":1,\"battleType\":0,\"report\":\"25|gj|11|0|1|99|sh|99;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;13|mv|0|30|21|5|1;111|mv|-30|70|211|1|5;211|mv|-30|70|111|1|5;121|mv|30|70|221|1|5;221|mv|30|70|121|1|5;12|mv|0|70|21|3|7;14|mv|0|30|21|7|3;11|gj|21|6|10|459|sh|86|sh|88|sh|89|sh|94|sh|102;11|jn|101009|16|21|sh|240;21|gj|11|6|10|173|sh|46|sh|42|sh|38|sh|29|sh|18;21|jn|101009|16|11|sh|10;13|gj|21|6|10|768|sh|144|sh|147|sh|150|sh|158|sh|169;13|jn|101009|16|21|sh|380;111|gj|211|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;111|jn|101009|16|211|sh|104;211|gj|111|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;211|jn|101009|16|111|sh|104;121|gj|221|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;121|jn|101009|16|221|sh|104;221|gj|121|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;221|jn|101009|16|121|sh|104;12|gj|21|10|7|418|sh|91|sh|97|sh|106|sh|124;14|gj|21|10|7|667|sh|150|sh|158|sh|169|sh|190;25|gj|11|18|1|44|sh|44;11|mv|-30|70|211|17|5;12|mv|-30|70|211|17|5;13|mv|-12|48|211|17|5;14|mv|-12|48|211|17|5;12|gj|211|22|2|91|sh|91;12|jn|101009|24|211|sh|196;14|gj|211|22|2|150|sh|150;14|jn|101009|24|211|sh|318;211|gj|111|18|9|197|sh|50|sh|49|sh|49|sh|36|sh|13;11|gj|211|22|5|292|sh|87|sh|94|sh|111;12|gj|211|26|1|116|sh|116;13|gj|211|22|5|490|sh|150|sh|159|sh|181;14|gj|211|26|1|181|sh|181;111|gj|211|18|9|264|sh|50|sh|49|sh|49|sh|52|sh|64;121|gj|221|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;121|jn|101009|28|221|sh|93;221|gj|121|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;221|jn|101009|28|121|sh|93;13|mv|4|56|221|27|5;14|mv|4|56|221|27|5;13|gj|221|32|4|316|sh|155|sh|161;13|jn|101009|36|221|sh|339;25|gj|11|36|1|10|sh|10;11|mv|30|70|221|27|11;12|mv|30|70|221|27|11;111|mv|30|70|221|27|11;111|jn|101009|38|221|sh|144;221|gj|121|30|9|155|sh|45|sh|44|sh|35|sh|25|sh|6;11|gj|221|38|1|122|sh|122;12|gj|221|38|1|126|sh|126;13|gj|221|38|1|193|sh|193;14|gj|221|32|7|678|sh|155|sh|161|sh|169|sh|193;121|gj|221|30|9|248|sh|45|sh|44|sh|46|sh|50|sh|63\",\"maxRound\":38},\"attacker\":{\"member\":\"1|107010|3000|3000|0|40;2|107010|3000|3000|0|30;3|107020|3000|3000|0|20;4|107020|3000|3000|0|10;11|107010|2100|2100|-30|40;21|107010|2100|2100|30|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;11|107010|2100|2100|-30|100;21|107010|2100|2100|30|100;5|107800|2100|2100|60|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}";
//
// std::string strReport5 = "{\"battlereport\":{\"winside\":-1,\"battleType\":0,\"report\":\"25|gj|11|0|1|0|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;11|jn|101009|16|21|sh|104;21|gj|11|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;21|jn|101009|16|11|sh|104;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|18|1|0|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;11|jn|101009|28|21|sh|93;21|gj|11|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;21|jn|101009|28|11|sh|93;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|36|1|0|sh|0;11|gj|21|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;11|jn|101009|40|21|sh|83;21|gj|11|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;21|jn|101009|40|11|sh|83;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;11|jn|101009|52|21|sh|72;21|gj|11|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;21|jn|101009|52|11|sh|72;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|54|1|1|sh|1;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;11|jn|101009|64|21|sh|62;21|gj|11|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;21|jn|101009|64|11|sh|62;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|72|1|1|sh|1;11|gj|21|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;11|jn|101009|76|21|sh|53;21|gj|11|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;21|jn|101009|76|11|sh|53;xj|107900|11|sh|0|107910|11|sh|0;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;11|jn|101009|88|21|sh|43;21|gj|11|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;21|jn|101009|88|11|sh|43;xj|107900|11|sh|0|107910|11|sh|0;25|gj|11|90|1|1|sh|1;xj|107900|11|sh|0|107910|11|sh|0;11|gj|21|90|10|92|sh|20|sh|19|sh|18|sh|18|sh|17;11|jn|101009|100|21|sh|33;21|gj|11|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;21|jn|101009|100|11|sh|34\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107010|2100|2100|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;5|107800|2100|2100|60|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}";
//
// std::string strReport6 = "{\"battlereport\":{\"winside\":0,\"battleType\":0,\"report\":\"25|gj|11|0|1|0|sh|0;26|gj|11|0|1|0|sh|0;11|mv|0|70|21|1|5;21|mv|0|70|11|1|5;111|mv|-30|70|211|1|5;211|mv|-30|70|111|1|5;11|gj|21|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;11|jn|101009|16|21|sh|104;21|gj|11|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;21|jn|101009|16|11|sh|104;111|gj|211|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;111|jn|101009|16|211|sh|104;211|gj|111|6|10|270|sh|56|sh|55|sh|54|sh|53|sh|52;211|jn|101009|16|111|sh|104;25|gj|11|18|1|0|sh|0;26|gj|11|18|1|0|sh|0;11|gj|21|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;11|jn|101009|28|21|sh|93;21|gj|11|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;21|jn|101009|28|11|sh|93;111|gj|211|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;111|jn|101009|28|211|sh|93;211|gj|111|18|10|243|sh|50|sh|49|sh|49|sh|48|sh|47;211|jn|101009|28|111|sh|93;25|gj|11|36|1|0|sh|0;26|gj|11|36|1|0|sh|0;11|gj|21|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;11|jn|101009|40|21|sh|83;21|gj|11|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;21|jn|101009|40|11|sh|83;111|gj|211|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;111|jn|101009|40|211|sh|83;211|gj|111|30|10|216|sh|45|sh|44|sh|43|sh|42|sh|42;211|jn|101009|40|111|sh|83;11|gj|21|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;11|jn|101009|52|21|sh|72;21|gj|11|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;21|jn|101009|52|11|sh|72;111|gj|211|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;111|jn|101009|52|211|sh|72;211|gj|111|42|10|191|sh|40|sh|39|sh|38|sh|37|sh|37;211|jn|101009|52|111|sh|72;25|gj|11|54|1|1|sh|1;26|gj|11|54|1|1|sh|1;11|gj|21|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;11|jn|101009|64|21|sh|62;21|gj|11|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;21|jn|101009|64|11|sh|62;111|gj|211|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;111|jn|101009|64|211|sh|62;211|gj|111|54|10|165|sh|34|sh|34|sh|33|sh|32|sh|32;211|jn|101009|64|111|sh|62;25|gj|11|72|1|1|sh|1;26|gj|11|72|1|1|sh|1;11|gj|21|66|10|140|sh|29|sh|29|sh|28|sh|27|sh|27;11|jn|101009|76|21|sh|52;21|gj|11|66|10|142|sh|30|sh|29|sh|28|sh|28|sh|27;21|jn|101009|76|11|sh|53;111|gj|211|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;111|jn|101009|76|211|sh|53;211|gj|111|66|10|141|sh|30|sh|29|sh|28|sh|27|sh|27;211|jn|101009|76|111|sh|53;11|gj|21|78|10|115|sh|24|sh|24|sh|23|sh|22|sh|22;11|jn|101009|88|21|sh|43;21|gj|11|78|10|118|sh|25|sh|24|sh|24|sh|23|sh|22;21|jn|101009|88|11|sh|44;111|gj|211|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;111|jn|101009|88|211|sh|43;211|gj|111|78|10|117|sh|25|sh|24|sh|23|sh|23|sh|22;211|jn|101009|88|111|sh|43;25|gj|11|90|1|1|sh|1;26|gj|11|90|1|1|sh|1;11|gj|21|90|10|91|sh|20|sh|19|sh|18|sh|17|sh|17;11|jn|101009|100|21|sh|32;21|gj|11|90|10|95|sh|20|sh|20|sh|19|sh|18|sh|18;21|jn|101009|100|11|sh|35;111|gj|211|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;111|jn|101009|100|211|sh|34;211|gj|111|90|10|93|sh|20|sh|19|sh|19|sh|18|sh|17;211|jn|101009|100|111|sh|34\",\"maxRound\":100},\"attacker\":{\"member\":\"1|107010|2100|2100|0|40;11|107010|2100|2100|-30|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"},\"defender\":{\"member\":\"1|107010|2100|2100|0|100;11|107010|2100|2100|-30|100;5|107800|2100|2100|-60|150;6|107800|2100|2100|50|150\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\"}}";
//
//
// std::string strReport11 = "{\"battlereport\":{\"winside\":1,\"battleType\":0,\"report\":\"2_1_3|gj|1_1_1|0|0|36|sh|36;2_1_4|gj|1_1_1|0|0|36|sh|36;2_1_2|mv|0|100|1_1_1|1|1;1_1_1|mv|0|50|2_1_1|1|1;2_1_1|mv|0|90|1_1_1|1|1;2_1_2|gj|1_1_1|2|0|2|sh|2\",\"maxRound\":2},\"attacker\":{\"member\":\"1|107000|50|50|0|40\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"\"},\"defender\":{\"member\":\"1|107100|150|150|0|100;2|107200|85|85|0|110;3|107800|100|100|-30|130;4|107800|100|100|30|130\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240020|4\"}}";
//
// std::string strReport12 = "{\"battlereport\":{\"winside\":0,\"battleType\":0,\"report\":\"1_2_1|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_2_1|sk|102020|2|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|mv|0|20|2_1_1|1|3;1_2_1|sk|102020|6|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;2_2_1|sk|102020|6|1_1_1|sh|40|1_1_2|sh|40|1_1_3|sh|40;2_2_2|sk|102020|8|1_1_1|sh|40|1_1_2|sh|40|1_1_3|sh|40;1_2_2|sk|102020|10|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|mv|0|70|2_1_1|5|9;2_1_1|mv|0|70|1_1_1|1|13;1_1_2|mv|0|70|2_1_1|1|13;2_1_2|mv|0|70|1_1_1|1|13;1_1_3|mv|0|70|2_1_1|1|13;2_1_3|mv|0|70|1_1_1|1|13;1_1_4|mv|0|70|2_1_1|1|13;2_1_4|mv|0|70|1_1_1|1|13;1_1_5|mv|0|70|2_1_1|1|13;2_1_5|mv|0|70|1_1_1|1|13;1_2_1|sk|102020|14|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_2_2|sk|102020|14|2_1_1|sh|40|2_1_2|sh|40|2_1_3|sh|40;1_1_1|gj|2_1_1|14|3|14|sh|14|sh|0;2_1_1|gj|1_1_1|14|2|13|sh|13;1_1_2|gj|2_1_1|14|4|15|sh|15|sh|0;2_1_2|gj|1_1_1|14|4|28|sh|14|sh|14;1_1_3|gj|2_1_1|14|4|23|sh|23|sh|0;2_1_3|gj|1_1_1|14|4|40|sh|20|sh|20;1_1_4|gj|2_1_1|14|4|48|sh|48|sh|0;2_1_4|gj|1_1_1|14|4|97|sh|47|sh|50;1_1_5|gj|2_1_1|14|4|82|sh|82|sh|0;2_1_5|gj|1_1_1|14|4|165|sh|80|sh|85;2_1_2|gj|1_1_2|18|3|18|sh|10|sh|8;2_2_2|sk|102020|20|1_1_2|sh|40|1_1_3|sh|40|1_1_4|sh|40;1_1_2|gj|2_1_2|18|4|27|sh|13|sh|14;1_1_3|gj|2_1_2|18|4|42|sh|19|sh|23;1_1_4|gj|2_1_2|18|4|86|sh|40|sh|46;1_1_5|gj|2_1_2|18|4|146|sh|69|sh|77;1_1_2|gj|2_1_3|22|1|4|sh|4;2_1_3|gj|1_1_2|18|6|48|sh|14|sh|15|sh|19;2_1_4|gj|1_1_2|18|6|122|sh|37|sh|39|sh|46;2_1_5|gj|1_1_2|18|6|209|sh|65|sh|68|sh|76;2_2_1|sk|102020|24|1_1_3|sh|40|1_1_4|sh|40|1_1_5|sh|40;2_1_3|gj|1_1_3|24|3|11|sh|6|sh|5;1_2_1|sk|102020|26|2_1_4|sh|40|2_1_5|sh|40;1_1_3|gj|2_1_3|22|6|30|sh|9|sh|10|sh|11;1_1_4|gj|2_1_3|22|6|67|sh|20|sh|22|sh|25;1_1_4|jn|102000|28|2_1_1|bj|0|2_1_2|bj|0;1_1_5|gj|2_1_3|22|6|123|sh|38|sh|41|sh|44;1_1_3|gj|2_1_4|28|3|32|sh|17|sh|15;2_2_2|sk|102020|30|1_1_4|sh|40|1_1_5|sh|40;2_1_4|gj|1_1_3|24|8|82|sh|19|sh|21|sh|21|sh|21;2_1_5|gj|1_1_3|24|8|151|sh|35|sh|38|sh|38|sh|40;2_1_4|gj|1_1_4|32|3|45|sh|31|sh|14;2_2_1|sk|102020|34|1_1_4|sh|40|1_1_5|sh|40;1_1_4|gj|2_1_4|30|6|130|sh|44|sh|44|sh|42;1_1_5|gj|2_1_4|28|8|319|sh|77|sh|79|sh|78|sh|85;1_1_4|gj|2_1_5|36|1|11|sh|11;2_1_5|gj|1_1_4|32|6|245|sh|78|sh|81|sh|86;1_2_2|sk|102020|38|2_1_5|sh|40;2_1_5|gj|1_1_5|38|4|82|sh|44|sh|38;2_1_5|jn|102000|42|1_1_1|bj|0|1_1_2|bj|0;2_2_2|sk|102020|46|1_1_5|sh|40;2_1_5|gj|1_1_5|44|9|129|sh|33|sh|29|sh|26|sh|23|sh|18;1_1_5|gj|2_1_5|36|17|311|sh|40|sh|41|sh|39|sh|37|sh|38|sh|36|sh|29|sh|27|sh|24\",\"maxRound\":52},\"attacker\":{\"member\":\"1|107000|400|400|0|0;2|107001|400|400|0|0;3|107003|400|400|0|0;4|107002|400|400|0|0;5|107004|400|400|0|0\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240000|1;2|240001|1\"},\"defender\":{\"member\":\"1|107000|400|400|0|140;2|107001|400|400|0|140;3|107003|400|400|0|140;4|107002|400|400|0|140;5|107004|400|400|0|140\",\"playerlevel\":1,\"playername\":\"\",\"playerid\":\"\",\"general\":\"1|240000|1;2|240001|1\"}}";
//
// //m_report = strReport1;
// Json* jReport = Json_create(m_report.c_str());
// Json* attack = Json_getItem(jReport,"attacker");
// BattlePlayer* attacker = this->createBPlayer(attack,0);
// BattleObjectManager::shared()->setAttacker(attacker);
// attacker->release();
//
// Json* def = Json_getItem(jReport,"defender");
// BattlePlayer* defender = this->createBPlayer(def,1);
// BattleObjectManager::shared()->setDefender(defender);
// defender->release();
//
// //Json* rewardJson = Json_getItem(jReport,"reward");
// if(BattleObjectManager::shared()->getRewardSpecialItems()==NULL){
// BattleObjectManager::shared()->setRewardSpecialItems(CCArray::create());
// }
// BattleObjectManager::shared()->getRewardSpecialItems()->removeAllObjects();
// if(BattleObjectManager::shared()->getBattleRewardRes()==NULL){
// BattleObjectManager::shared()->setBattleRewardRes(CCArray::create());
// }else{
// BattleObjectManager::shared()->getBattleRewardRes()->removeAllObjects();
// }
//
// if(BattleObjectManager::shared()->getDefGenerals()==NULL){
// BattleObjectManager::shared()->setDefGenerals(CCArray::create());
// }else{
// BattleObjectManager::shared()->getDefGenerals()->removeAllObjects();
// }
//
// Json* battleR=Json_getItem(jReport,"battlereport");
// std::string battleReport = Json_getString(battleR,"report","");
//
// BattleObjectManager::shared()->setWinside(Json_getInt(battleR,"winside",0));
// BattleObjectManager::shared()->setBattleType(Json_getInt(battleR,"battleType",0));
// BattleObjectManager::shared()->setMaxRound(Json_getInt(battleR,"maxRound",0));
// BattleObjectManager::shared()->setFround(Json_getInt(battleR,"fround",0));
// BattleObjectManager::shared()->setAttForces(Json_getInt(battleR,"attlost",0));
// BattleObjectManager::shared()->setDefForces(Json_getInt(battleR,"deflost",0));
// BattleObjectManager::shared()->setAttRemainForces(Json_getInt(battleR,"attRemainForces",0));
// BattleObjectManager::shared()->setDefRemainForces(Json_getInt(battleR,"defRemainForces",0));
//
// std::vector<std::string> reportItems;
// CCCommonUtils::splitString(battleReport,";",reportItems);
// int size = reportItems.size();
// std::vector<std::string> itemArr;
// if(BattleObjectManager::shared()->getBattleSequences()==NULL){
// BattleObjectManager::shared()->setBattleSequences(CCArray::create());
// }
// CCArray* battleSequences = BattleObjectManager::shared()->getBattleSequences();
// battleSequences->removeAllObjects();
// int num = Json_getInt(battleR,"maxRound",0)+2;//总序列
// BattleSequenceObject* sequenece;
// for(int i=0;i<num;i++){
// sequenece = new BattleSequenceObject();
// sequenece->setResults(CCArray::create());
// battleSequences->addObject(sequenece);
// sequenece->release();
// }
// int maxSequence = 0 ;
// for(int i=0;i<size;i++){
// itemArr.clear();
// CCCommonUtils::splitString(reportItems[i],"|",itemArr);
//
// std::string info = itemArr[0];
// std::vector<std::string> pros;
// CCCommonUtils::splitString(info,"_",pros);
// int side = 0;
// int attArmyType = 0;
// int index = 0;
// if (pros.size()==3) {
// side = atoi(pros[0].c_str())-1;//那一边的
// attArmyType = atoi(pros[1].c_str())-1;
// index = atoi(pros[2].c_str())-1;//兵位置的索引
// }
// std::string m_type = itemArr[1];//动作
// std::string m_specialAction = itemArr[0];//陷阱
// int startIndex = -1;
// int sequenceNum = 0;
// int targetSide = 0;
// int targetIndex = 0;
// int defArmyType = 0;
// std::string skillId = "";
// int x = 0;
// int y = 0;
// int m_value = 0;
// std::string m_target = "";
// std::vector<std::string> targetpros;
// if(m_type=="mv"){
// x = atoi(itemArr[2].c_str())-1;
// y = atoi(itemArr[3].c_str())-1;
// m_target = itemArr[4];//移动进攻的目标
// CCCommonUtils::splitString(m_target,"_",targetpros);
// targetSide = atoi(targetpros[0].c_str())-1;
// defArmyType = atoi(targetpros[1].c_str())-1;
// targetIndex = atoi(targetpros[2].c_str())-1;
// startIndex = atoi(itemArr[5].c_str());//开始的回合索引
// sequenceNum = atoi(itemArr[6].c_str());//回合数
// }else if(m_type=="gj"){
// m_target = itemArr[2];//进攻的目标
// CCCommonUtils::splitString(m_target,"_",targetpros);
// targetSide = atoi(targetpros[0].c_str())-1;
// defArmyType = atoi(targetpros[1].c_str())-1;
// targetIndex = atoi(targetpros[2].c_str())-1;
// m_value = atoi(itemArr[5].c_str());// sh
// startIndex = atoi(itemArr[3].c_str());//开始的回合索引
// sequenceNum = atoi(itemArr[4].c_str());//回合数
// }else if(m_type=="jn"){//13|jn|102022|28|23|sh|30;
// m_target = itemArr[4];//进攻的目标
// CCCommonUtils::splitString(m_target,"_",targetpros);
// targetSide = atoi(targetpros[0].c_str())-1;
// defArmyType = atoi(targetpros[1].c_str())-1;
// targetIndex = atoi(targetpros[2].c_str())-1;
// m_value = atoi(itemArr[6].c_str());// sh
// startIndex = atoi(itemArr[3].c_str());//开始的回合索引
// sequenceNum = 1;
// skillId = itemArr[2];
// }else if(m_specialAction=="xj"){//xj|4|107900|13|sh|0
// m_type = m_specialAction;
// m_target = itemArr[3];//进攻的目标
// CCCommonUtils::splitString(m_target,"_",targetpros);
// targetSide = atoi(targetpros[0].c_str())-1;
// defArmyType = atoi(targetpros[1].c_str())-1;
// targetIndex = atoi(targetpros[2].c_str())-1;
// m_value = atoi(itemArr[5].c_str());// sh
// startIndex = atoi(itemArr[1].c_str());//开始的回合索引
// sequenceNum = 1;
// skillId = itemArr[2];
// }else if(m_type=="sk"){//1_2_2|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40
// m_target = itemArr[4];//进攻的目标
// startIndex = atoi(itemArr[3].c_str());//开始的回合索引
// sequenceNum = 1;
// skillId = itemArr[2];
// }
//
// int temp = startIndex+sequenceNum;
// if(temp>maxSequence){
// maxSequence = temp;
// BattleObjectManager::shared()->setMaxRound(maxSequence);
// }
// BattleResult* res = new BattleResult();
// res->m_side = side;
// res->m_index = index;
// res->m_attArmyType = attArmyType;
// res->m_defArmyType = defArmyType;
// res->m_type = m_type;
// res->m_skillId = skillId;
//// BattleGrid* grid = new BattleGrid(x,y);
//// res->setAttackPos(grid);
//// grid->release();
// //lable->setPosition(ccp((j-1)*250, (i-5)*80));
// res->m_time = sequenceNum;
// res->m_targetSide = targetSide;
// res->m_targetIndex = targetIndex;
// res->m_sequenceIndex = startIndex;
// res->m_attack = 1;
// res->m_value = m_value;
// if(startIndex>battleSequences->count()){
// sequenece = new BattleSequenceObject();
// sequenece->setResults(CCArray::create());
// battleSequences->addObject(sequenece);
// sequenece->release();
// }
// if(startIndex<0) continue;
// sequenece = (BattleSequenceObject*)battleSequences->objectAtIndex(startIndex);
//// if(sequenece!=NULL){
//// sequenece->getResults()->addObject(res);
//// }
// res->setHurtList(CCArray::create());
// if(itemArr.size()>6 && m_type!="jn" && m_type!="sk"){
// std::string hurt_type = itemArr[6];
// if(hurt_type=="sh" || hurt_type=="bj"){
// int len = itemArr.size()-1;
// for (int i=6; i<len && len-i>=1;i=i+2) {
// std::string h_type = itemArr[i];
// if(h_type=="sh" || h_type=="bj"){
// if(itemArr.size()<=(i+1)) continue;
// std::string value = itemArr[i+1];
// SequenceResult* sr = new SequenceResult();
// sr->m_index = i+res->m_sequenceIndex;
// if(value==""){
// sr->m_value = 0;
// }else{
// sr->m_value = atoi(value.c_str());
// }
// sr->m_type = h_type;
// res->getHurtList()->addObject(sr);
// sr->release();
// }
// }
// }
// }
// res->setSkillhHurtEffs(CCArray::create());
// if(m_type=="sk"){//1_2_2|sk|102020|0|2_1_1|sh|40|2_1_2|sh|40
// int len = itemArr.size()-1;
// for (int i=4; i<len && len-i>=2;i=i+3) {
// m_target = itemArr[i];//进攻的目标
// targetpros.clear();
// CCCommonUtils::splitString(m_target,"_",targetpros);
// int side = atoi(targetpros[0].c_str())-1;
// int armyType = atoi(targetpros[1].c_str())-1;
// int pos = atoi(targetpros[2].c_str())-1;
// std::string hurtType = itemArr[i+1];
// int value = atoi(itemArr[i+2].c_str());
// SkillHurtResult* hr = new SkillHurtResult(side,armyType,pos,hurtType,value);
// res->getSkillhHurtEffs()->addObject(hr);
// hr->release();
// }
//
// sequenceNum = 1;
// skillId = itemArr[2];
// }
//// res->release();
// }
// Json_dispose(jReport);
// CCSafeNotificationCenter::sharedNotificationCenter()->postNotification(MSG_CITY_RESOURCES_UPDATE);
}
//BattlePlayer* BattleManager::createBPlayer(Json* json,int side){
// if(json==NULL) return NULL;
// BattlePlayer* player = new BattlePlayer();
// player->setPlayerid(Json_getString(json,"playerid",""));
// player->setPlayername(Json_getString(json,"playername",""));
// player->setPlayerlevel(Json_getInt(json,"playerlevel",1));
// player->setPic(Json_getString(json,"pic",""));
// player->setSide(side);
// CCArray* mArr = CCArray::create();
// player->setMember(mArr);
//
// Json* arenaJson = Json_getItem(json,"arenaRWD");
// if(arenaJson!=NULL){
// player->setReputation(Json_getInt(arenaJson,"reputation",0));
// }
// std::string member = Json_getString(json,"member","");
// std::vector<std::string> heros;
// CCCommonUtils::splitString(member,";",heros);
// int size = heros.size();
// BattleHero* hero;
// std::vector<std::string> heroPros;
// for(int i=0;i<size;i++){
// heroPros.clear();
// CCCommonUtils::splitString(heros[i],"|",heroPros);
// hero = new BattleHero();
// hero->setPostion(atoi(heroPros[0].c_str())-1);
// //hero->setColor(atoi(CCCommonUtils::getPropById(heroPros[1],"color").c_str()));
// hero->setArm(atoi(heroPros[1].c_str()));//
// hero->setInitForces(atoi(heroPros[2].c_str()));
// hero->setCurrForces(hero->getInitForces());
// hero->setMaxForces(atoi(heroPros[3].c_str()));
// BattleGrid* grid = new BattleGrid(atoi(heroPros[4].c_str())-1,atoi(heroPros[5].c_str())-1);
// hero->setGrid(grid);
// grid->release();
// mArr->addObject(hero);
// hero->release();
// }
//
// CCArray* mGeneral = CCArray::create();
// player->setGenerals(mGeneral);
// std::vector<std::string> generals;
// std::string generalStr = Json_getString(json,"general","");
// CCCommonUtils::splitString(generalStr,";", generals);
// size = generals.size();
// std::vector<std::string> gvector;
// for(int i=0;i<size;i++){
// gvector.clear();
// CCCommonUtils::splitString(generals[i],"|", gvector);
// hero = new BattleHero();
// hero->setPostion(atoi(gvector[0].c_str())-1);
// hero->setArm(atoi(gvector[1].c_str()));//
// hero->setInitForces(9999);
// hero->setCurrForces(9999);
// hero->setMaxForces(9999);
// hero->setLevel(atoi(gvector[2].c_str()));
// mGeneral->addObject(hero);
// hero->release();
// }
//
// return player;
//}
| [
"441066277@qq.com"
] | 441066277@qq.com |
f1cb42262d370ebeed06ea7008c9e1e22cb00249 | a3d6556180e74af7b555f8d47d3fea55b94bcbda | /chrome/browser/ash/child_accounts/website_approval_notifier.h | 017cb73fac83d08f474ed63d3a01a68e45c6ab6a | [
"BSD-3-Clause"
] | permissive | chromium/chromium | aaa9eda10115b50b0616d2f1aed5ef35d1d779d6 | a401d6cf4f7bf0e2d2e964c512ebb923c3d8832c | refs/heads/main | 2023-08-24T00:35:12.585945 | 2023-08-23T22:01:11 | 2023-08-23T22:01:11 | 120,360,765 | 17,408 | 7,102 | BSD-3-Clause | 2023-09-10T23:44:27 | 2018-02-05T20:55:32 | null | UTF-8 | C++ | false | false | 1,730 | h | // Copyright 2021 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_
#define CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_
#include <string>
#include "base/callback_list.h"
#include "base/memory/raw_ptr.h"
#include "base/memory/weak_ptr.h"
class Profile;
namespace ash {
// Displays system notifications when new websites are remotely approved for
// this child account. This class listens to the SupervisedUserSettingsService
// for new remote approvals.
class WebsiteApprovalNotifier {
public:
explicit WebsiteApprovalNotifier(Profile* profile);
WebsiteApprovalNotifier(const WebsiteApprovalNotifier&) = delete;
WebsiteApprovalNotifier& operator=(const WebsiteApprovalNotifier&) = delete;
~WebsiteApprovalNotifier();
private:
friend class WebsiteApprovalNotifierTest;
// |allowed_host| can be an exact hostname, or a pattern containing wildcards.
// Refer to SupervisedUserURLFilter::HostMatchesPattern for details and
// examples.
// This method displays a system notification If |allowed_host| is an exact
// hostname. Clicking the notification opens the site (defaulting to https) in
// a new tab.
// No notification is shown if |allowed_host| is a match pattern.
void MaybeShowApprovalNotification(const std::string& allowed_host);
const raw_ptr<Profile, ExperimentalAsh> profile_;
base::CallbackListSubscription website_approval_subscription_;
base::WeakPtrFactory<WebsiteApprovalNotifier> weak_ptr_factory_{this};
};
} // namespace ash
#endif // CHROME_BROWSER_ASH_CHILD_ACCOUNTS_WEBSITE_APPROVAL_NOTIFIER_H_
| [
"chromium-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromium-scoped@luci-project-accounts.iam.gserviceaccount.com |
fb9ca22a3037ce6b270ba9ca6b2670210d686764 | 50fb7bffeeca41da0ffd7b4f2e6e187f386030b9 | /src/ngraph/slice_plan.hpp | 49ab7c55fe8cb33fd87af2a8a5c588bc574e6353 | [
"Apache-2.0"
] | permissive | biswajitcsecu/ngraph | eaa0eb54a7bcf9a602e5fbd52c0c5a1856351977 | d6bff37d7968922ef81f3bed63379e849fcf3b45 | refs/heads/master | 2020-09-12T04:36:36.214712 | 2019-11-17T20:31:26 | 2019-11-17T20:31:26 | 222,307,789 | 1 | 0 | Apache-2.0 | 2019-11-17T20:30:18 | 2019-11-17T20:30:18 | null | UTF-8 | C++ | false | false | 2,376 | hpp | //*****************************************************************************
// Copyright 2017-2019 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include <set>
#include "ngraph/axis_set.hpp"
#include "ngraph/shape.hpp"
namespace ngraph
{
//
// In various places, like ConstantFolding and DynElimination, it is
// useful to transform DynSlice by converting it to a sequence of ops:
//
// Slice (to do the basic slicing)
// |
// v
// Reshape (non-transposing, to handle shrinks)
// |
// v
// Reverse (to emulate backwards stride)
//
// (The Reshape, Reverse, or both may be omitted if they would just be
// identities.)
//
// A SlicePlan is used to collect parameters for these ops.
//
struct SlicePlan
{
// Parameters for the Slice
std::vector<int64_t> begins;
std::vector<int64_t> ends;
std::vector<int64_t> strides;
// Shapes coming into, and going out of, the Reshape.
Shape reshape_in_shape;
Shape reshape_out_shape;
// Parameters for the Reverse
AxisSet reverse_axes;
};
SlicePlan make_slice_plan(const Shape& input_shape,
const std::vector<int64_t>& begins,
const std::vector<int64_t>& ends,
const std::vector<int64_t>& strides,
const AxisSet& lower_bounds_mask,
const AxisSet& upper_bounds_mask,
const AxisSet& new_axis_mask,
const AxisSet& shrink_axis_mask,
const AxisSet& ellipsis_mask);
}
| [
"diyessi@users.noreply.github.com"
] | diyessi@users.noreply.github.com |
0f36a8e151537d9d4a82649772d00112cb3ea247 | d0a05a30b92277e1e022bbbc9216c9f3cf8ddd58 | /EncryptedString.cpp | 6e82a0346f67cde2436f01451c546c15ef3f4d4a | [] | no_license | Averyvan/COSC2436-Lab-1 | 5b8fd346d9125c9a288604376d17052805e30aa2 | f7ce8a9d6da053530ba327035082ae4ea3479e45 | refs/heads/master | 2020-04-01T03:48:36.686977 | 2018-10-13T05:06:27 | 2018-10-13T05:06:27 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,392 | cpp | // Author: Avery VanAusdal
// Assignment Number: Lab 1
// File Name: EncryptedString.cpp
// Course/Section: COSC 1337 Section 3
// Date: 8/30/2018
// Instructor: Bernard Ku
#include "EncryptedString.h"
#include <string>
EncryptedString::EncryptedString()
{
}
EncryptedString::EncryptedString(string inputString)
{
set(inputString);
}
void EncryptedString::set(string inputString)
{
myString = "";
for (int i = 0; i < inputString.length(); i++)
{
char character = inputString[i];
if (character == 'Z') //wrap around at end
{
myString += 'A';
}
else if (character == 'z') //lowercase wrap around
{
myString += 'a';
}
else if (isalpha(character))
{
myString += character+1;
}
else if (character == ' ')
{
myString += character;
}
//otherwise leave character out of myString
}
}
//decrypt then return
string EncryptedString::get() const
{
string resultString = "";
for (int i = 0; i < myString.length(); i++)
{
char character = myString[i];
if (character == 'A') //wrap around at end
{
resultString += 'Z';
}
else if (character == 'a') //lowercase wrap around
{
resultString += 'z';
}
else if (isalpha(character))
{
resultString += character-1;
}
else if (character == ' ')
{
resultString += character;
}
}
return resultString;
}
string EncryptedString::getEncrypted() const
{
return myString;
}
| [
"42887561+Appleseed107@users.noreply.github.com"
] | 42887561+Appleseed107@users.noreply.github.com |
a3e54c2eb8dd56471b8f070da7508288b095e0d2 | d61d05748a59a1a73bbf3c39dd2c1a52d649d6e3 | /chromium/testing/libfuzzer/fuzzers/sha1_fuzzer.cc | 26224331af6768e01c647579fdc755dbfb4dc7e0 | [
"BSD-3-Clause"
] | permissive | Csineneo/Vivaldi | 4eaad20fc0ff306ca60b400cd5fad930a9082087 | d92465f71fb8e4345e27bd889532339204b26f1e | refs/heads/master | 2022-11-23T17:11:50.714160 | 2019-05-25T11:45:11 | 2019-05-25T11:45:11 | 144,489,531 | 5 | 4 | BSD-3-Clause | 2022-11-04T05:55:33 | 2018-08-12T18:04:37 | null | UTF-8 | C++ | false | false | 436 | cc | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stddef.h>
#include <stdint.h>
#include "base/sha1.h"
// Entry point for LibFuzzer.
extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) {
unsigned char sha1[base::kSHA1Length] = {};
base::SHA1HashBytes(data, size, sha1);
return 0;
}
| [
"csineneo@gmail.com"
] | csineneo@gmail.com |
a9c07f0054b6aa918a781f0fe9822b55c15851d2 | 186a05fcb725481c0c51c31b2b948819205c789d | /src/commands/string/RegexParseCommand.cpp | 07c28f11a6c8ac60b5d9acd99220f68b8887c9a0 | [] | no_license | benhj/jasl | e497c5e17bff05aa5bbd2cfb1528b54674835b72 | 6e2d6cdb74692e4eaa950e25ed661d615cc32f11 | refs/heads/master | 2020-12-25T16:49:00.699346 | 2019-12-09T18:57:47 | 2019-12-09T18:57:47 | 28,279,592 | 27 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,125 | cpp | //
// RegexParseCommand.cpp
// jasl
//
// Copyright (c) 2018 Ben Jones. All rights reserved.
//
#include "RegexParseCommand.hpp"
#include "caching/VarExtractor.hpp"
#include "core/RegisterCommand.hpp"
#include <regex>
#include <string>
#include <vector>
bool jasl::RegexParseCommand::m_registered =
registerCommand<jasl::RegexParseCommand>();
namespace {
inline
std::vector<std::string> extract(std::string const & text,
std::string const & reg)
{
static std::regex const hl_regex(reg, std::regex_constants::icase) ;
return { std::sregex_token_iterator( text.begin(), text.end(), hl_regex, 1 ),
std::sregex_token_iterator{} } ;
}
}
namespace jasl
{
RegexParseCommand::RegexParseCommand(Function &func_,
SharedCacheStack const &sharedCache,
OptionalOutputStream const &output)
: Command(func_, sharedCache, output)
{
}
RegexParseCommand::~RegexParseCommand() = default;
std::vector<std::string> RegexParseCommand::getCommandNames()
{
return {"regex_parse"};
}
bool RegexParseCommand::execute()
{
// Command syntax:
// regex_parse (text, reg) -> result;
std::string text;
if(!VarExtractor::trySingleStringExtraction(m_func.paramA, text, m_sharedCache)) {
setLastErrorMessage("regex_parse: couldn't determine string to parse");
return false;
}
std::string reg;
if(!VarExtractor::trySingleStringExtraction(m_func.paramB, reg, m_sharedCache)) {
setLastErrorMessage("regex_parse: couldn't determine regex_parse string");
return false;
}
std::string symbol;
if(!m_func.getValueC<std::string>(symbol, m_sharedCache)) {
setLastErrorMessage("regex_parse: couldn't determine symbol");
return false;
}
auto const result = extract(text, reg);
m_sharedCache->setVar(symbol, result, Type::StringArray);
return true;
}
}
| [
"bhj.research@gmail.com"
] | bhj.research@gmail.com |
c3bc0a76b928bf952eca1a476fba508fbc81132c | d89df4cf6e89529f91db28115059278b6691e77b | /src/vendors/OceanOptics/devices/NIR256.cpp | c1ba2bdb3e948852d214d08a7c38823ce7ac0c77 | [
"MIT"
] | permissive | udyni/seabreeze | d31f1abeac5489929318ca9406b6e2064eb1e197 | 3d3934f8f0df61c11cef70516cf62a8472cab974 | refs/heads/master | 2021-03-23T12:46:31.498576 | 2020-04-06T15:01:14 | 2020-04-06T15:01:14 | 247,455,100 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,877 | cpp | /***************************************************//**
* @file NIR256.cpp
* @date March 2020
* @author Michele Devetta
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2020, Michele Devetta
*
* 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 "common/globals.h"
#include "api/seabreezeapi/ProtocolFamilies.h"
#include "common/buses/BusFamilies.h"
#include "vendors/OceanOptics/devices/NIR256.h"
#include "vendors/OceanOptics/protocols/ooi/impls/OOIProtocol.h"
#include "vendors/OceanOptics/buses/usb/NIR256USB.h"
#include "vendors/OceanOptics/features/eeprom_slots/EEPROMSlotFeature.h"
#include "vendors/OceanOptics/features/eeprom_slots/WavelengthEEPROMSlotFeature.h"
#include "vendors/OceanOptics/features/eeprom_slots/SerialNumberEEPROMSlotFeature.h"
#include "vendors/OceanOptics/features/eeprom_slots/NonlinearityEEPROMSlotFeature.h"
#include "vendors/OceanOptics/features/eeprom_slots/StrayLightEEPROMSlotFeature.h"
#include "vendors/OceanOptics/features/spectrometer/NIR256SpectrometerFeature.h"
#include "vendors/OceanOptics/features/raw_bus_access/RawUSBBusAccessFeature.h"
#include "vendors/OceanOptics/features/thermoelectric/ThermoElectricNIRFeature.h"
using namespace seabreeze;
using namespace seabreeze::ooiProtocol;
using namespace seabreeze::api;
using namespace std;
NIR256::NIR256() {
this->name = "NIR256";
// 0 is the control address, since it is not valid in this context, means not used
this->usbEndpoint_primary_out = 0x02;
this->usbEndpoint_primary_in = 0x87;
this->usbEndpoint_secondary_out = 0;
this->usbEndpoint_secondary_in = 0x82;
this->usbEndpoint_secondary_in2 = 0;
/* Set up the available buses on this device */
this->buses.push_back(new NIR256USB());
/* Set up the available protocols understood by this device */
this->protocols.push_back(new OOIProtocol());
/* Set up the features that comprise this device */
this->features.push_back(new NIR256SpectrometerFeature());
this->features.push_back(new SerialNumberEEPROMSlotFeature());
this->features.push_back(new EEPROMSlotFeature(17));
this->features.push_back(new NonlinearityEEPROMSlotFeature());
this->features.push_back(new StrayLightEEPROMSlotFeature());
this->features.push_back(new RawUSBBusAccessFeature());
this->features.push_back(new ThermoElectricNIRFeature());
}
NIR256::~NIR256() {
}
ProtocolFamily NIR256::getSupportedProtocol(FeatureFamily family, BusFamily bus) {
ProtocolFamilies protocols;
BusFamilies busFamilies;
if(bus.equals(busFamilies.USB)) {
/* This device only supports one protocol over USB. */
return protocols.OOI_PROTOCOL;
}
/* No other combinations of buses and protocols are supported. */
return protocols.UNDEFINED_PROTOCOL;
}
| [
"michele.devetta@cnr.it"
] | michele.devetta@cnr.it |
54af83b92f0ff18156ca34848bd38291a34a3b1d | 696e35ccdf167c3f6b1a7f5458406d3bb81987c9 | /storage/browser/fileapi/file_system_context.h | 9e4c99fc7e1b661d2ffa5f9b49d3e46ef52260f8 | [
"BSD-3-Clause"
] | permissive | mgh3326/iridium-browser | 064e91a5e37f4e8501ea971483bd1c76297261c3 | e7de6a434d2659f02e94917be364a904a442d2d0 | refs/heads/master | 2023-03-30T16:18:27.391772 | 2019-04-24T02:14:32 | 2019-04-24T02:14:32 | 183,128,065 | 0 | 0 | BSD-3-Clause | 2019-11-30T06:06:02 | 2019-04-24T02:04:51 | null | UTF-8 | C++ | false | false | 17,370 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_
#define STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_
#include <stdint.h>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/component_export.h"
#include "base/files/file.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "base/sequenced_task_runner_helpers.h"
#include "build/build_config.h"
#include "storage/browser/fileapi/file_system_url.h"
#include "storage/browser/fileapi/open_file_system_mode.h"
#include "storage/browser/fileapi/plugin_private_file_system_backend.h"
#include "storage/browser/fileapi/sandbox_file_system_backend_delegate.h"
#include "storage/browser/fileapi/task_runner_bound_observer_list.h"
#include "storage/common/fileapi/file_system_types.h"
namespace base {
class FilePath;
class SequencedTaskRunner;
class SingleThreadTaskRunner;
}
namespace leveleb {
class Env;
}
namespace net {
class URLRequest;
}
namespace storage {
class AsyncFileUtil;
class CopyOrMoveFileValidatorFactory;
class ExternalFileSystemBackend;
class ExternalMountPoints;
class FileStreamReader;
class FileStreamWriter;
class FileSystemBackend;
class FileSystemOperation;
class FileSystemOperationRunner;
class FileSystemOptions;
class FileSystemQuotaUtil;
class FileSystemURL;
class IsolatedFileSystemBackend;
class MountPoints;
class QuotaManagerProxy;
class QuotaReservation;
class SandboxFileSystemBackend;
class SpecialStoragePolicy;
struct DefaultContextDeleter;
struct FileSystemInfo;
struct FileSystemRequestInfo {
// The original request URL (always set).
const GURL url;
// The network request (only set when not using the network service).
const net::URLRequest* request = nullptr;
// The storage domain (always set).
const std::string storage_domain;
// Set by the network service for use by callbacks.
int content_id = 0;
};
// An auto mount handler will attempt to mount the file system requested in
// |request_info|. If the URL is for this auto mount handler, it returns true
// and calls |callback| when the attempt is complete. If the auto mounter
// does not recognize the URL, it returns false and does not call |callback|.
// Called on the IO thread.
using URLRequestAutoMountHandler = base::RepeatingCallback<bool(
const FileSystemRequestInfo& request_info,
const FileSystemURL& filesystem_url,
base::OnceCallback<void(base::File::Error result)> callback)>;
// This class keeps and provides a file system context for FileSystem API.
// An instance of this class is created and owned by profile.
class COMPONENT_EXPORT(STORAGE_BROWSER) FileSystemContext
: public base::RefCountedThreadSafe<FileSystemContext,
DefaultContextDeleter> {
public:
// Returns file permission policy we should apply for the given |type|.
// The return value must be bitwise-or'd of FilePermissionPolicy.
//
// Note: if a part of a filesystem is returned via 'Isolated' mount point,
// its per-filesystem permission overrides the underlying filesystem's
// permission policy.
static int GetPermissionPolicy(FileSystemType type);
// file_task_runner is used as default TaskRunner.
// Unless a FileSystemBackend is overridden in CreateFileSystemOperation,
// it is used for all file operations and file related meta operations.
// The code assumes that file_task_runner->RunsTasksInCurrentSequence()
// returns false if the current task is not running on the sequence that
// allows blocking file operations (like SequencedWorkerPool implementation
// does).
//
// |external_mount_points| contains non-system external mount points available
// in the context. If not nullptr, it will be used during URL cracking.
// |external_mount_points| may be nullptr only on platforms different from
// ChromeOS (i.e. platforms that don't use external_mount_point_provider).
//
// |additional_backends| are added to the internal backend map
// to serve filesystem requests for non-regular types.
// If none is given, this context only handles HTML5 Sandbox FileSystem
// and Drag-and-drop Isolated FileSystem requests.
//
// |auto_mount_handlers| are used to resolve calls to
// AttemptAutoMountForURLRequest. Only external filesystems are auto mounted
// when a filesystem: URL request is made.
FileSystemContext(
base::SingleThreadTaskRunner* io_task_runner,
base::SequencedTaskRunner* file_task_runner,
ExternalMountPoints* external_mount_points,
storage::SpecialStoragePolicy* special_storage_policy,
storage::QuotaManagerProxy* quota_manager_proxy,
std::vector<std::unique_ptr<FileSystemBackend>> additional_backends,
const std::vector<URLRequestAutoMountHandler>& auto_mount_handlers,
const base::FilePath& partition_path,
const FileSystemOptions& options);
bool DeleteDataForOriginOnFileTaskRunner(const GURL& origin_url);
// Creates a new QuotaReservation for the given |origin_url| and |type|.
// Returns nullptr if |type| does not support quota or reservation fails.
// This should be run on |default_file_task_runner_| and the returned value
// should be destroyed on the runner.
scoped_refptr<QuotaReservation> CreateQuotaReservationOnFileTaskRunner(
const GURL& origin_url,
FileSystemType type);
storage::QuotaManagerProxy* quota_manager_proxy() const {
return quota_manager_proxy_.get();
}
// Discards inflight operations in the operation runner.
void Shutdown();
// Returns a quota util for a given filesystem type. This may
// return nullptr if the type does not support the usage tracking or
// it is not a quota-managed storage.
FileSystemQuotaUtil* GetQuotaUtil(FileSystemType type) const;
// Returns the appropriate AsyncFileUtil instance for the given |type|.
AsyncFileUtil* GetAsyncFileUtil(FileSystemType type) const;
// Returns the appropriate CopyOrMoveFileValidatorFactory for the given
// |type|. If |error_code| is File::FILE_OK and the result is nullptr,
// then no validator is required.
CopyOrMoveFileValidatorFactory* GetCopyOrMoveFileValidatorFactory(
FileSystemType type, base::File::Error* error_code) const;
// Returns the file system backend instance for the given |type|.
// This may return nullptr if it is given an invalid or unsupported filesystem
// type.
FileSystemBackend* GetFileSystemBackend(
FileSystemType type) const;
// Returns the watcher manager for the given |type|.
// This may return nullptr if the type does not support watching.
WatcherManager* GetWatcherManager(FileSystemType type) const;
// Returns true for sandboxed filesystems. Currently this does
// the same as GetQuotaUtil(type) != nullptr. (In an assumption that
// all sandboxed filesystems must cooperate with QuotaManager so that
// they can get deleted)
bool IsSandboxFileSystem(FileSystemType type) const;
// Returns observers for the given filesystem type.
const UpdateObserverList* GetUpdateObservers(FileSystemType type) const;
const ChangeObserverList* GetChangeObservers(FileSystemType type) const;
const AccessObserverList* GetAccessObservers(FileSystemType type) const;
// Returns all registered filesystem types.
std::vector<FileSystemType> GetFileSystemTypes() const;
// Returns a FileSystemBackend instance for external filesystem
// type, which is used only by chromeos for now. This is equivalent to
// calling GetFileSystemBackend(kFileSystemTypeExternal).
ExternalFileSystemBackend* external_backend() const;
// Used for OpenFileSystem.
using OpenFileSystemCallback =
base::OnceCallback<void(const GURL& root,
const std::string& name,
base::File::Error result)>;
// Used for ResolveURL.
enum ResolvedEntryType {
RESOLVED_ENTRY_FILE,
RESOLVED_ENTRY_DIRECTORY,
RESOLVED_ENTRY_NOT_FOUND,
};
using ResolveURLCallback =
base::OnceCallback<void(base::File::Error result,
const FileSystemInfo& info,
const base::FilePath& file_path,
ResolvedEntryType type)>;
// Used for DeleteFileSystem and OpenPluginPrivateFileSystem.
using StatusCallback = base::OnceCallback<void(base::File::Error result)>;
// Opens the filesystem for the given |origin_url| and |type|, and dispatches
// |callback| on completion.
// If |create| is true this may actually set up a filesystem instance
// (e.g. by creating the root directory or initializing the database
// entry etc).
void OpenFileSystem(const GURL& origin_url,
FileSystemType type,
OpenFileSystemMode mode,
OpenFileSystemCallback callback);
// Opens the filesystem for the given |url| as read-only, if the filesystem
// backend referred by the URL allows opening by resolveURL. Otherwise it
// fails with FILE_ERROR_SECURITY. The entry pointed by the URL can be
// absent; in that case RESOLVED_ENTRY_NOT_FOUND type is returned to the
// callback for indicating the absence. Can be called from any thread with
// a message loop. |callback| is invoked on the caller thread.
void ResolveURL(const FileSystemURL& url, ResolveURLCallback callback);
// Attempts to mount the filesystem needed to satisfy |request_info| made from
// |request_info.storage_domain|. If an appropriate file system is not found,
// callback will return an error.
void AttemptAutoMountForURLRequest(const FileSystemRequestInfo& request_info,
StatusCallback callback);
// Deletes the filesystem for the given |origin_url| and |type|. This should
// be called on the IO thread.
void DeleteFileSystem(const GURL& origin_url,
FileSystemType type,
StatusCallback callback);
// Creates new FileStreamReader instance to read a file pointed by the given
// filesystem URL |url| starting from |offset|. |expected_modification_time|
// specifies the expected last modification if the value is non-null, the
// reader will check the underlying file's actual modification time to see if
// the file has been modified, and if it does any succeeding read operations
// should fail with ERR_UPLOAD_FILE_CHANGED error.
// This method internally cracks the |url|, get an appropriate
// FileSystemBackend for the URL and call the backend's CreateFileReader.
// The resolved FileSystemBackend could perform further specialization
// depending on the filesystem type pointed by the |url|.
// At most |max_bytes_to_read| can be fetched from the file stream reader.
std::unique_ptr<storage::FileStreamReader> CreateFileStreamReader(
const FileSystemURL& url,
int64_t offset,
int64_t max_bytes_to_read,
const base::Time& expected_modification_time);
// Creates new FileStreamWriter instance to write into a file pointed by
// |url| from |offset|.
std::unique_ptr<FileStreamWriter> CreateFileStreamWriter(
const FileSystemURL& url,
int64_t offset);
// Creates a new FileSystemOperationRunner.
std::unique_ptr<FileSystemOperationRunner> CreateFileSystemOperationRunner();
base::SequencedTaskRunner* default_file_task_runner() {
return default_file_task_runner_.get();
}
FileSystemOperationRunner* operation_runner() {
return operation_runner_.get();
}
const base::FilePath& partition_path() const { return partition_path_; }
// Same as |CrackFileSystemURL|, but cracks FileSystemURL created from |url|.
FileSystemURL CrackURL(const GURL& url) const;
// Same as |CrackFileSystemURL|, but cracks FileSystemURL created from method
// arguments.
FileSystemURL CreateCrackedFileSystemURL(const GURL& origin,
FileSystemType type,
const base::FilePath& path) const;
#if defined(OS_CHROMEOS)
// Used only on ChromeOS for now.
void EnableTemporaryFileSystemInIncognito();
#endif
SandboxFileSystemBackendDelegate* sandbox_delegate() {
return sandbox_delegate_.get();
}
// Returns true if the requested url is ok to be served.
// (E.g. this returns false if the context is created for incognito mode)
bool CanServeURLRequest(const FileSystemURL& url) const;
// This must be used to open 'plugin private' filesystem.
// See "plugin_private_file_system_backend.h" for more details.
void OpenPluginPrivateFileSystem(const GURL& origin_url,
FileSystemType type,
const std::string& filesystem_id,
const std::string& plugin_id,
OpenFileSystemMode mode,
StatusCallback callback);
private:
// For CreateFileSystemOperation.
friend class FileSystemOperationRunner;
// For sandbox_backend().
friend class content::SandboxFileSystemTestHelper;
// For plugin_private_backend().
friend class content::PluginPrivateFileSystemBackendTest;
// Deleters.
friend struct DefaultContextDeleter;
friend class base::DeleteHelper<FileSystemContext>;
friend class base::RefCountedThreadSafe<FileSystemContext,
DefaultContextDeleter>;
~FileSystemContext();
void DeleteOnCorrectSequence() const;
// Creates a new FileSystemOperation instance by getting an appropriate
// FileSystemBackend for |url| and calling the backend's corresponding
// CreateFileSystemOperation method.
// The resolved FileSystemBackend could perform further specialization
// depending on the filesystem type pointed by the |url|.
//
// Called by FileSystemOperationRunner.
FileSystemOperation* CreateFileSystemOperation(
const FileSystemURL& url,
base::File::Error* error_code);
// For non-cracked isolated and external mount points, returns a FileSystemURL
// created by cracking |url|. The url is cracked using MountPoints registered
// as |url_crackers_|. If the url cannot be cracked, returns invalid
// FileSystemURL.
//
// If the original url does not point to an isolated or external filesystem,
// returns the original url, without attempting to crack it.
FileSystemURL CrackFileSystemURL(const FileSystemURL& url) const;
// For initial backend_map construction. This must be called only from
// the constructor.
void RegisterBackend(FileSystemBackend* backend);
void DidOpenFileSystemForResolveURL(const FileSystemURL& url,
ResolveURLCallback callback,
const GURL& filesystem_root,
const std::string& filesystem_name,
base::File::Error error);
// Returns a FileSystemBackend, used only by test code.
SandboxFileSystemBackend* sandbox_backend() const {
return sandbox_backend_.get();
}
// Used only by test code.
PluginPrivateFileSystemBackend* plugin_private_backend() const {
return plugin_private_backend_.get();
}
// Override the default leveldb Env with |env_override_| if set.
std::unique_ptr<leveldb::Env> env_override_;
scoped_refptr<base::SingleThreadTaskRunner> io_task_runner_;
scoped_refptr<base::SequencedTaskRunner> default_file_task_runner_;
scoped_refptr<storage::QuotaManagerProxy> quota_manager_proxy_;
std::unique_ptr<SandboxFileSystemBackendDelegate> sandbox_delegate_;
// Regular file system backends.
std::unique_ptr<SandboxFileSystemBackend> sandbox_backend_;
std::unique_ptr<IsolatedFileSystemBackend> isolated_backend_;
// Additional file system backends.
std::unique_ptr<PluginPrivateFileSystemBackend> plugin_private_backend_;
std::vector<std::unique_ptr<FileSystemBackend>> additional_backends_;
std::vector<URLRequestAutoMountHandler> auto_mount_handlers_;
// Registered file system backends.
// The map must be constructed in the constructor since it can be accessed
// on multiple threads.
// This map itself doesn't retain each backend's ownership; ownerships
// of the backends are held by additional_backends_ or other scoped_ptr
// backend fields.
std::map<FileSystemType, FileSystemBackend*> backend_map_;
// External mount points visible in the file system context (excluding system
// external mount points).
scoped_refptr<ExternalMountPoints> external_mount_points_;
// MountPoints used to crack FileSystemURLs. The MountPoints are ordered
// in order they should try to crack a FileSystemURL.
std::vector<MountPoints*> url_crackers_;
// The base path of the storage partition for this context.
const base::FilePath partition_path_;
bool is_incognito_;
std::unique_ptr<FileSystemOperationRunner> operation_runner_;
DISALLOW_IMPLICIT_CONSTRUCTORS(FileSystemContext);
};
struct DefaultContextDeleter {
static void Destruct(const FileSystemContext* context) {
context->DeleteOnCorrectSequence();
}
};
} // namespace storage
#endif // STORAGE_BROWSER_FILEAPI_FILE_SYSTEM_CONTEXT_H_
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
084d5b4793ca78f015b4f63d06937f55f8de02a0 | c8daba44b8a9d10208264b4a8ddef0979b1fe288 | /rendering/RenderableComponent.cpp | ce17dce80218519ea85d8349ad9917eeeb76dc5d | [
"LicenseRef-scancode-warranty-disclaimer"
] | no_license | noirb/FuLBLINKy | 3c1738cc92c11f998636dcf1b35cbf09dcabed38 | 2be81d24198b73a78e4928ab7ac8a44ffa5efd57 | refs/heads/master | 2021-01-25T00:37:48.654371 | 2015-11-26T20:09:12 | 2015-11-26T20:09:12 | 37,765,025 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,450 | cpp | #include "RenderableComponent.hpp"
#include <iostream>
// Destructor: clean up now-unused objects
RenderableComponent::~RenderableComponent()
{
if (_vertex_buffer_data)
{
delete _vertex_buffer_data;
}
glDeleteBuffers(1, &_VBO);
glDeleteVertexArrays(1, &_VAO);
}
void RenderableComponent::SetShader(ShaderProgram* program)
{
_shaderProgram = program;
}
void RenderableComponent::SetMaxColor(float r, float g, float b, float a)
{
_maxColor[0] = r;
_maxColor[1] = g;
_maxColor[2] = b;
_maxColor[3] = a;
}
void RenderableComponent::SetMinColor(float r, float g, float b, float a)
{
_minColor[0] = r;
_minColor[1] = g;
_minColor[2] = b;
_minColor[3] = a;
}
void RenderableComponent::SetInterpolator(Interpolation i)
{
_interpolator = i;
}
void RenderableComponent::SetInterpolationBias(double b)
{
_bias = b;
}
void RenderableComponent::SetColorField(std::string fieldName)
{
_colorParamField = fieldName;
}
void RenderableComponent::SetScaleField(std::string fieldName)
{
_scaleParamField = fieldName;
}
void RenderableComponent::SetAutoScale(bool b)
{
_autoScale = b;
}
void RenderableComponent::SetScale(double min, double max)
{
if (min >= 0)
_scaleFactorMin = min;
if (max >= 0)
_scaleFactorMax = max;
}
void RenderableComponent::Enable()
{
_enabled = true;
}
void RenderableComponent::Disable()
{
_enabled = false;
}
| [
"quetchl@gmail.com"
] | quetchl@gmail.com |
5826ea56e9f7674698d396f35264ac04f974e561 | 9792ff3e2512a70bf286363d5cfc451dae9f09ca | /SuperSequence.cpp | 29bb24abb88a80fa0f71235b10fbefc2ae12227f | [] | no_license | TheTypo36/competitive-Programming | 0ecffbb48c3fcccb110eb965cb2738de05a0aa10 | 59ae2bc2761b89461ef6948c84dbb3e4f68842d8 | refs/heads/master | 2023-07-06T19:56:18.125386 | 2021-08-19T15:13:47 | 2021-08-19T15:13:47 | 297,542,045 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 859 | cpp | #include <bits/stdc++.h>
using namespace std;
int lcs(char str1[], char str2[], int n, int m){
vector<vector<int>> dp(n+1,vector<int>(m+1, 0));
for (int i = 1; i < n + 1 ; ++i)
{
for (int j = 1; j < m+1; ++j)
{
if(str1[i-1] == str2[j-1]){
dp[i][j] = 1 + dp[i-1][j-1];
}else{
int option = dp[i-1][j];
int option2 = dp[i][j-1];
int option3 = dp[i-1][j-1];
dp[i][j] = max(option,max(option2,option3));
}
}
}
int ans = dp[n][m];
return ans;
}
int smallestSuperSequence(char str1[], int len1, char str2[], int len2) {
int ans = (len1 + len2) - lcs(str1,str2,len1,len2);
return ans;
}
int main()
{
char str1[50], str2[50];
cin>>str1;
cin>>str2;
int len1 = strlen(str1);
int len2 = strlen(str2);
int min_len = smallestSuperSequence(str1, len1, str2, len2);
cout<<min_len;
return 0;
}
| [
"thetypo36@gmail.com"
] | thetypo36@gmail.com |
054af09ae9989ac17046610f7a017755fd898f28 | ff6a8e462e51552d3b7da069df8f80239d8c9506 | /cs680-distsim/lab2/simplus/LogLogisticDist.cpp | b7278f634f83c02a274a7b11456dd21225a2bbff | [] | no_license | Salimlou/Class-Work | 5ad5463eff2c916c414d88c35a3c50c415ece5e3 | 2b8db821bd16ed5746bae42cfa03f0b6d45b713a | refs/heads/master | 2021-01-18T11:22:43.266151 | 2012-03-25T02:02:01 | 2012-03-25T02:02:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 612 | cpp | /*****************************************************************
Program: SimPlus
Class: LogLogisticDist
Group: Mark Randles, Dan Sinclair
*****************************************************************/
#include <math.h>
#include "LogLogisticDist.h"
/*
The contructor receives two parameters N and P
*/
LogLogisticDist::LogLogisticDist( double a, double b, RNGFactory::RNGType type ) : RawDist(type) {
A=a;
B=b;
}
// The destructor: empty right now
LogLogisticDist::~LogLogisticDist() {
}
double LogLogisticDist::getRandom() {
return( 1.0 / ( 1.0 + pow( rng->genRandReal1() / B , A) ) );
}
| [
"randlem@gmail.com"
] | randlem@gmail.com |
5524afa897048af3de99bb8ecc711893b2c1fd9c | e3ef6ff25d8322cf479210846ebc677702e8edab | /necrodancer/item_coin.cpp | 14ad596b07f39cdea05e98f319525a3117aa368e | [] | no_license | dongnamyoooooooooon/yoOoOoOon | 885dbfe0c982ddc3c79eca8b129a2b11bbfd53c5 | 8a1e84a053bcf752532fb102d54fe5d810ce255b | refs/heads/master | 2020-05-01T14:05:27.437184 | 2019-04-09T08:44:05 | 2019-04-09T08:44:05 | 177,509,953 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,669 | cpp | #include "stdafx.h"
#include "item_coin.h"
item_coin::item_coin()
{
}
item_coin::~item_coin()
{
}
HRESULT item_coin::init(string keyName, int idxX, int idxY, ITEM_TYPE type)
{
item::init(keyName, idxX, idxY, type);
_appliedValue = RND->getFromIntTo(1, 9) * (OBJECTMANAGER->getChainCount() + 1);
_posX = idxX * TILE_SIZE;
_posY = idxY * TILE_SIZE;
if (_appliedValue == 1) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_1]);
else if (_appliedValue == 2) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_2]);
else if (_appliedValue == 3) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_3]);
else if (_appliedValue == 4) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_4]);
else if (_appliedValue == 5) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_5]);
else if (_appliedValue == 6) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_6]);
else if (_appliedValue == 7) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_7]);
else if (_appliedValue == 8) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_8]);
else if (_appliedValue == 9) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_9]);
else if (_appliedValue == 10) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_10]);
else if (_appliedValue > 11 && _appliedValue < 26) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_25]);
else if (_appliedValue > 25 && _appliedValue < 36) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_35]);
else if (_appliedValue > 35) _img = IMAGEMANAGER->findImage(COIN_NAME[ITEM_COIN_50]);
return S_OK;
}
void item_coin::release()
{
}
void item_coin::update()
{
}
void item_coin::render()
{
_img->frameRender(_posX, _posY, 0, 0);
}
| [
"46731689+dongnamyoooooooooon@users.noreply.github.com"
] | 46731689+dongnamyoooooooooon@users.noreply.github.com |
3789891ff5b2b23acb87082352e49c577bef6930 | 60bd79d18cf69c133abcb6b0d8b0a959f61b4d10 | /libraries/TOPMAX/examples/TOPMAX_performance/TOPMAX_performance.ino | 2ca13efcc7fc120cdc0208f5d70e79e91df12058 | [
"MIT"
] | permissive | RobTillaart/Arduino | e75ae38fa6f043f1213c4c7adb310e91da59e4ba | 48a7d9ec884e54fcc7323e340407e82fcc08ea3d | refs/heads/master | 2023-09-01T03:32:38.474045 | 2023-08-31T20:07:39 | 2023-08-31T20:07:39 | 2,544,179 | 1,406 | 3,798 | MIT | 2022-10-27T08:28:51 | 2011-10-09T19:53:59 | C++ | UTF-8 | C++ | false | false | 2,246 | ino | //
// FILE: TOPMAX_performance.ino
// AUTHOR: Rob Tillaart
// PURPOSE: TOPMAX demo
// URL: https://github.com/RobTillaart/TOPMAX
#include "TOPMAX.h"
uint32_t start, stop;
uint32_t cnt = 0;
void setup()
{
Serial.begin(115200);
Serial.println(__FILE__);
Serial.print("TOPMAX_LIB_VERSION: ");
Serial.println(TOPMAX_LIB_VERSION);
Serial.println();
for (int sz = 1; sz <= 128; sz *= 2)
{
test_fill(sz);
}
Serial.println();
for (int sz = 1; sz <= 128; sz *= 2)
{
test_add(sz);
}
Serial.println();
for (int sz = 1; sz <= 128; sz *= 2)
{
test_fill_ext(sz);
}
Serial.println();
for (int sz = 1; sz <= 128; sz *= 2)
{
test_add_ext(sz);
}
Serial.println();
Serial.println("done...");
}
void loop()
{
}
void test_fill(uint8_t sz)
{
delay(100);
TOPMAX tm(sz);
start = micros();
for (int i = 0; i < 1000; i++) tm.fill(i);
stop = micros();
Serial.print("FILL\t");
Serial.print("size: ");
Serial.print(sz);
Serial.print("\t");
Serial.print(stop - start);
Serial.print("\t");
Serial.print((stop - start) * 0.001, 4);
Serial.println();
}
void test_add(uint8_t sz)
{
delay(100);
TOPMAX tm(sz);
start = micros();
for (int i = 0; i < 1000; i++) tm.add(i);
stop = micros();
Serial.print("ADD\t");
Serial.print("size: ");
Serial.print(sz);
Serial.print("\t");
Serial.print(stop - start);
Serial.print("\t");
Serial.print((stop - start) * 0.001, 4);
Serial.println();
}
void test_fill_ext(uint8_t sz)
{
delay(100);
TOPMAXext tm(sz);
start = micros();
for (int i = 0; i < 1000; i++) tm.fill(i, i);
stop = micros();
Serial.print("FILLext\t");
Serial.print("size: ");
Serial.print(sz);
Serial.print("\t");
Serial.print(stop - start);
Serial.print("\t");
Serial.print((stop - start) * 0.001, 4);
Serial.println();
}
void test_add_ext(uint8_t sz)
{
delay(100);
TOPMAXext tm(sz);
start = micros();
for (int i = 0; i < 1000; i++) tm.add(i, i);
stop = micros();
Serial.print("ADDext\t");
Serial.print("size: ");
Serial.print(sz);
Serial.print("\t");
Serial.print(stop - start);
Serial.print("\t");
Serial.print((stop - start) * 0.001, 4);
Serial.println();
}
// -- END OF FILE --
| [
"rob.tillaart@gmail.com"
] | rob.tillaart@gmail.com |
f10521d50edf11018cc7530cfc90d9434bdffe38 | 9a3b9d80afd88e1fa9a24303877d6e130ce22702 | /src/Providers/UNIXProviders/tests/UNIXProviders.Tests/UNIX_IPSubnetFixture.cpp | 641d8736b567017a28b9ff074dc8be2fc714681e | [
"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,383 | 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_IPSubnetFixture.h"
#include <IPSubnet/UNIX_IPSubnetProvider.h>
UNIX_IPSubnetFixture::UNIX_IPSubnetFixture()
{
}
UNIX_IPSubnetFixture::~UNIX_IPSubnetFixture()
{
}
void UNIX_IPSubnetFixture::Run()
{
CIMName className("UNIX_IPSubnet");
CIMNamespaceName nameSpace("root/cimv2");
UNIX_IPSubnet _p;
UNIX_IPSubnetProvider _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();
}
| [
"brunolauze@msn.com"
] | brunolauze@msn.com |
741fcac39fca998ea04115a8444e0fdc1e0e20fe | 5f12bccc76142365ba4e1a28db800d01c952a24a | /passive/AtMagnet.cxx | a4cee2a213b9bb9417c989374085a41dd9c625c0 | [] | no_license | sunlijie-msu/ATTPCROOTv2 | 7ad98fd6f85126e5b480f7897a2b98d1fc8bf184 | 870b75170990b0782918f17b2230045ab1f458ef | refs/heads/master | 2023-06-02T06:28:30.308596 | 2021-02-26T14:59:53 | 2021-02-26T14:59:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,930 | cxx | /********************************************************************************
* Copyright (C) 2014 GSI Helmholtzzentrum fuer Schwerionenforschung GmbH *
* *
* This software is distributed under the terms of the *
* GNU Lesser General Public Licence version 3 (LGPL) version 3, *
* copied verbatim in the file "LICENSE" *
********************************************************************************/
// -------------------------------------------------------------------------
// ----- AtMagnet file -----
// ----- Created 26/03/14 by M. Al-Turany -----
// -------------------------------------------------------------------------
#include "AtMagnet.h"
#include "TGeoManager.h"
#include "FairRun.h" // for FairRun
#include "FairRuntimeDb.h" // for FairRuntimeDb
#include "TList.h" // for TListIter, TList (ptr only)
#include "TObjArray.h" // for TObjArray
#include "TString.h" // for TString
#include "TGeoBBox.h"
#include "TGeoCompositeShape.h"
#include "TGeoTube.h"
#include "TGeoMaterial.h"
#include "TGeoElement.h"
#include "TGeoMedium.h"
#include <stddef.h> // for NULL
#include <iostream> // for operator<<, basic_ostream, etc
AtMagnet::~AtMagnet()
{
}
AtMagnet::AtMagnet()
: FairModule("AtMagnet", "")
{
}
AtMagnet::AtMagnet(const char* name, const char* Title)
: FairModule(name ,Title)
{
}
void AtMagnet::ConstructGeometry()
{
TGeoVolume *top=gGeoManager->GetTopVolume();
// define some materials
TGeoMaterial *matFe = new TGeoMaterial("Fe", 55.84, 26, 7.9);
// define some media
TGeoMedium *Fe = new TGeoMedium("Fe", 100, matFe);
// magnet yoke
TGeoBBox *magyoke1 = new TGeoBBox("magyoke1", 261/2.0, 221/2.0, 278/2.0);
TGeoBBox *magyoke2 = new TGeoBBox("magyoke2", 242/2.0, 202/2.0, 279/2.0);
TGeoCompositeShape *magyokec = new TGeoCompositeShape("magyokec", "magyoke1-magyoke2");
TGeoVolume *magyoke = new TGeoVolume("magyoke", magyokec, Fe);
magyoke->SetLineColor(kViolet+2);
magyoke->SetTransparency(50);
top->AddNode(magyoke, 1, new TGeoTranslation(0, 6.079, 90));
// magnet
TGeoTube *SolenoidGeo = new TGeoTube("SolenoidGeo",125./4.0,274./4.0,229.0/2.0);// Radius divided by 2.0
TGeoVolume *SolenoidVol = new TGeoVolume("SolenoidVol", SolenoidGeo, Fe);
SolenoidVol->SetLineColor(kWhite);
SolenoidVol->SetTransparency(50);
top->AddNode(SolenoidVol,1,new TGeoTranslation(0, 6.079, 110));
/* TGeoTubeSeg *magnet1a = new TGeoTubeSeg("magnet1a", 250, 300, 35, 45, 135);
TGeoTubeSeg *magnet1b = new TGeoTubeSeg("magnet1b", 250, 300, 35, 45, 135);
TGeoTubeSeg *magnet1c = new TGeoTubeSeg("magnet1c", 250, 270, 125, 45, 60);
TGeoTubeSeg *magnet1d = new TGeoTubeSeg("magnet1d", 250, 270, 125, 120, 135);
// magnet composite shape matrices
TGeoTranslation *m1 = new TGeoTranslation(0, 0, 160);
m1->SetName("m1");
m1->RegisterYourself();
TGeoTranslation *m2 = new TGeoTranslation(0, 0, -160);
m2->SetName("m2");
m2->RegisterYourself();
TGeoCompositeShape *magcomp1 = new TGeoCompositeShape("magcomp1", "magnet1a:m1+magnet1b:m2+magnet1c+magnet1d");
TGeoVolume *magnet1 = new TGeoVolume("magnet1", magcomp1, Fe);
magnet1->SetLineColor(kYellow);
top->AddNode(magnet1, 1, new TGeoTranslation(0, 0, 0));
TGeoRotation m3;
m3.SetAngles(180, 0, 0);
TGeoTranslation m4(0, 0, 0);
TGeoCombiTrans m5(m4, m3);
TGeoHMatrix *m6 = new TGeoHMatrix(m5);
top->AddNode(magnet1, 2, m6);*/
}
ClassImp(AtMagnet)
| [
"ayyadlim@nscl.msu.edu"
] | ayyadlim@nscl.msu.edu |
745bb03667097740477baec284743aa1685f0566 | ba7707734e366326a7deaed69e0d22c883f64230 | /cpp-code/PRIC-13553643-src.cpp | 71246215e01000537869dfc37925ea56f6869637 | [] | no_license | aseemchopra25/spoj | 2712ed84b860b7842b8f0ee863678ba54888eb59 | 3c785eb4141b35bc3ea42ffc07ff95136503a184 | refs/heads/master | 2023-08-13T14:07:58.461480 | 2021-10-18T12:26:44 | 2021-10-18T12:26:44 | 390,030,214 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,457 | cpp | #include<cstdio>
#include <cstdlib>
#define MOD 2147483648
#define ADD 1234567890
#define pc(x) putchar_unlocked(x)
#define ll long long
inline int mulmod(int a, int b, int mod)
{
ll x = 0,y = a % mod;
while (b > 0)
{
if (b&1)
{
x = (x +y) % mod;
}
y = (y<<1) % mod;
b >>=1;
}
return x % mod;
}
inline int modulo(int base, int exponent, int mod)
{
int x = 1;
int y = base;
while (exponent > 0)
{
if (exponent&1)
x = mulmod(x,y,mod);
y = mulmod(y,y,mod);
exponent >>=1;;
}
return x % mod;
}
inline bool M(int p)
{
if (p < 2)
return false;
if (p != 2 && (p&1)==0)
return false;
int s = p - 1;
while ((s&1) == 0)
{
s >>=1;
}
int i=2;
while(i--)
{
int a = rand() % (p - 1) + 1, temp = s;
int mod = modulo(a, temp, p);
while (temp != p - 1 && mod != 1 && mod != p - 1)
{
mod = mulmod(mod, mod, p);
temp<<=1;
}
if (mod != p - 1 && (temp&1) == 0)
return false;
}
return true;
}
int main()
{
int num=1;int prev=1;
pc('0');
int count=1;
while(count<=80000)
{
num=(prev+ADD)%MOD;
if (M(num))
pc('1');
else
pc('0');
prev=num;
count++;
}
return 0;
} | [
"aseemchopra@protonmail.com"
] | aseemchopra@protonmail.com |
f4ea3567630d2fe92edd70e17791c978b3ede9e3 | f84ee6582e88483aa337bc9bb9312294c1d79e23 | /src/events/sacpp_archiver_takeImageDone_send.cpp | ed278de6c5f9f822b03ed26c0c14b91b8091be0a | [] | no_license | provingground-curly/ctrl_iip | 41ab1fe1c70cd898019f5b75b6c0f5adf21e3d3f | 193859f72e1beb2fc5a940f6bb5f5f0bbef7f99a | refs/heads/master | 2020-05-16T13:15:24.731460 | 2019-04-20T02:36:40 | 2019-04-20T02:36:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,179 | cpp |
/*
* This file contains the implementation for the archiver_takeImageDone send test.
*
***/
#include <string>
#include <sstream>
#include <iostream>
#include <unistd.h>
#include "SAL_archiver.h"
#include "ccpp_sal_archiver.h"
#include "os.h"
#include <stdlib.h>
#include "example_main.h"
using namespace DDS;
using namespace archiver;
int main (int argc, char *argv[])
{
int priority = SAL__EVENT_INFO;
archiver_logevent_takeImageDoneC myData;
if (argc < 2) {
printf("Usage : input parameters...\n");
printf(" long priority;\n");
exit(1);
}
#ifdef SAL_SUBSYSTEM_ID_IS_KEYED
int archiverID = 1;
if (getenv("LSST_archiver_ID") != NULL) {
sscanf(getenv("LSST_archiver_ID"),"%d",&archiverID);
}
SAL_archiver mgr = SAL_archiver(archiverID);
#else
SAL_archiver mgr = SAL_archiver();
#endif
mgr.salEvent("archiver_logevent_takeImageDone");
sscanf(argv[1], "%d", &myData.priority);
// generate event
priority = myData.priority;
mgr.logEvent_takeImageDone(&myData, priority);
cout << "=== Event takeImageDone generated = " << endl;
sleep(1);
/* Remove the DataWriters etc */
mgr.salShutdown();
return 0;
}
| [
"htutkhwin@gmail.com"
] | htutkhwin@gmail.com |
e9d115176fabcc0454ac43a9a4a7148c86576940 | b43123758faa3d717d51000dcc82b125ef7fc41e | /UNITTESTS/stubs/ChainingBlockDevice_stub.cpp | 51134b3553702a2fb7e6cadba429cafa696ebd16 | [
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | codegrande/mbed-os | 806f1526dfd11b03e2c1de4508674cff5ea499ce | d847a07cb37c15cbe5b0cdc3937026411058d298 | refs/heads/master | 2020-03-30T14:24:12.879359 | 2019-06-20T14:38:49 | 2019-06-20T14:38:49 | 151,316,378 | 0 | 0 | Apache-2.0 | 2018-10-02T20:08:19 | 2018-10-02T20:08:19 | null | UTF-8 | C++ | false | false | 1,714 | cpp | /* mbed Microcontroller Library
* Copyright (c) 2017 ARM Limited
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "ChainingBlockDevice.h"
#include "mbed_critical.h"
ChainingBlockDevice::ChainingBlockDevice(BlockDevice **bds, size_t bd_count)
{
}
static bool is_aligned(uint64_t x, uint64_t alignment)
{
return true;
}
int ChainingBlockDevice::init()
{
return 0;
}
int ChainingBlockDevice::deinit()
{
return 0;
}
int ChainingBlockDevice::sync()
{
return 0;
}
int ChainingBlockDevice::read(void *b, bd_addr_t addr, bd_size_t size)
{
return 0;
}
int ChainingBlockDevice::program(const void *b, bd_addr_t addr, bd_size_t size)
{
return 0;
}
int ChainingBlockDevice::erase(bd_addr_t addr, bd_size_t size)
{
return 0;
}
bd_size_t ChainingBlockDevice::get_read_size() const
{
return 0;
}
bd_size_t ChainingBlockDevice::get_program_size() const
{
return 0;
}
bd_size_t ChainingBlockDevice::get_erase_size() const
{
return 0;
}
bd_size_t ChainingBlockDevice::get_erase_size(bd_addr_t addr) const
{
return 0;
}
int ChainingBlockDevice::get_erase_value() const
{
return 0;
}
bd_size_t ChainingBlockDevice::size() const
{
return 0;
}
| [
"antti.kauppila@arm.com"
] | antti.kauppila@arm.com |
2a0844a5b49abaf12edd7e63828bfe34001d068e | e6ef968145e4f9c5c4556e9ca7273b95377c39e9 | /singaporean name/main.cpp | 39a7c324a06ac835f279dd836dbb2d7c840424f2 | [] | no_license | FangShaoHua94/kattis-Cplusplus | 99cd9cecb1a84df116046671f5be073e6b5f1144 | 82049df6793682bb73b57913add04be28a3d3829 | refs/heads/master | 2023-02-11T12:11:42.966616 | 2021-01-15T08:25:57 | 2021-01-15T08:25:57 | 329,851,884 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,041 | cpp | #include <bits/stdc++.h>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
string call_as(string name);
int main() {
string name="Ng Zhen Rui Matthew";
name=call_as(name);
name="Tan Jun An";
name=call_as(name);
name="Lim Li";
name=call_as(name);
cout<<"lol";
return 0;
}
string call_as(string name){
// char n[]=name;
int count=0;
vector<char> q[4];
// char *pch;
// pch=strtok(n," ");
// while(pch!=NULL){
// q[count++]=pch;
// pch=strtok(NULL," ");
// }
for(int i=0;i<name.size();i++){
if(name[i]==' '){
count++;
}else{
q[count].push_back(name[i]);
}
}
switch(count){
case 1:
for(char ch:q[0]){
cout<<ch;
}cout<<" ";
for(char ch:q[1]){
cout<<ch;
}
break;
case 2:
for(char ch:q[1]){
cout<<ch;
}cout<<" ";
for(char ch:q[2]){
cout<<ch;
}
break;
case 3:
for(char ch:q[3]){
cout<<ch;
}cout<<" ";
for(char ch:q[0]){
cout<<ch;
}
break;
}
cout<<endl;
return name;
}
| [
"daythehangedman@hotmail.com"
] | daythehangedman@hotmail.com |
2fd9105a40880bf9cfddb8ee3f4185b2dbf07b03 | 6bda0d8a8aeb1357de3131e39d695685a727e148 | /src/drivers/disk_logger.cpp | 25800021495d3f424c23a4846a1eee82a31c0608 | [
"Apache-2.0"
] | permissive | xekoukou/IncludeOS | 78ac2a20463093a2cdff2f8f007ad46281b8ace0 | 34bb08cf4b01bdd7e9bb5ee49f59241cf5e73fe8 | refs/heads/master | 2021-05-13T23:14:27.434226 | 2018-01-04T15:37:07 | 2018-01-04T15:37:07 | 116,509,752 | 0 | 0 | null | 2018-01-06T19:28:25 | 2018-01-06T19:28:24 | null | UTF-8 | C++ | false | false | 2,517 | cpp | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <os>
#include <hw/block_device.hpp>
#include <fs/common.hpp>
#include <rtc>
#include "disk_logger.hpp"
static log_structure header;
static fs::buffer_t logbuffer;
static uint32_t position = 0;
static bool write_once_when_booted = false;
extern "C" void __serial_print1(const char*);
extern "C" void __serial_print(const char*, size_t);
static void write_all()
{
try {
auto& device = hw::Devices::drive(DISK_NO);
const auto sector = disklogger_start_sector(device);
const bool error = device.write_sync(sector, logbuffer);
if (error) {
__serial_print1("IDE::write_sync failed! Missing or wrong driver?\n");
}
} catch (std::exception& e) {
__serial_print1("IDE block device missing! Missing device or driver?\n");
}
}
static void disk_logger_write(const char* data, size_t len)
{
if (position + len > header.max_length) {
position = sizeof(log_structure);
//header.length = header.max_length;
}
__builtin_memcpy(&(*logbuffer)[position], data, len);
position += len;
if (header.length < position) header.length = position;
// update header
if (OS::is_booted()) {
header.timestamp = RTC::now();
}
else {
header.timestamp = OS::micros_since_boot() / 1000000;
}
__builtin_memcpy(logbuffer->data(), &header, sizeof(log_structure));
// write to disk when we are able
const bool once = OS::is_booted() && write_once_when_booted == false;
if (OS::block_drivers_ready() && (once || OS::is_panicking()))
{
write_once_when_booted = true;
write_all();
}
}
__attribute__((constructor))
static void enable_disk_logger()
{
logbuffer = fs::construct_buffer(DISKLOG_SIZE);
position = sizeof(log_structure);
header.max_length = logbuffer->capacity();
OS::add_stdout(disk_logger_write);
}
| [
"fwsgonzo@hotmail.com"
] | fwsgonzo@hotmail.com |
bf62c7c8e323bbb98f8ef9e3cd6f7a61e17a2d4a | 18cf4e58c04409e1372ec3a65223e5d5cf2c048c | /test/unit_tests/subscriber_test/Subscriber.h | 9b7b700b7b0a38434e979eea837a018d0c095b78 | [] | no_license | malzer42/lmis | 967fdfafde36690e8b12e96ff4986b4ec923fe8a | 6a621dfd07ba5c6b7cbf1b7ab5f97545f154b726 | refs/heads/master | 2020-03-19T22:57:58.646928 | 2020-03-10T14:18:19 | 2020-03-10T14:18:19 | 136,987,520 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,069 | h | // Subscriber.h: Header for the definition of the class Subscriber.
// Author(s): Pierre Abraham Mulamba.
// Date of creation (modification): 2018/06/10 (2018/06/12).
// Description: The class Subscriber is a concrete class that defines a Subscriber interface and representation.
// Usage: To create an instance of a Subscriber.
// Compilation: Makefile provided.
// Run: Included as header file
#ifndef LMIS_SUBSCRIBER_H
#define LMIS_SUBSCRIBER_H
#include <iostream>
#include <string>
#include <exception>
class Subscriber {
public:
// Ctor
Subscriber(const std::string &id = "", const std::string &firstName = "", const std::string &lastName = "", unsigned int age = 0);
Subscriber(const Subscriber &subscriber); // Copy ctor
Subscriber(Subscriber &&subscriber)noexcept; // Move ctor
Subscriber &operator=(const Subscriber &subscriber); //! Copy assignment operator
Subscriber &operator=(Subscriber &&subscriber)noexcept;// noexcept; //! Move assignment operator
// Exception
class BadSubscriber : public std::exception {
public:
const std::string exceptionMsg = "BadSubscriberError: Unable to create an instance of the class Subscriber\n";
};
// Dtor
virtual ~Subscriber() = default;
// Accessors or Getters
const std::string &getId() const;
const std::string &getFirstName() const;
const std::string &getLastName() const;
unsigned int getAge() const;
// Mutators or Setters
void setId(const std::string &id);
void setFirstName(const std::string &firstName);
void setLastName(const std::string &lastName);
void setAge(unsigned int age);
// Printing method
void print() const; // The actual printing method
void str() const; // For developer to know how the information of an instance of the class Subscriber will be displayed on the screen
void repr() const; // For developer to know how to create an instance of the class Subscriber
private:
std::string id_; // e.g. "1839456"
std::string firstName_; // e.g. "John"
std::string lastName_; // e.g. "Doe"
unsigned int age_; // e.g. 39
};
#endif //LMIS_SUBSCRIBER_H
| [
"pmulamba@gmail.com"
] | pmulamba@gmail.com |
404500c497ef435e178ff8d43a2ed6c775a0e118 | 694c05848157073888a6dd5cde215ada80c20fb2 | /src/DPPrimaryGeneratorAction.cxx | 80870ae27a0399de700a83089a1d93a6cabf05d2 | [] | no_license | dkleinja/DPSim | 240f30795b21ef39a6c8fc1646cfbaa4f2cf9a18 | 80d285a6183e730b72129f36322c479d0327c60b | refs/heads/dev | 2020-06-18T15:57:41.365444 | 2017-06-01T22:36:20 | 2017-06-01T22:36:20 | 75,128,510 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 28,955 | cxx | #include "DPPrimaryGeneratorAction.h"
#include <fstream>
#include <string>
#include "Randomize.hh"
#include "G4SystemOfUnits.hh"
#include "G4PhysicalConstants.hh"
#include <TFile.h>
#include <TTree.h>
#include <TMath.h>
#include <TVector3.h>
#include <TLorentzVector.h>
namespace DPGEN
{
// global parameters
const double pi = TMath::Pi();
const double twopi = 2.*pi;
const double sqrt2pi = TMath::Sqrt(twopi);
// masses
const double mp = 0.93827;
const double mmu = 0.10566;
const double mjpsi = 3.097;
const double mpsip = 3.686;
// 4-vectors
const double ebeam = 120.;
const TLorentzVector p_beam(0., 0., TMath::Sqrt(ebeam*ebeam - mp*mp), ebeam);
const TLorentzVector p_target(0., 0., 0., mp);
const TLorentzVector p_cms = p_beam + p_target;
const TVector3 bv_cms = p_cms.BoostVector();
const double s = p_cms.M2();
const double sqrts = p_cms.M();
//distribution-wise constants
const double pT0DY = 2.8;
const double pTpowDY = 1./(6. - 1.);
const double pT0JPsi = 3.0;
const double pTpowJPsi = 1./(6. - 1.);
//charmonium generation constants Ref: Schub et al Phys Rev D 52, 1307 (1995)
const double sigmajpsi = 0.2398; //Jpsi xf gaussian width
const double brjpsi = 0.0594; //Br(Jpsi -> mumu)
const double ajpsi = 0.001464*TMath::Exp(-16.66*mjpsi/sqrts);
const double bjpsi = 2.*sigmajpsi*sigmajpsi;
const double psipscale = 0.019; //psip relative to jpsi
}
DPPrimaryGeneratorAction::DPPrimaryGeneratorAction()
{
p_config = DPSimConfig::instance();
p_IOmamnger = DPIOManager::instance();
p_vertexGen = DPVertexGenerator::instance();
particleGun = new G4ParticleGun(1);
particleDict = G4ParticleTable::GetParticleTable();
proton = particleDict->FindParticle(2212);
mup = particleDict->FindParticle(-13);
mum = particleDict->FindParticle(13);
ep = particleDict->FindParticle(-11);
em = particleDict->FindParticle(11);
pip = particleDict->FindParticle(211);
pim = particleDict->FindParticle(-211);
pdf = LHAPDF::mkPDF("CT10nlo", 0);
//TODO: need to find a way to pass the random number seed to pythia as well
//initilize all kinds of generators
if(p_config->generatorType == "dimuon")
{
if(p_config->generatorEng == "legacyDY")
{
std::cout << " Using legacy Drell-Yan generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateDrellYan;
}
else if(p_config->generatorEng == "legacyJPsi")
{
std::cout << " Using legacy JPsi generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateJPsi;
}
else if(p_config->generatorEng == "legacyPsip")
{
std::cout << " Using Psip generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generatePsip;
}
else if(p_config->generatorEng == "PHSP")
{
std::cout << " Using phase space generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generatePhaseSpace;
}
else if(p_config->generatorEng == "pythia")
{
std::cout << " Using pythia pythia generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generatePythiaDimuon;
ppGen.readFile(p_config->pythiaConfig.Data());
pnGen.readFile(p_config->pythiaConfig.Data());
ppGen.readString("Beams:idB = 2212");
ppGen.readString("Beams:idB = 2112");
ppGen.init();
pnGen.init();
}
else if(p_config->generatorEng == "DarkPhotonFromEta")
{
std::cout << " Using dark photon generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateDarkPhotonFromEta;
ppGen.readFile(p_config->pythiaConfig.Data());
pnGen.readFile(p_config->pythiaConfig.Data());
ppGen.readString("Beams:idB = 2212");
ppGen.readString("Beams:idB = 2112");
ppGen.init();
pnGen.init();
}
else if(p_config->generatorEng == "custom")
{
std::cout << " Using custom LUT dimuon generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateCustomDimuon;
//read and parse the lookup table
std::ifstream fin(p_config->customLUT.Data());
std::cout << " Initializing custom dimuon cross section from LUT " << p_config->customLUT << std::endl;
//Load the range and number of bins in each dimension
std::string line;
int n, n_m, n_xF;
double m_min, m_max, xF_min, xF_max;
double m_bin, xF_bin;
getline(fin, line);
std::stringstream ss(line);
ss >> n >> n_m >> m_min >> m_max >> m_bin >> n_xF >> xF_min >> xF_max >> xF_bin;
//test if the range is acceptable
if(p_config->massMin < m_min || p_config->massMax > m_max || p_config->xfMin < xF_min || p_config->xfMax > xF_max)
{
std::cout << " ERROR: the specified phase space limits are larger than LUT limits!" << std::endl;
exit(EXIT_FAILURE);
}
lut = new TH2D("LUT", "LUT", n_m, m_min - 0.5*(m_max - m_min)/(n_m - 1), m_max + 0.5*(m_max - m_min)/(n_m - 1),
n_xF, xF_min - 0.5*(xF_max - xF_min)/(n_xF - 1), xF_max + 0.5*(xF_max - xF_min)/(n_xF - 1));
while(getline(fin, line))
{
double mass, xF, xsec;
std::stringstream ss(line);
ss >> mass >> xF >> xsec;
xsec *= (m_bin*xF_bin);
lut->Fill(mass, xF, xsec);
}
}
else
{
std::cout << "ERROR: Generator engine is not set or ncd /seaot supported in dimuon mode" << std::endl;
exit(EXIT_FAILURE);
}
}
else if(p_config->generatorType == "single")
{
if(p_config->generatorEng == "pythia")
{
std::cout << " Using pythia single generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generatePythiaSingle;
ppGen.readFile(p_config->pythiaConfig.Data());
pnGen.readFile(p_config->pythiaConfig.Data());
ppGen.readString("Beams:idB = 2212");
ppGen.readString("Beams:idB = 2112");
ppGen.init();
pnGen.init();
}
else if(p_config->generatorEng == "geant")
{
std::cout << " Using geant4 single generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateGeant4Single;
}
else if(p_config->generatorEng == "test")
{
std::cout << " Using test single generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateTestSingle;
if(p_config->testParticle == "mu")
{
testPar[0] = mup;
testPar[1] = mum;
}
else if(p_config->testParticle == "e")
{
testPar[0] = ep;
testPar[1] = em;
}
else if(p_config->testParticle == "pi")
{
testPar[0] = pip;
testPar[1] = pim;
}
}
else
{
std::cout << "ERROR: Generator engine is not set or not supported in single mode" << std::endl;
exit(EXIT_FAILURE);
}
}
else if(p_config->generatorType == "external")
{
std::cout << " Using external generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateExternal;
externalInputFile = new TFile(p_config->externalInput.Data(), "READ");
externalInputTree = (TTree*)externalInputFile->Get("save");
externalPositions = new TClonesArray("TVector3");
externalMomentums = new TClonesArray("TVector3");
externalInputTree->SetBranchAddress("eventID", &externalEventID);
externalInputTree->SetBranchAddress("n", &nExternalParticles);
externalInputTree->SetBranchAddress("pdg", externalParticlePDGs);
externalInputTree->SetBranchAddress("pos", &externalPositions);
externalInputTree->SetBranchAddress("mom", &externalMomentums);
//take over the control of the buffer flushing, TODO: move this thing to somewhere else
lastFlushPosition = 0;
p_IOmamnger->setBufferState(DPIOManager::CLEAN);
}
else if(p_config->generatorType == "Debug")
{
std::cout << " Using simple debug generator ..." << std::endl;
p_generator = &DPPrimaryGeneratorAction::generateDebug;
}
else
{
std::cout << "ERROR: Generator type not recognized! Will exit.";
exit(EXIT_FAILURE);
}
//force pion/kaon decay by changing the lifetime
if(p_config->forcePionDecay)
{
std::cout << " Forcing pion to decay immediately ..." << std::endl;
particleDict->FindParticle(211)->SetPDGStable(false);
particleDict->FindParticle(211)->SetPDGLifeTime(0.);
particleDict->FindParticle(-211)->SetPDGStable(false);
particleDict->FindParticle(-211)->SetPDGLifeTime(0.);
}
if(p_config->forceKaonDecay)
{
std::cout << " Forcing kaon to decay immediately ..." << std::endl;
particleDict->FindParticle(321)->SetPDGStable(false);
particleDict->FindParticle(321)->SetPDGLifeTime(0.);
particleDict->FindParticle(-321)->SetPDGStable(false);
particleDict->FindParticle(-321)->SetPDGLifeTime(0.);
}
}
DPPrimaryGeneratorAction::~DPPrimaryGeneratorAction()
{
delete pdf;
delete particleGun;
if(p_config->generatorType == "custom") delete lut;
}
void DPPrimaryGeneratorAction::GeneratePrimaries(G4Event* anEvent)
{
p_config->nEventsThrown++;
theEvent = anEvent;
(this->*p_generator)();
}
void DPPrimaryGeneratorAction::generateDrellYan()
{
DPMCDimuon dimuon;
double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin;
double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin;
if(!generateDimuon(mass, xF, dimuon, true)) return;
p_vertexGen->generateVertex(dimuon);
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
//calculate the cross section
//PDF-related
double zOverA = p_vertexGen->getPARatio();
double nOverA = 1. - zOverA;
double dbar1 = pdf->xfxQ(-1, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double ubar1 = pdf->xfxQ(-2, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double d1 = pdf->xfxQ(1, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double u1 = pdf->xfxQ(2, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double s1 = pdf->xfxQ(3, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double c1 = pdf->xfxQ(4, dimuon.fx1, dimuon.fMass)/dimuon.fx1;
double dbar2 = pdf->xfxQ(-1, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double ubar2 = pdf->xfxQ(-2, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double d2 = pdf->xfxQ(1, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double u2 = pdf->xfxQ(2, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double s2 = pdf->xfxQ(3, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double c2 = pdf->xfxQ(4, dimuon.fx2, dimuon.fMass)/dimuon.fx2;
double xsec_pdf = 4./9.*(u1*(zOverA*ubar2 + nOverA*dbar2) + ubar1*(zOverA*u2 + nOverA*d2) + 2*c1*c2) +
1./9.*(d1*(zOverA*dbar2 + nOverA*ubar2) + dbar1*(zOverA*d2 + nOverA*u2) + 2*s1*s2);
//KFactor
double xsec_kfactor = 1.;
if(dimuon.fMass < 2.5)
{
xsec_kfactor = 1.25;
}
else if(dimuon.fMass < 7.5)
{
xsec_kfactor = 1.25 + (1.82 - 1.25)*(dimuon.fMass - 2.5)/5.;
}
else
{
xsec_kfactor = 1.82;
}
//phase space
double xsec_phsp = dimuon.fx1*dimuon.fx2/(dimuon.fx1 + dimuon.fx2)/dimuon.fMass/dimuon.fMass/dimuon.fMass;
//generation limitation
double xsec_limit = (p_config->massMax - p_config->massMin)*(p_config->xfMax - p_config->xfMin)*
(p_config->cosThetaMax*p_config->cosThetaMax*p_config->cosThetaMax/3. + p_config->cosThetaMax
- p_config->cosThetaMin*p_config->cosThetaMin*p_config->cosThetaMin/3. - p_config->cosThetaMin)*4./3.;
double xsec = xsec_pdf*xsec_kfactor*xsec_phsp*xsec_limit*p_vertexGen->getLuminosity();
dimuon.fPosTrackID = 1;
dimuon.fNegTrackID = 2;
p_IOmamnger->fillOneDimuon(xsec, dimuon);
}
void DPPrimaryGeneratorAction::generateJPsi()
{
DPMCDimuon dimuon;
double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin;
if(!generateDimuon(DPGEN::mjpsi, xF, dimuon)) return;
p_vertexGen->generateVertex(dimuon);
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
//calculate the cross section
//xf distribution
double xsec_xf = DPGEN::ajpsi*TMath::Exp(-dimuon.fxF*dimuon.fxF/DPGEN::bjpsi)/(DPGEN::sigmajpsi*DPGEN::sqrt2pi);
//generation limitation
double xsec_limit = p_config->xfMax - p_config->xfMin;
double xsec = DPGEN::brjpsi*xsec_xf*xsec_limit*p_vertexGen->getLuminosity();
dimuon.fPosTrackID = 1;
dimuon.fNegTrackID = 2;
p_IOmamnger->fillOneDimuon(xsec, dimuon);
}
void DPPrimaryGeneratorAction::generatePsip()
{
DPMCDimuon dimuon;
double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin;
if(!generateDimuon(DPGEN::mpsip, xF, dimuon)) return;
p_vertexGen->generateVertex(dimuon);
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
//calculate the cross section
//xf distribution
double xsec_xf = DPGEN::ajpsi*TMath::Exp(-dimuon.fxF*dimuon.fxF/DPGEN::bjpsi)/(DPGEN::sigmajpsi*DPGEN::sqrt2pi);
//generation limitation
double xsec_limit = p_config->xfMax - p_config->xfMin;
double xsec = DPGEN::psipscale*DPGEN::brjpsi*xsec_xf*xsec_limit*p_vertexGen->getLuminosity();
dimuon.fPosTrackID = 1;
dimuon.fNegTrackID = 2;
p_IOmamnger->fillOneDimuon(xsec, dimuon);
}
void DPPrimaryGeneratorAction::generateDarkPhotonFromEta()
{
TVector3 vtx = p_vertexGen->generateVertex();
double pARatio = p_vertexGen->getPARatio();
Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen;
while(!p_pythia->next()) {}
int nEtas = 1;
Pythia8::Event& particles = p_pythia->event;
for(int i = 1; i < particles.size(); ++i)
{
if(particles[i].id() == 221)
{
//Fill eta to particle gun as well, it will probably make no difference in detector
G4ThreeVector g4vtx = G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(particles[i].xProd()*mm, particles[i].yProd()*mm, particles[i].zProd()*mm);
particleGun->SetParticleDefinition(particleDict->FindParticle(221));
particleGun->SetParticlePosition(g4vtx);
particleGun->SetParticleMomentum(G4ThreeVector(particles[i].px()*GeV, particles[i].py()*GeV, particles[i].pz()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
DPMCDimuon dimuon;
dimuon.fVertex.SetXYZ(g4vtx.x(), g4vtx.y(), g4vtx.z());
//eta -> gamma A', this step decays isotropically
TLorentzVector p_eta(particles[i].px(), particles[i].py(), particles[i].pz(), particles[i].e());
double mass_eta_decays[2] = {G4UniformRand()*(p_eta.M() - 2.*DPGEN::mmu) + 2.*DPGEN::mmu, 0.};
phaseGen.SetDecay(p_eta, 2, mass_eta_decays);
phaseGen.Generate();
TLorentzVector p_AP = *(phaseGen.GetDecay(0));
//A' -> mumu, this step has a 1 + cos^2\theta distribution
double mass_AP_decays[2] = {DPGEN::mmu, DPGEN::mmu};
phaseGen.SetDecay(p_AP, 2, mass_AP_decays);
bool angular = true;
while(angular)
{
phaseGen.Generate();
dimuon.fPosMomentum = *(phaseGen.GetDecay(0));
dimuon.fNegMomentum = *(phaseGen.GetDecay(1));
dimuon.calcVariables();
angular = 2.*G4UniformRand() > 1. + dimuon.fCosTh*dimuon.fCosTh;
}
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
//add to the IO stream
dimuon.fPosTrackID = nEtas*2 - 1;
dimuon.fNegTrackID = nEtas*2;
p_IOmamnger->fillOneDimuon(1., dimuon);
++nEtas;
}
}
}
void DPPrimaryGeneratorAction::generateCustomDimuon()
{
DPMCDimuon dimuon;
double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin;
double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin;
if(!generateDimuon(mass, xF, dimuon, true)) return; //TODO: maybe later need to add an option or flag in lut to specify angular distribution
p_vertexGen->generateVertex(dimuon);
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
//calculate the cross section
double xsec = lut->Interpolate(mass, xF)*p_vertexGen->getLuminosity();
dimuon.fPosTrackID = 1;
dimuon.fNegTrackID = 2;
p_IOmamnger->fillOneDimuon(xsec, dimuon);
}
void DPPrimaryGeneratorAction::generatePythiaDimuon()
{
p_config->nEventsPhysics++;
DPMCDimuon dimuon;
TVector3 vtx = p_vertexGen->generateVertex();
double pARatio = p_vertexGen->getPARatio();
Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen;
while(!p_pythia->next()) {}
int pParID = 0;
for(int i = 1; i < p_pythia->event.size(); ++i)
{
Pythia8::Particle par = p_pythia->event[i];
if(par.status() > 0 && par.id() != 22)
{
G4ThreeVector g4vtx = G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(par.xProd()*mm, par.yProd()*mm, par.zProd()*mm);
particleGun->SetParticleDefinition(particleDict->FindParticle(par.id()));
particleGun->SetParticlePosition(g4vtx);
particleGun->SetParticleMomentum(G4ThreeVector(par.px()*GeV, par.py()*GeV, par.pz()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
++pParID;
if(par.id() == -13)
{
dimuon.fPosTrackID = pParID;
dimuon.fPosMomentum.SetXYZM(par.px(), par.py(), par.pz(), DPGEN::mmu);
}
else if(par.id() == 13)
{
dimuon.fNegTrackID = pParID;
dimuon.fNegMomentum.SetXYZM(par.px(), par.py(), par.pz(), DPGEN::mmu);
}
dimuon.fVertex.SetXYZ(g4vtx.x(), g4vtx.y(), g4vtx.z());
}
}
p_IOmamnger->fillOneDimuon(1., dimuon);
}
void DPPrimaryGeneratorAction::generatePythiaSingle()
{
p_config->nEventsPhysics++;
TVector3 vtx = p_vertexGen->generateVertex();
double pARatio = p_vertexGen->getPARatio();
Pythia8::Pythia* p_pythia = G4UniformRand() < pARatio ? &ppGen : &pnGen;
while(!p_pythia->next()) {}
for(int j = 1; j < p_pythia->event.size(); ++j)
{
Pythia8::Particle par = p_pythia->event[j];
//for every muon track, find its mother and fill it to the track list as well
if(par.status() > 0 && par.id() != 22)
{
particleGun->SetParticleDefinition(particleDict->FindParticle(par.id()));
particleGun->SetParticlePosition(G4ThreeVector(vtx.X()*cm, vtx.Y()*cm, vtx.Z()*cm) + G4ThreeVector(par.xProd()*mm, par.yProd()*mm, par.zProd()*mm));
particleGun->SetParticleMomentum(G4ThreeVector(par.px()*GeV, par.py()*GeV, par.pz()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
}
}
}
void DPPrimaryGeneratorAction::generateGeant4Single()
{
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(proton);
particleGun->SetParticlePosition(G4ThreeVector(0., 0., -600*cm));
particleGun->SetParticleMomentum(G4ThreeVector(0., 0., p_config->beamMomentum*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
}
void DPPrimaryGeneratorAction::generateTestSingle()
{
p_config->nEventsPhysics++;
double mom = (5. + (p_config->beamMomentum - 5.)*G4UniformRand())*GeV;
double costheta = p_config->cosThetaMin + (p_config->cosThetaMax - p_config->cosThetaMin)*G4UniformRand();
double phi = G4UniformRand()*DPGEN::twopi;
double pz = mom*costheta;
double px = mom*TMath::Sqrt(1. - costheta*costheta)*TMath::Cos(phi);
double py = mom*TMath::Sqrt(1. - costheta*costheta)*TMath::Sin(phi);
double x = G4RandGauss::shoot(0., 1.5)*cm;
double y = G4RandGauss::shoot(0., 1.5)*cm;
double z = (G4UniformRand()*(p_config->zOffsetMax - p_config->zOffsetMin) + p_config->zOffsetMin)*cm;
particleGun->SetParticleDefinition(G4UniformRand() > 0.5 ? testPar[0] : testPar[1]);
particleGun->SetParticlePosition(G4ThreeVector(x, y, z));
particleGun->SetParticleMomentum(G4ThreeVector(px, py, pz));
particleGun->GeneratePrimaryVertex(theEvent);
}
void DPPrimaryGeneratorAction::generatePhaseSpace()
{
DPMCDimuon dimuon;
double mass = G4UniformRand()*(p_config->massMax - p_config->massMin) + p_config->massMin;
double xF = G4UniformRand()*(p_config->xfMax - p_config->xfMin) + p_config->xfMin;
if(!generateDimuon(mass, xF, dimuon)) return;
p_vertexGen->generateVertex(dimuon);
p_config->nEventsPhysics++;
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fPosMomentum.X()*GeV, dimuon.fPosMomentum.Y()*GeV, dimuon.fPosMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
particleGun->SetParticleDefinition(mum);
particleGun->SetParticlePosition(G4ThreeVector(dimuon.fVertex.X()*cm, dimuon.fVertex.Y()*cm, dimuon.fVertex.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(dimuon.fNegMomentum.X()*GeV, dimuon.fNegMomentum.Y()*GeV, dimuon.fNegMomentum.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
dimuon.fPosTrackID = 1;
dimuon.fNegTrackID = 2;
p_IOmamnger->fillOneDimuon(1., dimuon);
}
void DPPrimaryGeneratorAction::generateExternal()
{
int eventID = theEvent->GetEventID();
externalInputTree->GetEntry(eventID);
for(int i = 0; i < nExternalParticles; ++i)
{
TVector3 pos = *((TVector3*)externalPositions->At(i));
TVector3 mom = *((TVector3*)externalMomentums->At(i));
particleGun->SetParticleDefinition(particleDict->FindParticle(externalParticlePDGs[i]));
particleGun->SetParticlePosition(G4ThreeVector(pos.X()*cm, pos.Y()*cm, pos.Z()*cm));
particleGun->SetParticleMomentum(G4ThreeVector(mom.X()*GeV, mom.Y()*GeV, mom.Z()*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
}
//send the flush signal in two cases: 1. the external eventID increment exceeds bucket size,
// 2. this is the last event in external tree
if(p_config->bucket_size == 1) return;
if(externalEventID - lastFlushPosition >= p_config->bucket_size || eventID + 1 == p_config->nEvents)
{
lastFlushPosition = (externalEventID/p_config->bucket_size)*p_config->bucket_size;
p_IOmamnger->setBufferState(DPIOManager::FLUSH);
}
}
void DPPrimaryGeneratorAction::generateDebug()
{
particleGun->SetParticleDefinition(mup);
particleGun->SetParticlePosition(G4ThreeVector(0., 0., -500.*cm));
particleGun->SetParticleMomentum(G4ThreeVector(0., 0., 50.*GeV));
particleGun->GeneratePrimaryVertex(theEvent);
}
bool DPPrimaryGeneratorAction::generateDimuon(double mass, double xF, DPMCDimuon& dimuon, bool angular)
{
double pz = xF*(DPGEN::sqrts - mass*mass/DPGEN::sqrts)/2.;
double pTmaxSq = (DPGEN::s*DPGEN::s*(1. - xF*xF) - 2.*DPGEN::s*mass*mass + mass*mass*mass*mass)/DPGEN::s/4.;
if(pTmaxSq < 0.) return false;
double pTmax = sqrt(pTmaxSq);
double pT = 10.;
if(pTmax < 0.3)
{
pT = pTmax*sqrt(G4UniformRand());
}
else if(p_config->drellyanMode)
{
while(pT > pTmax) pT = DPGEN::pT0DY*TMath::Sqrt(1./TMath::Power(G4UniformRand(), DPGEN::pTpowDY) - 1.);
}
else
{
while(pT > pTmax) pT = DPGEN::pT0JPsi*TMath::Sqrt(1./TMath::Power(G4UniformRand(), DPGEN::pTpowJPsi) - 1.);
}
double phi = G4UniformRand()*DPGEN::twopi;
double px = pT*TMath::Cos(phi);
double py = pT*TMath::Sin(phi);
//configure phase space generator
TLorentzVector p_dimuon;
p_dimuon.SetXYZM(px, py, pz, mass);
p_dimuon.Boost(DPGEN::bv_cms);
double masses[2] = {DPGEN::mmu, DPGEN::mmu};
phaseGen.SetDecay(p_dimuon, 2, masses);
bool firstTry = true;
while(firstTry || angular)
{
firstTry = false;
phaseGen.Generate();
dimuon.fPosMomentum = *(phaseGen.GetDecay(0));
dimuon.fNegMomentum = *(phaseGen.GetDecay(1));
dimuon.calcVariables();
angular = 2.*G4UniformRand() > 1. + dimuon.fCosTh*dimuon.fCosTh;
}
if(dimuon.fx1 < p_config->x1Min || dimuon.fx1 > p_config->x1Max) return false;
if(dimuon.fx2 < p_config->x2Min || dimuon.fx2 > p_config->x2Max) return false;
if(dimuon.fCosTh < p_config->cosThetaMin || dimuon.fCosTh > p_config->cosThetaMax) return false;
return true;
}
| [
"liuk.pku@gmail.com"
] | liuk.pku@gmail.com |
7728dde8d0a1b8647862c1a202ab17783fe4c269 | f52bf7316736f9fb00cff50528e951e0df89fe64 | /Platform/vendor/samsung/common/packages/apps/SBrowser/src/chrome/app/android/sbr/sbr_chrome_main_delegate_android.h | 4e90870dafbf89a4fb110c265b9adeaf9cf20692 | [
"BSD-3-Clause"
] | permissive | git2u/sm-t530_KK_Opensource | bcc789ea3c855e3c1e7471fc99a11fd460b9d311 | 925e57f1f612b31ea34c70f87bc523e7a7d53c05 | refs/heads/master | 2021-01-19T21:32:06.678681 | 2014-11-21T23:09:45 | 2014-11-21T23:09:45 | 48,746,810 | 0 | 1 | null | 2015-12-29T12:35:13 | 2015-12-29T12:35:13 | null | UTF-8 | C++ | false | false | 802 | h | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_
#define CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_
#include "chrome/app/android/chrome_main_delegate_android.h"
class SbrChromeMainDelegateAndroid : public ChromeMainDelegateAndroid {
public:
SbrChromeMainDelegateAndroid();
virtual ~SbrChromeMainDelegateAndroid();
virtual bool BasicStartupComplete(int* exit_code) OVERRIDE;
virtual bool RegisterApplicationNativeMethods(JNIEnv* env) OVERRIDE;
private:
DISALLOW_COPY_AND_ASSIGN(SbrChromeMainDelegateAndroid);
};
#endif // CHROME_APP_ANDROID_SBR_SBR_CHROME_MAIN_DELEGATE_ANDROID_H_ | [
"digixp2006@gmail.com"
] | digixp2006@gmail.com |
1d8e91ffa3e877a62e3adeb5219c179dc1011011 | 65987a3251e26302d23396be2a14c8730caf9f6c | /CF/1295B.cpp | d6763f42fdf9cbdb130663167e66ad7198034a9a | [] | no_license | wuyuhang422/My-OI-Code | 9608bca023fa2e4506b2d3dc1ede9a2c7487a376 | f61181cc64fafc46711ef0e85522e77829b04b37 | refs/heads/master | 2021-06-16T08:15:52.203672 | 2021-02-01T05:16:41 | 2021-02-01T05:16:41 | 135,901,492 | 5 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,290 | cpp | /*
* Author: RainAir
* Time: 2020-03-05 10:10:42
*/
#include<bits/stdc++.h>
#define fi first
#define se second
#define U unsigned
#define P std::pair<int,int>
#define LL long long
#define pb push_back
#define MP std::make_pair
#define all(x) x.begin(),x.end()
#define CLR(i,a) memset(i,a,sizeof(i))
#define FOR(i,a,b) for(int i = a;i <= b;++i)
#define ROF(i,a,b) for(int i = a;i >= b;--i)
#define DEBUG(x) std::cerr << #x << '=' << x << std::endl
const int MAXN = 1e5 + 5;
char str[MAXN];
int n,x;
int main(){
int T;scanf("%d",&T);
while(T--){
scanf("%d%d",&n,&x);scanf("%s",str+1);
int p0 = 0,p1 =0,s0=0,s1=0;
FOR(i,1,n) s0 += (str[i]=='0'),s1 += (str[i] == '1');
int delta = s0-s1;
if(s0 == s1){
bool flag = false;
FOR(i,1,n){
p0+=(str[i]=='0');p1 += (str[i] == '1');
if(p0-p1 == x){
flag = true;break;
}
}
puts(flag ? "-1" : "0");continue;
}int ans = 0;
FOR(i,1,n){
p0 += (str[i]=='0');p1 += (str[i]=='1');
int t1 = p0-p1;
// DEBUG(t1);
if((x-t1)%delta == 0 && (x-t1)/delta >= 0) ans++;
}
printf("%d\n",ans+(x==0));
}
return 0;
}
| [
"wuyuhang422@gmail.com"
] | wuyuhang422@gmail.com |
647b77697765305dfb89ef91cbc034e4598faad0 | fba719746323ebb2a561cfc6f2cb448eec042d1a | /c++实用代码/tmp/New LCP+Suffix Array1.cpp | 1917eacfa25fb427e5684e359221722b70bb638f | [
"MIT"
] | permissive | zhzh2001/Learning-public | 85eedf205b600dfa64747b20bce530861050b387 | c7b0fe6ea64d2890ba2b25ae8a080d61c22f71c9 | refs/heads/master | 2021-05-16T09:44:08.380814 | 2017-09-23T04:55:33 | 2017-09-23T04:55:33 | 104,541,989 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 891 | cpp | #include<stdio.h>
#include<time.h>
#include<algorithm>
#define N 500010
#define CH 256
typedef int value;
value X[N][21],ra[CH];
int l2[N],sa[N];
char str[N];
int n,i,j;
int LCP(int x,int y){
int pre=x;
for (int i=l2[n];i>=0;--i)
if (x+(1<<i)-1<n&&y+(1<<i)-1<n&&X[x][i]==X[y][i])
x+=1<<i,y+=1<<i;
return x-pre;
}
bool cmp(int x,int y){
int len=LCP(x,y);
return str[x+len]<str[y+len];
}
int main(){
srand(time(0));
for (i=0;i<CH;++i)ra[i]=(rand()<<16)+rand();
//scanf("%s",str);
for (int i=0;i<500000;++i)str[i]=rand()%100+10;
n=strlen(str);
for (l2[0]=-1,i=1;i<=n;++i)l2[i]=!(i&(i-1))?l2[i-1]+1:l2[i-1];
for (i=0;i<n;++i)X[i][0]=ra[str[i]];
for (i=n-1;i>=0;--i)
for (j=1;j<=l2[n+1-i];++j)
X[i][j]=X[i][j-1]*ra[j]^X[i+(1<<(j-1))][j-1];
for (i=1;i<=N;++i)sa[i]=i-1;
std::sort(sa+1,sa+1+n,cmp);
//for (i=1;i<=n;++i)printf("%d ",sa[i]);printf("\n");
system("pause");
}
| [
"zhangzheng0928@163.com"
] | zhangzheng0928@163.com |
0a868b4c62c119d35a27f482f879384e97938929 | 67fee4c964cfba111dcb1a39d126987e6b9867fd | /src/header.h | 41fcc25eb66caa29994b64870ee9f3b27c017ac8 | [] | no_license | ss12330335/MEPL | f4fd3e02880f8cd511c7e5d7baa346bde8f44477 | 99629bf5ddb814480a1fd533346163c76a79090c | refs/heads/master | 2020-03-27T12:39:11.025795 | 2018-08-29T07:13:15 | 2018-08-29T07:13:15 | 146,559,449 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 277 | h | #ifndef __HEADER_H__
#define __HEADER_H__
#include <iostream>
#include <string>
#include <vector>
#include <set>
#include <map>
#include <list>
#include <algorithm>
#include <cmath>
#include <assert.h>
#include <fstream>
#include <limits.h> // for INT_MAX and INT_MIN
#endif | [
"614984958@qq.com"
] | 614984958@qq.com |
9a494a6c74e2f9add9a0a0083ca6fe5e9785a4ab | 5633c81bd22fa81d84a7dc2424ed04580250b7bb | /php-5.2.2/s60ext/s60_log/CLogImpl.h | ce93c874772a2911bc23ffd75d0c28d6386801dc | [] | no_license | tuankien2601/PAMP | bc104d5ec8411b570429e4f9b9bff299a75f86bd | 320b286d28c96356ef88b086a71c740b2ec91b44 | refs/heads/master | 2021-06-20T19:49:18.206942 | 2017-08-14T08:47:56 | 2017-08-14T08:47:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 774 | h | #ifndef __CLOGIMPL_H__
#define __CLOGIMPL_H__
#include <e32base.h> // CActive
#include <F32FILE.H>
#include <LOGVIEW.H>
#include <logcli.h>
#include "s60ext_tools.h"
class CWaitAndReturn : public CActive
{
public:
CWaitAndReturn();
~CWaitAndReturn();
TInt Wait();
private:
void RunL();
void DoCancel();
private:
CActiveSchedulerWait* iWait;
};
class CLogImpl : public CRefcounted
{
public:
static CLogImpl* NewL();
~CLogImpl();
const CLogEvent& FirstEntryL();
const CLogEvent& NextEntryL();
const CLogEvent& LastEntryL();
const CLogEvent& PrevEntryL();
void SetFilterL();
private:
CLogImpl();
void ConstructL();
private:
CLogClient* iLogClient;
CLogViewEvent* iLogView;
CLogFilter* iLogFilter;
RFs iFsSession;
};
#endif
| [
"lizhenfan902@gmail.com"
] | lizhenfan902@gmail.com |
01fb37a2a4adbe33e2a5f655d559f7cbd90bf349 | 5f6cef5c4dab7661b4ec6c9de53395ba425e0925 | /08_jumpFloor.cpp | f42da3f75ec0ab5c3cf0db3403faa4ead3b2f60d | [] | no_license | htyxiaoaiai/Offer | 89da97e6feea99fe5e2dabbe5768ac2cb1a978fa | a7ba10cd9f180256138db6afc633ebb8d8c85352 | refs/heads/master | 2021-01-17T12:48:44.148425 | 2016-07-21T15:48:30 | 2016-07-21T15:48:30 | 58,129,881 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 991 | cpp | 题目描述
一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法。
解法分析:
最简单的情况:
如果只有1级台阶,那么显然只有一种跳法。如果有2级台阶,那么则会有2种跳法:一种是分两次跳,每次跳1阶;另外一种则是一次跳2级。
一般情况:
当n大于2时,第一次跳的时候有两种选择:一种是第一次只跳1阶,此时的跳法就是f(n-1),另外一种跳法就是第一次跳2阶,然后此时的跳法就是f(n-2)。
所以总的次数就是f(n)=f(n-1)+f(n-2);很明显此时是一个斐波那契数列。
//跳台阶
long long jumpFloor(size_t number) {
size_t jump[2] = { 0,1 };
if (number < 2)
{
return jump[number];
}
long long jumpOne = 1;
long long jumpTwo = 1;
long long jumpN = 0;
for (size_t i = 2; i <= number; i++)
{
jumpN = jumpOne + jumpTwo;
jumpOne = jumpTwo;
jumpTwo = jumpN;
}
return jumpN;
}
| [
"htyxiaoaiai1314@gmail.com"
] | htyxiaoaiai1314@gmail.com |
76825cf2bd742ffb91ced0ecd0ae9ab91befacaa | 0058e203911ee4920b6962f4679e9b40461cffdb | /unique-datesize.cpp | 605ce39fa2dbc0302a6bfbd1c70dd3994fa3eb25 | [] | no_license | FeelUsM/scripts | 81f17eac43aa224c225a11b4b4d57416a64ea515 | 90867b733c94626f2203882dc90453bfbb793012 | refs/heads/master | 2023-08-09T23:13:08.741189 | 2023-07-31T08:04:54 | 2023-07-31T08:04:54 | 38,750,956 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,574 | cpp | #define ONE_SOURCE
#include <strstr/strin.h>
#include <iostream>
//#include <utime.h>
#include <map>
#include <string>
#include <stdlib.h>
#include <algorithm>
using std::string;
using std::pair;
using std::make_pair;
using std::multimap;
using std::cerr;
using std::cout;
using std::endl;
using std::sort;
using str::strin;
using str::read_start_line;
using str::dec;
using str::until_charclass;
using str::spn_crlf;
using str::linecol;
//удаляет все, что не повторяется
template<class cont_t, typename comp_t>
void antiuniq(cont_t * pset, const comp_t & comp)
{
typedef typename cont_t::iterator it_t;
if(pset->begin()==pset->end())
return;
it_t l,r;
l=r=pset->begin();
r++;
bool fl=false;//в первой итерации первый и (не существующий) минус первый элементы НЕ равны
while(r!=pset->end()){
if(comp(*l,*r))//если равны
fl=true;//в будущем - были равны
else{//если не равны
if(!fl){//и не были равны
pset->erase(l);//удаляем того, кто не равен ни левому ни правому
}
fl=false;//в будущем они не были равны
}
l=r;
r++;
}
if(!fl)//если последний и предпоследний(может не существовать) элементы не равны
pset->erase(l);
}
template<class cont_t>
void antiuniq(cont_t * pset){
antiuniq(pset, [](const typename cont_t::value_type & l, const typename cont_t::value_type & r){return l==r;});
}
int main(){
multimap<pair<long long,long long>,string> data;
read_start_line(strin);
while(!atend(strin)){
string path;
long long size, date;
#define ifnot(expr) if(!(expr))
ifnot(read(strin)>>dec(&size)>>'\t'>>dec(&date)
>>'\t'>>until_charclass(spn_crlf,&path)){
cerr<<"на позиции "<<linecol(strin)<<" произошла ошибка"<<endl;
exit(2);
}
data.insert(make_pair(make_pair(size,date),move(path)));
read_start_line(strin);
}
antiuniq(&data,
[](const pair<pair<long long,long long>,string> & l, const pair<pair<long long,long long>,string> & r){
return l.first.first==r.first.first && l.first.second==r.first.second;//size, date
}
);
auto oldit = data.end();
for(auto it = data.begin(); it!=data.end(); it++){
if(oldit!=data.end() && (oldit->first.first!=it->first.first || oldit->first.second!=it->first.second))
cout<<endl;
cout<<it->first.first<<'\t'<<it->first.second<<'\t'<<it->second<<endl;
oldit=it;
}
} | [
"fel1992@mail.ru"
] | fel1992@mail.ru |
7ce68329727ca3ba2995a1181c3a715f6438b4cb | ad8b3fd13cab0bde6ccde44db19607195d07828f | /server1.5_内存池/MessageHeader.hpp | cb3676d706bf86fde8c33c98c8f4a715f1b21f7c | [] | no_license | QaoKi/server | 43bc56e2462804a598a89eaeb0fcec3c4b1e8b32 | 0d745c7b7017bfb3bfbf63839c1d61f1d4b87981 | refs/heads/master | 2020-05-01T15:31:08.970524 | 2019-07-26T03:43:10 | 2019-07-26T03:43:10 | 177,548,642 | 1 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,259 | hpp | #ifndef _MessageHeader_hpp_
#define _MessageHeader_hpp_
/*
定义消息结构
*/
enum CMD
{
CMD_LOGIN = 0,
CMD_LOGIN_RESULT,
CMD_LOGOUT,
CMD_LOGOUT_RESULT,
CMD_EXIT,
CMD_NEW_USER_JOIN,
CMD_ERROR
};
struct DataHeader
{
DataHeader()
{
dataLength = sizeof(DataHeader);
cmd = CMD_ERROR;
}
short dataLength;
short cmd;
};
struct Login :public DataHeader
{
Login()
{
dataLength = sizeof(Login);
cmd = CMD_LOGIN;
}
char userName[32];
char PassWord[32];
char data[32];
};
struct LoginResult : public DataHeader
{
LoginResult()
{
dataLength = sizeof(LoginResult);
cmd = CMD_LOGIN_RESULT;
result = 0;
}
int result;
char data[92];
};
struct Logout : public DataHeader
{
Logout()
{
dataLength = sizeof(Logout);
cmd = CMD_LOGOUT;
}
char userName[32];
};
struct LogoutResult : public DataHeader
{
LogoutResult()
{
dataLength = sizeof(LogoutResult);
cmd = CMD_LOGOUT_RESULT;
result = 0;
}
int result;
};
struct ExitConnect : public DataHeader
{
ExitConnect()
{
dataLength = sizeof(ExitConnect);
cmd = CMD_EXIT;
result = 0;
}
int result;
};
struct NewUserJoin : public DataHeader
{
NewUserJoin()
{
dataLength = sizeof(NewUserJoin);
cmd = CMD_NEW_USER_JOIN;
scok = 0;
}
int scok;
};
#endif | [
"10330180@qq.com"
] | 10330180@qq.com |
80d4d416a5c7bb2e110441b825b961b878f6622e | 0c619682d82e155047ff1c9adcdecf5e9c4cc17a | /20200209/D/D.cpp | f890e94a51a398e7561d60aa4bf939f73decedf6 | [] | no_license | kasataku777/atcoder_solution | 822a6638ec78079c35877fadc78f6fad24dd5252 | 8838eb10bf844ac3209f527d7b5ac213902352ec | refs/heads/master | 2023-01-23T06:36:59.810060 | 2020-12-03T02:02:40 | 2020-12-03T02:02:40 | 247,486,743 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 489 | cpp | #include<iostream>
using namespace std;
int main() {
int n, k;
int p[200000];
double sum=0;
double max = 0;
double kitai[200000];
cin >> n >> k;
for (int i = 0; i < n; i++) {
cin >> p[i];
}
for (int i = 0; i < n; i++) {
kitai[i] = 1 + 0.50*(p[i] - 1);
}
for (int i = 0; i < k; i++) {
sum += kitai[i];
}
max = sum;
for (int i = k; i < n ; i++) {
sum = sum+kitai[i] - kitai[i - k];
if (sum > max) max = sum;
}
cout << max << endl;
return 0;
} | [
"takumi.jihen@gmail.com"
] | takumi.jihen@gmail.com |
c8b4a1d8bdfdc9f33cd5c4f56db93882a401a14b | 35635422101e1c0e4142ca1e176c5d976a6a6ff2 | /deps/glm.9.9.5/glm_inn/detail/type_mat4x3.hpp | 451c0341d7030e4cb5149ed4371b043b2acb9f19 | [
"BSD-3-Clause"
] | permissive | wanghaoxin1991/tprPix | e9ac6078dcf104b89e7db8bc6e973b47d4a46bfc | 877d2f3bcd2028b28f575deebf37bf7d19d1da52 | refs/heads/master | 2021-05-25T17:27:13.564129 | 2020-04-08T22:08:00 | 2020-04-08T22:08:00 | 253,843,248 | 0 | 0 | null | 2020-04-07T15:58:08 | 2020-04-07T15:58:08 | null | UTF-8 | C++ | false | false | 11,692 | hpp | <<<<<<< HEAD
/// @ref core
/// @file glm/detail/type_mat4x3.hpp
#pragma once
#include "type_vec3.hpp"
#include "type_vec4.hpp"
#include <limits>
#include <cstddef>
namespace glm
{
template<typename T, qualifier Q>
struct mat<4, 3, T, Q>
{
typedef vec<3, T, Q> col_type;
typedef vec<4, T, Q> row_type;
typedef mat<4, 3, T, Q> type;
typedef mat<3, 4, T, Q> transpose_type;
typedef T value_type;
private:
col_type value[4];
public:
// -- Accesses --
typedef length_t length_type;
GLM_FUNC_DECL static GLM_CONSTEXPR length_type length() { return 4; }
GLM_FUNC_DECL col_type & operator[](length_type i);
GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const;
// -- Constructors --
GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT;
template<qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 3, T, P> const& m);
GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
T const& x0, T const& y0, T const& z0,
T const& x1, T const& y1, T const& z1,
T const& x2, T const& y2, T const& z2,
T const& x3, T const& y3, T const& z3);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
col_type const& v0,
col_type const& v1,
col_type const& v2,
col_type const& v3);
// -- Conversions --
template<
typename X1, typename Y1, typename Z1,
typename X2, typename Y2, typename Z2,
typename X3, typename Y3, typename Z3,
typename X4, typename Y4, typename Z4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
X1 const& x1, Y1 const& y1, Z1 const& z1,
X2 const& x2, Y2 const& y2, Z2 const& z2,
X3 const& x3, Y3 const& y3, Z3 const& z3,
X4 const& x4, Y4 const& y4, Z4 const& z4);
template<typename V1, typename V2, typename V3, typename V4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
vec<3, V1, Q> const& v1,
vec<3, V2, Q> const& v2,
vec<3, V3, Q> const& v3,
vec<3, V4, Q> const& v4);
// -- Matrix conversions --
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, U, P> const& m);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x);
// -- Unary arithmetic operators --
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator*=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator/=(U s);
// -- Increment and decrement operators --
GLM_FUNC_DECL mat<4, 3, T, Q>& operator++();
GLM_FUNC_DECL mat<4, 3, T, Q>& operator--();
GLM_FUNC_DECL mat<4, 3, T, Q> operator++(int);
GLM_FUNC_DECL mat<4, 3, T, Q> operator--(int);
};
// -- Unary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m);
// -- Binary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(T const& s, mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 3, T, Q>::col_type operator*(mat<4, 3, T, Q> const& m, typename mat<4, 3, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 3, T, Q>::row_type operator*(typename mat<4, 3, T, Q>::col_type const& v, mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<2, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<2, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<3, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<3, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator/(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator/(T const& s, mat<4, 3, T, Q> const& m);
// -- Boolean operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator==(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator!=(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_mat4x3.inl"
#endif //GLM_EXTERNAL_TEMPLATE
=======
/// @ref core
/// @file glm/detail/type_mat4x3.hpp
#pragma once
#include "type_vec3.hpp"
#include "type_vec4.hpp"
#include <limits>
#include <cstddef>
namespace glm
{
template<typename T, qualifier Q>
struct mat<4, 3, T, Q>
{
typedef vec<3, T, Q> col_type;
typedef vec<4, T, Q> row_type;
typedef mat<4, 3, T, Q> type;
typedef mat<3, 4, T, Q> transpose_type;
typedef T value_type;
private:
col_type value[4];
public:
// -- Accesses --
typedef length_t length_type;
GLM_FUNC_DECL static GLM_CONSTEXPR length_type length() { return 4; }
GLM_FUNC_DECL col_type & operator[](length_type i);
GLM_FUNC_DECL GLM_CONSTEXPR col_type const& operator[](length_type i) const;
// -- Constructors --
GLM_FUNC_DECL GLM_CONSTEXPR mat() GLM_DEFAULT;
template<qualifier P>
GLM_FUNC_DECL GLM_CONSTEXPR mat(mat<4, 3, T, P> const& m);
GLM_FUNC_DECL explicit GLM_CONSTEXPR mat(T const& x);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
T const& x0, T const& y0, T const& z0,
T const& x1, T const& y1, T const& z1,
T const& x2, T const& y2, T const& z2,
T const& x3, T const& y3, T const& z3);
GLM_FUNC_DECL GLM_CONSTEXPR mat(
col_type const& v0,
col_type const& v1,
col_type const& v2,
col_type const& v3);
// -- Conversions --
template<
typename X1, typename Y1, typename Z1,
typename X2, typename Y2, typename Z2,
typename X3, typename Y3, typename Z3,
typename X4, typename Y4, typename Z4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
X1 const& x1, Y1 const& y1, Z1 const& z1,
X2 const& x2, Y2 const& y2, Z2 const& z2,
X3 const& x3, Y3 const& y3, Z3 const& z3,
X4 const& x4, Y4 const& y4, Z4 const& z4);
template<typename V1, typename V2, typename V3, typename V4>
GLM_FUNC_DECL GLM_CONSTEXPR mat(
vec<3, V1, Q> const& v1,
vec<3, V2, Q> const& v2,
vec<3, V3, Q> const& v3,
vec<3, V4, Q> const& v4);
// -- Matrix conversions --
template<typename U, qualifier P>
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 3, U, P> const& m);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 3, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<2, 4, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<4, 2, T, Q> const& x);
GLM_FUNC_DECL GLM_EXPLICIT GLM_CONSTEXPR mat(mat<3, 4, T, Q> const& x);
// -- Unary arithmetic operators --
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator+=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator-=(mat<4, 3, U, Q> const& m);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator*=(U s);
template<typename U>
GLM_FUNC_DECL mat<4, 3, T, Q> & operator/=(U s);
// -- Increment and decrement operators --
GLM_FUNC_DECL mat<4, 3, T, Q>& operator++();
GLM_FUNC_DECL mat<4, 3, T, Q>& operator--();
GLM_FUNC_DECL mat<4, 3, T, Q> operator++(int);
GLM_FUNC_DECL mat<4, 3, T, Q> operator--(int);
};
// -- Unary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m);
// -- Binary operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator+(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator-(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(T const& s, mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 3, T, Q>::col_type operator*(mat<4, 3, T, Q> const& m, typename mat<4, 3, T, Q>::row_type const& v);
template<typename T, qualifier Q>
GLM_FUNC_DECL typename mat<4, 3, T, Q>::row_type operator*(typename mat<4, 3, T, Q>::col_type const& v, mat<4, 3, T, Q> const& m);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<2, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<2, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<3, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<3, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator*(mat<4, 3, T, Q> const& m1, mat<4, 4, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator/(mat<4, 3, T, Q> const& m, T const& s);
template<typename T, qualifier Q>
GLM_FUNC_DECL mat<4, 3, T, Q> operator/(T const& s, mat<4, 3, T, Q> const& m);
// -- Boolean operators --
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator==(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
template<typename T, qualifier Q>
GLM_FUNC_DECL bool operator!=(mat<4, 3, T, Q> const& m1, mat<4, 3, T, Q> const& m2);
}//namespace glm
#ifndef GLM_EXTERNAL_TEMPLATE
#include "type_mat4x3.inl"
#endif //GLM_EXTERNAL_TEMPLATE
>>>>>>> f8aea6f7d63dae77b8d83ba771701e3561278dc4
| [
"wanghaoxin8@163.com"
] | wanghaoxin8@163.com |
8d7d31f152cf7c0b4fbce6e353c988728bb03ef6 | 93f20091d507fa59ee2492e03a5e950341cc2662 | /BOJ/BOJ/17140 이차원 배열과 연산.cpp | 46efd2ac304cb4c9246b0b7d2f775dd961e942fb | [] | no_license | Wonjyeon/BOJ | f90ab0881fa25cb6b0893902143d3a6477cc4307 | 56554d4c964dc3c4d749de86a3ddc40d9dda58fc | refs/heads/master | 2021-03-04T18:20:18.499160 | 2020-11-01T12:12:32 | 2020-11-01T12:12:32 | 246,055,134 | 0 | 0 | null | null | null | null | UHC | C++ | false | false | 2,321 | cpp | #include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int r, c, k, map[101][101];
int N = 3, M = 3, ans = 0, max_row = 0, max_col = 0;
bool cmp(pair<int, int> p1, pair<int, int> p2) {
if (p1.second < p2.second) return true;
else if (p1.second == p2.second) {
if (p1.first < p2.first) return true;
}
return false;
}
int col_solve() {
for (int i = 1; i <= N; i++) {
vector<pair<int, int>> v;
int maxNum = 0;
int IDX[101] = { 0, };
for (int j = 1; j <= M; j++) {
int num = map[i][j];
if (num == 0) continue;
IDX[num]++;
if (maxNum < num) maxNum = num;
}
for (int k = 1; k <= maxNum; k++) {
if (IDX[k] > 0) {
v.push_back({ k, IDX[k] });
}
}
sort(v.begin(), v.end(), cmp);
int index = 1;
for (int k = 0; k < v.size(); k++) {
map[i][index++] = v[k].first;
map[i][index++] = v[k].second;
if (index == 101) break;
}
if (max_row < v.size() * 2)
max_row = v.size() * 2;
for (int k = v.size() * 2 + 1; k <= max_row; k++) {
map[i][k] = 0;
}
if (map[r][c] == k) return true;
}
return false;
}
int row_solve() {
for (int i = 1; i <= M; i++) {
vector<pair<int, int>> v;
int maxNum = 0;
int IDX[101] = { 0, };
for (int j = 1; j <= N; j++) {
int num = map[j][i];
if (num == 0) continue;
IDX[num]++;
if (maxNum < num) maxNum = num;
}
for (int k = 1; k <= maxNum; k++) {
if (IDX[k] > 0) {
v.push_back({ k, IDX[k] });
}
}
sort(v.begin(), v.end(), cmp);
int index = 1;
for (int k = 0; k < v.size(); k++) {
map[index++][i] = v[k].first;
map[index++][i] = v[k].second;
if (index == 101) break;
}
if (max_col < v.size() * 2)
max_col = v.size() * 2;
for (int k = v.size() * 2 + 1; k <= max_col; k++) {
map[k][i] = 0;
}
if (map[r][c] == k) return true;
}
return false;
}
int main() {
ios::sync_with_stdio(0); cin.tie(0);
cin >> r >> c >> k;
for (int i = 1; i <= 3; i++)
for (int j = 1; j <= 3; j++)
cin >> map[i][j];
if (map[r][c] == k) {
cout << "0\n";
return 0;
}
while ((N < 101 || M < 101) && ans <= 100) {
// 행 정렬
if (N >= M) {
ans++;
if (col_solve()) break;
M = max_row;
}
// 열 정렬
else {
ans++;
if (row_solve()) break;
N = max_col;
}
}
if (ans > 100) cout << "-1\n";
else cout << ans << '\n';
return 0;
} | [
"wndus9382@naver.com"
] | wndus9382@naver.com |
4dc60b4f8ee843237ffa6a0d1bebcabd694530a4 | 6b96c03193a050b18a5b5c433b0791a602702a31 | /tensorflow/core/util/debug_data_dumper.cc | a4599bb7c7e003bb364e26ff5c08141ee13c2c07 | [
"Apache-2.0",
"LicenseRef-scancode-generic-cla",
"BSD-2-Clause"
] | permissive | engelmi/tensorflow | c7d3a6114fa5a88c715ca242302f94fb24410364 | 9bc55d66eca16143e16e824eeef7de23c7bb9623 | refs/heads/master | 2023-04-21T19:12:34.491700 | 2023-04-10T10:25:01 | 2023-04-10T10:28:02 | 111,595,000 | 0 | 0 | null | 2017-11-21T19:57:15 | 2017-11-21T19:57:14 | null | UTF-8 | C++ | false | false | 5,332 | cc | /* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/core/util/debug_data_dumper.h"
#include "absl/strings/str_format.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/path.h"
#include "tensorflow/core/util/dump_graph.h"
namespace tensorflow {
DebugDataDumper* DebugDataDumper::Global() {
static DebugDataDumper* global_instance_ = new DebugDataDumper();
return global_instance_;
}
bool DebugDataDumper::ShouldDump(const std::string& name) const {
// Do not dump data for the wrapped functions.
if (absl::StartsWith(name, "__wrapped__")) return false;
// Get the name filter from TF_DUMP_GRAPH_NAME_FILTER.
const char* name_filter = getenv("TF_DUMP_GRAPH_NAME_FILTER");
if (name_filter == nullptr) {
VLOG(1) << "Skip dumping graph '" << name
<< "', because TF_DUMP_GRAPH_NAME_FILTER is not set";
return false;
}
// If name_filter is not '*' or name doesn't contain the name_filter,
// skip the dump.
std::string str_name_filter = std::string(name_filter);
if (str_name_filter != "*" &&
name.find(str_name_filter) == std::string::npos) {
VLOG(1) << "Skip dumping graph '" << name
<< "', because TF_DUMP_GRAPH_NAME_FILTER is not '*' and "
<< "it is not contained by the graph name";
return false;
}
// If all conditions are met, return true to allow the dump.
return true;
}
void DebugDataDumper::DumpOpCreationStackTraces(const std::string& name,
const std::string& tag,
const Graph* graph) {
const char* dump_stacktraces = getenv("TF_DUMP_OP_CREATION_STACKTRACES");
if (dump_stacktraces == nullptr) {
VLOG(1) << "Skip dumping op creation stacktraces for '" << name
<< "', because TF_DUMP_OP_CREATION_STACKTRACES is not set";
return;
}
// Construct the dump filename.
std::string dump_filename = GetDumpFilename(name, tag);
// Dump module txt to file.
DumpToFile(dump_filename, "", ".csv", "StackTrace",
[&graph, &dump_filename](WritableFile* file) {
auto status = file->Append("node_id,node_name,stackframes\n");
if (!status.ok()) {
LOG(WARNING) << "error writing to file to " << dump_filename
<< ": " << status.error_message();
return status;
}
for (Node* node : graph->nodes()) {
auto stack_trace = node->GetStackTrace();
if (stack_trace == nullptr) continue;
int node_id = node->id();
std::string node_name = node->name();
std::vector<std::string> stackframes;
for (auto& frame : stack_trace->ToFrames()) {
stackframes.push_back(
absl::StrFormat("%s(%d): %s", frame.file_name,
frame.line_number, frame.function_name));
}
status = file->Append(
absl::StrFormat("%d,%s,%s\n", node_id, node_name,
absl::StrJoin(stackframes, ";")));
if (!status.ok()) {
LOG(WARNING) << "error writing to file to " << dump_filename
<< ": " << status.error_message();
return status;
}
}
return file->Close();
});
}
void DebugDataDumper::DumpGraph(const std::string& name, const std::string& tag,
const Graph* graph,
const FunctionLibraryDefinition* func_lib_def) {
// Construct the dump filename.
std::string dump_filename = GetDumpFilename(name, tag);
// Make sure the dump filename is not longer than 255,
// because Linux won't take filename that long.
if (dump_filename.size() > 255) {
LOG(WARNING) << "Failed to dump graph " << dump_filename << " to "
<< ", because the file name is longer than 255";
return;
}
// Construct a graph def.
GraphDef graph_def;
graph->ToGraphDef(&graph_def);
if (func_lib_def) *graph_def.mutable_library() = func_lib_def->ToProto();
// Now dump the graph into the target file.
DumpGraphDefToFile(dump_filename, graph_def);
}
std::string DebugDataDumper::GetDumpFilename(const std::string& name,
const std::string& tag) {
std::string dump_name = name.empty() ? "unknown_graph" : name;
return absl::StrFormat("%s.%04d.%s", dump_name, GetNextDumpId(name), tag);
}
} // namespace tensorflow
| [
"gardener@tensorflow.org"
] | gardener@tensorflow.org |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.