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 986
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 3.89k
681M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 23
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 145
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 122
values | content
stringlengths 3
10.4M
| authors
listlengths 1
1
| author_id
stringlengths 0
158
|
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
8aa4b42a0f95e473b03ad222c03449c1897a7893
|
1f2737e41a6d72dff53a5e7949d1da9a1011cb99
|
/angelscript_2.28.0/angelscript/source/as_scriptobject.h
|
afe72cc8b8754b72170000a97b4c4a11ea714eea
|
[] |
no_license
|
leadcoder/gass-dependencies
|
bd58c3c7502562b41a8ebb868e841491bba7925e
|
7c0895f54a22313071a8b556a664f2e0f995b4de
|
refs/heads/master
| 2021-01-23T18:48:29.500615
| 2019-04-23T20:59:48
| 2019-04-23T20:59:48
| 40,589,311
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,287
|
h
|
/*
AngelCode Scripting Library
Copyright (c) 2003-2013 Andreas Jonsson
This software is provided 'as-is', without any express or implied
warranty. In no event will the authors be held liable for any
damages arising from the use of this software.
Permission is granted to anyone to use this software for any
purpose, including commercial applications, and to alter it and
redistribute it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you
must not claim that you wrote the original software. If you use
this software in a product, an acknowledgment in the product
documentation would be appreciated but is not required.
2. Altered source versions must be plainly marked as such, and
must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source
distribution.
The original version of this library can be located at:
http://www.angelcode.com/angelscript/
Andreas Jonsson
andreas@angelcode.com
*/
//
// as_scriptobject.h
//
// A generic class for handling script declared structures
//
#ifndef AS_SCRIPTOBJECT_H
#define AS_SCRIPTOBJECT_H
#include "as_config.h"
#include "as_atomic.h"
BEGIN_AS_NAMESPACE
class asCObjectType;
// TODO: Add const overload for GetAddressOfProperty
// TODO: weak: Should move to its own file
class asCLockableSharedBool : public asILockableSharedBool
{
public:
asCLockableSharedBool();
int AddRef() const;
int Release() const;
bool Get() const;
void Set(bool);
void Lock() const;
void Unlock() const;
protected:
mutable asCAtomic refCount;
bool value;
DECLARECRITICALSECTION(mutable lock);
};
class asCScriptObject : public asIScriptObject
{
public:
//===================================
// From asIScriptObject
//===================================
asIScriptEngine *GetEngine() const;
// Memory management
int AddRef() const;
int Release() const;
// Type info
int GetTypeId() const;
asIObjectType *GetObjectType() const;
// Class properties
asUINT GetPropertyCount() const;
int GetPropertyTypeId(asUINT prop) const;
const char *GetPropertyName(asUINT prop) const;
void *GetAddressOfProperty(asUINT prop);
int CopyFrom(asIScriptObject *other);
//====================================
// Internal
//====================================
asCScriptObject(asCObjectType *objType, bool doInitialize = true);
virtual ~asCScriptObject();
asCScriptObject &operator=(const asCScriptObject &other);
// GC methods
void Destruct();
int GetRefCount();
void SetFlag();
bool GetFlag();
void EnumReferences(asIScriptEngine *engine);
void ReleaseAllHandles(asIScriptEngine *engine);
// Weakref methods
asILockableSharedBool *GetWeakRefFlag() const;
// Used for properties
void *AllocateUninitializedObject(asCObjectType *objType, asCScriptEngine *engine);
void FreeObject(void *ptr, asCObjectType *objType, asCScriptEngine *engine);
void CopyObject(void *src, void *dst, asCObjectType *objType, asCScriptEngine *engine);
void CopyHandle(asPWORD *src, asPWORD *dst, asCObjectType *objType, asCScriptEngine *engine);
void CallDestructor();
//=============================================
// Properties
//=============================================
public:
asCObjectType *objType;
protected:
mutable asCAtomic refCount;
mutable asBYTE gcFlag:1;
mutable asBYTE hasRefCountReachedZero:1;
bool isDestructCalled;
mutable asCLockableSharedBool *weakRefFlag;
};
void ScriptObject_Construct(asCObjectType *objType, asCScriptObject *self);
asCScriptObject &ScriptObject_Assignment(asCScriptObject *other, asCScriptObject *self);
void ScriptObject_ConstructUnitialized(asCObjectType *objType, asCScriptObject *self);
void ScriptObject_Construct_Generic(asIScriptGeneric *gen);
void ScriptObject_Assignment_Generic(asIScriptGeneric *gen);
void RegisterScriptObject(asCScriptEngine *engine);
asIScriptObject *ScriptObjectFactory(const asCObjectType *objType, asCScriptEngine *engine);
END_AS_NAMESPACE
#endif
|
[
"leadcoder@03e3fbca-29a6-eb1c-c96b-1d8cf88ad296"
] |
leadcoder@03e3fbca-29a6-eb1c-c96b-1d8cf88ad296
|
abfe60b9d62c7fa4d5233174dd9aa0ce3f62eb35
|
49536aafb22a77a6caf249c7fadef46d63d24dfe
|
/tensorflow/tensorflow/core/grappler/optimizers/constant_folding.h
|
91a3f277b87741c0db888f64937a43d2027ec653
|
[
"Apache-2.0"
] |
permissive
|
wangzhi01/deeplearning-1
|
4e5ad93f0d9ecd302b74352f80fe1fa6ae70bf0d
|
46ab82253d956953b8aa98e97ceb6cd290e82288
|
refs/heads/master
| 2020-05-28T03:14:55.687567
| 2018-09-12T16:52:09
| 2018-09-12T16:52:09
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,419
|
h
|
/* Copyright 2017 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.
==============================================================================*/
#ifndef TENSORFLOW_GRAPPLER_OPTIMIZERS_CONSTANT_FOLDING_H_
#define TENSORFLOW_GRAPPLER_OPTIMIZERS_CONSTANT_FOLDING_H_
#include "tensorflow/core/framework/device_base.h"
#include "tensorflow/core/framework/op_kernel.h"
#include "tensorflow/core/framework/resource_mgr.h"
#include "tensorflow/core/grappler/costs/graph_properties.h"
#include "tensorflow/core/grappler/optimizers/graph_optimizer.h"
#include "tensorflow/core/grappler/utils.h"
namespace tensorflow {
namespace grappler {
const char kConstantFoldingConst[] = "ConstantFolding";
const char kConstantFoldingCtrl[] = "ConstantFoldingCtrl";
// Constant folding optimization for a graph.
class ConstantFolding : public GraphOptimizer {
public:
ConstantFolding(DeviceBase* cpu_device);
~ConstantFolding() override {}
string name() const override { return "constant folding"; };
Status Optimize(Cluster* cluster, const GrapplerItem& item,
GraphDef* output) override;
void Feedback(Cluster* cluster, const GrapplerItem& item,
const GraphDef& optimize_output, double result) override;
private:
string AddControlDependency(const string& input_name);
Status MaterializeShapes(const GrapplerItem& item,
const GraphProperties& properties);
bool IsFoldable(const NodeDef& node) const;
NodeDef CreateNodeDef(const string& name, const TensorValue& tensor);
Status EvaluateNode(const NodeDef& node,
const gtl::InlinedVector<TensorValue, 4>& inputs,
gtl::InlinedVector<TensorValue, 4>* output) const;
Status EvaluateOneFoldable(const NodeDef& node,
std::vector<NodeDef>* outputs);
Status FoldNode(NodeDef* node, GraphDef* output_graph);
Status FoldGraph(GraphDef* output);
bool IsSimplifiableReduction(const NodeDef& node) const;
bool IsSimplifiableReshape(const NodeDef& node,
const GraphProperties& properties) const;
Status SimplifyGraph(GraphDef* output, const GraphProperties& properties);
Status RunOptimizationPass(Cluster* cluster, const GrapplerItem& item,
GraphDef* output);
// Points to an externally provided device or to owned_device_;
DeviceBase* cpu_device_;
std::unique_ptr<DeviceBase> owned_device_;
std::unique_ptr<ResourceMgr> resource_mgr_;
GraphDef graph_;
std::unique_ptr<NodeMap> node_map_;
std::unordered_set<string> nodes_to_preserve_;
std::unordered_set<string> nodes_whitelist_;
bool has_fetch_;
};
} // end namespace grappler
} // end namespace tensorflow
#endif // TENSORFLOW_GRAPPLER_OPTIMIZERS_CONSTANT_FOLDING_H_
|
[
"hanshuobest@163.com"
] |
hanshuobest@163.com
|
c98421d3300af40fc197dfb9ba0efd5619450650
|
9f34e12675a3d3f4bdadda2ea6e4bd7e43cbad0c
|
/leet_lint_code/lint_code/fibonacci.cpp
|
9147a7c6a18b50607b3aeeb5e4c1e2626ce8abe4
|
[] |
no_license
|
hailingu/leet_lint_code
|
125bc403123c0f2ebef76f9a5667886c6a4bdd44
|
ff45eaa40ade4184f14c59a46db10d648c421de4
|
refs/heads/master
| 2021-06-02T01:44:19.621561
| 2020-04-24T02:14:49
| 2020-04-24T02:14:49
| 129,344,064
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 566
|
cpp
|
// Copyright © 2018 Hailin Gu. All rights reserved.
// License(GPL)
// Author: Hailin Gu
// This is a answer of lint code problem 366.
#ifndef LEETLINTCODE_LINTCODE_FIBONACCI_CPP
#define LEETLINTCODE_LINTCODE_FIBONACCI_CPP
#include <vector>
class Fibonacci {
public:
int fibonacci(int n) {
if (1 == n) return 0;
if (2 == n) return 1;
std::vector<int> v;
v.push_back(0);
v.push_back(1);
int i = 1, j = 0;
while(i < n) v.push_back(v[i++] + v[j++]);
return v[n-1];
}
};
#endif // LEETLINTCODE_LINTCODE_FIBONACCI_CPP
|
[
"hailin.gu@hypers.com"
] |
hailin.gu@hypers.com
|
7d2130e161265aab9ef04461a96e45b6ef462cba
|
cefb732ca99b8bb2484c1a23443da5f4a07600fc
|
/funciones.hpp
|
98afa2805b438e0c8a992a040961f2edb24c12b5
|
[] |
no_license
|
klavman/Error-polygonal-approximation-Cplusplus
|
a3d78834f74863675633f59d9f29d38948bb6298
|
82ff19f465c5a049ffe793b42b4f513d44872432
|
refs/heads/master
| 2021-05-29T13:44:07.334669
| 2015-03-03T11:46:10
| 2015-03-03T11:46:10
| 31,595,461
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 545
|
hpp
|
/*!
\file funciones.hpp
\brief Calcular el error cometido por la aproximación poligonal de un contorno
\author Francisco Javier Clavero Alvarez
\date 16-02-2015
*/
#include <vector>
#include "punto2D.hpp"
using namespace ed;
void cargaContorno(std::vector<Punto2D> &contorno, std::string ficheroContorno);
void cargaAproximacionPoligonal (std::vector<int> &aproximacionPoligonal, std::string ficheroAproximacionPoligonal);
double calcularError(const std::vector<Punto2D> &contorno, const std::vector<int> &aproximacionPoligonal);
|
[
"jc.klavman76@gmail.com"
] |
jc.klavman76@gmail.com
|
a2f3eb17eb8845ae0fe8047212ab49301d49a4c7
|
187f38b099a09bed572d8ff96785a27d30d11bdb
|
/applications/mne_scan/plugins/rtfwd/rtfwd.cpp
|
146645a6a13e08aeb3042e951056e1d9322f4459
|
[
"BSD-3-Clause"
] |
permissive
|
svdecomposer/mne-cpp
|
20f172438eafae1b13fa6626b90318af8ee51383
|
dad9a6da135a46cd4985d99881e6f6a569b66e5a
|
refs/heads/master
| 2021-07-11T00:59:19.541378
| 2020-08-14T14:34:25
| 2020-08-14T18:21:28
| 186,504,467
| 3
| 1
|
NOASSERTION
| 2020-01-14T14:26:43
| 2019-05-13T22:29:44
|
C++
|
UTF-8
|
C++
| false
| false
| 19,630
|
cpp
|
//=============================================================================================================
/**
* @file rtfwd.cpp
* @author Ruben Dörfel <ruben.doerfel@tu-ilmenau.de>
* @since 0.1.1
* @date May, 2020
*
* @section LICENSE
*
* Copyright (C) 2020, Ruben Dörfel. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
* * Redistributions of source code must retain the above copyright notice, this list of conditions and the
* following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
* the following disclaimer in the documentation and/or other materials provided with the distribution.
* * Neither the name of MNE-CPP authors nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief Definition of the RtFwd class.
*
*/
//=============================================================================================================
// INCLUDES
//=============================================================================================================
#include "rtfwd.h"
#include <disp/viewers/fwdsettingsview.h>
#include <fwd/computeFwd/compute_fwd.h>
#include <fwd/computeFwd/compute_fwd_settings.h>
#include <inverse/hpiFit/hpifit.h>
#include <fs/annotationset.h>
#include <mne/mne_forwardsolution.h>
#include <scMeas/realtimehpiresult.h>
#include <scMeas/realtimefwdsolution.h>
#include <scMeas/realtimemultisamplearray.h>
//=============================================================================================================
// QT INCLUDES
//=============================================================================================================
#include <QtCore/QtPlugin>
#include <QDebug>
//=============================================================================================================
// EIGEN INCLUDES
//=============================================================================================================
#include <Eigen/Core>
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================
using namespace RTFWDPLUGIN;
using namespace SCSHAREDLIB;
using namespace SCMEASLIB;
using namespace IOBUFFER;
using namespace FWDLIB;
using namespace FSLIB;
using namespace FIFFLIB;
using namespace INVERSELIB;
using namespace MNELIB;
using namespace DISPLIB;
using namespace Eigen;
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================
RtFwd::RtFwd()
: m_bBusy(false)
, m_bDoRecomputation(false)
, m_bDoClustering(false)
, m_bDoFwdComputation(false)
, m_pFwdSettings(new ComputeFwdSettings)
{
// set init values
m_pFwdSettings->solname = QCoreApplication::applicationDirPath() + "/MNE-sample-data/your-solution-fwd.fif";
m_pFwdSettings->mriname = QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/all-trans.fif";
m_pFwdSettings->bemname = QCoreApplication::applicationDirPath() + "/MNE-sample-data/subjects/sample/bem/sample-5120-5120-5120-bem.fif";
m_pFwdSettings->srcname = QCoreApplication::applicationDirPath() + "/MNE-sample-data/subjects/sample/bem/sample-oct-6-src.fif";
m_pFwdSettings->measname = QCoreApplication::applicationDirPath() + "/MNE-sample-data/MEG/sample/sample_audvis_raw.fif";
m_pFwdSettings->transname.clear();
m_pFwdSettings->eeg_model_name = "Default";
m_pFwdSettings->include_meg = true;
m_pFwdSettings->include_eeg = true;
m_pFwdSettings->accurate = true;
m_pFwdSettings->mindist = 5.0f/1000.0f;
m_sAtlasDir = QCoreApplication::applicationDirPath() + "/MNE-sample-data/subjects/sample/label";
}
//=============================================================================================================
RtFwd::~RtFwd()
{
m_future.waitForFinished();
if(this->isRunning()) {
stop();
}
}
//=============================================================================================================
QSharedPointer<IPlugin> RtFwd::clone() const
{
QSharedPointer<RtFwd> pRtFwdClone(new RtFwd);
return pRtFwdClone;
}
//=============================================================================================================
void RtFwd::init()
{
// Inits
m_pAnnotationSet = AnnotationSet::SPtr(new AnnotationSet(m_sAtlasDir+"/lh.aparc.a2009s.annot", m_sAtlasDir+"/rh.aparc.a2009s.annot"));
// Input
m_pHpiInput = PluginInputData<RealTimeHpiResult>::create(this, "rtFwd RTHR In", "rtFwd real time HPI result input data");
connect(m_pHpiInput.data(), &PluginInputConnector::notify,
this, &RtFwd::update, Qt::DirectConnection);
m_inputConnectors.append(m_pHpiInput);
m_pRTMSAInput = PluginInputData<RealTimeMultiSampleArray>::create(this, "rtFwd RTMSA In", "rtFwd real-time multi sample array input data");
connect(m_pRTMSAInput.data(), &PluginInputConnector::notify,
this, &RtFwd::update, Qt::DirectConnection);
m_inputConnectors.append(m_pRTMSAInput);
// Output
m_pRTFSOutput = PluginOutputData<RealTimeFwdSolution>::create(this, "rtFwdOut", "rtFwd real-time forward solution output data");
m_pRTFSOutput->data()->setName(this->getName());//Provide name to auto store widget settings
m_outputConnectors.append(m_pRTFSOutput);
}
//=============================================================================================================
void RtFwd::unload()
{
m_future.waitForFinished();
}
//=============================================================================================================
bool RtFwd::start()
{
// Maybe we can move all of this to the run() method?
// Read BEM
QFile t_fBem(m_pFwdSettings->bemname);
FiffStream::SPtr stream(new FiffStream(&t_fBem));
if(!stream->open()) {
QMessageBox msgBox;
msgBox.setText("The bem model cannot be opend. Chosse another file.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox.exec();
stream->close();
return false;
}
stream->close();
// Read source space
QFile t_fSource(m_pFwdSettings->srcname);
stream = FiffStream::SPtr(new FiffStream(&t_fSource));
if(!stream->open()) {
QMessageBox msgBox;
msgBox.setText("The source space cannot be opend. Chosse another file.");
msgBox.setText(m_pFwdSettings->srcname);
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox.exec();
stream->close();
return false;
}
stream->close();
// Read MRI transformation
QFile t_fMri(m_pFwdSettings->mriname);
stream = FiffStream::SPtr(new FiffStream(&t_fMri));
if(!stream->open()) {
QMessageBox msgBox;
msgBox.setText("The mri - head transformation cannot be opend. Chosse another file.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox.exec();
stream->close();
return false;
}
stream->close();
// Read measurement
QFile t_fMeas(m_pFwdSettings->measname);
stream = FiffStream::SPtr(new FiffStream(&t_fMri));
if(!stream->open()) {
QMessageBox msgBox;
msgBox.setText("The meaurement file cannot be opend. Chosse another file.");
msgBox.setStandardButtons(QMessageBox::Ok);
msgBox.setWindowFlags(Qt::WindowStaysOnTopHint);
msgBox.exec();
stream->close();
return false;
}
stream->close();
//Start thread
QThread::start();
return true;
}
//=============================================================================================================
bool RtFwd::stop()
{
requestInterruption();
wait(500);
m_bPluginControlWidgetsInit = false;
return true;
}
//=============================================================================================================
IPlugin::PluginType RtFwd::getType() const
{
return _IAlgorithm;
}
//=============================================================================================================
QString RtFwd::getName() const
{
return "Forward Solution";
}
//=============================================================================================================
QWidget* RtFwd::setupWidget()
{
RtFwdSetupWidget* setupWidget = new RtFwdSetupWidget(this);
return setupWidget;
}
//=============================================================================================================
void RtFwd::update(SCMEASLIB::Measurement::SPtr pMeasurement)
{
if(QSharedPointer<RealTimeMultiSampleArray> pRTMSA = pMeasurement.dynamicCast<RealTimeMultiSampleArray>()) {
//Fiff information
m_mutex.lock();
if(!m_pFiffInfo) {
m_pFiffInfo = pRTMSA->info();
}
m_mutex.unlock();
if(!m_bPluginControlWidgetsInit) {
initPluginControlWidgets();
}
} else if(QSharedPointer<RealTimeHpiResult> pRTHPI = pMeasurement.dynamicCast<RealTimeHpiResult>()) {
//Fiff information
m_mutex.lock();
if(!m_pFiffInfo) {
m_pFiffInfo = pRTHPI->getFiffInfo();
}
if(!m_bBusy) {
m_pHpiFitResult = pRTHPI->getValue();
}
m_mutex.unlock();
if(!m_bPluginControlWidgetsInit) {
initPluginControlWidgets();
}
}
}
//=============================================================================================================
void RtFwd::initPluginControlWidgets()
{
bool bFiffInfo = false;
m_mutex.lock();
if(m_pFiffInfo) {
bFiffInfo = true;
}
m_mutex.unlock();
if(bFiffInfo) {
QList<QWidget*> plControlWidgets;
FwdSettingsView* pFwdSettingsView = new FwdSettingsView(QString("MNESCAN/%1/").arg(this->getName()));
connect(this, &RtFwd::guiModeChanged,
pFwdSettingsView, &FwdSettingsView::setGuiMode);
pFwdSettingsView->setObjectName("widget_");
// connect incoming signals
connect(pFwdSettingsView, &FwdSettingsView::recompStatusChanged,
this, &RtFwd::onRecompStatusChanged);
connect(pFwdSettingsView, &FwdSettingsView::clusteringStatusChanged,
this, &RtFwd::onClusteringStatusChanged);
connect(pFwdSettingsView, &FwdSettingsView::atlasDirChanged,
this, &RtFwd::onAtlasDirChanged);
connect(pFwdSettingsView, &FwdSettingsView::doForwardComputation,
this, &RtFwd::onDoForwardComputation);
// connect outgoing signals
connect(this, &RtFwd::statusInformationChanged,
pFwdSettingsView, &FwdSettingsView::setRecomputationStatus, Qt::BlockingQueuedConnection);
connect(this, &RtFwd::fwdSolutionAvailable,
pFwdSettingsView, &FwdSettingsView::setSolutionInformation, Qt::BlockingQueuedConnection);
connect(this, &RtFwd::clusteringAvailable,
pFwdSettingsView, &FwdSettingsView::setClusteredInformation, Qt::BlockingQueuedConnection);
plControlWidgets.append(pFwdSettingsView);
emit pluginControlWidgetsChanged(plControlWidgets, this->getName());
m_bPluginControlWidgetsInit = true;
}
}
//=============================================================================================================
void RtFwd::onDoForwardComputation()
{
m_mutex.lock();
m_bDoFwdComputation = true;
m_mutex.unlock();
}
//=============================================================================================================
void RtFwd::onRecompStatusChanged(bool bDoRecomputation)
{
m_mutex.lock();
if(!m_pHpiInput) {
QMessageBox msgBox;
msgBox.setText("Please connect the Hpi plugin.");
msgBox.exec();
return;
}
m_bDoRecomputation = bDoRecomputation;
m_mutex.unlock();
}
//=============================================================================================================
void RtFwd::onClusteringStatusChanged(bool bDoClustering)
{
if(m_pAnnotationSet->isEmpty()) {
QMessageBox msgBox;
msgBox.setText("Please load an annotation set befor clustering.");
msgBox.exec();
return;
}
m_mutex.lock();
m_bDoClustering = bDoClustering;
m_mutex.unlock();
}
//=============================================================================================================
void RtFwd::onAtlasDirChanged(const QString& sDirPath, const AnnotationSet::SPtr pAnnotationSet)
{
m_mutex.lock();
m_sAtlasDir = sDirPath;
m_pAnnotationSet = pAnnotationSet;
m_mutex.unlock();
}
//=============================================================================================================
void RtFwd::run()
{
// Wait for fiff the info to arrive
while(true) {
m_mutex.lock();
if(m_pFiffInfo) {
m_mutex.unlock();
break;
}
m_mutex.unlock();
msleep(200);
}
m_mutex.lock();
m_pFwdSettings->pFiffInfo = m_pFiffInfo;
m_pRTFSOutput->data()->setFiffInfo(m_pFiffInfo);
FiffCoordTransOld transMegHeadOld = m_transDevHead.toOld();
m_mutex.unlock();
// initialize fwd solution
emit statusInformationChanged(0); // initializing
ComputeFwd::SPtr pComputeFwd = ComputeFwd::SPtr(new ComputeFwd(m_pFwdSettings));
QFile t_fSolution(m_pFwdSettings->solname);
MNEForwardSolution::SPtr pFwdSolution;
MNEForwardSolution::SPtr pClusteredFwd;
emit statusInformationChanged(4); // not computed
// do recomputation if requested, not busy and transformation is different
bool bIsLargeHeadMovement = false; // indicate if movement was large
bool bIsDifferent = false; // indicate if incoming transformation matrix is different
bool bDoRecomputation = false; // indicate if we want to recompute
bool bDoClustering = false; // indicate if we want to cluster
bool bFwdReady = false; // only cluster if fwd is ready
bool bHpiConnectected = false; // only update/recompute if hpi is connected
bool bDoFwdComputation = false; // compute forward if requested
bool bIsInit = false; // only recompute if initial fwd solulion is calculated
while(!isInterruptionRequested()) {
m_mutex.lock();
bDoFwdComputation = m_bDoFwdComputation;
m_mutex.unlock();
if(bDoFwdComputation) {
emit statusInformationChanged(1); // computing
m_mutex.lock();
m_bBusy = true;
m_mutex.unlock();
// compute and store
pComputeFwd->calculateFwd();
pComputeFwd->storeFwd();
// get Mne Forward Solution (in future this is not necessary, ComputeForward will have this as member)
pFwdSolution = MNEForwardSolution::SPtr(new MNEForwardSolution(t_fSolution, false, true));
// emit results to control widget
emit fwdSolutionAvailable(pFwdSolution->source_ori,
pFwdSolution->coord_frame,
pFwdSolution->nsource,
pFwdSolution->nchan,
pFwdSolution->src.size());
m_mutex.lock();
if(!m_bDoClustering) {
m_pRTFSOutput->data()->setValue(pFwdSolution);
bFwdReady = false; // make sure to not cluster
emit statusInformationChanged(5); //finished
}
bFwdReady = true; // enable cluster
m_bDoFwdComputation = false; // don't call this again if not requested
bIsInit = true; // init computation finished -> recomputation possible
m_mutex.unlock();
}
// check if hpi is connected
m_mutex.lock();
if(m_pHpiFitResult) {
bHpiConnectected = true;
}
m_mutex.unlock();
if(bHpiConnectected && bIsInit) {
// only recompute if hpi is connected
m_mutex.lock();
bIsLargeHeadMovement = m_pHpiFitResult->bIsLargeHeadMovement;
bIsDifferent = !(transMegHeadOld == m_pHpiFitResult->devHeadTrans.toOld());
bDoRecomputation = m_bDoRecomputation;
m_mutex.unlock();
// do recomputation if requested, a large head movement occured and devHeadTrans is different
if(bIsLargeHeadMovement && bIsDifferent && bDoRecomputation) {
emit statusInformationChanged(2); // recomputing
m_mutex.lock();
m_bBusy = true;
transMegHeadOld = m_pHpiFitResult->devHeadTrans.toOld();
m_mutex.unlock();
pComputeFwd->updateHeadPos(&transMegHeadOld);
pFwdSolution->sol = pComputeFwd->sol;
pFwdSolution->sol_grad = pComputeFwd->sol_grad;
m_mutex.lock();
m_bBusy = false;
m_mutex.unlock();
bFwdReady = true;
if(!bDoClustering) {
m_pRTFSOutput->data()->setValue(pFwdSolution);
bFwdReady = false;
emit statusInformationChanged(5); //finished
}
}
}
// do clustering if requested and fwd is ready
m_mutex.lock();
bDoClustering = m_bDoClustering;
m_mutex.unlock();
if(bDoClustering && bFwdReady) {
emit statusInformationChanged(3); // clustering
pClusteredFwd = MNEForwardSolution::SPtr(new MNEForwardSolution(pFwdSolution->cluster_forward_solution(*m_pAnnotationSet.data(), 200)));
emit clusteringAvailable(pClusteredFwd->nsource);
m_pRTFSOutput->data()->setValue(pClusteredFwd);
bFwdReady = false;
emit statusInformationChanged(5); //finished
}
}
}
|
[
"lorenzesch@hotmail.com"
] |
lorenzesch@hotmail.com
|
85c2fdf420718d0d679d51bba0b37d148a9e9d8c
|
a04a81dab51b4c69b6aec9c3e2a80275a5de8798
|
/BOJ/5719_gps.cpp
|
60530070c5e887ae0e5561c7d27655a6bb73c9e2
|
[] |
no_license
|
joseoyeon/Algorithm
|
afdfd8fb8c30a6d4b8571a713e92ead4e04c652d
|
78d5d238529bee931230449631730f3771608eb6
|
refs/heads/master
| 2023-01-21T11:54:03.331075
| 2023-01-06T05:25:32
| 2023-01-06T05:25:32
| 176,685,215
| 1
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,614
|
cpp
|
#include<bits/stdc++.h>
#define INF 987654321
using namespace std;
struct Data {
int node, weight;
Data(int node, int weight) : node(node), weight(weight){};
bool operator <(const Data d) const {
return weight > d.weight;
}
};
int main(){
ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int n,m;
int u,v,p;
int s,d;
vector <Data> vec[502];
bool visite[502];
int dis[502];
cin >> n >> m;
while(n || m){
cin >> s >> d;
// 초기화
for(int i =0; i<=n; i++){
vec[i].clear();
dis[i] = INF;
visite[i] = false;
}
while(m--){
cin >> u >> v >> p;
vec[u].push_back(Data(v,p));
}
/// 다익스트라 시작
dis[s] = 0;
priority_queue<Data> pq;
priority_queue<int> q;
pq.push(Data(s,0));
while(true) {
if(pq.empty()) break;
Data cur = pq.top();
pq.pop();
if(visite[cur.node]) continue;
visite[cur.node] = true;
for(auto &next : vec[cur.node]) {
if(next.node == d) {q.push(-(dis[cur.node] + next.weight));}
if(dis[next.node] > dis[cur.node] + next.weight){
dis[next.node] = dis[cur.node] + next.weight;
pq.push(Data(next.node, dis[next.node]));
}
}
}
int tmp = -1;
while(!q.empty()) {
cout<< -q.top() << endl;
q.pop();
}
cin >> n >> m;
}
return 0;
}
|
[
"joseoyoen60@gmail.com"
] |
joseoyoen60@gmail.com
|
c625ff75462e1eca84c2c57c1ef677a9f60da66f
|
8b5652e5e3823739a18d9a7966fedddf17bc183d
|
/External/cocos2dx-store/Soomla/rewards/CCVirtualItemReward.h
|
b418af209e9017abc3403f2109b4f442bf0bde78
|
[
"MIT"
] |
permissive
|
tovchenko/espreso
|
4d6ed4a13f7dd4a82b3d4176e5f586e20baa54aa
|
71c2a2f0e5bbd046b8b8cb63084b84bccabb7aa7
|
refs/heads/master
| 2016-09-06T10:44:20.370679
| 2015-02-25T14:39:20
| 2015-02-25T14:39:20
| 18,293,105
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,467
|
h
|
//
// Created by Fedor on 04/06/14.
//
#ifndef __CCVirtualItemReward_H_
#define __CCVirtualItemReward_H_
#include "../../../soomla-cocos2dx-core/Soomla/rewards/CCReward.h"
#include "../../../soomla-cocos2dx-core/Soomla/CCCommonConsts.h"
#include "../CCStoreConsts.h"
namespace soomla {
class CCVirtualItemReward : public CCReward {
SL_SYNTHESIZE_RETAIN_WITH_DICT(cocos2d::__Integer *, mAmount, Amount, CCStoreConsts::JSON_AMOUNT);
SL_SYNTHESIZE_RETAIN_WITH_DICT(cocos2d::__String *, mAssociatedItemId, AssociatedItemId, CCStoreConsts::JSON_ASSOCIATED_ITEM_ID);
public:
static CCVirtualItemReward *create(
cocos2d::__String *rewardId,
cocos2d::__String *name,
cocos2d::__Bool *repeatable,
cocos2d::__Integer * amount,
cocos2d::__String * associatedItemId
);
SL_CREATE_WITH_DICTIONARY(CCVirtualItemReward);
virtual bool init(
cocos2d::__String *rewardId,
cocos2d::__String *name,
cocos2d::__Bool *repeatable,
cocos2d::__Integer * amount,
cocos2d::__String * associatedItemId
);
virtual bool initWithDictionary(cocos2d::__Dictionary *dict);
virtual cocos2d::__Dictionary *toDictionary();
virtual ~CCVirtualItemReward();
virtual const char *getType() override;
};
};
#endif //__CCVirtualItemReward_H_
|
[
"doctorset@gmail.com"
] |
doctorset@gmail.com
|
a3415b510d15bc284e8e47ec40d4eaf0385e3f52
|
0657de9b1587ac081855ecf564c832045cb707be
|
/1300 - 1399 ladder/Difficulty Level - 4/Ciel and Flowers.cpp
|
4d524d54e6abc14d32a83a3bfd97623e9515585b
|
[] |
no_license
|
anuragdvd/a2oj-ladders
|
cb49f431ad03a3272b35691e4b6cb1c5133648b8
|
2fe258013ed33325c8365b81662ece7a6a7a602f
|
refs/heads/master
| 2023-01-22T05:12:51.941348
| 2020-12-04T00:46:29
| 2020-12-04T00:46:29
| 287,341,586
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 948
|
cpp
|
// Ciel and Flowers :: https://codeforces.com/problemset/problem/322/B
#include<bits/stdc++.h>
#define fr(i,c,b) for(int i=c;i<b;i++)
#define frl(i,c,b) for(ll i=c;i<b;i++)
#define si(x) int x; scanf("%d", &x)
#define sll(x) ll x; scanf("%lld", &x)
#define pi(x) printf("%d", x)
#define pll(x) printf("%lld", x)
#define nl printf("\n")
#define watch(x) cout << (#x) << " is " << (x) << endl
#define MAX 100001
#define M 1000000007
#define pb push_back
typedef long long int ll;
using namespace std;
int main()
{
sll(r); sll(g); sll(b);
ll ans=0;
int c=0; if(r%3==0) c++; if(g%3==0) c++; if(b%3==0) c++;
if(r==0||b==0||g==0)
{
ans=(r/3)+(b/3)+(g/3);
}
else if(c>1)
{
ans+=(r/3)+(b/3)+(g/3);
}
else{
ans+=(r/3)+(b/3)+(g/3);
r=r%3; b=b%3; g=g%3;
if(r==0) r+=3,ans--; if(b==0) b+=3,ans--; if(g==0) g+=3,ans--;
ans+=min(min(r,b),g);
}
cout<<ans;
}
|
[
"alltrickbyte@gmail.com"
] |
alltrickbyte@gmail.com
|
f81deb172854e584d189ffb6bdbed62c34890e25
|
d07a162fae98a9092f5eaa9588898436bb6c29f9
|
/cosesdelpen/Geometry/Plane.cpp
|
ab22420a778cc3fd4d51cd1727b40a02a6829b1e
|
[] |
no_license
|
Setsilvestre/codipen
|
8b6ae74d2610777f22f9760b0fca9e45beb628b1
|
3e2659e9f25ab67fd460c3163a0ca206c7e000ec
|
refs/heads/master
| 2016-08-04T17:02:52.299401
| 2015-02-23T09:30:01
| 2015-02-23T09:30:01
| 31,201,147
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,609
|
cpp
|
#include "Plane.h"
//Constructor
Plane::Plane()
{
}
//Destructor
Plane::~Plane()
{
}
//Setters
void Plane::setPlanePoint(const float& x, const float& y, const float& z){
this->point.coord.x = x;
this->point.coord.y = y;
this->point.coord.z = z;
}
void Plane::setPlaneNormal(const float& x, const float& y, const float& z){
this->normal.x = x;
this->normal.y = y;
this->normal.z = z;
}
void Plane::setPlaneDirect1(const float& x, const float& y, const float& z){
this->direc1.x = x;
this->direc1.y = y;
this->direc1.z = z;
}
void Plane::setPlaneDirect2(const float& x, const float& y, const float& z){
this->direc2.x = x;
this->direc2.y = y;
this->direc2.z = z;
}
void Plane::setPlaneFrom3Points(Point p1, Point p2, Point p3){
this->point.coord.x = p1.coord.x;
this->point.coord.y = p1.coord.y;
this->point.coord.z = p1.coord.z;
direc1.x = p2.coord.x - p1.coord.x;
direc1.y = p2.coord.y - p1.coord.y;
direc1.z = p2.coord.z - p1.coord.z;
direc2.x = p3.coord.x - p1.coord.x;
direc2.y = p3.coord.y - p1.coord.y;
direc2.z = p3.coord.z - p1.coord.z;
normal=cross(direc1, direc2);
}
void Plane::setDirectFromNormal(){
setPlaneDirect1(-normal.y, normal.x, 0);
setPlaneDirect2(normal.y, -normal.x, 0);
}
void Plane::computeD(){
this->d = dot(-normal, point.coord);
}
//Functions
float Plane::distPlaneToPoint(Point q){
d = dot(-normal, point.coord);
return (length(normal.x*q.coord.x + normal.y*q.coord.y + normal.z*q.coord.z + d)) / length(normal);
}
vec3 Plane::computePlaneNormal(){
normal = cross(direc1, direc2);
return normal;
}
Point Plane::closestPointInPlane(Point q){
Line newLine;
newLine.setPointLine(q.coord.x, q.coord.y, q.coord.z);
newLine.setDirectionLine(normal.x, normal.y, normal.z);
vec3 newPoint;
newPoint.x = point.coord.x;
newPoint.y = point.coord.y;
newPoint.z = point.coord.z;
d = dot(-normal, newPoint);
newPoint.x = q.coord.x;
newPoint.y = q.coord.y;
newPoint.z = q.coord.z;
float alfa = (-d - dot(normal, newPoint)) / dot(normal, normal);
return newLine.pointwithAlfa(alfa);
}
Point Plane::entryPointSegmentPlane(Point p, Point q){
Line newLine;
newLine.setPointLine(p.coord.x, p.coord.y, p.coord.z);
newLine.setDirectionLine(q.coord.x - p.coord.x, q.coord.y - p.coord.y, q.coord.z - p.coord.z);
float alfa = (-d - dot(normal, p.coord)) / dot(normal, newLine.returnDirection());
return newLine.pointwithAlfa(alfa);
}
bool Plane::changePosition(Point p){
if ((normal.x*p.coord.x + normal.y*p.coord.y + normal.z*p.coord.z + d) / sqrt(normal.x*normal.x + normal.y*normal.y + normal.z*normal.z) < 0){
return false;
}
else return true;
}
|
[
"xavier_figuerola@hotmail.com"
] |
xavier_figuerola@hotmail.com
|
7f0e00213a43bf75e10b8f5cf3f0c9ee8b353dcb
|
29b2e290739a85506a1067424c94e357e287da3b
|
/optimizer/BigTreeException.h
|
2b085aed5a7ba188da9cc7eefc5596c896e253a3
|
[] |
no_license
|
CalderWhite/hash-bash
|
23969560638e614975fbe61747057fbd4f1f0e77
|
15b693d3f555e640df48bb99593dab266f119097
|
refs/heads/master
| 2020-06-28T04:36:47.678936
| 2020-01-24T00:57:44
| 2020-01-24T00:57:44
| 200,144,483
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 246
|
h
|
#pragma once
#include <iostream>
#include <exception>
/**
* Custom exceptions to improve error catching/info.
*/
class BigTreeException: public std::runtime_error {
public:
BigTreeException(const char* msg) : std::runtime_error(msg){}
};
|
[
"calderwhite1@gmail.com"
] |
calderwhite1@gmail.com
|
953559733610011e8e3c321319846ee810d2a104
|
9168d79f8668e4e704d361a03396bc01b7a6fc54
|
/OpenCV/Function.cpp
|
4e50e177b18e9df5d78c9aef3a46a9790f1a66fe
|
[] |
no_license
|
Satvik-Verma/Virtual-Paint-Project-1
|
42e872c7f8335b240f20ac178d0f136087f885d6
|
4ac8baf19bf1d7dac87e61d14374e7847b34bb23
|
refs/heads/master
| 2023-06-18T22:06:35.908501
| 2021-07-06T20:24:23
| 2021-07-06T20:24:23
| 383,536,037
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 707
|
cpp
|
#include<iostream>
#include<opencv2/highgui.hpp>
#include<opencv2/imgcodecs.hpp>
#include<opencv2/imgproc.hpp>
using namespace cv;
using namespace std;
void main() {
string path = "Resources/shapes.png";
Mat img = imread(path);
Mat imgGray, imgBlur, imgCanny, imgDil, imgErod;
Mat kernel = getStructuringElement(MORPH_RECT, Size(3, 3));
cvtColor(img, imgGray, COLOR_BGR2GRAY);
GaussianBlur(img, imgBlur, Size(7, 7), 5, 0);
Canny(img, imgCanny, 100, 100);
dilate(imgCanny, imgDil, kernel);
erode(imgDil, imgErod, kernel);
imshow("Image", imgGray);
imshow("ImageBlur", imgBlur);
imshow("ImageCanny", imgCanny);
imshow("ImageDia", imgDil);
imshow("ImageErod", imgErod);
waitKey(0);
}
|
[
"satvikrohella@gmail.com"
] |
satvikrohella@gmail.com
|
7de3450b35d4d3b2f59fedcbeb03acb8a1f2c130
|
63f31d35c65d44e0f40190d0d6e1170e540cd226
|
/BaiTapTuan14/BTtuan14.cpp
|
65999edc1ce03a0f867de10a4c8e85473432e5f2
|
[] |
no_license
|
Tannb9119/KyThuatLapTrinhC-Cplusplus
|
a3fdd978022b9981ba85a85dfb7e98e2e94e1923
|
2edd8fb2a7f9451743957095cca1659df6d295f3
|
refs/heads/main
| 2023-02-13T02:46:41.436573
| 2021-01-14T14:09:52
| 2021-01-14T14:09:52
| 314,602,733
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,239
|
cpp
|
#include <iostream>
#include <string>
using namespace std;
template <class T>
class Node
{
public:
T value;
Node *next;
Node(T v) : value(v), next(0){};
};
template <class T>
class List
{
Node<T> *head, *tail;
int count;
public:
List() : count(0) { head = 0, tail = 0; }
~List()
{
delete head;
delete tail;
} //Ham huy
void RemoveAll() // Ham xoa danh sach
{
while (count)
{
--count;
Node<T> *p = this->head;
this->head = p->next;
}
}
void add(T v) // ham bo sung mot node v vao ds
{
Node<T> *newNode = new Node<T>(v);
if (count++ == 0)
{
head = newNode;
tail = newNode;
}
else
{
tail->next = newNode;
tail = newNode;
}
}
Node<T> *First() const // Ham lay ra node dau tien
{
return head;
}
int Count() const // Ham tinh tong so node trong list
{
return count;
}
T *ToArray() // Ham duyet cac node de lay ra thuoc tinh value trong list
{
T *arr = new T[count];
Node<T> *p = head;
for (int i = 0; i < count; i++, p = p->next)
{
arr[i] = p->value;
}
return arr;
}
void remove(int pos)
{
Node<T> *p = head;
int k = 1;
if (pos <= 1) // kiem tra xem node muon xoa co phai node dau tien ko
{
Node<T> *tmp = head;
head = tmp->next;
delete tmp;
}
else
{
if (pos > count)
pos = count;
while (k++ != pos - 1) // tra ve node truoc node can xoa
{
p = p->next;
}
Node<T> *tmp = p->next;
p->next = tmp->next;
if (pos == count)
tail = p;
delete tmp;
}
count--;
}
void display()
{
T *arr = this->ToArray();
for (int i = 0; i < count; i++)
{
cout << "Thong tin nguoi thu: " << i + 1 << endl;
arr[i].display();
}
}
void sort()
{
for (Node<T> *p1 = head; p1 != 0; p1 = p1->next)
{
for (Node<T> *p2 = p1->next; p2 != 0; p2 = p2->next)
{
if (p1->value.getID() > p2->value.getID())
{
T tmp = p1->value;
p1->value = p2->value;
p2->value = tmp;
}
}
}
}
void modify(int pos)
{
Node<T> *p = head;
int k = 1;
if (pos < 1)
pos = 1;
else if (pos > count)
pos = count;
while (k++ != pos)
p = p->next;
p->value.input();
}
};
//Dinh nghio lop co so
class person
{
private:
int id;
string name;
string gender;
public:
person(int _id = 0, string _name = "unknown", string _gender = "unknown")
{
id = _id;
name = _name;
gender = _gender;
}
person(const person &per1)
{
id = per1.id;
name = per1.name;
gender = per1.gender;
}
~person(){};
void input()
{
cout << "Nhap ma dinh danh:";
cin >> this->id;
cout << "Nhap ho ten: ";
cin.ignore(1);
getline(cin, this->name);
cout << "Nhap gioi tinh: ";
getline(cin, this->gender);
}
void display()
{
cout << "Person:\n";
cout << "ID:\t" << id << endl;
cout << "Name:\t" << name << endl;
cout << "Gender:\t" << gender << endl;
}
int getID()
{
return id;
}
};
class student : public person
{
private:
int stuID;
string clas;
public:
student(int _id = 0, string _name = "unknown", string _gender = "unknown", int _stuID = 0, string _clas = "unknown") : person(_id, _name, _gender)
{
stuID = _stuID;
clas = _clas;
}
void display()
{
person::display();
cout << "student ID:\t" << stuID << endl;
cout << "Class:\t" << clas << endl;
}
void input()
{
person::input();
cout << " + Nhap stuID: ";
cin >> this->stuID;
cin.ignore(1);
cout << " + Nhap ten lop: ";
getline(cin, this->clas);
}
};
int main()
{
List<student> lofstuds;
student std1(1, "le thi mai", "female", 22, "ET4");
student std2(2, "le thi hoa", "female", 23, "ET4");
student std3(3, "Pham thanh long", "male", 24, "ET4");
lofstuds.add(std3);
lofstuds.add(std2);
lofstuds.add(std1);
lofstuds.sort();
cout << "=======================List hien tai:=========================" << endl;
lofstuds.display();
cout << "Nhap thong tin sua doi:" << endl;
lofstuds.modify(2); // chinh sua value o node thu 2
cout << "======================List sau khi sua doi:===================" << endl;
lofstuds.display();
cout << "======================List sau khi xoa:=======================" << endl;
lofstuds.remove(3); // xoa node thu 3
lofstuds.display();
cout << endl;
return 0;
}
|
[
"="
] |
=
|
f1285e6c1b8361df6f6adcb5be8acf3785991172
|
15b0d541817cd26cb2c5706d8211131142119f59
|
/cuboid.h
|
485de00b0eabeeddf6c381a8316a453a7fe846dc
|
[] |
no_license
|
isaiasfrederick/CudaFragCubing
|
07a5a7c642e48e11c31bb44469b646e377b15e4e
|
1b12609f61e481442cb45a3a0f7b372b8644c0db
|
refs/heads/master
| 2021-01-10T10:23:47.601434
| 2016-04-10T00:23:06
| 2016-04-10T00:59:07
| 55,873,762
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,143
|
h
|
#ifndef CUBOID_H
#define CUBOID_H
#include <vector>
#include <map>
#include <iostream>
#include <list>
#include <map>
#include <fstream>
#include <string>
#include <sstream>
#include <algorithm>
#include "constantes.h"
using namespace std;
typedef struct
{
vector<int> dimensions;
} CubDim;
typedef struct
{
vector<int> values;
} AttVal;
string label_attribute_values(AttVal attribute);
typedef struct
{
bool operator() (CubDim cd1, CubDim cd2) const {
for (register int i = 0; i < cd1.dimensions.size() && i < cd2.dimensions.size(); i++)
if (cd1.dimensions[i] > cd2.dimensions[i])
return true;
else if (cd1.dimensions[i] < cd2.dimensions[i])
return false;
return cd1.dimensions.size() > cd2.dimensions.size();
}
} CompCubDim;
typedef struct
{
bool operator() (AttVal av1, AttVal av2) const {
for (register int i = 0; i < av1.values.size() && i < av2.values.size(); i++)
if (av1.values[i] > av2.values[i])
return true;
else if (av1.values[i] < av2.values[i])
return false;
return av1.values.size() > av2.values.size();
}
} CompAttVal;
typedef struct
{
map<AttVal, vector<int>, CompAttVal> values;
} Cuboid;
typedef struct
{
int tamanho_fragmento;
int total_tuplas;
vector<int> all_ids;
map<CubDim, Cuboid, CompCubDim> cuboids;
set<int> cardinalidades_ordenadas;
vector<int> cardinalidades_por_coluna;
map<int, vector<int>> map_colunas;
vector<int> colunas_ordenadas;
} Fragmentos;
inline Cuboid* get_cuboid(Fragmentos* fragmentos, CubDim cub_dim)
{
return &(fragmentos->cuboids[cub_dim]);
}
inline map < AttVal, vector<int>>::iterator get_attval_iterator(Cuboid* cuboid)
{
return cuboid->values.begin();
}
inline vector<int> get_tids(Cuboid* cuboid, AttVal attVal)
{
return cuboid->values[attVal];
}
inline bool attribute_values_equals(AttVal av1, AttVal av2)
{
set<AttVal, CompAttVal> set;
set.insert(av1);
return set.find(av2) != set.end();
}
inline CubDim create_cuboid_dimensions(vector<int> dimensions)
{
CubDim cd;
sort(dimensions.begin(), dimensions.end());
cd.dimensions = dimensions;
return cd;
}
inline CubDim create_cuboid_dimensions(CubDim cub_dim, int dimensao)
{
CubDim cd = cub_dim;
cd.dimensions.push_back(dimensao);
sort(cd.dimensions.begin( ), cd.dimensions.end( ));
return cd;
}
inline CubDim create_cuboid_dimensions(int dimension)
{
CubDim cd;
vector<int> dimensions = { dimension };
sort(dimensions.begin(), dimensions.end());
cd.dimensions = dimensions;
return cd;
}
inline CubDim create_cuboid_dimensions(CubDim cd1, CubDim cd2)
{
CubDim cd = cd1;
cd.dimensions.insert(cd.dimensions.end( ), cd2.dimensions.begin( ), cd2.dimensions.end( ));
sort(cd.dimensions.begin( ), cd.dimensions.end( ));
return cd;
}
inline AttVal create_attribute_value(vector<int> values)
{
AttVal av;
sort(values.begin(), values.end());
av.values = values;
return av;
}
inline AttVal create_attribute_value(int value)
{
AttVal av;
vector<int>values = { value };
sort(values.begin( ), values.end( ));
av.values = values;
return av;
}
inline AttVal concatenate_attribute_value(AttVal av1, AttVal av2)
{
AttVal av_retorno = av1;
av_retorno.values.insert(av_retorno.values.end( ), av2.values.begin( ), av2.values.end( ));
sort(av_retorno.values.begin( ), av_retorno.values.end( ));
return av_retorno;
}
inline AttVal concatenate_attribute_value_ws(AttVal av1, AttVal av2)
{
AttVal av_retorno = av1;
av_retorno.values.insert(av_retorno.values.end( ), av2.values.begin( ), av2.values.end( ));
return av_retorno;
}
inline AttVal concatenate_attribute_value(AttVal av1, AttVal av2, CubDim cd1, CubDim cd2)
{
AttVal av_retorno;
int pos_cd1 = 0;
int pos_cd2 = 0;
while (pos_cd1 < cd1.dimensions.size() && pos_cd2 < cd2.dimensions.size())
{
if (cd1.dimensions[pos_cd1] < cd2.dimensions[pos_cd2])
{
av_retorno.values.push_back(av1.values[pos_cd1]);
pos_cd1++;
}
else
{
av_retorno.values.push_back(av2.values[pos_cd2]);
pos_cd2++;
}
}
while (pos_cd1 < cd1.dimensions.size())
{
av_retorno.values.push_back(av1.values[pos_cd1]);
pos_cd1++;
}
while (pos_cd2 < cd2.dimensions.size())
{
av_retorno.values.push_back(av2.values[pos_cd2]);
pos_cd2++;
}
return av_retorno;
}
inline AttVal concatenate_attribute_value(AttVal av1, int v)
{
AttVal av_retorno = av1;
av_retorno.values.push_back(v);
sort(av_retorno.values.begin(), av_retorno.values.end());
return av_retorno;
}
inline CubDim concatenate_cuboid_dimensions(CubDim cd1, CubDim cd2)
{
CubDim cd_retorno = cd1;
cd_retorno.dimensions.insert(cd_retorno.dimensions.end( ), cd2.dimensions.begin( ), cd2.dimensions.end( ));
sort(cd_retorno.dimensions.begin( ), cd_retorno.dimensions.end( ));
return cd_retorno;
}
inline CubDim concatenate_cuboid_dimensions(CubDim cd1, int d)
{
CubDim cd_retorno = cd1;
cd_retorno.dimensions.push_back(d);
sort(cd_retorno.dimensions.begin( ), cd_retorno.dimensions.end( ));
return cd_retorno;
}
template <typename T>
inline string label_vector(vector<T> v)
{
string label = "";
register int d;
for (d = 0; d < v.size( ); d++)
label += to_string(v[d]) + " ";
return label;
}
inline string label_cuboid_dimensions(CubDim cuboid)
{
string label = "";
register int d;
for (d = 0; d < cuboid.dimensions.size( ) - 1; d++)
label += to_string(cuboid.dimensions[d]) + " ";
label += to_string(cuboid.dimensions[d]);
return label;
}
inline string label_attribute_values(AttVal attribute)
{
string label = "";
for (int v = 0; v < attribute.values.size()-1; v++)
if (attribute.values[v] == ALL)
label += string({AGGREGATED_CARACTER}) + " ";
else
label += to_string(attribute.values[v]) + " ";
int index = attribute.values.size() - 1;
if (attribute.values[index] == ALL)
label += string({ AGGREGATED_CARACTER });
else
label += to_string(attribute.values[index]);
return label;
}
inline string label_tuple_id_list(vector<int>* tuple_id_list)
{
string label = "";
int i = 0;
for (i = 0; i < tuple_id_list->size()-1; i++)
label += to_string((*tuple_id_list)[i]) + ", ";
label += to_string((*tuple_id_list)[i]);
return label;
}
#endif
|
[
"isaiasfrederick@gmail.com"
] |
isaiasfrederick@gmail.com
|
cb3fc2db580103a09d0a6e91da85c04b0181b64f
|
7e797415eddea48580c78f10a571b1e2cb596d65
|
/source/thirdparty/GL/GL/VertexBuffer.hpp
|
0fba4a91358d846ac9764734fbfc407460f4e95a
|
[] |
no_license
|
razzie/PotatoGame
|
dcf8a393221faf3d0cdd41a6f5f88b141fcb5536
|
495d243693d82df43a053dbf75b38163f598a9b7
|
refs/heads/master
| 2022-08-19T16:42:23.278074
| 2018-08-09T20:00:46
| 2018-08-09T20:02:22
| 144,187,201
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,434
|
hpp
|
/*
Copyright (C) 2012 Alexander Overvoorde
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE
*/
#pragma once
#ifndef OOGL_VERTEXBUFFER_HPP
#define OOGL_VERTEXBUFFER_HPP
#include <GL/Platform.hpp>
#include <GL/GL/GC.hpp>
#include <GL/GL/Extensions.hpp>
#include <GL/Util/Mesh.hpp>
#include <GL/Math/Vec4.hpp>
#include <functional>
#include <cstdint>
namespace GL
{
/*
Buffer usage types
*/
namespace BufferUsage
{
enum buffer_usage_t
{
StreamDraw = GL_STREAM_DRAW,
StreamRead = GL_STREAM_READ,
StreamCopy = GL_STREAM_COPY,
StaticDraw = GL_STATIC_DRAW,
StaticRead = GL_STATIC_READ,
StaticCopy = GL_STATIC_COPY,
DynamicDraw = GL_DYNAMIC_DRAW,
DynamicRead = GL_DYNAMIC_READ,
DynamicCopy = GL_DYNAMIC_COPY
};
}
/*
Helper class for building vertex data
*/
class VertexDataBuffer
{
public:
void Float( float v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Int8( int8_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Int16( int16_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Int32( int32_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Uint8( uint8_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Uint16( uint16_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Uint32( uint32_t v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Vec2( const Vec2& v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Vec3( const Vec3& v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void Vec4( const Vec4& v ) { Bytes( (uchar*)&v, sizeof( v ) ); }
void* Pointer() { return &data[0]; }
int Size() { return data.size(); }
private:
std::vector<uchar> data;
void Bytes( uchar* bytes, uint count ) {
for ( uint i = 0; i < count; i++ )
data.push_back( bytes[i] );
}
};
/*
Vertex Buffer
*/
class VertexBuffer
{
public:
VertexBuffer();
VertexBuffer( const VertexBuffer& other );
VertexBuffer( const void* data, size_t length, BufferUsage::buffer_usage_t usage );
VertexBuffer( const Mesh& mesh, BufferUsage::buffer_usage_t usage, std::function<void ( const Vertex& v, VertexDataBuffer& data )> f );
~VertexBuffer();
operator GLuint() const;
const VertexBuffer& operator=( const VertexBuffer& other );
void Data( const void* data, size_t length, BufferUsage::buffer_usage_t usage );
void SubData( const void* data, size_t offset, size_t length );
void GetSubData( void* data, size_t offset, size_t length );
private:
static GC gc;
GLuint obj;
};
}
#endif
|
[
"gabor@gorzsony.com"
] |
gabor@gorzsony.com
|
16c081a77af26565f3ef7cd92ae51a7c9a182159
|
2be90d61ff00b1b9f9e0ab807d1b6e6e7877c783
|
/main.cpp
|
34deff1848fab78318f073459aaa2b62eee7526d
|
[
"BSD-3-Clause"
] |
permissive
|
pietrotedeschi/secureais
|
791f97fa3f5504bcd309dc03c9c92b917922538e
|
a2531191849e1eabb15aa223912d73b2bb80f287
|
refs/heads/master
| 2020-12-28T14:48:55.429255
| 2020-01-19T11:31:02
| 2020-01-19T11:31:02
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 26,867
|
cpp
|
/*
main.cpp
@authors Ahmed Aziz, Pietro Tedeschi, Savio Sciancalepore, Roberto Di Pietro
@Description: A program for implementing the SecureAIS Protocol PoC
@version 1.0 17/01/19
Compile command, add flag -DPORT_SEND or -DPORT_RECEIVE to set another port,
-DGEN_KEYS= true or false to set whether to generate keys or not
g++ -O2 main.cpp -DSECURITY_LEVEL=1 ./secure_ais_protocol.cpp ./ais_receiver/*.c core-master/cpp/core.a -o main
**/
#include "secure_ais_protocol.h"
#include "ais_receiver/ais_rx.h"
#include "core-master/cpp/randapi.h"
//WARNING, Moving below functions can break this program!!!!
/**
* @brief read an ais message from socket coming from GNURadio
* @param fd1 file descriptor being used by read socket
* @param ais struct that will store AIS messages
* @param message_count, index where current message will be stored
* @return void
*/
void read_ais(int fd1, ais_message_t *ais, int message_count){
AISConfiguration ais_config;
load_configuration(NULL, &ais_config);
ais[message_count].fd = fd1;
ais[message_count].d.seqnr = 0;
read_ais_message(&ais[message_count]);
}
/**
* @brief send an ais message from socket to GNURadio
* @param message to be sent
* @return success/fail
*/
int sendmessage(string message){
int sock = socket_init(PORT_SEND);
message = message + '\0';
send(sock , message.c_str(), message.length(), 0 );
printf("Message sent\n");
close(sock);
return 0;
}
/**
* @brief send an ais certificate over socket to AIS GNURadio flowgraph
* @param Ship a struct storing Ship whose data has to be sent
* @param Ship_2 a struct storing Ship which will receive data from Ship
* @param CApublic public key of Certificate Authorty
* @param fd1 file descriptor of read socket
* @return success is 0 /fail
*/
int send_ais_certificate(ship_state_t *Ship, ship_state_t *Ship_2, octet* CApublic, int fd1){
auto start = std::chrono::high_resolution_clock::now();
//Generation of random number for nonce
std::random_device seed_gen{};
std::mt19937_64 mt_rand(seed_gen());
Ship->nonce = {std::bitset<64>(mt_rand()).to_string()}; //to binary
//Initialize and store certificate in char_certificate
char char_certificate[2 * Ship->ECQVCert.len + 1]={'\0'};
OCT_toHex(&Ship->ECQVCert, char_certificate);
//First add certificate to payload
// std::cout<<"\n char_certificate ="<<string(char_certificate)<<endl;
string payload = hextobin(string(char_certificate));
//DEBUG std::cout<<"Payload length ="<< payload.length()<<endl<<"Payload=\n"<<string(char_certificate)<<endl;
//Remove last 32 bits as they are same as src MMSI, will be concatenated by receiver
payload.erase(payload.length()-32);
//std::cout<<"Certifcate Payload length ="<< payload.length()/8<<endl<<"Certifcate Payload=\n"<<payload<<endl;
//Then add nonce
payload = Ship->nonce+payload;
Ship->nonce = bintohex(Ship->nonce);
//Add security level to the beginning of payload
payload = std::bitset<8>(SECURITY_LEVEL).to_string() + payload;
ais_message_t ais[MAX_ALLOWABLE_MESSAGES];
int message_count=0;
const int max_payload_size_bytes = MAX_SLOTS_DATA_SIZE;
const int payload_size_bytes = payload.length()/8;//Ship->ECQVCert.len + Ship->nonce.length()/8;
//DEBUG printf("\nSize of payload = %d\n", payload_size_bytes);
const int number_of_messages = ceil(payload_size_bytes / (float) max_payload_size_bytes);
//DEBUG printf("\n Number of messages to be send = %d\n", number_of_messages);
int start_index = 0, end_index = 0;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Preprocessing of SecureAIS exchange message(nonce,certificate) before transmitting", microseconds);
//check size of payload, fit in 3 slots, max size allowed in 3 slots = 62 bytes according to AIS standard
for (int i=0; i<number_of_messages; i++){
string message={'\0'};
//Send multiple messages, Divide payload into different slot messages if size > 3 continous slots
end_index = max_payload_size_bytes*(i+1)*8;
if(end_index > payload.length() ){
end_index = payload.length();
}
//DEBUG std::cout<<"Payload length ="<< payload.length()<<endl<<"Payload=\n"<<payload<<endl;
//DEBUG std::cout<<"\nMessage #"<<i<<"Startindex "<< start_index <<" End index"<<end_index <<endl;
string payload_2_send = payload.substr(start_index, end_index - start_index );
//DEBUG std::cout<<"\nMessage "<<payload_2_send;
message = encode_ais_message_6(123456789, 123456789, i, payload_2_send);
//DEBUG std::cout<<"\nMessage #"<<i<<"Startindex "<< start_index <<" End index"<<end_index <<endl<<message<<"payload:"<<payload_2_send<<endl;
start_index = end_index;
Ship->message_sent += message;
auto start = std::chrono::high_resolution_clock::now();
int res = sendmessage(message);
if (res != 0)
{
printf("Message not sent over socket....Exiting!\n");
return 0;
}
read_ais(fd1, ais, message_count);
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Sending/Receiving SecureAIS (nonce,certificate) packet# "+to_string(i), microseconds);
message_count++;
}
//DEBUG printf("\nsequence: %d", ais[0].d.sequence );
//DEBUG printf("\nPayload: %s\n", ais[0].d.payload_buffer );
start = std::chrono::high_resolution_clock::now();
string received_cert = "";
int src_mmsi;
string security_level_bits;
for (int i=0; i<number_of_messages; i++){
// cout<<"\n AIS message"<<ais[i].d.payload_buffer;
if(i==0){
src_mmsi = ais[i].d.src_mmsi;
string char2string = string(ais[i].d.payload_buffer);
//first 3 bits are security level
security_level_bits = char2string.substr(0,8);
//first 64 bits are nonce
Ship_2->received_nonce = bintohex(char2string.substr(8, 64));
//Rest is part of certificate
received_cert += char2string.substr(72, std::string::npos );
//cout<<"\n AIS message"<<ais[i].d.payload_buffer;
}else{
received_cert += (string) ais[i].d.payload_buffer;
}
Ship_2->message_received += ais[i].d.message;
}
int security_level = (int)( std::bitset<64>(security_level_bits).to_ulong() );
if (security_level == 0)
return 0;
//DEBUG cout<<"Received certificate:"<<received_cert.length()<<endl;
//First get certificate
received_cert = bintohex(received_cert);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Preprocessing AIS cert packets to get complete certificate", microseconds);
///Second get pub.key, remove last 8 hex characters, are validity time
//cout<<"Received certificate:"<<received_cert<<endl;
start = std::chrono::high_resolution_clock::now();
string received_pubkey = received_cert.substr(0, received_cert.length() - 8 );
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Extraction of secret material from certificate to gen Public Key later", microseconds);
//cout<<"Received certificate:"<<received_pubkey<<endl;
//3.5 Certificate Public Key Extraction Process: Cert PK Extraction
//QU = ePU + QCA .
char PU_extract_size[2 * field_size_EFS + 1];
octet PU_extract = {0, sizeof(PU_extract_size), PU_extract_size}; //This is PU
//Join bytes till public key size
auto start_Pk = std::chrono::high_resolution_clock::now();
start = std::chrono::high_resolution_clock::now();
OCT_fromHex(&Ship_2->recvd_cert, (char *) received_cert.data());
OCT_jint(&Ship_2->recvd_cert, src_mmsi, sizeof(src_mmsi));//32
BIG e={0};
Hn(&Ship_2->recvd_cert, e);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Addition of Src MMSI to cert and Hash operation to get e", microseconds);
OCT_fromHex(&PU_extract, (char *) received_pubkey.data());
//printf("Received cert extract: \n");
//OCT_output(&Ship_2->recvd_cert);
ECP QCA, QU, ECP_PU_extract;
int res = ECP_fromOctet(&QCA, CApublic);
if (res != 1)
{
printf("ECP from octet is invalid!\n");
return 0;
}
ECP_fromOctet(&ECP_PU_extract, &PU_extract);
//printf("\nECP_PU_extract!\n");
//ECP_output(&ECP_PU_extract);
start = std::chrono::high_resolution_clock::now();
ECP_copy(&QU, &ECP_PU_extract);
ECP_mul(&QU, e);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Compute H(Pa ,Ia )Pa", microseconds);
start = std::chrono::high_resolution_clock::now();
ECP_add(&QU, &QCA);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("C + H(Pa ,Ia ) Pa", microseconds);
ECP_toOctet(&Ship_2->recvd_public_key, &QU, false);
res = ECP_PUBLIC_KEY_VALIDATE(&Ship_2->recvd_public_key);
if (res != 0)
{
printf("ECP Public Key is invalid!\n");
return res;
}
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start_Pk).count();
test2_write_message("Total time to Compute Pk", microseconds);
// printf("\nReceived ECP Public Key is:\n");
// OCT_output(&Ship_2->recvd_public_key);
return 0;
}
/**
* @brief Send AIS Tag function
* @param Ship Ship 1 data
* @param Ship_2 Ship 2 data
* @param type describe whether Ship 1 is transmitter = 1 or receiver = 2
* @param fd1 file descriptor of read socket
*/
int send_ais_auth_tag(ship_state_t *Ship, ship_state_t *Ship_2, int type, int fd1){
auto start = std::chrono::high_resolution_clock::now();
if (SECURITY_LEVEL != 0){
//Complete Auth tag will be stored
char auth_tag_message_size[5 * field_size_EFS + 1];
octet auth_tag_message = {0, sizeof(auth_tag_message_size), auth_tag_message_size};
if(type == 1){
//if transmitter then sent data comes first
OCT_jstring(&auth_tag_message, (char *)Ship->message_sent.data() );
OCT_jstring(&auth_tag_message, (char *)Ship->message_received.data());
}else{
//if receiver then received data comes first
OCT_jstring(&auth_tag_message, (char *)Ship->message_received.data());
OCT_jstring(&auth_tag_message, (char *)Ship->message_sent.data() );
}
//generate 256 bit Auth tag using HMAC
HMAC(MC_SHA2, SHA256, &Ship->auth_tag, SHA256, &Ship->session_key, &auth_tag_message);
}else{
OCT_fromHex(&Ship->auth_tag, (char *) "2028b65a7d8cb1a51745067e63ae9eee7e1bc4b52fc6680c7ac126414109c570" );
OCT_fromHex(&Ship_2->auth_tag, (char *) "2028b65a7d8cb1a51745067e63ae9eee7e1bc4b52fc6680c7ac126414109c570" );
}
printf("\nAuth tag HMAC: ");
OCT_output(&Ship->auth_tag);
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of Auth tag using HMAC function", microseconds);
start = std::chrono::high_resolution_clock::now();
//Change Octet to char for transmission
char char_payload[Ship->auth_tag.len*2 + 1]={'\0'};
OCT_toHex(&Ship->auth_tag, char_payload);
string payload = string(char_payload);
cout<<"\n auth_tag Payload = "<<payload<<endl;
payload = hextobin(payload);
//check size of payload, fit in 3 slots, max size allowed in 3 slots = 62 bytes according to AIS standard
ais_message_t ais[MAX_ALLOWABLE_MESSAGES];
int message_count=0;
int max_payload_size_bytes = MAX_SLOTS_DATA_SIZE;
int payload_size_bytes = Ship->auth_tag.len;
//DEBUG printf("\nSize of payload = %d\n", payload_size_bytes);
int counter = ceil(payload_size_bytes / (float) max_payload_size_bytes);
//DEBUG printf("\nNumber of messages to be send = %d\n", counter);
int start_index = 0, end_index = 0;
//std::cout<<"Payload length ="<< payload.length()<<endl<<"Payload=\n"<<payload<<endl;
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Preprocessing of SecureAIS auth tag before transmitting", microseconds);
for (int i=0; i<counter; i++){
//Send multiple messages, Divide payload into different slot messages if size > 3 continous slots
end_index = max_payload_size_bytes*(i+1)*8;
if(end_index > payload.length() ){
end_index = payload.length();
}
//DEBUG std::cout<<"Payload length ="<< payload.length()<<endl<<"Payload=\n"<<payload<<endl;
//DEBUG std::cout<<"\nMessage #"<<i<<"Startindex "<< start_index <<" End index"<<end_index <<endl;
string payload_2_send = payload.substr(start_index, end_index - start_index );
string message = encode_ais_message_6(123456789,123456789, i, payload_2_send);
//DEBUG std::cout<<"\nMessage #"<<i<<"Startindex "<< start_index <<" End index"<<end_index<<endl<<message<<"\npayload:"<<payload_2_send<<endl;
start_index = end_index;
auto start = std::chrono::high_resolution_clock::now();
int res = sendmessage(message);
if (res != 0)
{
printf("Message not sent over socket....Exiting!\n");
return res;
}
start = std::chrono::high_resolution_clock::now();
read_ais(fd1, ais, message_count);
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Sending/Receiving of auth tag packet#"+to_string(i), microseconds);
message_count++;
}
//DEBUG printf("\nsequence: %d", ais[0].d.sequence );
//DEBUG printf("\nAIS Payload: %s\n", ais[0].d.payload_buffer );
string received_auth_tag = "";
for (int i=0; i<message_count; i++){
received_auth_tag += (string) ais[i].d.payload_buffer;
}
//DEBUG cout<<"\nReceived received_auth_tag:"<<received_auth_tag<<endl;
received_auth_tag = bintohex(received_auth_tag);
cout<<"\n Received received_auth_tag:"<<received_auth_tag<<endl;
OCT_fromHex(&Ship_2->rcvd_auth_tag, (char *)received_auth_tag.data() );
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Complete time for preprocessing/sending/receiving auth tag ", microseconds);
return 0;
}
int Secure_AIS_protocol(csprng *RNG, int fd1, bool generate_keys = GEN_KEYS)
{
int res, MMSI = 123456789;
//Variables to store Public/private keys of certificate authority
char cPr0[field_size_EGS], cPb0[2 * field_size_EFS + 1];
octet CAprivate = {0, sizeof(cPr0), cPr0};
octet CApublic = {0, sizeof(cPb0), cPb0};
//Variables to store ship data
ship_state_t Ship_1, Ship_2;
if (generate_keys){
printf("\nGenerating keys\n");
//Generation of Random keys for Certificate Authority
ECP_KEY_PAIR_GENERATE(RNG, &CAprivate, &CApublic);
res = ECP_PUBLIC_KEY_VALIDATE(&CApublic);
if (res != 0)
{
printf("ECP Public Key is invalid!\n");
return 0;
}
printf("\nCertificate Authority private key= 0x");
OCT_output(&CAprivate);
printf("Certificate Authority public key= 0x");
OCT_output(&CApublic);
//Generation of Random keys for Ship 1
ECP_KEY_PAIR_GENERATE(RNG, &Ship_1.private_key, &Ship_1.public_key);
res = ECP_PUBLIC_KEY_VALIDATE(&Ship_1.public_key);
if (res != 0)
{
printf("ECP Public Key is invalid!\n");
return res;
}
//Generation of ECQV certificate for Ship 1
res = genECQVCert(RNG, &Ship_1, &CAprivate, &CApublic, MMSI);
if (res != 0)
{
printf("ECQV certificate is invalid!\n");
return res;
}
printf("\nCertificate of Ship 1: ");
OCT_output(&Ship_1.ECQVCert);
printf("\nPrivate key data oct Ship 1: ");
OCT_output(&Ship_1.r_private_key);
//Generation of Random keys for ship 2
ECP_KEY_PAIR_GENERATE(RNG, &Ship_2.private_key, &Ship_2.public_key);
res = ECP_PUBLIC_KEY_VALIDATE(&Ship_2.public_key);
if (res != 0)
{
printf("ECP Public Key is invalid!\n");
return 0;
}
//Generation of ECQV certificate for Ship 2
res = genECQVCert(RNG, &Ship_2, &CAprivate, &CApublic, MMSI);
if (res != 0)
{
printf("ECQV certificate is invalid!\n");
return -1;
}
printf("\nCertificate of Ship 2: ");
OCT_output(&Ship_2.ECQVCert);
printf("\nPrivate key data oct Ship 2: ");
OCT_output(&Ship_2.r_private_key);
}else{
printf("\n Using precompute keys\n");
//Using precompute keys
precompute_key_data_t key_pairs;
setup_keys(key_pairs);
//keys for Certificate Authority
OCT_fromHex(&CAprivate, key_pairs.CAprivate );
OCT_fromHex(&CApublic, key_pairs.CApublic );
//keys for Ship 1
OCT_fromHex(&Ship_1.ECQVCert, key_pairs.Ship_1_ECQVCert );
OCT_fromHex(&Ship_1.r_private_key, key_pairs.Ship_1_r_private_key );
// keys for Ship 2
OCT_fromHex(&Ship_2.ECQVCert, key_pairs.Ship_2_ECQVCert );
OCT_fromHex(&Ship_2.r_private_key, key_pairs.Ship_2_r_private_key );
}
auto start = std::chrono::high_resolution_clock::now();
//Send ECQV certificate over the wire
send_ais_certificate(&Ship_1, &Ship_2, &CApublic, fd1);
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Total time for first protocol exchange from Ship 1 to Ship 2", microseconds);
printf("Certificate of Ship1 received by Ship 2: \n");
OCT_output(&Ship_2.recvd_cert);
printf("Public key extract by Ship2 received from Ship 1 : \n");
OCT_output(&Ship_2.recvd_public_key);
//Do same thing for ship 2
printf("\nShip 2 starting process\n");
//Send ECQV certificate over the wire
printf("\nSending ECQV Ship 2\n");
start = std::chrono::high_resolution_clock::now();
send_ais_certificate(&Ship_2, &Ship_1, &CApublic, fd1);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Total time for second protocol exchange from Ship 2 to Ship 1", microseconds);
printf("Public key extract by Ship1 received from Ship 2: \n");
OCT_output(&Ship_1.recvd_public_key);
if(SECURITY_LEVEL != 0){
// Calculate common key using DH - IEEE 1363 method
auto start = std::chrono::high_resolution_clock::now();
ECP_SVDP_DH(&Ship_1.r_private_key, &Ship_1.recvd_public_key, &Ship_1.DH_shared_key);
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of DH key on Ship 1", microseconds);
start = std::chrono::high_resolution_clock::now();
ECP_SVDP_DH(&Ship_2.r_private_key, &Ship_2.recvd_public_key, &Ship_2.DH_shared_key);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of DH key on Ship 2", microseconds);
printf("\n DH Ship 1: ");
OCT_output(&Ship_1.DH_shared_key);
printf("\n DH Ship 2: ");
OCT_output(&Ship_2.DH_shared_key);
if (!OCT_comp(&Ship_1.DH_shared_key, &Ship_2.DH_shared_key))
{
printf("*** ECPSVDP-DH Failed\n");
return -1;
}
//Generate preliminary session key
start = std::chrono::high_resolution_clock::now();
KDF2(MC_SHA2, SHA256, &Ship_1.session_key, AESKEY, &Ship_1.DH_shared_key, NULL);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of preliminary session key on Ship 1", microseconds);
start = std::chrono::high_resolution_clock::now();
KDF2(MC_SHA2, SHA256, &Ship_2.session_key, AESKEY, &Ship_2.DH_shared_key, NULL);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of preliminary session key on Ship 2", microseconds);
printf("\nShip 1's preliminary session Key= 0x");
OCT_output(&Ship_1.session_key);
printf("\nShip 2's preliminary session Key= 0x");
OCT_output(&Ship_2.session_key);
}
//Auth tag
printf("\nShip 1 Sending AIS Auth tag");
send_ais_auth_tag(&Ship_1, &Ship_2, 1, fd1);
printf("\nShip 2 Sending AIS Auth tag");
send_ais_auth_tag(&Ship_2, &Ship_1, 2, fd1);
if(SECURITY_LEVEL != 0){
auto start = std::chrono::high_resolution_clock::now();
if (!OCT_comp(&Ship_1.rcvd_auth_tag, &Ship_2.rcvd_auth_tag))
{
printf("*** Auth tag exchanged Failed\n");
return -1;
}
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Verify auth tag", microseconds);
//Generate link session key
start = std::chrono::high_resolution_clock::now();
OCT_jstring(&Ship_1.session_key, (char *)Ship_1.nonce.data() );
OCT_jstring(&Ship_1.session_key, (char *)Ship_1.received_nonce.data() );
KDF2(MC_SHA2, SHA256, &Ship_1.l_session_key, AESKEY, &Ship_1.session_key, NULL);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of link session key on Ship 1", microseconds);
start = std::chrono::high_resolution_clock::now();
OCT_jstring(&Ship_2.session_key, (char *)Ship_2.received_nonce.data() );
OCT_jstring(&Ship_2.session_key, (char *)Ship_2.nonce.data() );
KDF2(MC_SHA2, SHA256, &Ship_2.l_session_key, AESKEY, &Ship_2.session_key, NULL);
microseconds = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::high_resolution_clock::now() - start).count();
test2_write_message("Generation of link session key on Ship 2", microseconds);
if (!OCT_comp(&Ship_1.l_session_key, &Ship_2.l_session_key))
{
printf("*** Failed: Link session key generation do not match!\n");
return -1;
}
printf("\nShip 1's Link Key= 0x");
OCT_output(&Ship_1.l_session_key);
printf("\nShip 2's Link Key= 0x");
OCT_output(&Ship_2.l_session_key);
}
return 0;
}
void test1(csprng *RNG, int fd1){
//Test1 is getting 10 readings for each security level
int i=0, number_of_reps = 10;
ofstream outfile;
outfile.open("test_1.csv", ios::out | ios::app );
while( i<number_of_reps ){
auto start = std::chrono::high_resolution_clock::now();
int res = Secure_AIS_protocol(RNG, fd1);
if (res != 0){
//Failed, try again
continue;
}
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
printf("\nTime taken for exchange: %lld microseconds\n\n", microseconds);
if(i==0){
string header="";
if (SECURITY_LEVEL == 0)
header="No security";
else if (SECURITY_LEVEL == 1)
header="80 bits";
else if (SECURITY_LEVEL == 2)
header="128 bits";
else if (SECURITY_LEVEL == 3)
header="192 bits";
else if (SECURITY_LEVEL == 4)
header="256 bits";
outfile << header << ", ";
}
// write inputted data into the file.
if (i!=(number_of_reps-1)){
outfile << microseconds << ", ";
}else{
outfile << microseconds << endl;
}
i++;
sleep(1);
}
// close the opened file.
outfile.close();
}
int main()
{
int i,fd1;
unsigned long ran;
time((time_t *)&ran);
char raw[100];
octet RAW = {0, sizeof(raw), raw};
csprng RNG; // Crypto Strong RNG
RAW.len = 100; // fake random seed source
RAW.val[0] = ran;
RAW.val[1] = ran >> 8;
RAW.val[2] = ran >> 16;
RAW.val[3] = ran >> 24;
for (i = 4; i < 100; i++) RAW.val[i] = i;
CREATE_CSPRNG(&RNG, &RAW); // initialise strong RNG
printf("\nStarting SecureAIS protocol \n");
do {
sleep(1);
fd1 = socket_init(PORT_RECEIVE);
}while(fd1 == -1);
printf("Connected to receive socket!\n");
if(TEST==1 ){
test1(&RNG, fd1);
}
else{
auto start = std::chrono::high_resolution_clock::now();
Secure_AIS_protocol(&RNG, fd1);
auto elapsed = std::chrono::high_resolution_clock::now() - start;
long long microseconds = std::chrono::duration_cast<std::chrono::microseconds>(elapsed).count();
printf("\nTime taken for exchange: %lld microseconds\n\n", microseconds);
test2_write_message("Total time taken by protocol for exchange", microseconds);
}
KILL_CSPRNG(&RNG);
}
|
[
"crilabhbku@gmail.com"
] |
crilabhbku@gmail.com
|
27432c6fc66843527454e4ad982b9385c1dcec37
|
303eede865fa5d517dab4674167211a7dc47faf5
|
/engine.cpp
|
688fd52b6227352d5b22fef82f1662c417f4355a
|
[
"CC-BY-4.0"
] |
permissive
|
andras-szabo/brick-by-brick
|
3ceb0712db2474a19955025fd8f2c4ce60b084f8
|
271fcf9296ea6787465f4ed870f5c021f194c57e
|
refs/heads/master
| 2021-01-01T15:31:17.661237
| 2014-06-26T09:56:01
| 2014-06-26T09:56:01
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,389
|
cpp
|
#include "engine.h"
#include "introState.h"
#include "menuState.h"
#include "gameState.h"
#include "pauseState.h"
#include "controlState.h"
#include "messageState.h"
#include "ResourcePath.hpp"
#include <fstream>
cEngine::cEngine()
{
mWindow.create(sf::VideoMode(gkWindowSize.x, gkWindowSize.y), " Brick by brick " + gkVersion);
mWindow.setVerticalSyncEnabled(true);
mWindow.setKeyRepeatEnabled(false);
mFontHolder.load(FontID::GBFont, "Super-Mario-Land-Game-Boy.ttf");
mTextureHolder.load(TexID::introScreen, "sisu_splash.png");
mTextureHolder.load(TexID::gameBoyTex, "gbttrs.png");
mView.setSize(gkViewSize.x, gkViewSize.y);
mView.setCenter(gkViewSize.x / 2, gkViewSize.y / 2);
mView.setViewport(sf::FloatRect(0,0,1,1));
mWindow.setView(mView);
// Set up key bindings
std::map<sf::Keyboard::Key, Move> kb;
kb[sf::Keyboard::Key::Left] = Move::moveLeft;
kb[sf::Keyboard::Key::Right] = Move::moveRight;
kb[sf::Keyboard::Key::Up] = Move::rotateRight;
kb[sf::Keyboard::Key::RShift] = Move::rotateLeft;
kb[sf::Keyboard::Key::Down] = Move::fall;
mKeyBindings.push_back(kb);
kb.clear();
kb[sf::Keyboard::Key::H] = Move::moveLeft;
kb[sf::Keyboard::Key::L] = Move::moveRight;
kb[sf::Keyboard::Key::K] = Move::rotateRight;
kb[sf::Keyboard::Key::Space] = Move::rotateLeft;
kb[sf::Keyboard::Key::J] = Move::fall;
mKeyBindings.push_back(kb);
kb.clear();
kb[sf::Keyboard::Key::A] = Move::moveLeft;
kb[sf::Keyboard::Key::D] = Move::moveRight;
kb[sf::Keyboard::Key::Space] = Move::rotateRight;
kb[sf::Keyboard::Key::W] = Move::rotateLeft;
kb[sf::Keyboard::Key::S] = Move::fall;
mKeyBindings.push_back(kb);
// Load hi scores
std::ifstream in { resourcePath() + "hiscore.dat" };
if ( in.fail() )
{
// No hiscore file just yet, so let's create it
in.close();
mHiScores[100] = "Fran";
mHiScores[200] = "Liam";
mHiScores[400] = "Noel";
mHiScores[600] = "Alex";
mHiScores[800] = "Ringo";
mHiScores[1000] = "George";
mHiScores[1200] = "Paul";
mHiScores[1400] = "John";
std::ofstream out { resourcePath() + "hiscore.dat" };
for ( const auto& i : mHiScores )
{
out << i.first << i.second << "\n";
}
out.close();
} else // hiScore file found
{
mHiScores.clear();
unsigned int utmp;
std::string stmp;
while ( in >> utmp >> stmp )
{
mHiScores[utmp] = stmp;
}
in.close();
}
mLowestHiScore = std::begin(mHiScores)->first; // That's all you have to beat
// to make it onto the hall of fame :)
}
void cEngine::addHiScore(unsigned int score, const std::string& name)
{
mHiScores[score] = name;
mHiScores.erase(std::begin(mHiScores)); // When adding new hiscore, remove previous lowest
std::ofstream out { resourcePath() + "hiscore.dat" };
for ( const auto& i : mHiScores )
{
out << i.first << i.second << "\n";
}
out.close();
}
template <typename T>
void cEngine::launchState()
{
// Create new state ( initializing through constructor to which "*this,"
// i.e. ref to the engine, is passed.
std::unique_ptr<cState> p { new T { *this } };
p->init();
mStateStack.push_back(std::move(p));
}
void cEngine::request(SAID action, const std::string& s)
{
if ( mCurrentStackAction == SAID::nothing )
{
mCurrentStackAction = action;
mStackParam = s;
}
}
void cEngine::executeStackChanges()
{
// Parameters expected in mCurrentStackAction and mStackParam
switch ( mCurrentStackAction ) {
case SAID::pop:
{
popState();
break;
}
case SAID::push:
{
pushState(mStackParam);
break;
}
case SAID::swap:
{
swapState(mStackParam);
break;
}
case SAID::returnTo:
{
returnToState(mStackParam);
break;
}
case SAID::clear:
{
clearStateStack();
break;
}
default: break;
}
// Reset stack requests:
mCurrentStackAction = SAID::nothing;
}
void cEngine::pushState(const std::string& s)
{
if ( !mStateStack.empty() ) ( *mStateStack.rbegin())->deactivate();
if ( s == "mainMenu" ) launchState<cMenuState>();
if ( s == "game" ) launchState<cGameState>();
if ( s == "pause" ) launchState<cPauseState>();
if ( s == "controlMenu" ) launchState<cControlState>();
if ( s == "hiScore" ) { mStrParam = "__HISCORES__"; launchState<cMessageState>(); }
if ( s == "gameOver" ) { mStrParam = "__GAMEOVER__"; launchState<cMessageState>(); }
}
void cEngine::popState()
{
if ( mStateStack.empty() ) return;
// If state stack not empty: clean up after state that's being popped,
// then simply pop it. mStateStack is a vector of unique_ptrs, so
// no need to worry about memory leaks.
(*mStateStack.rbegin())->cleanup();
mStateStack.pop_back();
if ( !mStateStack.empty() )
(*mStateStack.rbegin())->reset();
}
void cEngine::swapState(const std::string& s)
{
// Pops the current state and pushes onto the stack a new one to
// replace it.
popState();
if ( !mStateStack.empty() ) (*mStateStack.rbegin())->deactivate();
pushState(s);
}
void cEngine::returnToState(const std::string& s)
{
// Pop states until finding requested one. If no such state,
// this will terminate the program.
while (!mStateStack.empty() && (*mStateStack.rbegin())->mName != s )
popState();
}
void cEngine::clearStateStack()
{
// Clear state stack: terminate program
while ( !mStateStack.empty() )
popState();
}
void cEngine::run()
{
launchState<cIntroState>();
// Main loop
while ( !mStateStack.empty() )
{
mWindow.clear();
for ( const auto& i : mStateStack )
i->render();
mWindow.display();
(*mStateStack.rbegin())->run();
executeStackChanges();
}
}
|
[
"andras.szabo.fin@gmail.com"
] |
andras.szabo.fin@gmail.com
|
b39b9827bc29280e3c0d0715a372181b32657d2c
|
a994c13785b94adf85e725fccf620eb6396238f4
|
/practice/20181003/2103.cc
|
a48907494b0cadad628f7d3db1910c7c9a434dd4
|
[] |
no_license
|
vijaybnotion/DSnP_textbook
|
4f0f8b9cab4916cd90fdcf7adcde0e74a18a5790
|
4872bf446cd336fa31ac323a34d9fa2d60311dd2
|
refs/heads/master
| 2023-03-27T02:12:04.310413
| 2019-01-13T13:13:45
| 2019-01-13T13:13:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 237
|
cc
|
#include <iostream>
using namespace std;
void f( const int * ptr ){
cout << "inside f()" << endl;
cout << ptr;
}
int main(){
int ptr[] = {3,1,4,1,5};
cout << "inside main: ptr = " << &ptr << endl;
f( ptr );
return 0;
}
|
[
"a58524andy@gmail.com"
] |
a58524andy@gmail.com
|
33f0a9d73dedde95f85b4068ddc8ffb6b001cb1f
|
3a578cc42c4b740f15bc594dbaaa31bb9d87c947
|
/contrib/devtools/syscoin-tidy/syscoin-tidy.cpp
|
7dbd7634f0bf907a40375066d5e47e28193c0ebf
|
[
"MIT",
"LicenseRef-scancode-public-domain"
] |
permissive
|
syscoin/syscoin
|
7dded55aaf33a454bf1be1e80cb89b60f4fe5409
|
310151bd2e4860375de146c0568293559ad8b459
|
refs/heads/master
| 2023-08-17T06:35:29.025512
| 2023-08-16T11:57:03
| 2023-08-17T01:25:08
| 52,762,278
| 144
| 90
|
MIT
| 2023-09-08T17:52:13
| 2016-02-29T03:47:32
|
C++
|
UTF-8
|
C++
| false
| false
| 729
|
cpp
|
// Copyright (c) 2023 Bitcoin Developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "logprintf.h"
#include <clang-tidy/ClangTidyModule.h>
#include <clang-tidy/ClangTidyModuleRegistry.h>
class SyscoinModule final : public clang::tidy::ClangTidyModule
{
public:
void addCheckFactories(clang::tidy::ClangTidyCheckFactories& CheckFactories) override
{
CheckFactories.registerCheck<syscoin::LogPrintfCheck>("syscoin-unterminated-logprintf");
}
};
static clang::tidy::ClangTidyModuleRegistry::Add<SyscoinModule>
X("syscoin-module", "Adds syscoin checks.");
volatile int SyscoinModuleAnchorSource = 0;
|
[
"sidhujag@syscoin.org"
] |
sidhujag@syscoin.org
|
98edec6bf509a33f8a25ab4d4d30aae113c3327e
|
02a471403eb0d6d13edac3dbcd985e6fca467b23
|
/AutoWeight.cpp
|
56577fa1a4c1cbb93f28cdc7a362e0ee564e9125
|
[] |
no_license
|
qiuri2008/repoCkd
|
d2786dcb2357ca227bba350b91465b7f9ddcb1f4
|
c34ea043053b5dfc541bf410ccde85c2c2f90785
|
refs/heads/master
| 2021-05-11T11:48:04.567837
| 2018-01-16T07:14:18
| 2018-01-16T07:14:18
| 117,645,548
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 28,723
|
cpp
|
// AutoWeight.cpp : implementation file
//
#include "stdafx.h"
#include "CKD录入.h"
#include "PageCkd.h"
#include <bitset>
#include "Global.h"
#include <afxtempl.h>
#include "excel2003.h"
#include "user.h"
#include "PropSheet.h"
#include "SaveDlg.h"
#include "AutoWeight.h"
#include ".\autoweight.h"
#define TEST_AUTOWEIGHT 0 //打开 会忽略未称 重量
using std::bitset;
bitset<3> g_bitPallet;
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CAutoWeight property page
IMPLEMENT_DYNCREATE(CAutoWeight, CPropertyPage)
CAutoWeight::CAutoWeight() : CPropertyPage(CAutoWeight::IDD)
{
//{{AFX_DATA_INIT(CAutoWeight)
m_csPallet = _T("");
m_csOutBox = _T("");
m_csReceive = _T("");
m_strZCS = _T("");
m_srtPalletWeight = _T("托盘重量");
m_strOutBoxWeight = _T("");
//}}AFX_DATA_INIT
m_listInit = false;
m_dPalletWeight = 0;
}
CAutoWeight::~CAutoWeight()
{
}
void CAutoWeight::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CAutoWeight)
DDX_Control(pDX, IDC_LIST2, m_ListMain);
DDX_Text(pDX, IDC_EDIT1_BIGBOX, m_csPallet);
DDX_Text(pDX, IDC_EDIT1_OUTBOX, m_csOutBox);
DDX_Text(pDX, IDC_EDIT1_RECEIVE, m_csReceive);
DDX_Text(pDX, IDC_EDIT1_ZCS, m_strZCS);
DDX_Text(pDX, IDC_STATIC_1, m_srtPalletWeight);
DDX_Text(pDX, IDC_EDIT_OUTBOX_WEIGHT, m_strOutBoxWeight);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CAutoWeight, CPropertyPage)
//{{AFX_MSG_MAP(CAutoWeight)
ON_BN_CLICKED(IDC_BTN_LOAD, OnBtnLoadWeightList)
ON_WM_CTLCOLOR()
ON_BN_CLICKED(IDC_BTN1_SAVE, OnBtnSave)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CAutoWeight message handlers
BOOL CAutoWeight::OnSetActive()
{
// TODO: Add your specialized code here and/or call the base class
CPropSheet* pParent = (CPropSheet*) GetParent();
CPageShipMark* prop1 = (CPageShipMark*)pParent->GetPage(pParent->GetPageCount()-1);
g_flgSpeak = prop1->m_bSpeak;
DWORD dwStyle;
if(!m_listInit)
{
dwStyle=m_ListMain.GetExtendedStyle();
dwStyle|=LVS_EX_FULLROWSELECT;
dwStyle|=LVS_EX_GRIDLINES;
(void)m_ListMain.SetExtendedStyle( dwStyle );///整行选择模式//LVS_EX_FULLROWSELECT
m_ListMain.SetHeadings("序号,100;托盘,60;外箱,60;内箱,60;重量,80"); ///设置列头信息
m_ListMain.LoadColumnInfo();
m_listInit = true;
}
//=================================================
//=== 不同模块交替使用时,要重新加载数据===========
else if(m_flgTaojian == TRUE && !m_strZCS.IsEmpty())
ReloadData();
//=================================================
return CPropertyPage::OnSetActive();
}
BOOL CAutoWeight::PreTranslateMessage(MSG* pMsg)
{
// TODO: Add your specialized code here and/or call the base class
CString cs, cs1;
if(pMsg->message == WM_KEYDOWN)
{
if(pMsg->wParam == VK_RETURN)
{
UINT nID = GetFocus()->GetDlgCtrlID();
switch(nID)
{
case IDC_EDIT1_ZCS:
ReloadData();
return true;
break;
case IDC_EDIT1_RECEIVE:
UpdateData(TRUE);
m_csReceive.MakeUpper();
if(g_ttsCreate)
tts.Pause();
if(!m_flgTaojian)
{
MessageBox1("没有指定套件,请先指定套件号!","错误", MB_ICONERROR);
m_csReceive.Empty();
UpdateData(false);
return true;
}
// 录入-托盘
if(m_csReceive.Find('<') != -1 && m_csReceive.Find('>') != -1)
{
CString cs1,csTemp;
csTemp = m_csReceive.Mid(m_csReceive.Find('<')+1,m_csReceive.Find('>')-m_csReceive.Find('<')-1);
if(!m_csPallet.IsEmpty() && m_csPallet != csTemp)
{
//MessageBox1("托盘已变更为" + csTemp,"托盘变更提示",MB_ICONINFORMATION);
//if(MessageBox("托盘已变更为" + csTemp + ",请确认?","托盘变更提示",MB_OKCANCEL) == IDOK)
//{
m_csPallet = csTemp;
g_bitPallet.set(STYLE_PALLET);
m_csReceive.Empty();
m_dPalletWeight = PalletWeight(m_csPallet);
m_srtPalletWeight.Format("%.2f",m_dPalletWeight);
UpdateData(false);
MessageBox1("托盘确认变更为" + csTemp + "," + m_srtPalletWeight + "公斤开始录入","托盘变更",MB_ICONINFORMATION);
return true;
//}
//else
//{
//MessageBox1("取消变更托盘," + m_csPallet + "继续录入","托盘变更",MB_ICONINFORMATION);
//return true;
//}
}
else
m_csPallet = csTemp;
g_bitPallet.set(STYLE_PALLET);
m_csReceive.Empty();
m_dPalletWeight = PalletWeight(m_csPallet);
m_srtPalletWeight.Format("%.2f",m_dPalletWeight);
if(m_dPalletWeight)
MessageBox1("托盘" + m_csPallet + "," + m_srtPalletWeight + "公斤继续录入","托盘",MB_ICONINFORMATION);
else
MessageBox1("托盘" + m_csPallet + "开始录入","托盘",MB_ICONINFORMATION);
UpdateData(false);
}
// 录入-外箱
else if(m_csReceive.Find('{') != -1 && m_csReceive.Find('}') != -1)
{
CString csPallet, csWeight;
int count = 0;
m_csOutBox = m_csReceive.Mid(m_csReceive.Find('{')+1,m_csReceive.Find('}')-m_csReceive.Find('{')-1);
g_bitPallet.set(STYLE_PALLET_OUTBOX);
if(!mapOutBox.Lookup(m_csOutBox,count))
{
MessageBox1(m_csOutBox+"不存于"+m_strZCS + "的套件中","外箱检查",MB_ICONINFORMATION);
return true;
}
if(g_bitPallet.count() == STYLE_PALLET_END)
{
double dOutBoxWeight = 0;
if(mapOutboxPallet.Lookup(m_csOutBox,csPallet))
{
if(csPallet == m_csPallet)
{
mapOutboxPallet.RemoveKey(m_csOutBox);
//GetOutBoxWeight 将托盘号更新到 mapInBox
dOutBoxWeight = GetOutBoxWeight(m_csOutBox,csPallet,false);
m_dPalletWeight -= dOutBoxWeight;
csWeight.Format("删除%g公斤",dOutBoxWeight);
}
else
MessageBox1("不能删除外箱" + m_csOutBox + "存在于" + csPallet +"托盘中","外箱检查",MB_ICONINFORMATION);
}
else
{
mapOutboxPallet.SetAt(m_csOutBox, m_csPallet);
//GetOutBoxWeight 将托盘号更新到 mapInBox
dOutBoxWeight = GetOutBoxWeight(m_csOutBox,m_csPallet,true);
m_dPalletWeight += dOutBoxWeight;
csWeight.Format("添加%g公斤",dOutBoxWeight);
}
m_csReceive.Empty();
m_srtPalletWeight.Format("%.2fKg",m_dPalletWeight);
m_strOutBoxWeight.Format("%g",dOutBoxWeight);
UpdateData(false);
MessageBox1(csWeight, "外箱录入", MB_ICONINFORMATION);
UpdateList();
}
else if(!g_bitPallet[STYLE_PALLET])
{
g_bitPallet.reset();
m_csPallet.Empty(); m_csOutBox.Empty();
MessageBox1("托盘未录入,请先录入托盘!","托盘未录入",MB_ICONERROR);
}
}
return true;
break;
default:
{
CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT1_RECEIVE);
pEdit->SetFocus();
}
return true;
break;
}
}
}
return CPropertyPage::PreTranslateMessage(pMsg);
}
void CAutoWeight::UpdateList()
{
CString strKey,cs1;
m_ListMain.DeleteAllItems();
m_LayerList.RemoveAll();
g_iReOrder = 0;
POSITION pos = mapInBox.GetStartPosition();
CLayers cValue;
while(pos)
{
mapInBox.GetNextAssoc(pos, strKey, cValue);
if(!cValue.strPallet.IsEmpty())
{
g_iReOrder++;
cs1.Format("%g", cValue.iQty*cValue.iUnitWeight*cValue.iRadio);
m_ListMain.AddItem(cValue.strOrder, cValue.strPallet,cValue.strOutBox, strKey, cs1);
}
//生成保存清单容器
CLayers* pLayersItem = new CLayers(cValue);
m_LayerList.AddTail(pLayersItem);
}
m_ListMain.Sort(0,true);
m_ListMain.EnsureVisible(g_iReOrder-1,TRUE);
CPropSheet* pParent = (CPropSheet*) GetParent();
CPageShipMark* prop1 = (CPageShipMark*)pParent->GetPage(pParent->GetPageCount()-1);
//保存内箱总清单
CFile file;
CString strFileName = CExcel::GetAppPath() + "\\Record List\\" + m_strZCS + ".ckd";
file.Open(strFileName, CFile::modeCreate|CFile::modeReadWrite);
CArchive ar(&file, CArchive::store);
ar<<prop1->m_cs11<<prop1->m_cs12<<prop1->m_cs13<<prop1->m_cs14
<<prop1->m_cs21<<prop1->m_cs22<<prop1->m_cs23<<prop1->m_cs24
<<prop1->m_cs31<<prop1->m_cs32<<prop1->m_cs33<<prop1->m_cs34;
m_LayerList.Serialize(ar);
ar.Close();
file.Close();
//保存“外箱-托盘”清单
if(mapOutboxPallet.GetSize() == 0)
return;
strFileName = CExcel::GetAppPath() + "\\Record List\\" + m_strZCS + "_PalletList" + ".ckd";
file.Open(strFileName, CFile::modeCreate|CFile::modeReadWrite);
CArchive ar1(&file, CArchive::store);
mapOutboxPallet.Serialize(ar1);
ar1.Close();
file.Close();
}
double CAutoWeight::GetOutBoxWeight(CString strOutbox,CString strPallet, bool bAddFlag)
{
POSITION pos = mapInBox.GetStartPosition();
CString strinbox;
CLayers cValue;
double outBoxWeight = 0;
/////////////////////////////////////////////////////////////////
//检索某个外箱的所有内箱 并计算整个外箱的重量
while(pos)
{
mapInBox.GetNextAssoc(pos, strinbox, cValue);
if(strOutbox == cValue.strOutBox)
{
outBoxWeight += cValue.iQty*cValue.iUnitWeight*cValue.iRadio;
if(cValue.strPallet == "" && bAddFlag)
{
cValue.strPallet = strPallet;
CTime tm = CTime::GetCurrentTime();
CString strTime = tm.Format("%m-%d %X");
cValue.strOrder = strTime;
mapInBox.SetAt(strinbox, cValue);
}
else if(cValue.strPallet != "" && bAddFlag == false)
{
cValue.strPallet = "";
mapInBox.SetAt(strinbox, cValue);
}
}
}
return outBoxWeight;
}
double CAutoWeight::PalletWeight(CString csPallet)
{
double palletWeight = 0;
CString strOutbox,strPallet;
/*
POSITION pos = mapOutboxPallet.GetStartPosition();
while(pos)
{
mapOutboxPallet.GetNextAssoc(pos, strOutbox, strPallet);
if(csPallet == strPallet)
palletWeight += GetOutBoxWeight(strOutbox);
}
*/
CLayers cValue;
CString strinbox;
POSITION pos = mapInBox.GetStartPosition();
while(pos)
{
mapInBox.GetNextAssoc(pos, strinbox, cValue);
if(csPallet == cValue.strPallet)
palletWeight += cValue.iQty*cValue.iUnitWeight*cValue.iRadio;
}
return palletWeight;
}
void CAutoWeight::OnBtnLoadWeightList()
{
// TODO: Add your control notification handler code here
CFileDialog dlg(true,"*.xls","",OFN_HIDEREADONLY,"Excel文件(*.xls)|*.xls");
//===========================================================
//打开特定目录
CString strFileName = CExcel::GetAppPath() + "\\托盘清单";
dlg.m_ofn.lpstrInitialDir = strFileName;
//===========================================================
if(dlg.DoModal()==IDOK)
g_strOpenFile=dlg.GetPathName();
if(g_strOpenFile.Find(".xls")<0) //没有读取则直接返回
return;
unsigned int i,j;
CString strCell, cs1, cs2;
CExcel Excel;
Excel.AddNewFile(g_strOpenFile); // 打开一个文件
Excel.SetVisible(false); // 设置可见
Excel.SelectSheet(1); // 激活工作簿1
m_usedRow = Excel.GetUsedRowCount();
m_usedCol = Excel.GetUsedColCount();
Excel.SelectSheet(1); // 重新设置RANGE
m_icolProductCnt = m_icolPart = m_irowPart = m_icolDetail = m_icolUserCode = m_icolWeight = m_icolRadio = m_icolUnitPrice =0;
m_flgCheck = false;
//////////////////////////////////////
//获取部品号 位号 描述 封装列位置
for(i=1;i<=m_usedRow;i++)
{
for(j=1;j<=m_usedCol;j++)
{
strCell = Excel.GetCell(i,j).bstrVal;
strCell = Excel.DeleteBlackSpace(strCell); //删除空格
char *pCell = (LPTSTR)(LPCTSTR)strCell;
if(strcmp(pCell,TOULIAO_LIST_PART) == 0)
{
m_icolPart = j;
m_irowPart = i;
}
else if(strcmp(pCell,TOULIAO_LIST_DETAIL) == 0)
{
m_icolDetail = j;
}
else if(strcmp(pCell,"序号") == 0)
{
m_icolNo = j;
}
else if(strcmp(pCell,"单位重量") == 0)
{
m_icolWeight = j;
}
else if(strcmp(pCell,"加乘系数") == 0)
{
m_icolRadio = j;
}
else if(strcmp(pCell,"单价") == 0)
{
m_icolUnitPrice = j;
}
if(m_icolPart && m_irowPart && m_icolDetail && m_icolNo && m_icolWeight && m_icolRadio && m_icolUnitPrice)
{
m_flgCheck = true;
break;
}
}
if(m_icolPart && m_irowPart && m_icolDetail && m_icolNo && m_icolWeight && m_icolRadio && m_icolUnitPrice)
{
m_flgCheck = true;
break;
}
}
/////////////////////////////////////////////////////
//检查
if(!m_flgCheck)
{
Excel.Save(true);
MessageBox("请导入正确的重量清单!!!", "错误", MB_ICONERROR);
return ;
}
CLayers ssk;
mapWeightList.RemoveAll();
/////////////////////////////////////////////////////
for(i=m_irowPart+1;i<=m_usedRow;i++)
{
strCell = Excel.GetCell(i,m_icolPart).bstrVal;
strCell = Excel.DeleteBlackSpace(strCell);
if(strCell.GetLength() >= 13)
{
///////////////////////////////////////////////////
//写入哈希表
strCell.MakeUpper();
ssk.strPartNo = strCell;
strCell = Excel.GetCell(i,m_icolDetail).bstrVal;
strCell.MakeUpper();
ssk.strDetail = strCell;
strCell = Excel.GetCell(i,m_icolNo ).bstrVal;
strCell.MakeUpper();
ssk.strNo = strCell;
//文件清单中单位是g,要转换为Kg
ssk.iUnitWeight = Excel.GetCellValueFloat(i,m_icolWeight)/1000;
ssk.iRadio = Excel.GetCellValueFloat(i,m_icolRadio);
ssk.iUnitPrice = Excel.GetCellValueFloat(i,m_icolUnitPrice);
mapWeightList.SetAt(ssk.strPartNo,ssk);
}
}
m_ListMain.DeleteAllItems();
m_LayerList.RemoveAll();
POSITION pos = mapWeightList.GetStartPosition();
CString strKey;
g_iOrder = 0;
while(pos)
{
g_iOrder++;
mapWeightList.GetNextAssoc(pos, strKey, ssk);
cs1.Format("%g", ssk.iUnitWeight);
cs2.Format("%g", ssk.iRadio);
m_ListMain.AddItem(ssk.strNo,strKey,cs1,cs2,"");
//生成保存清单容器
CLayers* pLayersItem = new CLayers(ssk);
m_LayerList.AddTail(pLayersItem);
}
m_ListMain.Sort(0,true);
m_ListMain.EnsureVisible(g_iOrder-1,TRUE);
//保存清单
CFile file;
strFileName = CExcel::GetAppPath() + "\\托盘清单\\" + "_WeightList" + ".ckd";
file.Open(strFileName, CFile::modeCreate|CFile::modeReadWrite);
CArchive ar(&file, CArchive::store);
m_LayerList.Serialize(ar);
ar.Close();
file.Close();
MessageBox1("重量清单载入成功!", "载入成功", MB_ICONINFORMATION);
}
HBRUSH CAutoWeight::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor)
{
HBRUSH hbr = CPropertyPage::OnCtlColor(pDC, pWnd, nCtlColor);
// TODO: Change any attributes of the DC here
CFont *f;
f = new CFont;
switch(pWnd->GetDlgCtrlID())
{
case IDC_EDIT_OUTBOX_WEIGHT:
//f->CreateFont(14,0,0,0,FW_SEMIBOLD,FALSE,FALSE,0,
//ANSI_CHARSET,OUT_DEFAULT_PRECIS,
//CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,
//DEFAULT_PITCH&FF_SWISS,"Arial");
//pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(RGB(255,0, 0));
//pDC->SelectObject(f);//设置字体
break;
case IDC_STATIC_LOOKUP:
f->CreateFont(16,0,0,0,FW_SEMIBOLD,FALSE,FALSE,0,
ANSI_CHARSET,OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,
DEFAULT_PITCH&FF_SWISS,"Arial");
pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(RGB(0,0, 255));
pDC->SelectObject(f);//设置字体
break;
case IDC_STATIC_1:
f->CreateFont(26,0,0,0,FW_SEMIBOLD,FALSE,FALSE,0,
ANSI_CHARSET,OUT_DEFAULT_PRECIS,
CLIP_DEFAULT_PRECIS,DEFAULT_QUALITY,
DEFAULT_PITCH&FF_SWISS,"Arial");
pDC->SetBkMode(TRANSPARENT);
pDC->SetTextColor(RGB(255,0, 0));
pDC->SelectObject(f);//设置字体
default :
break;
}
// TODO: Return a different brush if the default is not desired
return hbr;
}
template <typename T, typename U> void BubbleSort(T& collection, U element, int count, bool ascend = true)
{
for (int i = 0; i < count-1; i++)
for (int j = 0; j < count-1-i; j++)
if (ascend)
{
// 升序
if (collection[j] > collection[j+1])
{
U temp = collection[j];
collection[j] = collection[j+1];
collection[j+1] = temp;
}
}
else
{
// 降序
if (collection[j] < collection[j+1])
{
U temp = collection[j];
collection[j] = collection[j+1];
collection[j+1] = temp;
}
}
}
void CAutoWeight::SaveInvoiceDate(CExcel &Excel)
{
CString strCell;
Excel.SelectSheet(2); // 激活工作簿1
Excel.ActiveSheet().SetName("发票");
Excel.SetColWidth(1,14);
Excel.SetCell(1,1,"PO No.");
Excel.SetCell(1,2,"Item Code");
Excel.SetCell(1,3,"Item Description");
Excel.SetCell(1,4,"Kitking Code");
Excel.SetCell(1,5,"Name");
Excel.SetCell(1,6,"Quantity");
Excel.SetCell(1,7,"Unit Price");
Excel.SetCell(1,8,"Total Amount");
POSITION pos = mapInBox.GetStartPosition();
CString strKey;
CLayers cValue,cBase;
int i = 2;
CArrayClayer NoArray;
//================================================================
//按料号排序
while(pos)
{
mapInBox.GetNextAssoc(pos, strKey, cValue);
if(cValue.strPallet != "") //只有放进托盘的内箱才做发票
NoArray.Add(cValue);
}
g_OrderMode = ORDER_NO;
BubbleSort(NoArray, NoArray[0], NoArray.GetSize(), true);
//================================================================
unsigned int iBorder = 2;
for(int j=0; j<NoArray.GetSize();)
{
//===========================================
//检索相同部品号
unsigned int count = 1;
cValue = NoArray[j];
cValue.strOrder = cValue.strOrder.Left(5);
for(int k=j+1; k<NoArray.GetSize(); k++)
{
if(cValue.strNo == NoArray[k].strNo)
{
cValue.iQty += NoArray[k].iQty;
count++;
}
else
break;
}
j = j+count;
Excel.SetCell(i,2,cValue.strUserCode);
Excel.SetCell(i,3,cValue.strDetail);
Excel.SetCell(i,4,cValue.strPartNo);
Excel.SetCell(i,6,(long)cValue.iQty);
Excel.SetCell(i,7,cValue.iUnitPrice,6);
Excel.SetCell(i,8,cValue.iUnitPrice*cValue.iQty,6);
i++;
}
for(i=1;i<=8;i++)
Excel.SetColAutoFit(i);
}
void CAutoWeight::OnBtnSave()
{
// TODO: Add your control notification handler code here
if(!m_flgTaojian)
{
MessageBox1("没有指定套件,请先指定套件号!","错误", MB_ICONERROR);
return ;
}
if(mapInBox.GetCount() == 0)
{
MessageBox1("未录入任何数据,请先录入!","保存错误",MB_ICONERROR);
return ;
}
CFileDialog dlg(FALSE, "xls", "", OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT, "Excel文件(*.xls)|*.xls" );
//===========================================================
//保存到指定目录
CString strFileName = CExcel::GetAppPath() + "\\托盘清单";
dlg.m_ofn.lpstrInitialDir = strFileName;
//===========================================================
if(dlg.DoModal()==IDOK)
g_strSaveFile=dlg.GetPathName();
if(g_strSaveFile.Find(".xls")<0) //没有保存则直接返回
return;
CExcel Excel;
Excel.AddNewFile(); // 新建一个文件
Excel.SetVisible(FALSE); // 设置不可见
Excel.SelectSheet(1);
Excel.ActiveSheet().SetName("箱单");
Excel.SetColWidth(1,14);
Excel.SetCell(1,1,"SUPPLIER NAME");
Excel.SetCell(1,2,"P/T NO.");
CRange range(Excel.GetRange(1,3,1,4));
range.Merge();
range = "CTN NO.";
Excel.SelectSheet(1);
Excel.SetCell(1,5,"P/O NO.");
Excel.SetCell(1,6,"CODE NO.");
Excel.SetCell(1,7,"DESCRIPTION");
Excel.SetCell(1,8,"KITKING CODE");
Excel.SetCell(1,9,"Unit");
Excel.SetCell(1,10,"QTY");
Excel.SetCell(1,11,"N/wet(kg)");
Excel.SetCell(1,12,"G/wet(kg)");
POSITION pos = mapInBox.GetStartPosition();
CString strKey,csTemp;
CLayers cValue;
int i = 2;
int count = 0;
//double dPalletWeight = 0;
CArrayClayer palletArray;
mapPalletCnt.RemoveAll();
//================================================================
//按托盘号排序
while(pos)
{
mapInBox.GetNextAssoc(pos, strKey, cValue);
if(!cValue.strPallet.IsEmpty())
{
palletArray.Add(cValue);
if(mapPalletCnt.Lookup(cValue.strPallet,count))
mapPalletCnt.SetAt(cValue.strPallet, count+1);
else
mapPalletCnt.SetAt(cValue.strPallet, 1);
}
}
g_OrderMode = ORDER_PALLET;
BubbleSort(palletArray, palletArray[0], palletArray.GetSize(), true);
//================================================================
for(int j=0; j<palletArray.GetSize(); j++)
{
cValue = palletArray[j];
Excel.SetCell(i,2, cValue.strPallet);
Excel.SetCell(i,3, cValue.strOutBox);
if(cValue.strInBox.Find(INBOX_COMMON) != -1)
Excel.SetCell(i,4,INBOX_COMMON);
else
Excel.SetCell(i,4,cValue.strInBox);
Excel.SetCell(i,6,cValue.strUserCode);
Excel.SetCell(i,7,cValue.strDetail);
Excel.SetCell(i,8,cValue.strPartNo);
Excel.SetCell(i,10,(long)cValue.iQty);
Excel.SetCell(i,11,cValue.iQty*cValue.iUnitWeight*cValue.iRadio,2);
if(csTemp.IsEmpty())
csTemp = cValue.strPallet;
//==============================================================
//框选第N个托盘,并结算当前托盘重量
if(j == palletArray.GetSize()-1)
{
if(mapPalletCnt.Lookup(csTemp,count))
{
Excel.SetCell(i,12,(long)PalletWeight(cValue.strPallet));
CRange range(Excel.GetRange(i-count+1,1,i,12));
range.Border();
Excel.SelectSheet(1);
}
}
//=============================================================
//=============================================================
//框选第N-1个托盘,并计算当前托盘重量
if(csTemp != cValue.strPallet)
{
if(mapPalletCnt.Lookup(csTemp,count))
{
Excel.SetCell(i-1,12,(long)PalletWeight(csTemp));
CRange range(Excel.GetRange(i-count,1,i-1,12));
range.Border();
Excel.SelectSheet(1);
}
csTemp = cValue.strPallet;
}
//=============================================================
i++;
}
for(i=1;i<=12;i++)
Excel.SetColAutoFit(i);
SaveInvoiceDate(Excel);
Excel.SaveAs(g_strSaveFile);
MessageBox1("保存成功!", "保存成功", MB_ICONINFORMATION);
}
void CAutoWeight::ReloadData(void)
{
CString cs, cs1;
UpdateData(TRUE);
m_strZCS.MakeUpper();
mapInBox.RemoveAll();
mapOutBox.RemoveAll();
m_LayerList.RemoveAll();
mapPartCnt.RemoveAll();
mapWeightList.RemoveAll();
mapOutboxPallet.RemoveAll();
mapPalletCnt.RemoveAll();
CString strFileName = CExcel::GetAppPath() + "\\Record List\\" + m_strZCS + ".ckd";
if(IsFileExist(strFileName,FALSE)==TRUE)
{
//==============================================================================================
//载入录入清单 复活 mapInBox mapOutBox
m_ListMain.DeleteAllItems();
g_iOrder = 0;
CPropSheet* pParent = (CPropSheet*) GetParent();
CPageShipMark* prop1 = (CPageShipMark*)pParent->GetPage(pParent->GetPageCount()-1);
//序列化文件
CFile file;
file.Open(strFileName, CFile::modeReadWrite);
CArchive ar(&file, CArchive::load);
ar>>prop1->m_cs11>>prop1->m_cs12>>prop1->m_cs13>>prop1->m_cs14
>>prop1->m_cs21>>prop1->m_cs22>>prop1->m_cs23>>prop1->m_cs24
>>prop1->m_cs31>>prop1->m_cs32>>prop1->m_cs33>>prop1->m_cs34;
m_LayerList.Serialize(ar);
ar.Close();
file.Close();
POSITION pos = m_LayerList.GetHeadPosition();
while (pos != NULL)
{
CLayers* pLayer = m_LayerList.GetNext(pos);
int count = 0;
g_iOrder++;
//pLayer->strPallet = "";
mapInBox.SetAt(pLayer->strInBox, *pLayer);
if(mapOutBox.Lookup(pLayer->strOutBox,count))
mapOutBox.SetAt(pLayer->strOutBox, count+1);
else
mapOutBox.SetAt(pLayer->strOutBox, 1);
cs.Format("%d",pLayer->iQty);
m_ListMain.AddItem(pLayer->strOrder,pLayer->strPallet,pLayer->strOutBox,pLayer->strInBox,cs);
}
m_ListMain.Sort(0,true);
m_ListMain.EnsureVisible(g_iOrder-1,TRUE);
//MessageBox1("套件载入成功!");
//return true;
//==================================================================================================
//==================================================================================================
//载入重量清单 复活 mapWeightList
//郇工测量的重量清单,部品号作为关键键,重量单位为“g”
strFileName = CExcel::GetAppPath() + "\\托盘清单\\" + "_WeightList" + ".ckd";
if(IsFileExist(strFileName,FALSE)==TRUE)
{
mapWeightList.RemoveAll();
m_LayerList.RemoveAll();
m_ListMain.DeleteAllItems();
g_iOrder = 0;
//序列化文件
CFile file;
file.Open(strFileName, CFile::modeReadWrite);
CArchive ar(&file, CArchive::load);
m_LayerList.Serialize(ar);
ar.Close();
file.Close();
pos = m_LayerList.GetHeadPosition();
while (pos != NULL)
{
g_iOrder++;
CLayers* pLayer = m_LayerList.GetNext(pos);
mapWeightList.SetAt(pLayer->strPartNo, *pLayer);
cs.Format("%g", pLayer->iUnitWeight);
cs1.Format("%g", pLayer->iRadio);
m_ListMain.AddItem(pLayer->strNo,pLayer->strPartNo,cs,cs1,"");
}
m_ListMain.Sort(0,true);
m_ListMain.EnsureVisible(g_iOrder-1,TRUE);
//MessageBox1("套件载入成功,重量清单载入成功!", "载入成功", MB_ICONINFORMATION);
}
else
{
MessageBox1("套件载入成功,重量清单未载入!", "载入", MB_ICONINFORMATION);
m_strZCS.Empty();
UpdateData(false);
return ;
}
//==================================================================================================
m_ListMain.DeleteAllItems();
pos = mapInBox.GetStartPosition();
CString strInBox;
CLayers cV, cBase;
g_iOrder = 0;
CMapInBox mapLossWeight;
BOOL bLossFlag = false;
while(pos)
{
// 完善记录表 mapInBox 缺失的 [单位重量] [加乘系数]以及[单价]
mapInBox.GetNextAssoc(pos, strInBox, cV);
if(mapWeightList.Lookup(cV.strPartNo, cBase))
{
cV.iUnitWeight = cBase.iUnitWeight;
cV.iRadio = cBase.iRadio;
cV.iUnitPrice = cBase.iUnitPrice;
mapInBox.SetAt(strInBox,cV);
}
else
{
#if TEST_AUTOWEIGHT
cV.iUnitWeight = 0.0;//cBase.iUnitWeight;
cV.iRadio = 1;//cBase.iRadio;
cV.iUnitPrice = 0;
mapInBox.SetAt(strInBox,cV);
#else
m_strZCS.Empty();
UpdateData(false);
bLossFlag = true;
//============================================
//如果有重量缺失情况,表格只做显示缺失项用
//所以在第一次发现缺失重量时,即清空表格
static BOOL bClearList = true;
if(bClearList)
{
m_ListMain.DeleteAllItems();
g_iOrder = 0;
bClearList = false;
}
//============================================
//============================================
//显示缺失重量的项目
if(!mapLossWeight.Lookup(cV.strPartNo, cBase))
{
g_iOrder++;
m_ListMain.AddItem(cV.strNo,cV.strPartNo,"","","缺失");
mapLossWeight.SetAt(cV.strPartNo,cV);
}
//============================================
#endif
}
if(!cV.strPallet.IsEmpty()
#if !TEST_AUTOWEIGHT
&& bLossFlag == false
#endif
)
{
g_iOrder++;
cs1.Format("%g",cV.iQty*cV.iUnitWeight*cV.iRadio);
m_ListMain.AddItem(cV.strOrder,cV.strPallet,cV.strOutBox,cV.strInBox,cs1);
}
m_ListMain.Sort(0,true);
m_ListMain.EnsureVisible(g_iOrder-1,TRUE);
}
#if !TEST_AUTOWEIGHT
if(bLossFlag)
{
MessageBox("重量缺失,缺失项详见列表,请补齐后重新载入清单!","重量缺失", MB_ICONERROR);
return ;
}
#endif
//==================================================================================================
//载入托盘清单
strFileName = CExcel::GetAppPath() + "\\Record List\\" + m_strZCS + "_PalletList" + ".ckd";
if(IsFileExist(strFileName,FALSE)==TRUE)
{
CString cs1,cs2,strOutbox,strPallet;
mapOutboxPallet.RemoveAll();
g_iOrder = 0;
//序列化文件
CFile file;
file.Open(strFileName, CFile::modeReadWrite);
CArchive ar(&file, CArchive::load);
mapOutboxPallet.Serialize(ar);
ar.Close();
file.Close();
MessageBox1("套件载入成功,重量清单载入成功,托盘清单载入成功!", "托盘清单", MB_ICONINFORMATION);
}
else
{
pos = mapInBox.GetStartPosition();
while(pos)
{
mapInBox.GetNextAssoc(pos, strInBox, cV);
cV.strPallet.Empty();
mapInBox.SetAt(strInBox,cV);
}
m_ListMain.DeleteAllItems();
UpdateList();
MessageBox1("新套件开始录入,重量清单载入成功!", "托盘清单", MB_ICONINFORMATION);
}
//==================================================================================================
m_flgTaojian = TRUE;
}
else if(m_strZCS.IsEmpty())
{
MessageBox("请输入有效的套件号!","错误",MB_ICONERROR);
m_flgTaojian = FALSE;
}
else
{
m_flgTaojian = FALSE;
MessageBox1("不是有效套件,请输入有效套件!","提示",MB_OK);
}
CEdit* pEdit = (CEdit*)GetDlgItem(IDC_EDIT1_RECEIVE);
pEdit->SetFocus();
}
|
[
"jiangzhaowei2002@126.com"
] |
jiangzhaowei2002@126.com
|
aa72d34c3b4faa2363a5713430d9414a4c2f9a50
|
a62342d6359a88b0aee911e549a4973fa38de9ea
|
/0.6.0.3/Internal/SDK/CustomPlaySound_AnimNotify_classes.h
|
6c2d4f43889a36a6f3e788be34e71d559dc86460
|
[] |
no_license
|
zanzo420/Medieval-Dynasty-SDK
|
d020ad634328ee8ee612ba4bd7e36b36dab740ce
|
d720e49ae1505e087790b2743506921afb28fc18
|
refs/heads/main
| 2023-06-20T03:00:17.986041
| 2021-07-15T04:51:34
| 2021-07-15T04:51:34
| 386,165,085
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,325
|
h
|
#pragma once
// Name: Medieval Dynasty, Version: 0.6.0.3
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass CustomPlaySound_AnimNotify.CustomPlaySound_AnimNotify_C
// 0x0010 (FullSize[0x0048] - InheritedSize[0x0038])
class UCustomPlaySound_AnimNotify_C : public UAnimNotify
{
public:
class USoundBase* Sound; // 0x0038(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
struct FName Animal_PreviewOnly; // 0x0040(0x0008) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData, NoDestructor, HasGetValueTypeHash)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass CustomPlaySound_AnimNotify.CustomPlaySound_AnimNotify_C");
return ptr;
}
bool Received_Notify(class USkeletalMeshComponent* MeshComp, class UAnimSequenceBase* Animation);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
|
[
"zp2kshield@gmail.com"
] |
zp2kshield@gmail.com
|
6b7960ad74263d8b9bd62c9199bcdeda9d76f5cb
|
f0b2c4dccd80bdd5f79f695204e92bac46209279
|
/warmup-j.cpp
|
5c130245d8de80c8e848c0be7fe0938558629698
|
[] |
no_license
|
alexanderfs/acm
|
e22437a369d9c357a0af93c059c4d63ee7f5d221
|
8d7ae810ee08f0ad24e54c3236f8f3fc7b63aa18
|
refs/heads/master
| 2021-01-01T17:32:58.257647
| 2014-04-30T06:42:33
| 2014-04-30T06:42:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,187
|
cpp
|
/*******************************************************************
* Copyright (C) Alex AN
*
* File Name :
* Author : Alex AN
* Create :
* Mail : alexbupt@gmail.com
* Blog : http://blog.csdn.net/alexbupt
*
* Description :
*
******************************************************************/
#include <iostream>
#include <fstream>
using namespace std;
const int MAXLEN = 1005;
int n;
int numList[MAXLEN];
int f[MAXLEN];
int main()
{
ifstream in("test_input.txt");
cin.rdbuf(in.rdbuf());
int tcn;
cin >> tcn;
while(tcn--) {
cin >> n;
for(int i = 0; i < n; i++) {
cin >> numList[i];
}
int maxval = -1;
for(int i = 0; i < n; i++) {
if(i == 0) {
f[i] = 0;
} else if(i == 1) {
f[i] = numList[i] == numList[i - 1] ? 1 : 0;
if(f[i] > maxval) {
maxval = f[i];
}
} else {
f[i] = 0;
if(numList[i] == numList[i - 1]) {
f[i] = f[i - 1] + 1;
}
if(numList[i] == numList[i - 2] && f[i - 2] >= f[i]) {
f[i] = f[i - 2] + 1;
}
if(f[i] > maxval) {
maxval = f[i];
}
}
}
cout << maxval + 1 << endl;
}
return 0;
}
|
[
"alexbupt@gmail.com"
] |
alexbupt@gmail.com
|
05f46100030f15be4809d68873a7bdeeb58712d3
|
ba9485e8ea33acee24dc7bd61049ecfe9f8b8930
|
/ac/prev/agc007_b.cpp
|
ca064571630340034f5a259192b9f378d90d89cd
|
[] |
no_license
|
diohabara/competitive_programming
|
a0b90a74b0b923a636b9c82c75b690fef11fe8a4
|
1fb493eb44ce03e289d1245bf7d3dc450f513135
|
refs/heads/master
| 2021-12-11T22:43:40.925262
| 2021-11-06T12:56:49
| 2021-11-06T12:56:49
| 166,757,685
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 786
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i, n) for (ll i = 0; i < (ll)n; ++i)
#define all(obj) (obj).begin(), (obj).end()
static const int dx[4] = {0, 1, 0, -1};
static const int dy[4] = {1, 0, -1, 0};
static const char dir[4] = {'u', 'r', 'd', 'l'};
static const ll INF = 1 << 21;
static const ll MOD = 1e9 + 7;
int N;
signed main() {
cin >> N;
vector<int> p(N), a(N), b(N);
rep(i, N) {
cin >> p[i];
--p[i];
}
int aim = 30000;
rep(i, N) {
a[i] = 1 + aim * i;
b[i] = 1 + aim * (N - i + 1);
}
rep(i, N) { a[p[i]] += i; }
rep(i, N) {
if (i) {
cout << " ";
}
cout << a[i];
}
cout << endl;
rep(i, N) {
if (i) {
cout << " ";
}
cout << b[i];
}
cout << endl;
return 0;
}
|
[
"kadoitakemaru0902@g.ecc.u-tokyo.ac.jp"
] |
kadoitakemaru0902@g.ecc.u-tokyo.ac.jp
|
068ef801e623d3e8ec33918857a85af0b15317cf
|
568fa24f8de432ed5b6c9f1d6ad0a9e32c5274b7
|
/source/app/collector/registry/gaggle_collector_impl.h
|
77703c71d8fb88725f15e790f064208c3d8f87e3
|
[] |
no_license
|
ankeesler/btool
|
2cb450041e589c78bf93e5a5d9eb238b3e494224
|
9f4a4c919cb4d40d6d91fa8aafd814d74edf7d09
|
refs/heads/main
| 2022-07-21T18:51:42.962440
| 2022-06-01T21:54:58
| 2022-06-01T21:54:58
| 188,036,175
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 998
|
h
|
#ifndef BTOOL_APP_COLLECTOR_REGISTRY_GAGGLECOLLECTORIMPL_H_
#define BTOOL_APP_COLLECTOR_REGISTRY_GAGGLECOLLECTORIMPL_H_
#include <string>
#include <vector>
#include "app/collector/registry/registry_collectini.h"
#include "app/collector/resolver_factory_delegate.h"
#include "app/collector/store.h"
#include "node/node.h"
namespace btool::app::collector::registry {
class GaggleCollectorImpl : public RegistryCollectini::GaggleCollector {
public:
class ResolverFactory {
public:
virtual ::btool::node::Node::Resolver *New(const Resolver &r) = 0;
};
void AddResolverFactoryDelegate(
::btool::app::collector::ResolverFactoryDelegate *rfd) {
rfds_.push_back(rfd);
}
void Collect(::btool::app::collector::Store *s, Gaggle *g,
std::string root) override;
private:
std::vector<::btool::app::collector::ResolverFactoryDelegate *> rfds_;
};
}; // namespace btool::app::collector::registry
#endif // BTOOL_APP_COLLECTOR_REGISTRY_GAGGLECOLLECTORIMPL_H_
|
[
"ankeesler1@gmail.com"
] |
ankeesler1@gmail.com
|
96b792709fc414ce6a0caa61efbcb08e0db096b6
|
0eff74b05b60098333ad66cf801bdd93becc9ea4
|
/second/download/CMake/CMake-gumtree/Kitware_CMake_old_hunk_1261.cpp
|
9bda79a22808389d66ed0ae68e9e65797881ab57
|
[] |
no_license
|
niuxu18/logTracker-old
|
97543445ea7e414ed40bdc681239365d33418975
|
f2b060f13a0295387fe02187543db124916eb446
|
refs/heads/master
| 2021-09-13T21:39:37.686481
| 2017-12-11T03:36:34
| 2017-12-11T03:36:34
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 166
|
cpp
|
return;
}
fprintf(stderr, "Writing %s...\n", currentFilename.c_str());
this->WriteHeader(str);
this->WriteConnections(ptrIt->first.c_str(),
|
[
"993273596@qq.com"
] |
993273596@qq.com
|
25805ab7c8ccb759cf7d00dd138ed4c05bc719b6
|
61b4ff34410a8af8291a940c4fb32c4cc20408c4
|
/mit-carbon-Graphite-baecdec/common/tile/memory_subsystem/cache/compressed_cache_set.cc
|
d06adee0de6b8c21187b49f178ef342eab36f683
|
[
"MIT"
] |
permissive
|
puyuning/graphite_git
|
84d1138907fccfe4427b3d238a629c6c2151f09c
|
99576d50d3647baf813757bd9b8ca7338d44b920
|
refs/heads/master
| 2021-01-10T04:44:15.067633
| 2015-11-13T11:52:57
| 2015-11-13T11:52:57
| 46,118,450
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,157
|
cc
|
#include <cstring>
#include "compressed_cache_set.h"
#include "compressed_cache.h"
#include "log.h"
#include <vector>
CompressedCacheSet::CompressedCacheSet(UInt32 set_num, CachingProtocolType caching_protocol_type, SInt32 cache_level,
CacheReplacementPolicy* replacement_policy, UInt32 associativity, UInt32 line_size, CompressedCache *compressed_cache_ptr)
: _set_num(set_num)
, _replacement_policy(replacement_policy)
, _associativity(associativity)
, _line_size(line_size)
, _compressed_cache_ptr(compressed_cache_ptr)
{
//LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
_cache_line_info_array = new CacheLineInfo*[_associativity];
for (UInt32 i = 0; i < _associativity; i++)
{
_cache_line_info_array[i] = CacheLineInfo::create(caching_protocol_type, cache_level);
}
_lines = new char[_associativity * _line_size];
memset(_lines, 0x00, _associativity * _line_size);
// _comp_size_vec = vector<UInt32>(_associativity, _line_size);
_comp_size_vec = vector<UInt32>(_associativity, 0);
_comp_method = FPC;//the default method, TODO
threshold = 4;
}
CompressedCacheSet::~CompressedCacheSet()
{
for (UInt32 i = 0; i < _associativity; i++)
delete _cache_line_info_array[i];
delete [] _cache_line_info_array;
delete [] _lines;
}
void
CompressedCacheSet::read_line(UInt32 line_index, UInt32 offset, Byte *out_buf, UInt32 bytes)
{
//LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
assert(offset + bytes <= _line_size);
assert((out_buf == NULL) == (bytes == 0));
if (out_buf != NULL)
memcpy((void*) out_buf, &_lines[line_index * _line_size + offset], bytes);
decompress(_comp_size_vec[line_index], out_buf);
vector<UInt32> s;
s.push_back(line_index);
// Update replacement policy
_replacement_policy->update(_cache_line_info_array, _set_num, s); // rereference
}
//Compressed cache only support full line write
void
CompressedCacheSet::write_line(UInt32 line_index, UInt32 offset, Byte *in_buf, UInt32 bytes, IntPtr tag)
{
//LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
UInt32 comp_size;
vector<UInt32> s;
s.push_back(line_index);
assert((offset == 0) && (in_buf != NULL) && (bytes == _line_size));
memcpy(&_lines[line_index * _line_size + offset], (void*) in_buf, bytes);
comp_size = compress(bytes, in_buf, _set_num, line_index, tag); // bimod compress
//if(_comp_size_vec[line_index] < comp_size) // Here set
_comp_size_vec[line_index] = comp_size;
_cache_line_info_array[line_index]->setcomsize(comp_size);
// Update replacement policy
//_replacement_policy->update(_cache_line_info_array, _set_num, line_index);
_replacement_policy->update(_cache_line_info_array, _set_num, s);
}
CacheLineInfo*
CompressedCacheSet::find(IntPtr tag, UInt32* line_index)
{
//LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
for (SInt32 index = _associativity-1; index >= 0; index--)
{
if (_cache_line_info_array[index]->getTag() == tag)
{
if (line_index != NULL)
*line_index = index;
return (_cache_line_info_array[index]);
}
}
return NULL;
}
void
CompressedCacheSet::insert(CacheLineInfo* inserted_cache_line_info, Byte* fill_buf,
int * eviction, CacheLineInfo* evicted_cache_line_info1,CacheLineInfo* evicted_cache_line_info2, Byte* writeback_buf1,Byte* writeback_buf2,/*ShmemMsg::*/PrL1ShL2MSI:: ShmemMsg* shmem_msg)
{
//UInt32 index;
vector<UInt32> s;
//UInt32 l = s.size();
// LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
// This replacement strategy does not take into account the fact that
// cache lines can be voluntarily flushed or invalidated due to another write request
// UInt32 comp_size;
//const UInt32 = _replacement_policy->getReplacementWay(_cache_line_info_array, _set_num);
//index=_replacement_policy->getReplacementWay(_cache_line_info_array, _set_num); // return vector
//LOG_PRINT_WARNING("get into compressedcache set insert \n");//////
assert(shmem_msg!=NULL);
if(shmem_msg == NULL)
LOG_PRINT_WARNING("shmem_msg = 0x%x \n",shmem_msg);
//LOG_PRINT_WARNING("set_num = %d , shmem_msg = 0x%x \n",_set_num,shmem_msg);//////
s =_replacement_policy->getReplacementWay(_cache_line_info_array, _set_num, shmem_msg);
//LOG_PRINT_WARNING("get out of getreplacementway\n");///////
UInt32 l = s.size();
assert(l>=0&&l<=2);
if(l<0||l>2)
LOG_PRINT_WARNING("wrong return number \n");
for(UInt32 i=0;i <l; i++)
{
assert(s[i] < _associativity); //further processing
if(s[i] > _associativity)
LOG_PRINT_WARNING("wrong return number \n");
}
assert(eviction != NULL);
if(eviction == NULL)
{
LOG_PRINT_WARNING("wrong eviction pointer \n");
}
//int ev = *eviction; Here not used *eviction
//while(ev)
if(l==2)
{
UInt32 size = 0;
*eviction = 2;
evicted_cache_line_info1->assign(_cache_line_info_array[s[0]]);
evicted_cache_line_info2->assign(_cache_line_info_array[s[1]]);
if (writeback_buf1 != NULL)
memcpy((void*) writeback_buf1, &_lines[s[0] * _line_size], _line_size);
if (writeback_buf2 != NULL)
memcpy((void*) writeback_buf2, &_lines[s[1] * _line_size], _line_size);
_comp_size_vec[s[0]] = 0;
_comp_size_vec[s[1]] = 0;
//ShL2CacheLineInfo* L2_cache_line_info1 = dynamic_cast<ShL2CacheLineInfo*>(evicted_cache_line_info1); //->setcomsize(size);
//ShL2CacheLineInfo* L2_cache_line_info2 = dynamic_cast<ShL2CacheLineInfo*>(evicted_cache_line_info2); //->setcomsize(size);
evicted_cache_line_info1->setcomsize(size);
evicted_cache_line_info2->setcomsize(size);
}
else if (l==1 && _cache_line_info_array[s[0]]->isValid())
{
UInt32 size = 0;
*eviction = 1;
evicted_cache_line_info1->assign(_cache_line_info_array[s[0]]);
if (writeback_buf1 != NULL)
memcpy((void*) writeback_buf1, &_lines[s[0] * _line_size], _line_size);
_comp_size_vec[s[0]] = 0; //restore the line size
//ShL2CacheLineInfo* L2_cache_line_info1 = dynamic_cast<ShL2CacheLineInfo*>(evicted_cache_line_info1); //->setcomsize(size);
evicted_cache_line_info1->setcomsize(size);
// _comp_size_vec[index] = _line_size; //restore the line size
}
//else if (l==1 && !_cache_line_info_array[s[0]]->isValid())
else
{
*eviction = 0; ////
// Get the line info for the purpose of getting the utilization and birth time
}
//LOG_PRINT_WARNING("%s, %x", __func__, fill_buf);
_cache_line_info_array[s[0]]->assign(inserted_cache_line_info);
/* if (fill_buf != NULL)
{
assert(false);
// memcpy(&_lines[index * _line_size], (void*) fill_buf, _line_size);
//
// comp_size = get_comp_size(_line_size, fill_buf, _set_num, index);
// _comp_size_vec[index] = comp_size;
}*/
// Update replacement policy
//_replacement_policy->update(_cache_line_info_array, _set_num, index);
//LOG_PRINT_WARNING("finished insert \n");//////
_replacement_policy->update(_cache_line_info_array, _set_num, s);
} // while
double
CompressedCacheSet::get_comp_ratio(UInt32 &valid_blks)
{
// LOG_PRINT_WARNING("%s:%d:%s", __FILE__, __LINE__, __func__);
vector<UInt32>::iterator iter;
UInt32 comp_set_size=0;
valid_blks = 0;
assert(_comp_size_vec.size()==_associativity);
for (iter=_comp_size_vec.begin();iter!=_comp_size_vec.end();iter++)
{
if(*iter>0)
{
comp_set_size += *iter;
valid_blks ++;
}
}
if(valid_blks==0)return 0;
return ((double)comp_set_size)/((double)(valid_blks*_line_size));
}
/*
* FPC
* 000 zero run
* 001 4b sign-ext
* 010 1B sign-ext
* 011 2B sign-ext
* 100 2B zero-padding
* 101 2HW each 1B sign-ext
* 110 1B repeat
* 111 uncomp
*/
UInt32
CompressedCacheSet::compress(UInt32 line_size, Byte *line_buf, UInt32 set_num, UInt32 set_index, IntPtr tag)
{
assert(line_size==64);
UInt32 *dwordptr=NULL;
// double compressed_bits=0;
UInt32 compressed_bits=0;
// double cr =1;
UInt32 bits;
// //UInt32 comp_size;
// LOG_PRINT_DATA("DATA @%d/%d 0x%llx", set_num, set_index, tag);
for(int i = 0; i<16; i++)
{
dwordptr = (UInt32 *)line_buf+i;
bits = _compressed_cache_ptr->compress(*dwordptr);
// LOG_PRINT_DATA("%08x %d",*dwordptr, bits);
compressed_bits+= bits;
}
// cr = compressed_bits/512;
// LOG_PRINT_DATA("CR: %f\n", cr);
compressed_bits = compressed_bits/8;
if(compressed_bits == 0)
{compressed_bits = 1;}
if(compressed_bits > 64)
{compressed_bits = 64;}
//return compressed_bits/8; compressed_bits [1,64]
return compressed_bits;
//return compressed_bits/8;
}
/*UInt32
CompressedCacheSet::compress(UInt32 line_size, Byte *line_buf, UInt32 set_num, UInt32 set_index, IntPtr tag)
{
assert(line_size==64);
UInt32 *dwordptr=NULL;
double compressed_bits=0;
// double cr =1;
UInt32 bits;
// //UInt32 comp_size;
// LOG_PRINT_DATA("DATA @%d/%d 0x%llx", set_num, set_index, tag);
for(int i=0; i<16; i++)
{
dwordptr = (UInt32*) line_buf+i;
if((*dwordptr)==0x00||(*dwordptr)==0x01||(*dwordptr)==0x02||(*dwordptr)==0xffffffff)
compressed_bits+=0;
else
compressed_bits+=32;
}
compressed_bits/=8;
if(compressed_bits<=threshold)
return compressed_bits;
else compressed_bits = 0;
for(int i = 0; i<16; i++)
{
dwordptr = (UInt32 *)line_buf+i;
bits = _compressed_cache_ptr->compress(*dwordptr);
// LOG_PRINT_DATA("%08x %d",*dwordptr, bits);
compressed_bits+= bits;
}
// cr = compressed_bits/512;
// LOG_PRINT_DATA("CR: %f\n", cr);
return compressed_bits/8;
}*/
// return set segment;
void
CompressedCacheSet::decompress(UInt32 comp_line_size, Byte *line_buf)
{
// UInt32 *dwordptr=NULL;
//
//// UInt32 bits;
//// //UInt32 comp_size;
// for(int i = 0; i<16; i++)
// {
// dwordptr = (UInt32 *)line_buf+i;
// _compressed_cache_ptr->decompress(*dwordptr);
// }
}
|
[
"puyuning@puyuning-System-Product-Name.(none)"
] |
puyuning@puyuning-System-Product-Name.(none)
|
960a08a58d8c01125f884184ad7a009457d6e4b5
|
0fdb6565a31358a7021c30bbfd0e95a1a9d39e25
|
/src/morganaFields/feQr3d.hpp
|
69e541472ce844d827c3f0c3e2b4a0905f002d2d
|
[] |
no_license
|
feof81/morganaPublic
|
b8b61a08d222a2ade3484cbdfc80c9790c0e5508
|
540cdbcdcf56e5cd13c0dc98c04f724543025bce
|
refs/heads/master
| 2023-01-28T01:12:51.711178
| 2023-01-11T16:56:37
| 2023-01-11T16:56:37
| 216,569,123
| 3
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,052
|
hpp
|
/*%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
This file is part of Morgana.
Author: Andrea Villa, andrea.villa81@fastwebnet.it
Morgana is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
Morgana is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Morgana. If not, see <http://www.gnu.org/licenses/>.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%*/
#ifndef FEQR3D_HPP
#define FEQR3D_HPP
#include "morganaTypes.hpp"
#include "geoMapInterface.hpp"
#include "morganaFields.hpp"
#include "elCard3d.hpp"
#include "feStaticDofCard3d.h"
#include "feStaticEvalIterators.hpp"
//_________________________________________________________________________________________________
// FE CARD
//-------------------------------------------------------------------------------------------------
/*! Dummy card */
class feQr3d_card
{
public:
feQr3d_card() { };
};
//Forward declaration______________________________________________________________________________
template<Int R, typename PMAPTYPE> class feQr3d;
//_________________________________________________________________________________________________
// Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0 Q0
//-------------------------------------------------------------------------------------------------
/*! Hexahedral nodal finite element - Q0 */
template<typename PMAPTYPE>
class feQr3d<0, PMAPTYPE>
{
/*! @name Typedefs */ //@{
public:
typedef PMAPTYPE FETYPE_PMAPTYPE;
typedef Real BASETYPE;
typedef linearHexa GEOSHAPE;
typedef feQr3d_card FECARD;
typedef elCard3d<GEOSHAPE,PMAPTYPE> ELCARD;
typedef feStaticDofCard3d DOFCARD;
//@}
/*! @name Static flags */ //@{
public:
static const FEClass feClass = feStatic;
static const FEGridType feGridType = primal;
static const FEBaseType feBaseType = scalar;
static const FELabel feLabel = FE_Q0_3d;
static const FEBaseLabel feBaseLabel = BL_Qr_3d;
//@}
/*! @name Static numbers */ //@{
public:
static const UInt numPoly = 1;
static const UInt numBasis = 1;
static const UInt dim = 3;
static const UInt dofPerVertex = 0;
static const UInt dofPerEdge = 0;
static const UInt dofPerFace = 0;
static const UInt dofPerVolume = 1;
static const bool isNodal = true;
//@}
/*! @name Links and flags */ //@{
public:
bool elCardLoaded;
bool feCardLoaded;
FECARD FeCard;
ELCARD ElCard;
//@}
/*! @name Constructors and setting functions */ //@{
public:
feQr3d();
feQr3d(const FECARD & FECard, const ELCARD & ELCard);
void setCards(const FECARD & FECard, const ELCARD & ELCard);
//@}
/*! @name Eval functions */ //@{
public:
static DOFCARD getDofCard(const UInt & i);
static point3d getRefNode(const UInt & i);
void localEval(const point3d & Y, sVect<BASETYPE> & val) const;
void localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
void globalEval(const point3d & Y, sVect<BASETYPE> & val) const;
void globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
//@}
};
template<typename PMAPTYPE>
feQr3d<0, PMAPTYPE>::
feQr3d()
{
elCardLoaded = false;
feCardLoaded = false;
}
template<typename PMAPTYPE>
feQr3d<0, PMAPTYPE>::
feQr3d(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
FeCard = FECard;
ElCard = ELCard;
}
template<typename PMAPTYPE>
void
feQr3d<0, PMAPTYPE>::
setCards(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
ElCard = ELCard;
FeCard = FECard;
}
template<typename PMAPTYPE>
typename feQr3d<0, PMAPTYPE>::DOFCARD
feQr3d<0, PMAPTYPE>::
getDofCard(const UInt & i)
{
assert(i == 1);
return( DOFCARD(VOLUME,1,1) );
}
template<typename PMAPTYPE>
point3d
feQr3d<0, PMAPTYPE>::
getRefNode(const UInt & i)
{
assert(i == 1);
return(point3d(0.5, 0.5, 0.5));
}
template<typename PMAPTYPE>
void
feQr3d<0, PMAPTYPE>::
localEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<0, PMAPTYPE>::
localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numPoly);
assert(gradY.size() == numPoly);
assert(gradZ.size() == numPoly);
//Polynomial evaluation
feStaticRealDx<feLabel,numPoly>::eval(gradX,Y);
feStaticRealDy<feLabel,numPoly>::eval(gradY,Y);
feStaticRealDz<feLabel,numPoly>::eval(gradZ,Y);
}
template<typename PMAPTYPE>
void
feQr3d<0, PMAPTYPE>::
globalEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<0, PMAPTYPE>::
globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numBasis);
assert(gradY.size() == numBasis);
assert(gradZ.size() == numBasis);
//Compute tensor
geoMapInterface<GEOSHAPE> geoInterface;
tensor3d T = geoInterface.getGradient(ElCard.getNodes(),Y);
T.computeInverse();
//Local grad
sVect<BASETYPE> locX(numBasis), locY(numBasis), locZ(numBasis);
localGrad(Y,locX,locY,locZ);
//Compute gradient
for(UInt i=1; i <= numBasis; ++i)
{
gradX(i) = locX(i) * T(1,1) + locY(i) * T(2,1) + locZ(i) * T(3,1);
gradY(i) = locX(i) * T(1,2) + locY(i) * T(2,2) + locZ(i) * T(3,2);
gradZ(i) = locX(i) * T(1,3) + locY(i) * T(2,3) + locZ(i) * T(3,3);
}
}
//_________________________________________________________________________________________________
// Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1 Q1
//-------------------------------------------------------------------------------------------------
/*! Hexahedral nodal finite element - Q1 */
template<typename PMAPTYPE>
class feQr3d<1, PMAPTYPE>
{
/*! @name Typedefs */ //@{
public:
typedef PMAPTYPE FETYPE_PMAPTYPE;
typedef Real BASETYPE;
typedef linearHexa GEOSHAPE;
typedef feQr3d_card FECARD;
typedef elCard3d<GEOSHAPE,PMAPTYPE> ELCARD;
typedef feStaticDofCard3d DOFCARD;
//@}
/*! @name Static flags */ //@{
public:
static const FEClass feClass = feStatic;
static const FEGridType feGridType = primal;
static const FEBaseType feBaseType = scalar;
static const FELabel feLabel = FE_Q1_3d;
static const FEBaseLabel feBaseLabel = BL_Qr_3d;
//@}
/*! @name Static numbers */ //@{
public:
static const UInt numPoly = 8;
static const UInt numBasis = 8;
static const UInt dim = 3;
static const UInt dofPerVertex = 1;
static const UInt dofPerEdge = 0;
static const UInt dofPerFace = 0;
static const UInt dofPerVolume = 0;
static const bool isNodal = true;
//@}
/*! @name Links and flags */ //@{
public:
bool elCardLoaded;
bool feCardLoaded;
FECARD FeCard;
ELCARD ElCard;
//@}
/*! @name Constructors and setting functions */ //@{
public:
feQr3d();
feQr3d(const FECARD & FECard, const ELCARD & ELCard);
void setCards(const FECARD & FECard, const ELCARD & ELCard);
//@}
/*! @name Eval functions */ //@{
public:
static DOFCARD getDofCard(const UInt & i);
static point3d getRefNode(const UInt & i);
void localEval(const point3d & Y, sVect<BASETYPE> & val) const;
void localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
void globalEval(const point3d & Y, sVect<BASETYPE> & val) const;
void globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
//@}
};
template<typename PMAPTYPE>
feQr3d<1, PMAPTYPE>::
feQr3d()
{
elCardLoaded = false;
feCardLoaded = false;
}
template<typename PMAPTYPE>
feQr3d<1, PMAPTYPE>::
feQr3d(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
FeCard = FECard;
ElCard = ELCard;
}
template<typename PMAPTYPE>
void
feQr3d<1, PMAPTYPE>::
setCards(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
ElCard = ELCard;
FeCard = FECard;
}
template<typename PMAPTYPE>
typename feQr3d<1, PMAPTYPE>::DOFCARD
feQr3d<1, PMAPTYPE>::
getDofCard(const UInt & i)
{
assert(i >= 1);
assert(i <= 8);
static DOFCARD list[8] =
{
DOFCARD(VERTEX,1,1),
DOFCARD(VERTEX,1,2),
DOFCARD(VERTEX,1,3),
DOFCARD(VERTEX,1,4),
DOFCARD(VERTEX,1,5),
DOFCARD(VERTEX,1,6),
DOFCARD(VERTEX,1,7),
DOFCARD(VERTEX,1,8) };
return( list[i-1] );
}
template<typename PMAPTYPE>
point3d
feQr3d<1, PMAPTYPE>::
getRefNode(const UInt & i)
{
assert(i >= 1);
assert(i <= 8);
static point3d list[8] =
{
point3d(0.0, 0.0, 0.0),
point3d(1.0, 0.0, 0.0),
point3d(1.0, 1.0, 0.0),
point3d(0.0, 1.0, 0.0),
point3d(0.0, 0.0, 1.0),
point3d(1.0, 0.0, 1.0),
point3d(1.0, 1.0, 1.0),
point3d(0.0, 1.0, 1.0)
};
return( list[i-1] );
}
template<typename PMAPTYPE>
void
feQr3d<1, PMAPTYPE>::
localEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<1, PMAPTYPE>::
localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numPoly);
assert(gradY.size() == numPoly);
assert(gradZ.size() == numPoly);
//Polynomial evaluation
feStaticRealDx<feLabel,numPoly>::eval(gradX,Y);
feStaticRealDy<feLabel,numPoly>::eval(gradY,Y);
feStaticRealDz<feLabel,numPoly>::eval(gradZ,Y);
}
template<typename PMAPTYPE>
void
feQr3d<1, PMAPTYPE>::
globalEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<1, PMAPTYPE>::
globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numBasis);
assert(gradY.size() == numBasis);
assert(gradZ.size() == numBasis);
//Compute tensor
geoMapInterface<GEOSHAPE> geoInterface;
tensor3d T = geoInterface.getGradient(ElCard.getNodes(),Y);
T.computeInverse();
//Local grad
sVect<BASETYPE> locX(numBasis), locY(numBasis), locZ(numBasis);
localGrad(Y,locX,locY,locZ);
//Compute gradient
for(UInt i=1; i <= numBasis; ++i)
{
gradX(i) = locX(i) * T(1,1) + locY(i) * T(2,1) + locZ(i) * T(3,1);
gradY(i) = locX(i) * T(1,2) + locY(i) * T(2,2) + locZ(i) * T(3,2);
gradZ(i) = locX(i) * T(1,3) + locY(i) * T(2,3) + locZ(i) * T(3,3);
}
}
//_________________________________________________________________________________________________
// Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2 Q2
//-------------------------------------------------------------------------------------------------
/*! Hexahedral nodal finite element - Q2 */
template<typename PMAPTYPE>
class feQr3d<2, PMAPTYPE>
{
/*! @name Typedefs */ //@{
public:
typedef PMAPTYPE FETYPE_PMAPTYPE;
typedef Real BASETYPE;
typedef linearHexa GEOSHAPE;
typedef feQr3d_card FECARD;
typedef elCard3d<GEOSHAPE,PMAPTYPE> ELCARD;
typedef feStaticDofCard3d DOFCARD;
//@}
/*! @name Static flags */ //@{
public:
static const FEClass feClass = feStatic;
static const FEGridType feGridType = primal;
static const FEBaseType feBaseType = scalar;
static const FELabel feLabel = FE_Q2_3d;
static const FEBaseLabel feBaseLabel = BL_Qr_3d;
//@}
/*! @name Static numbers */ //@{
public:
static const UInt numPoly = 27;
static const UInt numBasis = 27;
static const UInt dim = 3;
static const UInt dofPerVertex = 1;
static const UInt dofPerEdge = 1;
static const UInt dofPerFace = 1;
static const UInt dofPerVolume = 1;
static const bool isNodal = true;
//@}
/*! @name Links and flags */ //@{
public:
bool elCardLoaded;
bool feCardLoaded;
FECARD FeCard;
ELCARD ElCard;
//@}
/*! @name Constructors and setting functions */ //@{
public:
feQr3d();
feQr3d(const FECARD & FECard, const ELCARD & ELCard);
void setCards(const FECARD & FECard, const ELCARD & ELCard);
//@}
/*! @name Eval functions */ //@{
public:
static DOFCARD getDofCard(const UInt & i);
static point3d getRefNode(const UInt & i);
void localEval(const point3d & Y, sVect<BASETYPE> & val) const;
void localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
void globalEval(const point3d & Y, sVect<BASETYPE> & val) const;
void globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const;
//@}
};
template<typename PMAPTYPE>
feQr3d<2, PMAPTYPE>::
feQr3d()
{
elCardLoaded = false;
feCardLoaded = false;
}
template<typename PMAPTYPE>
feQr3d<2, PMAPTYPE>::
feQr3d(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
FeCard = FECard;
ElCard = ELCard;
}
template<typename PMAPTYPE>
void
feQr3d<2, PMAPTYPE>::
setCards(const FECARD & FECard, const ELCARD & ELCard)
{
elCardLoaded = true;
feCardLoaded = true;
ElCard = ELCard;
FeCard = FECard;
}
template<typename PMAPTYPE>
typename feQr3d<2, PMAPTYPE>::DOFCARD
feQr3d<2, PMAPTYPE>::
getDofCard(const UInt & i)
{
assert(i >= 1);
assert(i <= 27);
static DOFCARD list[27] =
{
DOFCARD(VERTEX,1,1),
DOFCARD(VERTEX,1,2),
DOFCARD(VERTEX,1,3),
DOFCARD(VERTEX,1,4),
DOFCARD(EDGE,1,1),
DOFCARD(EDGE,1,2),
DOFCARD(EDGE,1,3),
DOFCARD(EDGE,1,4),
DOFCARD(FACE,1,1),
DOFCARD(EDGE,1,5),
DOFCARD(EDGE,1,6),
DOFCARD(EDGE,1,7),
DOFCARD(EDGE,1,8),
DOFCARD(FACE,1,2),
DOFCARD(FACE,1,3),
DOFCARD(FACE,1,4),
DOFCARD(FACE,1,5),
DOFCARD(VOLUME,1,1),
DOFCARD(VERTEX,1,5),
DOFCARD(VERTEX,1,6),
DOFCARD(VERTEX,1,7),
DOFCARD(VERTEX,1,8),
DOFCARD(EDGE,1,9),
DOFCARD(EDGE,1,10),
DOFCARD(EDGE,1,11),
DOFCARD(EDGE,1,12),
DOFCARD(FACE,1,6) };
return( list[i-1] );
}
template<typename PMAPTYPE>
point3d
feQr3d<2, PMAPTYPE>::
getRefNode(const UInt & i)
{
assert(i >= 1);
assert(i <= 27);
static point3d list[27] =
{
point3d(0.0, 0.0, 0.0),
point3d(1.0, 0.0, 0.0),
point3d(1.0, 1.0, 0.0),
point3d(0.0, 1.0, 0.0),
point3d(0.5, 0.0, 0.0),
point3d(1.0, 0.5, 0.0),
point3d(0.5, 1.0, 0.0),
point3d(0.0, 0.5, 0.0),
point3d(0.5, 0.5, 0.0),
point3d(0.0, 0.0, 0.5),
point3d(1.0, 0.0, 0.5),
point3d(1.0, 1.0, 0.5),
point3d(0.0, 1.0, 0.5),
point3d(0.5, 0.0, 0.5),
point3d(1.0, 0.5, 0.5),
point3d(0.5, 1.0, 0.5),
point3d(0.0, 0.5, 0.5),
point3d(0.5, 0.5, 0.5),
point3d(0.0, 0.0, 1.0),
point3d(1.0, 0.0, 1.0),
point3d(1.0, 1.0, 1.0),
point3d(0.0, 1.0, 1.0),
point3d(0.5, 0.0, 1.0),
point3d(1.0, 0.5, 1.0),
point3d(0.5, 1.0, 1.0),
point3d(0.0, 0.5, 1.0),
point3d(0.5, 0.5, 1.0)
};
return( list[i-1] );
}
template<typename PMAPTYPE>
void
feQr3d<2, PMAPTYPE>::
localEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<2, PMAPTYPE>::
localGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numPoly);
assert(gradY.size() == numPoly);
assert(gradZ.size() == numPoly);
//Polynomial evaluation
feStaticRealDx<feLabel,numPoly>::eval(gradX,Y);
feStaticRealDy<feLabel,numPoly>::eval(gradY,Y);
feStaticRealDz<feLabel,numPoly>::eval(gradZ,Y);
}
template<typename PMAPTYPE>
void
feQr3d<2, PMAPTYPE>::
globalEval(const point3d & Y, sVect<BASETYPE> & val) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(val.size() == numPoly);
//Polynomial evaluation
feStaticRealEval<feLabel,numPoly>::eval(val,Y);
}
template<typename PMAPTYPE>
void
feQr3d<2, PMAPTYPE>::
globalGrad(const point3d & Y, sVect<BASETYPE> & gradX, sVect<BASETYPE> & gradY, sVect<BASETYPE> & gradZ) const
{
assert(elCardLoaded);
assert(feCardLoaded);
assert(gradX.size() == numBasis);
assert(gradY.size() == numBasis);
assert(gradZ.size() == numBasis);
//Compute tensor
geoMapInterface<GEOSHAPE> geoInterface;
tensor3d T = geoInterface.getGradient(ElCard.getNodes(),Y);
T.computeInverse();
//Local grad
sVect<BASETYPE> locX(numBasis), locY(numBasis), locZ(numBasis);
localGrad(Y,locX,locY,locZ);
//Compute gradient
for(UInt i=1; i <= numBasis; ++i)
{
gradX(i) = locX(i) * T(1,1) + locY(i) * T(2,1) + locZ(i) * T(3,1);
gradY(i) = locX(i) * T(1,2) + locY(i) * T(2,2) + locZ(i) * T(3,2);
gradZ(i) = locX(i) * T(1,3) + locY(i) * T(2,3) + locZ(i) * T(3,3);
}
}
#endif
|
[
"andrea.massimo.villa@gmail.com"
] |
andrea.massimo.villa@gmail.com
|
5759f73d1d981f5ed3d2a81e1fad2bc8b91f9413
|
211105066f0b0406bb98db261fdaff542c07c574
|
/Season 2/day 5/Programs/2WriteData/WriteData/WriteData.ino
|
64fe2833e5f79746d38d7f47a55863ba8e9a7aec
|
[] |
no_license
|
WShme2017/kaderisasiWS
|
550db1bf366d79b11951dbb1bb70910e2ab7fe9c
|
af7ba81d40abf670001d651e55c735be2d0f76a1
|
refs/heads/master
| 2021-01-19T15:13:06.622994
| 2018-02-21T10:22:19
| 2018-02-21T10:22:19
| 100,951,107
| 7
| 73
| null | 2018-02-21T10:22:20
| 2017-08-21T12:40:29
|
Arduino
|
UTF-8
|
C++
| false
| false
| 1,173
|
ino
|
// include ThingSpeak and ESP8266 WiFi Libraries
#include <ThingSpeak.h>
#include <ESP8266WiFi.h>
// set your Router user name and passward
char ssid[] = "yashf"; // your network SSID (name)
char pass[] = "12211221"; // your network password
// that you have already remembered from ThingSpeak websie
unsigned long myChannelNumber = 325405;
const char * myWriteAPIKey = "PK3Q0KXF1RPK2G44";
int sensorValue; // variable to save analog reading
WiFiClient client;
void setup() {
delay(1000);
Serial.begin(115200);
Serial.println("");
WiFi.begin(ssid, pass);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
WiFi.printDiag(Serial);
ThingSpeak.begin(client);
}
void loop() {
// read the input on analog pin 0:
sensorValue = analogRead(A0);
// Write to ThingSpeak.
// send your Channel Number
// write to field 1
// send sensorValue
// send your Write API Key
Serial.println(sensorValue);
ThingSpeak.writeField(myChannelNumber, 1, sensorValue, myWriteAPIKey);
delay(10000); // ThingSpeak will accept updates every 10 seconds.
}
|
[
"noreply@github.com"
] |
WShme2017.noreply@github.com
|
d242be82b461880aca0c7dbe09b6e7ea63901ce8
|
ed53676faf6a1c4dcc30182be0934337abcd1047
|
/trantor/tests/AsyncFileLoggerTest.cc
|
298f5cc94f4fc9d655eda677e096a310dd30df89
|
[] |
no_license
|
flyish/trantor
|
7c83fdec1f59ec439b0e71cd1bdb0fcde51b3ada
|
b4c959616e29e01b3ded28da08fa5e0c90435065
|
refs/heads/master
| 2021-06-15T05:31:27.048414
| 2017-03-31T14:12:53
| 2017-03-31T14:12:53
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,206
|
cc
|
#include <trantor/utils/Logger.h>
#include <trantor/utils/AsyncFileLogger.h>
#include <stdlib.h>
#include <thread>
int main()
{
trantor::AsyncFileLogger asyncFileLogger;
asyncFileLogger.setFileName("async_test");
asyncFileLogger.startLogging();
trantor::Logger::setOutputFunction([&](const char *msg,const uint64_t len){
asyncFileLogger.output(msg,len);
},[&](){
asyncFileLogger.flush();
});
asyncFileLogger.setFileSizeLimit(100000000);
// LOG_DEBUG<<"debug log!"<<1;
// LOG_TRACE<<"trace log!"<<2;
// LOG_INFO<<"info log!"<<3;
// LOG_WARN<<"warning log!"<<4;
// if(1)
// LOG_ERROR<<"error log!"<<5;
// std::thread thread_([](){
// LOG_FATAL<<"fatal log!"<<6;
// });
//
// FILE *fp=fopen("/notexistfile","rb");
// if(fp==NULL)
// {
// LOG_SYSERR<<"syserr log!"<<7;
// }
int i=0;
while(i<1000000)
{
i++;
if(i%100==0)
{
LOG_ERROR<<"this is the "<<i<<"th log";
continue;
}
LOG_INFO<<"this is the "<<i<<"th log";
i++;
LOG_DEBUG<<"this is the "<<i<<"th log";
}
}
|
[
"20741618@qq.com"
] |
20741618@qq.com
|
840428f9dc4a9dae8ba417e86e718d6103f71031
|
64f44cf54f71eb01cbec30e199b38c5215c6f69f
|
/computer/spectrum/computer.cpp
|
8e1d3267701a0c4de3196669c809032b4de015f5
|
[] |
no_license
|
electrified/cpuqt
|
a988495c087d6d1b6dfef2bba02aada51c38ce54
|
958908efc431d6c55638e40425be8d537493a7b5
|
refs/heads/main
| 2023-03-05T06:24:12.880916
| 2021-02-15T20:14:15
| 2021-02-15T20:35:15
| 333,570,656
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 73
|
cpp
|
#include "computer.h"
Computer::Computer() {}
Computer::~Computer() {}
|
[
"ebwibble@hotmail.com"
] |
ebwibble@hotmail.com
|
25fee1fc2abe6efc254d66caf6b399d8d6ac161e
|
39e0af37e018858dfa5513d3aedaa26270bedc11
|
/Src/1075.cpp
|
8d0f8fc6c35252b06f568749e3304c141f04238d
|
[] |
no_license
|
BeyondSword/JPAT
|
1089e65d08ad32352662059f7cb6be18a20a0f8b
|
9ceb22ade20485afb70514d47bb19b09666f1370
|
refs/heads/master
| 2020-06-28T19:37:17.751477
| 2019-09-07T15:21:04
| 2019-09-07T15:21:04
| 200,321,637
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 2,356
|
cpp
|
#include<iostream>
#include<algorithm>
#include<stdio.h>
using namespace std;
const int MAXN=10001;
struct Stu{
int id;
int p[6];
int sub[6];
int ac;
int tot;
int need_sort;
int rank;
}stu[MAXN+1];
bool comparison(struct Stu &A, struct Stu &B){
if(A.need_sort == B.need_sort){
if(A.tot == B.tot){
if(A.ac == B.ac){
return A.id < B.id;
}
return A.ac > B.ac;
}
return A.tot > B.tot;
}
return A.need_sort > B.need_sort;
}
int p[6];
int main(){
int N,K,M;
cin >> N >> K >> M;
for(int i=1; i<=K; i++){
cin >> p[i];
}
//submission
for(int i=0; i<M; i++){
int id, p_id, score;
cin >> id >> p_id >> score;
//有一道题通过编译器就排序
if(score != -1){
stu[id].need_sort = 1;
}
//之前的提交没满分,第一次满分ac++
if(stu[id].p[p_id]!=p[p_id] && score == p[p_id]){
stu[id].ac += 1;
}
//分数比之前高,更新
if(stu[id].p[p_id] < score){
if(stu[id].p[p_id] > 0){
stu[id].tot -= stu[id].p[p_id];
}
stu[id].p[p_id] = score;
stu[id].tot += score;
}
stu[id].id = id;
stu[id].sub[p_id] = 1;
}
//输入结束
sort(stu+1, stu+MAXN+1, comparison);
//output
int rank = 1;
stu[1].rank = rank;
stu[0].tot = -1;
for(int i=1; i<MAXN; i++){
if(!stu[i].need_sort){
break;
}
if(stu[i].tot == stu[i-1].tot){
printf("%d", stu[i-1].rank);
stu[i].rank = stu[i-1].rank;
}
else{
printf("%d", rank);
stu[i].rank = rank;
}
rank++;
//输出其他信息
printf(" %05d %d", stu[i].id, stu[i].tot);
for(int j=1; j<=K; j++){
//未提交
if(!stu[i].sub[j]){
printf(" -");
}
else{
//提交没通过编译器,显示0分
if(stu[i].p[j] == -1){
printf(" 0");
}
else{
printf(" %d", stu[i].p[j]);
}
}
}
printf("\n");
}
return 0;
}
|
[
"andyjiangandy@outlook.com"
] |
andyjiangandy@outlook.com
|
73f62caf4451954a9c2789309ab935ff220cb0cd
|
7e5be101928eb7ea43bc1a335d3475536f8a5bb2
|
/2016 Training/11.19/A.cpp
|
bd3f6f2e4284dc3d941d36d7351cd75393c64828
|
[] |
no_license
|
TaoSama/ICPC-Code-Library
|
f94d4df0786a8a1c175da02de0a3033f9bd103ec
|
ec80ec66a94a5ea1d560c54fe08be0ecfcfc025e
|
refs/heads/master
| 2020-04-04T06:19:21.023777
| 2018-11-05T18:22:32
| 2018-11-05T18:22:32
| 54,618,194
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,965
|
cpp
|
//
// Created by TaoSama on 2016-11-19
// Copyright (c) 2016 TaoSama. All rights reserved.
//
#pragma comment(linker, "/STACK:102400000,102400000")
#include <algorithm>
#include <cctype>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <iomanip>
#include <iostream>
#include <map>
#include <queue>
#include <string>
#include <set>
#include <vector>
using namespace std;
#define pr(x) cout << #x << " = " << x << " "
#define prln(x) cout << #x << " = " << x << endl
const int N = 1e5 + 10, INF = 0x3f3f3f3f, MOD = 1e9 + 7;
int n, m, s;
vector<pair<int, int> > G[N], rG[N];
int f[N], rf[N];
bool in[N];
void spfa(int* f, vector<pair<int, int> >* G) {
memset(f, 0x3f, sizeof(int) * (n + 5));
memset(in, 0, sizeof(bool) * (n + 5));
f[s] = 0; in[s] = 1;
queue<int> q; q.push(s);
while(q.size()) {
int u = q.front(); q.pop();
in[u] = false;
for(int i = 0; i < G[u].size(); ++i) {
int v = G[u][i].first, c = G[u][i].second;
if(f[v] > f[u] + c) {
f[v] = f[u] + c;
if(!in[v]) in[v] = true, q.push(v);
}
}
}
}
int main() {
#ifdef LOCAL
freopen("C:\\Users\\TaoSama\\Desktop\\in.txt", "r", stdin);
// freopen("C:\\Users\\TaoSama\\Desktop\\out.txt","w",stdout);
#endif
ios_base::sync_with_stdio(0);
while(scanf("%d%d%d", &n, &m, &s) == 3) {
for(int i = 1; i <= n; ++i) G[i].clear(), rG[i].clear();
for(int i = 1; i <= m; ++i) {
int u, v, c; scanf("%d%d%d", &u, &v, &c);
G[u].push_back(make_pair(v, c));
swap(u, v);
rG[u].push_back(make_pair(v, c));
}
spfa(f, G);
spfa(rf, rG);
int ans = -INF;
for(int i = 1; i <= n; ++i) {
// printf("%d: %d %d\n", i, f[i], rf[i]);
ans = max(ans, f[i] + rf[i]);
}
printf("%d\n", ans);
}
return 0;
}
|
[
"lwt1367@gmail.com"
] |
lwt1367@gmail.com
|
927362a0fa9e5fb524c704b530e12a5f9a33b340
|
8152a57e4a931b69bf03f847e9436fd06b1d80a4
|
/src/mixTX.h
|
2a84f1bd81ba10bf805b157b9d188fe8527dbb1b
|
[
"MIT"
] |
permissive
|
coinrescue/helmin
|
42a536862fe90ba79aea37989efdd964c5577492
|
b692f30779049acb1d35728f2f511adc3bfa66b8
|
refs/heads/master
| 2020-11-23T22:00:16.249177
| 2019-12-13T22:54:27
| 2019-12-13T22:54:27
| 227,838,716
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 15,792
|
h
|
// Copyright (c) 2014-2015 The Dash developers
// Copyright (c) 2015-2017 The PIVX developers
// Copyright (c) 2018 The Helmin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef DARKSEND_H
#define DARKSEND_H
#include "main.h"
#include "masternode-payments.h"
#include "masternode-sync.h"
#include "masternodeman.h"
#include "Darksend-relay.h"
#include "sync.h"
class CTxIn;
class CDarksendPool;
class CDarKsendSigner;
class CMasterNodeVote;
class CBitcoinAddress;
class CDarksendQueue;
class CDarksendBroadcastTx;
class CActiveMasternode;
// pool states for mixing
#define POOL_STATUS_UNKNOWN 0 // waiting for update
#define POOL_STATUS_IDLE 1 // waiting for update
#define POOL_STATUS_QUEUE 2 // waiting in a queue
#define POOL_STATUS_ACCEPTING_ENTRIES 3 // accepting entries
#define POOL_STATUS_FINALIZE_TRANSACTION 4 // master node will broadcast what it accepted
#define POOL_STATUS_SIGNING 5 // check inputs/outputs, sign final tx
#define POOL_STATUS_TRANSMISSION 6 // transmit transaction
#define POOL_STATUS_ERROR 7 // error
#define POOL_STATUS_SUCCESS 8 // success
// status update message constants
#define MASTERNODE_ACCEPTED 1
#define MASTERNODE_REJECTED 0
#define MASTERNODE_RESET -1
#define DARKSEND_QUEUE_TIMEOUT 30
#define DARKSEND_SIGNING_TIMEOUT 15
// used for anonymous relaying of inputs/outputs/sigs
#define DARKSEND_RELAY_IN 1
#define DARKSEND_RELAY_OUT 2
#define DARKSEND_RELAY_SIG 3
static const int64_t DARKSEND_COLLATERAL = (10 * COIN);
static const int64_t DARKSEND_POOL_MAX = (99999.99 * COIN);
extern CDarksendPool DarKsendPool;
extern CDarKsendSigner DarKsendSigner;
extern std::vector<CDarksendQueue> vecDarksendQueue;
extern std::string strMasterNodePrivKey;
extern map<uint256, CDarksendBroadcastTx> mapDarksendBroadcastTxes;
extern CActiveMasternode activeMasternode;
/** Holds an Darksend input
*/
class CTxDSIn : public CTxIn
{
public:
bool fHasSig; // flag to indicate if signed
int nSentTimes; //times we've sent this anonymously
CTxDSIn(const CTxIn& in)
{
prevout = in.prevout;
scriptSig = in.scriptSig;
prevPubKey = in.prevPubKey;
nSequence = in.nSequence;
nSentTimes = 0;
fHasSig = false;
}
};
/** Holds an Darksend output
*/
class CTxDSOut : public CTxOut
{
public:
int nSentTimes; //times we've sent this anonymously
CTxDSOut(const CTxOut& out)
{
nValue = out.nValue;
nRounds = out.nRounds;
scriptPubKey = out.scriptPubKey;
nSentTimes = 0;
}
};
// A clients transaction in the Darksend pool
class CDarKsendEntry
{
public:
bool isSet;
std::vector<CTxDSIn> sev;
std::vector<CTxDSOut> vout;
int64_t amount;
CTransaction collateral;
CTransaction txSupporting;
int64_t addedTime; // time in UTC milliseconds
CDarKsendEntry()
{
isSet = false;
collateral = CTransaction();
amount = 0;
}
/// Add entries to use for Darksend
bool Add(const std::vector<CTxIn> vinIn, int64_t amountIn, const CTransaction collateralIn, const std::vector<CTxOut> voutIn)
{
if (isSet) {
return false;
}
BOOST_FOREACH (const CTxIn& in, vinIn)
sev.push_back(in);
BOOST_FOREACH (const CTxOut& out, voutIn)
vout.push_back(out);
amount = amountIn;
collateral = collateralIn;
isSet = true;
addedTime = GetTime();
return true;
}
bool AddSig(const CTxIn& vin)
{
BOOST_FOREACH (CTxDSIn& s, sev) {
if (s.prevout == vin.prevout && s.nSequence == vin.nSequence) {
if (s.fHasSig) {
return false;
}
s.scriptSig = vin.scriptSig;
s.prevPubKey = vin.prevPubKey;
s.fHasSig = true;
return true;
}
}
return false;
}
bool IsExpired()
{
return (GetTime() - addedTime) > DARKSEND_QUEUE_TIMEOUT; // 120 seconds
}
};
/**
* A currently inprogress Darksend merge and denomination information
*/
class CDarksendQueue
{
public:
CTxIn vin;
int64_t time;
int nDenom;
bool ready; //ready for submit
std::vector<unsigned char> vchSig;
CDarksendQueue()
{
nDenom = 0;
vin = CTxIn();
time = 0;
vchSig.clear();
ready = false;
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action, int nType, int nVersion)
{
READWRITE(nDenom);
READWRITE(vin);
READWRITE(time);
READWRITE(ready);
READWRITE(vchSig);
}
bool GetAddress(CService& addr)
{
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
addr = pmn->addr;
return true;
}
return false;
}
/// Get the protocol version
bool GetProtocolVersion(int& protocolVersion)
{
CMasternode* pmn = mnodeman.Find(vin);
if (pmn != NULL) {
protocolVersion = pmn->protocolVersion;
return true;
}
return false;
}
/** Sign this Darksend transaction
* \return true if all conditions are met:
* 1) we have an active Masternode,
* 2) we have a valid Masternode private key,
* 3) we signed the message successfully, and
* 4) we verified the message successfully
*/
bool Sign();
bool Relay();
/// Is this Darksend expired?
bool IsExpired()
{
return (GetTime() - time) > DARKSEND_QUEUE_TIMEOUT; // 120 seconds
}
/// Check if we have a valid Masternode address
bool CheckSignature();
};
/** Helper class to store Darksend transaction (tx) information.
*/
class CDarksendBroadcastTx
{
public:
CTransaction tx;
CTxIn vin;
vector<unsigned char> vchSig;
int64_t sigTime;
};
/** Helper object for signing and checking signatures
*/
class CDarKsendSigner
{
public:
/// Is the inputs associated with this public key? (and there is 10000 HLMN - checking if valid masternode)
bool IsVinAssociatedWithPubkey(CTxIn& vin, CPubKey& pubkey);
/// Set the private/public key values, returns true if successful
bool GetKeysFromSecret(std::string strSecret, CKey& keyRet, CPubKey& pubkeyRet);
/// Set the private/public key values, returns true if successful
bool SetKey(std::string strSecret, std::string& errorMessage, CKey& key, CPubKey& pubkey);
/// Sign the message, returns true if successful
bool SignMessage(std::string strMessage, std::string& errorMessage, std::vector<unsigned char>& vchSig, CKey key);
/// Verify the message, returns true if succcessful
bool VerifyMessage(CPubKey pubkey, std::vector<unsigned char>& vchSig, std::string strMessage, std::string& errorMessage);
};
/** Used to keep track of current status of Darksend pool
*/
class CDarksendPool
{
private:
mutable CCriticalSection cs_Darksend;
std::vector<CDarKsendEntry> entries; // Masternode/clients entries
CMutableTransaction finalTransaction; // the finalized transaction ready for signing
int64_t lastTimeChanged; // last time the 'state' changed, in UTC milliseconds
unsigned int state; // should be one of the POOL_STATUS_XXX values
unsigned int entriesCount;
unsigned int lastEntryAccepted;
unsigned int countEntriesAccepted;
std::vector<CTxIn> lockedCoins;
std::string lastMessage;
bool unitTest;
int sessionID;
int sessionUsers; //N Users have said they'll join
bool sessionFoundMasternode; //If we've found a compatible Masternode
std::vector<CTransaction> vecSessionCollateral;
int cachedLastSuccess;
int minBlockSpacing; //required blocks between mixes
CMutableTransaction txCollateral;
int64_t lastNewBlock;
//debugging data
std::string strAutoDenomResult;
public:
enum messages {
ERR_ALREADY_HAVE,
ERR_DENOM,
ERR_ENTRIES_FULL,
ERR_EXISTING_TX,
ERR_FEES,
ERR_INVALID_COLLATERAL,
ERR_INVALID_INPUT,
ERR_INVALID_SCRIPT,
ERR_INVALID_TX,
ERR_MAXIMUM,
ERR_MN_LIST,
ERR_MODE,
ERR_NON_STANDARD_PUBKEY,
ERR_NOT_A_MN,
ERR_QUEUE_FULL,
ERR_RECENT,
ERR_SESSION,
ERR_MISSING_TX,
ERR_VERSION,
MSG_NOERR,
MSG_SUCCESS,
MSG_ENTRIES_ADDED
};
// where collateral should be made out to
CScript collateralPubKey;
CMasternode* pSubmittedToMasternode;
int sessionDenom; //Users must submit an denom matching this
int cachedNumBlocks; //used for the overview screen
CDarksendPool()
{
/* Darksend uses collateral addresses to trust parties entering the pool
to behave themselves. If they don't it takes their money. */
cachedLastSuccess = 0;
cachedNumBlocks = std::numeric_limits<int>::max();
unitTest = false;
txCollateral = CMutableTransaction();
minBlockSpacing = 0;
lastNewBlock = 0;
SetNull();
}
/** Process a Darksend message using the Darksend protocol
* \param pfrom
* \param strCommand lower case command string; valid values are:
* Command | Description
* -------- | -----------------
* dsa | Darksend Acceptable
* dsc | Darksend Complete
* dsf | Darksend Final tx
* dsi | Darksend vIn
* dsq | Darksend Queue
* dss | Darksend Signal Final Tx
* dssu | Darksend status update
* dssub | Darksend Subscribe To
* \param vRecv
*/
void ProcessMessageDarksend(CNode* pfrom, std::string& strCommand, CDataStream& vRecv);
void InitCollateralAddress()
{
SetCollateralAddress(Params().DarksendPoolDummyAddress());
}
void SetMinBlockSpacing(int minBlockSpacingIn)
{
minBlockSpacing = minBlockSpacingIn;
}
bool SetCollateralAddress(std::string strAddress);
void Reset();
void SetNull();
void UnlockCoins();
bool IsNull() const
{
return state == POOL_STATUS_ACCEPTING_ENTRIES && entries.empty();
}
int GetState() const
{
return state;
}
std::string GetStatus();
int GetEntriesCount() const
{
return entries.size();
}
/// Get the time the last entry was accepted (time in UTC milliseconds)
int GetLastEntryAccepted() const
{
return lastEntryAccepted;
}
/// Get the count of the accepted entries
int GetCountEntriesAccepted() const
{
return countEntriesAccepted;
}
// Set the 'state' value, with some logging and capturing when the state changed
void UpdateState(unsigned int newState)
{
if (fMasterNode && (newState == POOL_STATUS_ERROR || newState == POOL_STATUS_SUCCESS)) {
LogPrint("Darksend", "CDarksendPool::UpdateState() - Can't set state to ERROR or SUCCESS as a Masternode. \n");
return;
}
LogPrintf("CDarksendPool::UpdateState() == %d | %d \n", state, newState);
if (state != newState) {
lastTimeChanged = GetTimeMillis();
if (fMasterNode) {
RelayStatus(DarKsendPool.sessionID, DarKsendPool.GetState(), DarKsendPool.GetEntriesCount(), MASTERNODE_RESET);
}
}
state = newState;
}
/// Get the maximum number of transactions for the pool
int GetMaxPoolTransactions()
{
return Params().PoolMaxTransactions();
}
/// Do we have enough users to take entries?
bool IsSessionReady()
{
return sessionUsers >= GetMaxPoolTransactions();
}
/// Are these outputs compatible with other client in the pool?
bool IsCompatibleWithEntries(std::vector<CTxOut>& vout);
/// Is this amount compatible with other client in the pool?
bool IsCompatibleWithSession(int64_t nAmount, CTransaction txCollateral, int& errorID);
/// Passively run Darksend in the background according to the configuration in settings (only for QT)
bool DoAutomaticDenominating(bool fDryRun = false);
bool PrepareDarksendDenominate();
/// Check for process in Darksend
void Check();
void CheckFinalTransaction();
/// Charge fees to bad actors (Charge clients a fee if they're abusive)
void ChargeFees();
/// Rarely charge fees to pay miners
void ChargeRandomFees();
void CheckTimeout();
void CheckForCompleteQueue();
/// Check to make sure a signature matches an input in the pool
bool SignatureValid(const CScript& newSig, const CTxIn& newVin);
/// If the collateral is valid given by a client
bool IsCollateralValid(const CTransaction& txCollateral);
/// Add a clients entry to the pool
bool AddEntry(const std::vector<CTxIn>& newInput, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxOut>& newOutput, int& errorID);
/// Add signature to a vin
bool AddScriptSig(const CTxIn& newVin);
/// Check that all inputs are signed. (Are all inputs signed?)
bool SignaturesComplete();
/// As a client, send a transaction to a Masternode to start the denomination process
void SendDarksendDenominate(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout, int64_t amount);
/// Get Masternode updates about the progress of Darksend
bool StatusUpdate(int newState, int newEntriesCount, int newAccepted, int& errorID, int newSessionID = 0);
/// As a client, check and sign the final transaction
bool SignFinalTransaction(CTransaction& finalTransactionNew, CNode* node);
/// Get the last valid block hash for a given modulus
bool GetLastValidBlockHash(uint256& hash, int mod = 1, int nBlockHeight = 0);
/// Process a new block
void NewBlock();
void CompletedTransaction(bool error, int errorID);
void ClearLastMessage();
/// Used for liquidity providers
bool SendRandomPaymentToSelf();
/// Split up large inputs or make fee sized inputs
bool MakeCollateralAmounts();
bool CreateDenominated(int64_t nTotalValue);
/// Get the denominations for a list of outputs (returns a bitshifted integer)
int GetDenominations(const std::vector<CTxOut>& vout, bool fSingleRandomDenom = false);
int GetDenominations(const std::vector<CTxDSOut>& vout);
void GetDenominationsToString(int nDenom, std::string& strDenom);
/// Get the denominations for a specific amount of helmin.
int GetDenominationsByAmount(int64_t nAmount, int nDenomTarget = 0); // is not used anymore?
int GetDenominationsByAmounts(std::vector<int64_t>& vecAmount);
std::string GetMessageByID(int messageID);
//
// Relay Darksend Messages
//
void RelayFinalTransaction(const int sessionID, const CTransaction& txNew);
void RelaySignaturesAnon(std::vector<CTxIn>& vin);
void RelayInAnon(std::vector<CTxIn>& vin, std::vector<CTxOut>& vout);
void RelayIn(const std::vector<CTxDSIn>& vin, const int64_t& nAmount, const CTransaction& txCollateral, const std::vector<CTxDSOut>& vout);
void RelayStatus(const int sessionID, const int newState, const int newEntriesCount, const int newAccepted, const int errorID = MSG_NOERR);
void RelayCompletedTransaction(const int sessionID, const bool error, const int errorID);
};
void ThreadCheckDarKsendPool();
#endif
|
[
"seniormanagement@computerstudio.eu"
] |
seniormanagement@computerstudio.eu
|
43d2249bc3fc5e5c53d10347ef988619fbeaf107
|
ac13959437a22b0dd7a0e808e44e12971ff6f79f
|
/CodeC3/NhuQuynh_C3_Bai1.cpp
|
07aefd09b726b3daaf52a75146c6b4ac2afe4f28
|
[] |
no_license
|
hieu-ln/IT81-09
|
a6a8845ed1565ce11a1a1ba98f3f7a9a554dcba0
|
f84c8322926a05fe6b2ae5832cfb4a1ba073e0f8
|
refs/heads/master
| 2020-06-11T06:42:04.968585
| 2019-08-17T17:04:54
| 2019-08-17T17:04:54
| 193,879,288
| 0
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,023
|
cpp
|
#include <iostream>
#include <ctime>
using namespace std;
//1.1
#define max 1000
int a[max];
int n;
//1.2
//khoi tao ngau nhien
void Init(int a[], int &n)
{
cout << "Nhap sluong ptu: ";
do{
cin >> n;
if (n < 0 || n > max)
cout << "Nhap n tu 1 - " << max << ". nhap lai: ";
} while(n < 0 || n > max);
for (int i = 0; i < n; i++)
a[i] = rand() % 1000;
cout << "Danh sach vua khoi tao ngau nhien la:\n";
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
//Khoi tao bang cach nhap
void Input(int a[], int &n)
{
cout << "Nhap sluong ptu: ";
do{
cin >> n;
if (n < 0 || n > max)
cout << "Nhap n tu 1 - " << max << ". nhap lai: ";
} while(n < 0 || n > max);
for (int i = 0; i < n; i++)
{
cout << "Nhap a[" << i << "] = ";
cin >> a[i];
}
}
//1.3
void Output(int a[], int n)
{
for (int i = 0; i < n; i++)
cout << a[i] << " ";
cout << endl;
}
//ham hoan doi
void Swap(int &a, int &b)
{
int tam = a;
a = b;
b = tam;
}
//1.4
void InsertionSort(int a[], int n)
{
int i, j, key;
for (i = 0; i < n; i++)
{
key = a[i];
j = i - 1;
while (j >= 0 && a[j] > key)
{
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
}
//1.5
void SelectionSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
{
int min = i;
for (int j = i + 1; j < n; j++)
if (a[j] < a[min])
min = j;
Swap(a[min], a[i]);
}
}
//1.6
void InterchangeSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = i + 1; j < n; j++)
if (a[j] < a[i])
Swap(a[i], a[j]);
}
//1.7
void BubbleSort(int a[], int n)
{
for (int i = 0; i < n - 1; i++)
for (int j = i; j < n - 1; j++)
if (a[j] > a[j + 1])
Swap(a[j + 1], a[j]);
}
//1.8
void QuickSort(int a[], int l, int r)
{
int x = a[(l + r) / 2];
int i = l, j = r;
while (i < j)
{
while (a[i] < x)
i++;
while (a[j] > x)
j--;
if (i <= j)
{
Swap(a[i], a[j]);
i++;
j--;
}
}
if (i < r)
QuickSort(a, i, r);
if (j > l)
QuickSort(a, l, j);
}
//1.9
void shift(int a[], int i, int n)
{
int j = 2 * i + 1;
if (j >= n)
return;
if (j + 1 < n)
if (a[j] < a[j + 1])
j++;
if (a[i] >= a[j])
return;
else
{
Swap(a[i], a[j]);
shift(a, j, n);
}
}
void HeapSort(int a[], int n)
{
int i = n / 2;
while (i >= 0)
{
shift(a, i, n - 1);
i--;
}
int r = n - 1;
while (r > 0)
{
Swap(a[0], a[r]);
r--;
if (r > 0)
shift(a, 0, r);
}
}
//1.10
int Search(int a[], int n, int x)
{
for (int i = 0; i < n; i++)
if (a[i] == x)
return i;
return 0;
}
//1.11
int BinarySearch(int a[], int n, int x)
{
int l = 0, r = n - 1, m;
while (l <= r)
{
m = (l + r) / 2;
if (a[m] == x)
return m;
else
if (a[m] > x)
l = m + 1;
else
r = m - 1;
}
return 0;
}
//menu
void menu()
{
cout << "------CHUONG 3 - BAI 1------" << endl;
cout << "1. Khoi tao danh sach ngau nhien" << endl;
cout << "2. Nhap danh sach" << endl;
cout << "3. Xuat danh sach" << endl;
cout << "4. Sap xep danh sach bang thuat toan InsertionSort" << endl;
cout << "5. Sap xep danh sach bang thuat toan SelectionSort" << endl;
cout << "6. Sap xep danh sach bang thuat toan interchangeSort" << endl;
cout << "7. Sap xep danh sach bang thuat toan BubbleSort" << endl;
cout << "8. Sap xep danh sach bang thuat toan QuickSort" << endl;
cout << "9. Sap xep danh sach bang thuat toan HeapSort" << endl;
cout << "10. Tim kiem 1 ptu trong danh sach dung pp tim kiem tuan tu" << endl;
cout << "11. Tim kiem 1 ptu trong danh sach dung pp tim kiem nhi phan" << endl;
cout << "0. Thoat" << endl;
}
void main()
{
int choice, x, kq;
srand(time(NULL));
menu();
do{
cout << "Chon 1 so de thuc hien: ";
cin >> choice;
switch(choice)
{
case 1:
Init(a, n);
break;
case 2:
Input(a, n);
break;
case 3:
cout << "Danh sach hien tai la:\n";
Output(a, n);
break;
case 4:
InsertionSort(a, n);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 5:
SelectionSort(a, n);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 6:
InterchangeSort(a, n);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 7:
BubbleSort(a, n);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 8:
QuickSort(a, 0, n - 1);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 9:
HeapSort(a, n);
cout << "Danh sach sau khi sap xep la:\n";
Output(a, n);
break;
case 10:
cout << "Nhap gtri can tim: ";
cin >> x;
kq = Search(a, n, x);
if (kq != 0)
cout << "Tim thay gtri x = " << x << " tai vi tri i = " << kq << endl;
else
cout << "Khong tim thay gtri x = " << x << endl;
break;
case 11:
cout << "Nhap gtri can tim: ";
cin >> x;
kq = BinarySearch(a, n, x);
if (kq != 0)
cout << "Tim thay gtri x = " << x << " tai vi tri i = " << kq << endl;
else
cout << "Khong tim thay gtri x = " << x << endl;
break;
default:
cout << "Goodbey" << endl;
}
} while(choice != 0);
}
|
[
"1851050124quynh@ou.edu.vn"
] |
1851050124quynh@ou.edu.vn
|
3d585e6d4c3d720bcf54ea3c0f396818dc5a370a
|
a8c588bae9db3b73c8b6aac4deb6a914cf718a65
|
/PAT-A/1094.cpp
|
accf3c13b5bc99850bce9b41738d203c408dbaaf
|
[] |
no_license
|
zzhhch/pat
|
688f9227fe161135074c7b31e85c5a6b8ff51e1d
|
fd7592869be5218bb73fa572dc75d474418828c3
|
refs/heads/master
| 2020-03-24T11:09:31.025066
| 2019-06-03T06:29:14
| 2019-06-03T06:29:14
| 142,677,123
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 635
|
cpp
|
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int maxn=110;
vector<int> tree[maxn];
int n,m,maxNum=0,Depth=0;
int hashTable[maxn]={0};
void DFS(int index,int depth){
hashTable[depth]++;
for(int i=0;i<tree[index].size();i++){
DFS(tree[index][i],depth+1);
}
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=0;i<m;i++)
{
int temp,num,x;
scanf("%d%d",&temp,&num);
for(int j=0;j<num;j++){
scanf("%d",&x);
tree[temp].push_back(x);
}
}
DFS(1,1);
for(int i=0;i<maxn;i++){
if(hashTable[i]>maxNum){
maxNum=hashTable[i];
Depth=i;
}
}
printf("%d %d\n",maxNum,Depth);
return 0;
}
|
[
"zhanghength@163.com"
] |
zhanghength@163.com
|
f8a17f6c889f8a106e3089bbeb9973b54b9a2a53
|
c64c4f679ce0ba061c58bbf25e2eea5a196c53a7
|
/sartajekram/450-D/450-D-95263919.cpp
|
45d1c1b27a1a8ce4993982f7f3dc1416340027b3
|
[] |
no_license
|
sartajekram419/CodeforcesSolutions
|
b6c564e8b8ce2718d99fe4829a63bd6629b92461
|
f9d3594a84e95e0df6456adf2ea535b7399bf232
|
refs/heads/master
| 2023-03-23T07:44:12.527848
| 2021-03-21T07:19:54
| 2021-03-21T07:19:54
| 248,037,922
| 3
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,833
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define fastio ios_base::sync_with_stdio(false);cin.tie(NULL)
#define ll long long
#define inf 1e18
#define PI acos(-1.0)
#define mod 1000000007
typedef pair<ll, ll> pi;
ll n,m,k;
ll dis[100005],in[100005];
vector<pi>g[100005];
vector<pi>v;
void initialize()
{
for(ll i=0;i<=n;i++)dis[i]=inf,in[i]=0;
}
void dijkstra()
{
dis[1]=0;
priority_queue<pi,vector<pi>,greater<pi>>pq;
pq.push({0,1});
while(!pq.empty())
{
pair<int,int>p=pq.top();
pq.pop();
ll u=p.second;
ll w=p.first;
if(w!=dis[u])continue;
ll l=g[u].size(),i;
for(i=0;i<l;i++)
{
ll x=g[u][i].first;
ll w=g[u][i].second;
if(dis[x]>dis[u]+w)
{
dis[x]=dis[u]+w;
pq.push({dis[x],x});
in[x]=1;
}
else if(dis[x]==dis[u]+w)
{
in[x]++;
}
}
}
}
int main(void)
{
fastio;
ll a,b,c,i,ans=0;
cin >> n >> m >> k;
initialize();
while(m--)
{
cin >> a >> b >> c;
g[a].push_back({b,c});
g[b].push_back({a,c});
}
for(i=0;i<k;i++)
{
cin >> a >> b;
g[1].push_back({a,b});
//g[a].push_back({1,b});
v.push_back({a,b});
}
dijkstra();
for(i=0;i<k;i++)
{
pi p=v[i];
if(dis[p.first]<p.second)ans++;
else if(dis[p.first]==p.second && in[p.first]>1){ans++;in[p.first]--;}
}
cout << ans;
return 0;
}
|
[
"sartajekram419@gmail.com"
] |
sartajekram419@gmail.com
|
b8dab793f83a666322450cc2879e8d0044359a4c
|
64ad587f239164671b5e82fa12783e3ff9f5d627
|
/PGA/EA_library/random.h
|
f6a516f53a22cb61b815d2be90aa95e09eeb3a1d
|
[
"MIT"
] |
permissive
|
LandBuffalo/PGA
|
246ed50fd6341ef591a7c2c91f1b3a69599ebb17
|
d73dcf625231917c9685b4dedf4f05d9406ded6c
|
refs/heads/master
| 2020-03-28T14:43:11.290877
| 2018-09-12T17:13:32
| 2018-09-12T17:13:32
| 148,512,425
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 625
|
h
|
#ifndef __RANDOM_H__
#define __RANDOM_H__
#pragma once
#include "config.h"
class Random
{
public:
Random();
~Random();
int Permutate(vector<int> & requested_island_ID, int arrary_length, int permutation_length);
vector<int> Permutate(int arrary_length, int permutation_length);
vector<int> Permutate(int arrary_length, int permutation_length, vector<int> &avoid_index);
int Permutate(int * permutate_index, int arrary_length, int permutation_length);
int RandIntUnif(int min_value, int max_value);
double RandDoubleUnif(double min_value, double max_value);
};
#endif
|
[
"roy.chenjin@gmail.com"
] |
roy.chenjin@gmail.com
|
aca6b390fbcac12f337778b65ca88b67f48d8621
|
b08df58bd0f7f5c7d1919845f616234b8a763331
|
/Conditional and loops/LeapYear.cpp
|
aa8984f132bb1dfe6584bfd055213db71a57eb7d
|
[] |
no_license
|
harshbhandari7/CPP
|
55ba1e763f1a7e6d319baba89caeca08888439f3
|
c4b07f2c325f0d5d829498d498c175304c7ead71
|
refs/heads/master
| 2020-09-24T22:34:49.232005
| 2020-02-04T03:01:37
| 2020-02-04T03:01:37
| 225,859,077
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 258
|
cpp
|
#include<stdio.h>
int main(){
int year;
printf("Enter the year ");
scanf("%d",&year);
if(year%4==0&&year%400==0)
{
printf("%d ",year);
printf("is a Leap year");
}
else
{ printf("%d ",year);
printf("is not a Leap year");
}
}
|
[
"harshbhandari32@gmail.com"
] |
harshbhandari32@gmail.com
|
f87826e20a209c53a06a7e6862f3f53aa531958a
|
c8e62b5a343a9853ee570af208247c31745eea13
|
/zadace/dz04-teorija-brojeva/bomboni.dosilovic.cpp
|
be667ecc2663695abb2e1d4855998c4c3b3b3e43
|
[] |
no_license
|
hermanzdosilovic/natpro
|
9b9e6ab9273801b1f75c9bfade784980faf1f493
|
10b6c5d8a91492856ce6b22a19de79a3b0906d2b
|
refs/heads/master
| 2021-01-24T10:59:52.150688
| 2015-02-28T17:51:32
| 2015-02-28T17:51:32
| 70,276,664
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 741
|
cpp
|
#include <cstdio>
#include <cmath>
#define MAX(X, Y) ((X) > (Y) ? (X) : (Y))
const int MAXLEN = 200000;
const int MAXN = 2000000;
int N, n[MAXLEN + 3], maxn;
int zastupljenost[MAXN + 3];
int main() {
scanf("%d", &N);
for (int i = 0; i < N; i++) {
scanf("%d", &n[i]);
maxn = MAX(maxn, n[i]);
}
for (int i = 0; i < N; i++) {
int root = sqrt(n[i]);
for (int x = 1; x <= root; x++) {
if (n[i]%x == 0) {
zastupljenost[x]++;
if (x != n[i]/x)
zastupljenost[n[i]/x]++;
}
}
}
long long sol = 0;
for (long long i = 1; i <= maxn; i++) {
if (zastupljenost[i]*i >= sol && zastupljenost[i] >= 2)
sol = zastupljenost[i]*i;
}
printf("%lld\n", sol);
return 0;
}
|
[
"hermanz.dosilovic@gmail.com"
] |
hermanz.dosilovic@gmail.com
|
25014ca98787233f095932c6ae51a511df81ac45
|
2835cbdb95f8e223ab8ab972df1f124687205860
|
/task02/part1-2/complexnumber.cpp
|
ce0f4e4c957920d24dfb82df0fc57e76a948f769
|
[] |
no_license
|
beerfekt/Fortgeschrittene-Programmiertechniken
|
433406981805fd738f7093f0dec2cc03089cc3bd
|
ead2b7b18213823375e9849586a51f56d2be8567
|
refs/heads/master
| 2021-04-30T15:25:29.798268
| 2018-02-12T11:37:00
| 2018-02-12T11:37:00
| 121,238,852
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 220
|
cpp
|
#include "complexnumber.h"
//Konstruktoren
//standart eigen -> wird hier nicht angegeben
ComplexNumber::ComplexNumber(){};
//allgemein
ComplexNumber::ComplexNumber(double x, double y): allgemeinx(x), allgemeiny(y){};
|
[
"christoph.beer@gmx.de"
] |
christoph.beer@gmx.de
|
3c3a35c67dc03e54de32be7a7ebdd941f4e8099e
|
fd451cb1a829c72ea51a93168eba81a475f983a1
|
/liuyubo/08-Minimum-Span-Trees/Course Code (C++)/05-Implementation-of-Optimized-Prim-Algorithm/DenseGraph.h
|
4b0ee41b08810d713a19ce407ce3a66038c3cde2
|
[] |
no_license
|
shapigou123/Programming
|
e9fd63f509fb2b45ba9792b13092da6aa8abe935
|
64215eb0f333b583690e32cd9fcce02236713603
|
refs/heads/master
| 2021-06-26T02:33:56.623872
| 2017-09-07T07:12:11
| 2017-09-07T07:12:11
| 94,725,535
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 3,559
|
h
|
//
// Created by liuyubobobo on 9/26/16.
//
#ifndef INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_DENSEGRAPH_H
#define INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_DENSEGRAPH_H
#include <iostream>
#include <vector>
#include <cassert>
#include "Edge.h"
using namespace std;
// 稠密图 - 邻接矩阵
template <typename Weight>
class DenseGraph{
private:
int n, m; // 节点数和边数
bool directed; // 是否为有向图
vector< vector<Edge<Weight> *> > g; // 图的具体数据
public:
// 构造函数
DenseGraph( int n , bool directed){
assert( n >= 0 );
this->n = n;
this->m = 0;
this->directed = directed;
// g初始化为n*n的矩阵, 每一个g[i][j]指向一个边的信息, 初始化为NULL
g = vector< vector<Edge<Weight> *> >(n, vector<Edge<Weight> *>(n, NULL));
}
// 析构函数
~DenseGraph(){
for( int i = 0 ; i < n ; i ++ )
for( int j = 0 ; j < n ; j ++ )
if( g[i][j] != NULL )
delete g[i][j];
}
int V(){ return n;} // 返回节点个数
int E(){ return m;} // 返回边的个数
// 向图中添加一个边, 权值为weight
void addEdge( int v, int w , Weight weight ){
assert( v >= 0 && v < n );
assert( w >= 0 && w < n );
// 如果从v到w已经有边, 删除这条边
if( hasEdge( v , w ) ){
delete g[v][w];
if( v != w && !directed )
delete g[w][v];
m --;
}
g[v][w] = new Edge<Weight>(v, w, weight);
if( v != w && !directed )
g[w][v] = new Edge<Weight>(w, v, weight);
m ++;
}
// 验证图中是否有从v到w的边
bool hasEdge( int v , int w ){
assert( v >= 0 && v < n );
assert( w >= 0 && w < n );
return g[v][w] != NULL;
}
// 显示图的信息
void show(){
for( int i = 0 ; i < n ; i ++ ){
for( int j = 0 ; j < n ; j ++ )
if( g[i][j] )
cout<<g[i][j]->wt()<<"\t";
else
cout<<"NULL\t";
cout<<endl;
}
}
// 邻边迭代器, 传入一个图和一个顶点,
// 迭代在这个图中和这个顶点向连的所有边
class adjIterator{
private:
DenseGraph &G; // 图G的引用
int v;
int index;
public:
// 构造函数
adjIterator(DenseGraph &graph, int v): G(graph){
this->v = v;
this->index = -1; // 索引从-1开始, 因为每次遍历都需要调用一次next()
}
~adjIterator(){}
// 返回图G中与顶点v相连接的第一个边
Edge<Weight>* begin(){
// 索引从-1开始, 因为每次遍历都需要调用一次next()
index = -1;
return next();
}
// 返回图G中与顶点v相连接的下一个边
Edge<Weight>* next(){
// 从当前index开始向后搜索, 直到找到一个g[v][index]为true
for( index += 1 ; index < G.V() ; index ++ )
if( G.g[v][index] )
return G.g[v][index];
// 若没有顶点和v相连接, 则返回NULL
return NULL;
}
// 查看是否已经迭代完了图G中与顶点v相连接的所有边
bool end(){
return index >= G.V();
}
};
};
#endif //INC_05_IMPLEMENTATION_OF_OPTIMIZED_PRIM_ALGORITHM_DENSEGRAPH_H
|
[
"563594467@qq.com"
] |
563594467@qq.com
|
f47aecc5552035e92bd068814d4bbe10b833d9e5
|
f431304e068b60713b3a449347a9de07a81c7926
|
/src/app/bsp.hpp
|
059540ec72aa36edd8e8ba57cc8728df4e46f4f1
|
[] |
no_license
|
khoinguyentran/hdb-node
|
538ae51baa0ec82a32779cccd7521ef398ae4c88
|
073157d197b3aa850789bd75440dd814069b7c35
|
refs/heads/master
| 2021-01-21T10:13:23.771689
| 2013-09-19T04:51:37
| 2013-09-19T04:51:37
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 224
|
hpp
|
#ifndef BSP_HPP
#define BSP_HPP
#include <cstddef>
namespace app
{
size_t const BSP_TICKS_PER_SEC = static_cast< size_t >(50);
inline size_t SECONDS(size_t duration)
{
return duration * BSP_TICKS_PER_SEC;
}
}
#endif
|
[
"hans@freebies.i.kaisquare.com"
] |
hans@freebies.i.kaisquare.com
|
8d68cff26c934db88e5a24edf371ac5bb95171a6
|
b1a7cce559cda225fe0b57033cd93c826185fafd
|
/数据结构/ 第二次竞赛/2-树递归创建:遍历/test-2-2/main.cpp
|
d44cdcdb27d7fb5b98512737e9424dfd3389f9aa
|
[
"Apache-2.0"
] |
permissive
|
nju-rookie/DS
|
cf59374576f7e514725f385c63d0ece3322b2b59
|
507f933af618dc2d9644406a42d925dc93517fb4
|
refs/heads/master
| 2020-09-17T00:47:46.416451
| 2019-11-25T12:00:48
| 2019-11-25T12:00:48
| 223,937,110
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,664
|
cpp
|
//
// main.cpp
// test-2-2
//
// Created by 谢宇 on 2019/10/31.
// Copyright © 2019 谢宇. All rights reserved.
// 给定两个二叉树,检查它们是否呈镜像对称的。即树的结构成轴对称,且对应节点的节点值相同
#include <iostream>
using namespace std;
struct node{
int data;
node* left;
node* right;
};
void InOrder(node *Tree);
void PostOrder(node *Tree);
int a[200];
int b[200];
int num1=0;
int num2=0;
node* create(node* Tree);
int main()
{
node *Tree_1 = NULL;
Tree_1 = create(Tree_1);
node *Tree_2 = NULL;
Tree_2 = create(Tree_2);
if(Tree_1 == NULL && Tree_2 == NULL)
{cout << "YES";return 0;}
if((Tree_1 == NULL && Tree_2 != NULL) || (Tree_1 != NULL && Tree_2 == NULL)) {cout <<"NO";return 0;}
InOrder(Tree_1);
PostOrder(Tree_2);
if(num1 != num2)
{cout << "NO";return 0;}
for(int i = 0;i < num1;i++){
if(a[i] != b[i])
{cout << "NO";return 0;}
}
cout <<"YES";
return 0;
}
node* create(node* Tree)
{
int c;
cin >> c;
if(c == -1) Tree = NULL;
else{
Tree = (node*)malloc(sizeof(node));
Tree -> data = c;
Tree -> left = create(Tree -> left);
Tree -> right = create(Tree -> right);
}
return Tree;
}
void InOrder(node *Tree)
{
node *p = Tree;
if(p != NULL){
InOrder(p -> left);
a[num1++] = p -> data;
InOrder(p -> right);
}
}
void PostOrder(node *Tree)
{
node *p = Tree;
if(p != NULL){
PostOrder(p -> right);
b[num2++] = p -> data;
PostOrder(p -> left);
}
}
|
[
"xieyu@xieyudeMBP.lan"
] |
xieyu@xieyudeMBP.lan
|
aa985e6922293e952d3822e0052f298606a79140
|
cb47afd436e34d6f49243ef1b228aa020d9f31b6
|
/OpenGLFramework/OpenGLFramework/RHomingRockets.cpp
|
87d937cebd44c25ff05f47da119a28b27ef8fb50
|
[
"MIT"
] |
permissive
|
PlayeRom/SpaceShooter
|
b803993380d22c9ddd1388bca4f2e3ad926a7b8c
|
c284ca6503800ed1e45fc8ceeaf9d98d38917f30
|
refs/heads/master
| 2022-06-17T22:16:20.473496
| 2020-05-08T22:53:56
| 2020-05-08T22:53:56
| 262,427,517
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,065
|
cpp
|
#include "StdAfx.h"
#include "GameControl.h"
#include "RGame.h"
#include "RBonus.h"
#include "../Draw/3DObjManager.h"
#include "RHomingRockets.h"
CRHomingRockets::CRHomingRockets()
{
m_pGameCtrl = CGameControl::GetInstance();
// tworzenie tablicy rakiet
SHomingRockets sHomingRockets;
sHomingRockets.sShot.bDraw = GL_FALSE;
sHomingRockets.sShot.fSpeed = 600.0f;//150.0f; //900.0f i predkosc statku wroga 260.0f - za szybko
sHomingRockets.sShot.iTexture = -1;//m_pGameCtrl->m_iTexParticle01;//czasteczka
sHomingRockets.sShot.i3DObjIndex = -1;
sHomingRockets.sShot.eWeaponType = EWeaponHomingRocket;
sHomingRockets.sShot.uiGroupIndex = 0;
sHomingRockets.sShot.iModeFly = 0;
for( GLint i = 0; i < MAX_HOMING_ROCKETS_ARRAY; ++i ) {
sHomingRockets.iAnimIndex = m_pGameCtrl->GetSpeedCtrl()->CreateAnimationControl();
m_aHomingRockets.push_back( sHomingRockets );
}
m_aIndices = new CVector3[ 2 ];
}
CRHomingRockets::~CRHomingRockets()
{
m_aHomingRockets.clear();
delete [] m_aIndices;
}
GLvoid CRHomingRockets::SetForStart()
{
for( GLint i = 0; i < GetHomingRocketsSize(); ++i )
m_aHomingRockets[ i ].sShot.bDraw = GL_FALSE;
}
GLvoid CRHomingRockets::AddPlayerShot_HomingRocket()
{
//oblicz czestotliwosc wystrzalu zaleznie od gwiazdki dla uzbrojenia
// czestotliwosc strzelania 2 razy mniejsza od lasera
// sila rakiety 2 razy wieksza od lasera
unsigned long ulMS = static_cast<unsigned long>( m_pGameCtrl->GetRGame()->GetPlayer()->GetStarsArmament() );
switch( ulMS) {
case 0:
ulMS = 900 - m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsRateShoot();
break;
case 1:
ulMS = 770 - m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsRateShoot();
break;
case 2:
ulMS = 640 - m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsRateShoot();
break;
case 3:
ulMS = 510 - m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsRateShoot();
break;
}
if( !m_pGameCtrl->GetSpeedCtrl()->CheckAnimationTime( ulMS, 2 ) )
return;
m_pGameCtrl->GetRGame()->GetRBonus()->ReduceAmmoHomingRockets( 1 );
GLint iHowMuch = m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsNumberShots(); //ile wystrzelic na raz
for( GLint i = 0; i < GetHomingRocketsSize(); ++i ) {
if( !m_aHomingRockets[ i ].sShot.bDraw ) {
m_aHomingRockets[ i ].sShot.bDraw = GL_TRUE;
m_aHomingRockets[ i ].cPos = m_pGameCtrl->GetRGame()->GetPlayer()->GetPosition();
m_aHomingRockets[ i ].cPos.z -= m_pGameCtrl->GetRGame()->GetPlayer()->GetCollisionA();
m_aHomingRockets[ i ].fStartPosX = 0.0f;
m_aHomingRockets[ i ].iSmokeCounter = 0;
m_aHomingRockets[ i ].sShot.iArmament = ( m_pGameCtrl->GetRGame()->GetPlayer()->GetArmamentActual() + m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsPowerShoot() ) * 2;
m_aHomingRockets[ i ].sShot.i3DObjIndex = -1;
switch( m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsNumberShots() ) {
case 2:
if( iHowMuch == 2 )
m_aHomingRockets[ i ].sShot.iModeFly = 1;
else if( iHowMuch == 1 )
m_aHomingRockets[ i ].sShot.iModeFly = -1;
break;
case 3:
if( iHowMuch == 2 )
m_aHomingRockets[ i ].sShot.iModeFly = 1;
else if( iHowMuch == 1 )
m_aHomingRockets[ i ].sShot.iModeFly = -1;
else
m_aHomingRockets[ i ].sShot.iModeFly = 0;
break;
default: //1
m_aHomingRockets[ i ].sShot.iModeFly = 0;
break;
}
if( --iHowMuch == 0 )
break;
}
}
if( CWindowData::GetInstance()->SettingFile().bSound )
COpenALManager::GetInstance()->PlayNo3D( m_pGameCtrl->m_iSoundHomingRocket );
}
GLvoid CRHomingRockets::DrawHomingRocket()
{
glEnable( GL_DEPTH_TEST );
glEnable( GL_LIGHTING );
glDisable( GL_LIGHT0 );
glEnable( GL_LIGHT2 );
glDisable( GL_BLEND );
m_pGameCtrl->Disable2D();
for( GLint i = GetHomingRocketsSize() - 1; i >= 0; --i ) {
if( !m_aHomingRockets[ i ].sShot.bDraw )
continue;
CVector4 cLightPosShadow;
if( CWindowData::GetInstance()->SettingFile().bShadows ) {
glLoadIdentity();
//glScalef(-0.5f, -1.0f, -0.5f );
glRotatef(-180.0f, 0.0f, 1.0f, 0.0f );
glTranslatef( -m_aHomingRockets[ i ].cPos.x, -m_aHomingRockets[ i ].cPos.y, -m_aHomingRockets[ i ].cPos.z );
m_pGameCtrl->GetRGame()->SetCamera();
cLightPosShadow = m_pGameCtrl->GetStencilShadow()->GetLightPos( m_pGameCtrl->GetLighting()->GetPosition( GL_LIGHT2 ) );
}
glLoadIdentity();
m_pGameCtrl->GetRGame()->SetCamera();
glTranslatef( m_aHomingRockets[ i ].cPos.x, m_aHomingRockets[ i ].cPos.y, m_aHomingRockets[ i ].cPos.z );
glRotatef( 180.0f, 0.0f, 1.0f, 0.0f );
//glScalef( 0.5f, 1.0f, 0.5f );
m_pGameCtrl->Get3DObjManager()->Draw3DObject_Lists( REMOTE_ROCKET_3DOBJ_INDEX, GL_FALSE );
if( CWindowData::GetInstance()->SettingFile().bShadows )
m_pGameCtrl->GetStencilShadow()->DrawShadowForObj( REMOTE_ROCKET_3DOBJ_INDEX, cLightPosShadow );
m_aHomingRockets[ i ].cPos.z -= ( m_aHomingRockets[ i ].sShot.fSpeed * m_pGameCtrl->GetSpeedCtrl()->GetMultiplier() );
if( m_aHomingRockets[ i ].cPos.z < MAX_GAME_DISTANCE )
m_aHomingRockets[ i ].sShot.bDraw = GL_FALSE;
if( m_aHomingRockets[ i ].fStartPosX < 0.25f && m_aHomingRockets[ i ].sShot.iModeFly != 0 ) {
if( m_aHomingRockets[ i ].sShot.iModeFly == -1 )
m_aHomingRockets[ i ].cPos.x -= ( ( m_aHomingRockets[ i ].sShot.fSpeed / 2.0f ) * m_pGameCtrl->GetSpeedCtrl()->GetMultiplier() );
else if( m_aHomingRockets[ i ].sShot.iModeFly == 1 )
m_aHomingRockets[ i ].cPos.x += ( ( m_aHomingRockets[ i ].sShot.fSpeed / 2.0f ) * m_pGameCtrl->GetSpeedCtrl()->GetMultiplier() );
m_aHomingRockets[ i ].fStartPosX += m_pGameCtrl->GetSpeedCtrl()->GetMultiplier();
}
if( m_aHomingRockets[ i ].sShot.bDraw ) {
GLint iSmokeLimit = 75;
switch( m_pGameCtrl->GetRGame()->GetRBonus()->GetHomingRocketsNumberShots() ) {
case 2:
iSmokeLimit = 40;
break;
case 3:
iSmokeLimit = 25;
break;
}
if( m_aHomingRockets[ i ].iSmokeCounter < iSmokeLimit && m_pGameCtrl->GetSpeedCtrl()->CheckAnimationTime( 10, m_aHomingRockets[ i ].iAnimIndex ) ) {
m_pGameCtrl->GetRGame()->GetUnivBillboard()->AddSmokeRemoteRocket( m_aHomingRockets[ i ].cPos );
++m_aHomingRockets[ i ].iSmokeCounter;
}
//sprawdz czy rakieta nie zderzyla sie z jakims wrogim statkiem
m_pGameCtrl->GetRGame()->CheckCollisionEnemyShot( m_aHomingRockets[ i ].sShot, m_aHomingRockets[ i ].cPos );
//#ifdef HOMING_ROCKETS
if( m_aHomingRockets[ i ].sShot.bDraw ) {
//samonaprowadzaj
//znajdz pierwszy, najblizszy wrogi statek, od zadanej odleglosci od rakiety
GLfloat fDistActual = -MAX_GAME_DISTANCE;
GLint iHomingIndex = -1; //indeks statku na ktorego bedziemy sie naprowadzac
CEnemyShip *objEnemyShip = m_pGameCtrl->GetRGame()->GetEnemyShip();
for( GLint j = objEnemyShip->GetEnemyShipSize() - 1; j >= 0; --j ) {
//naprowadza sie takze na wraki
if( !objEnemyShip->GetEnemyShip( j ).bAlive || !objEnemyShip->GetEnemyShip( j ).bStart )
continue;
if( objEnemyShip->GetEnemyShip( j ).cActualPos.z >= m_aHomingRockets[ i ].cPos.z )
continue;
//sprawdz czy sie angazowac
// os Z
// ^
// | x
// +-----E
// | /
// | /
// d| /20 stopni
// | /
// |/
// R------------> os X
//
// R - rakieta lecaca ku gorze
// E - enemy
// d - odleglosc po os Z od rakiety do statku
// x - dludos ktora wyliczamy, dla zalozenia ze tak mieczy statkiem a rakieta wynosi 45 stopni
//odleglosc po osi Z, miedzy rakieta a statkiem, gdyby statek byl pod katem 0 stopni
GLfloat d = objEnemyShip->GetEnemyShip( j ).cActualPos.CalcDistanceZ( m_aHomingRockets[ i ].cPos );
//odleglosc po osi x, miedzy rakieta a statkiem, gdyby statek byl pod katem 20 stopni
GLfloat fDistXAngle = d * tan( DEG2RAD( 20.0f ) );
//odleglosc po osi x, miedzy rakieta a statkiem, gdyby statek byl pod katem 90 stopni
GLfloat fDistXReal = objEnemyShip->GetEnemyShip( j ).cActualPos.CalcDistanceX( m_aHomingRockets[ i ].cPos );
if( fDistXReal >= fDistXAngle )
continue;
//oblicz odleglosc aby alokowac sie na najblizszy cel
GLfloat fDistance = objEnemyShip->GetEnemyShip( j ).cActualPos.CalcDistanceXZ( m_aHomingRockets[ i ].cPos );
if( fDistance < fDistActual ) {
fDistActual = fDistance;
iHomingIndex = j;
}
}
if( iHomingIndex >= 0 ) {
//objEnemyShip->GetEnemyShip( iHomingIndex ).iEngageHomingRocket = i;
if( m_pGameCtrl->GetRGame()->GetRBonus()->GetNumberViewFinder() >= 1 ) {
glLoadIdentity();
glDisable( GL_LIGHTING );
glDisable( GL_TEXTURE_2D );
m_pGameCtrl->GetRGame()->SetCamera();
GLint iIndexColor = CWindowData::GetInstance()->SettingFile().iHudColor;
glColor3f( m_pGameCtrl->GetRGame()->GetHudColor( iIndexColor ).x,
m_pGameCtrl->GetRGame()->GetHudColor( iIndexColor ).y,
m_pGameCtrl->GetRGame()->GetHudColor( iIndexColor ).z );
m_pGameCtrl->GetRGame()->DrawEngageSquare( objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos );
}
//
if( m_pGameCtrl->GetRGame()->GetRBonus()->GetNumberViewFinder() >= 4 ) {
//dla co najmniej 5 zchwytanych znajdziek viewfindef rysuj linie laczaca rakiete ze statkiem
m_aIndices[ 0 ] = m_aHomingRockets[ i ].cPos;
m_aIndices[ 1 ] = objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos;
glEnableClientState( GL_VERTEX_ARRAY );
glDisableClientState( GL_NORMAL_ARRAY );
glDisableClientState( GL_COLOR_ARRAY );
glDisableClientState( GL_TEXTURE_COORD_ARRAY );
glVertexPointer( 3, GL_FLOAT, 0, m_aIndices );
glDrawArrays( GL_LINES, 0, 2 );
}
//
glColor3f( 1.0f, 1.0f, 1.0f );
glEnable( GL_LIGHTING );
glEnable( GL_TEXTURE_2D );
if( objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x < m_aHomingRockets[ i ].cPos.x ) {
//przesun w lewo
m_aHomingRockets[ i ].cPos.x -= ( ( m_aHomingRockets[ i ].sShot.fSpeed / 5.0f ) * m_pGameCtrl->GetSpeedCtrl()->GetMultiplier() );
if( m_aHomingRockets[ i ].cPos.x < objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x )
m_aHomingRockets[ i ].cPos.x = objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x;
}
else if( objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x > m_aHomingRockets[ i ].cPos.x ) {
//przesun w prawo
m_aHomingRockets[ i ].cPos.x += ( ( m_aHomingRockets[ i ].sShot.fSpeed / 5.0f ) * m_pGameCtrl->GetSpeedCtrl()->GetMultiplier() );
if( m_aHomingRockets[ i ].cPos.x > objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x )
m_aHomingRockets[ i ].cPos.x = objEnemyShip->GetEnemyShip( iHomingIndex ).cActualPos.x;
}
}
}
//#endif
}
}
glEnable( GL_LIGHT0 );
glDisable( GL_LIGHT2 );
}
|
[
"romek21@op.pl"
] |
romek21@op.pl
|
9c8180e754aeb606796ef1345fd4ca90db6a9224
|
0d37a489416e75ff013ebec2fbc2fdad80a521ac
|
/lib-properties/include/devicesparamsconst.h
|
d90c8d8de1266b484454e10c883f6c0ac7dc7b9b
|
[] |
no_license
|
JohnSHoover/rpidmx512
|
fc26f7ee9ead5c1a9cb4dbbac5b4963744d3353d
|
ed1416b693d28030ba9ae45a25adf0f280bfc70b
|
refs/heads/master
| 2022-04-10T17:31:36.334680
| 2020-04-10T16:48:45
| 2020-04-10T16:48:45
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,979
|
h
|
/**
* @file devicesparamsconst.h
*
*/
/* Copyright (C) 2019-2020 by Arjan van Vught mailto:info@orangepi-dmx.nl
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#ifndef DEVICESPARAMSCONST_H_
#define DEVICESPARAMSCONST_H_
#include <stdint.h>
class DevicesParamsConst {
public:
alignas(uint32_t) static const char FILE_NAME[];
alignas(uint32_t) static const char LED_TYPE[];
alignas(uint32_t) static const char LED_RGB_MAPPING[];
alignas(uint32_t) static const char LED_T0H[];
alignas(uint32_t) static const char LED_T1H[];
alignas(uint32_t) static const char LED_COUNT[];
alignas(uint32_t) static const char LED_GROUPING[];
alignas(uint32_t) static const char LED_GROUP_COUNT[];
alignas(uint32_t) static const char SPI_SPEED_HZ[];
alignas(uint32_t) static const char GLOBAL_BRIGHTNESS[];
alignas(uint32_t) static const char ACTIVE_OUT[];
alignas(uint32_t) static const char USE_SI5351A[];
};
#endif /* DEVICESPARAMSCONST_H_ */
|
[
"Arjan.van.Vught@gmail.com"
] |
Arjan.van.Vught@gmail.com
|
0842487825c671eeb0286937b4eda9976f1b00ba
|
bec96028ff3184d61bb08b79fcde54ae11052838
|
/models/gen_models/opcuacnc_cncaxistypebase.h
|
6115d138ddafc45c373e5eb59eff1fe4f2bc38db
|
[] |
no_license
|
impulze/thesiscode
|
2b8d9bc31721746359de67b904533d5704be0689
|
e5502db149aeaa436867ea4454c05d7958de0f78
|
refs/heads/master
| 2020-12-24T14:01:14.851387
| 2016-08-24T04:13:52
| 2016-08-24T04:13:52
| 65,730,896
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 7,256
|
h
|
/******************************************************************************
** opcuacnc_cncaxistypebase.h
**
** **************************** auto-generated ****************************
** This code was generated by a tool: UaModeler
** Runtime Version: 1.5.0, using C++ OPC UA SDK 1.5.0 template (version 4)
**
** Changes to this file may cause incorrect behavior and will be lost if
** the code is regenerated.
** **************************** auto-generated ****************************
**
** Copyright (c) 2006-2016 Unified Automation GmbH. All rights reserved.
**
** Software License Agreement ("SLA") Version 2.5
**
** Unless explicitly acquired and licensed from Licensor under another
** license, the contents of this file are subject to the Software License
** Agreement ("SLA") Version 2.5, or subsequent versions
** as allowed by the SLA, and You may not copy or use this file in either
** source code or executable form, except in compliance with the terms and
** conditions of the SLA.
**
** All software distributed under the SLA is provided strictly on an
** "AS IS" basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,
** AND LICENSOR HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT
** LIMITATION, ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
** PURPOSE, QUIET ENJOYMENT, OR NON-INFRINGEMENT. See the SLA for specific
** language governing rights and limitations under the SLA.
**
** The complete license agreement can be found here:
** http://unifiedautomation.com/License/SLA/2.5/
**
** Project: C++ OPC Server SDK information model for namespace http://opcfoundation.org/UA/CNC/
**
** Description: OPC Unified Architecture Software Development Kit.
**
** Created: 19.08.2016
**
******************************************************************************/
#ifndef __OPCUACNC_CNCAXISTYPEBASE_H__
#define __OPCUACNC_CNCAXISTYPEBASE_H__
#include "opcuacnc_cncdrivetype.h"
#include "opcuacnc_datatypes.h"
#include "basenodes.h"
#include "opcua_analogitemtype.h"
#include "opcua_basedatavariabletype.h"
#include "opcua_dataitemtype.h"
#include "opcua_propertytype.h"
#include "opcuacnc_cncpositiontype.h"
#include "opcuacnc_identifiers.h"
#include "opcuacnc_instancefactory_cnc.h"
#include "uaeuinformation.h"
#include "uarange.h"
// Namespace for the UA information model http://opcfoundation.org/UA/CNC/
namespace OpcUaCnc {
class CncPositionVariableType;
/** Generated base class for a CncAxisType.
*
* This class contains the generated base code for the object type CncAxisType
* representing an OPC UA ObjectType. This class is used to create the object type and to
* create and represent instances of the object type in the server address space.
*
* **Variable members of the CncAxisType:**
*
* Browse Name | DataType | TypeDefinition | Modelling Rule | See Also
* -------------|-----------------|-------------------------|----------------|-------------------------------------------
* ActStatus | CncAxisStatus | DataItemType | Mandatory | \ref getActStatus, \ref setActStatus
* IsReferenced | Boolean | DataItemType | Mandatory | \ref getIsReferenced, \ref setIsReferenced
* IsRotational | Boolean | DataItemType | Mandatory | \ref getIsRotational, \ref setIsRotational
* PosDirect | CncPositionType | CncPositionVariableType | Mandatory | \ref getPosDirect, \ref setPosDirect
* PosIndirect | CncPositionType | CncPositionVariableType | Mandatory | \ref getPosIndirect, \ref setPosIndirect
* ZeroOffset | Boolean | AnalogItemType | Mandatory | \ref getZeroOffset, \ref setZeroOffset
*
*/
class UAMODELS_EXPORT CncAxisTypeBase:
public OpcUaCnc::CncDriveType
{
UA_DISABLE_COPY(CncAxisTypeBase);
protected:
virtual ~CncAxisTypeBase();
public:
// construction / destruction
CncAxisTypeBase(const UaNodeId& nodeId, UaObject* pInstanceDeclarationObject, NodeManagerConfig* pNodeConfig, UaMutexRefCounted* pSharedMutex = NULL);
CncAxisTypeBase(const UaNodeId& nodeId, const UaString& name, OpcUa_UInt16 browseNameNameSpaceIndex, NodeManagerConfig* pNodeConfig, UaMutexRefCounted* pSharedMutex = NULL);
CncAxisTypeBase(
UaBase::Object* pBaseNode,
XmlUaNodeFactoryManager* pFactory,
NodeManagerConfig* pNodeConfig,
UaMutexRefCounted* pSharedMutex = NULL);
static void createTypes();
static void clearStaticMembers();
virtual UaNodeId typeDefinitionId() const;
virtual void setActStatus(OpcUaCnc::CncAxisStatus ActStatus);
virtual OpcUaCnc::CncAxisStatus getActStatus() const;
virtual void setIsReferenced(OpcUa_Boolean IsReferenced);
virtual OpcUa_Boolean getIsReferenced() const;
virtual void setIsRotational(OpcUa_Boolean IsRotational);
virtual OpcUa_Boolean getIsRotational() const;
virtual void setPosDirect(const OpcUaCnc::CncPositionType& PosDirect);
virtual OpcUaCnc::CncPositionType getPosDirect() const;
virtual void setPosIndirect(const OpcUaCnc::CncPositionType& PosIndirect);
virtual OpcUaCnc::CncPositionType getPosIndirect() const;
virtual void setZeroOffset(OpcUa_Boolean ZeroOffset);
virtual OpcUa_Boolean getZeroOffset() const;
virtual OpcUa::DataItemType* getActStatusNode();
virtual const OpcUa::DataItemType* getActStatusNode() const;
virtual OpcUa::DataItemType* getIsReferencedNode();
virtual const OpcUa::DataItemType* getIsReferencedNode() const;
virtual OpcUa::DataItemType* getIsRotationalNode();
virtual const OpcUa::DataItemType* getIsRotationalNode() const;
virtual OpcUaCnc::CncPositionVariableType* getPosDirectNode();
virtual const OpcUaCnc::CncPositionVariableType* getPosDirectNode() const;
virtual OpcUaCnc::CncPositionVariableType* getPosIndirectNode();
virtual const OpcUaCnc::CncPositionVariableType* getPosIndirectNode() const;
virtual OpcUa::AnalogItemType* getZeroOffsetNode();
virtual const OpcUa::AnalogItemType* getZeroOffsetNode() const;
// NodeAccessInfo management
virtual void useAccessInfoFromType();
void useAccessInfoFromInstance(CncAxisTypeBase *pInstance);
protected:
// Variable nodes
// Variable ActStatus
static OpcUa::DataItemType* s_pActStatus;
OpcUa::DataItemType* m_pActStatus;
// Variable IsReferenced
static OpcUa::DataItemType* s_pIsReferenced;
OpcUa::DataItemType* m_pIsReferenced;
// Variable IsRotational
static OpcUa::DataItemType* s_pIsRotational;
OpcUa::DataItemType* m_pIsRotational;
// Variable PosDirect
static OpcUaCnc::CncPositionVariableType* s_pPosDirect;
OpcUaCnc::CncPositionVariableType* m_pPosDirect;
// Variable PosIndirect
static OpcUaCnc::CncPositionVariableType* s_pPosIndirect;
OpcUaCnc::CncPositionVariableType* m_pPosIndirect;
// Variable ZeroOffset
static OpcUa::AnalogItemType* s_pZeroOffset;
OpcUa::AnalogItemType* m_pZeroOffset;
private:
void initialize();
private:
static bool s_typeNodesCreated;
};
} // End namespace for the UA information model http://opcfoundation.org/UA/CNC/
#endif // #ifndef __OPCUACNCCNCAXISTYPEBASE_H__
|
[
"daniel.b.mierswa@student.hs-rm.de"
] |
daniel.b.mierswa@student.hs-rm.de
|
f0d864dec0604091e2ea47ed56c4079da5e7c982
|
faee03fb630344384e670290fd84b5594a009e1c
|
/C++ Tutorial Hackerrank/6-Functions/Solution.h
|
a992f518b23fd432f7be38ee9a6f073e52d40138
|
[] |
no_license
|
Toxiedo/Hackerrank-Problems
|
438c3bbedc745b8b789ac1c087a2dbcc8cfc9f9a
|
6c6c9e59a5ef6f514fa67d440494a5316e68676f
|
refs/heads/master
| 2020-03-18T05:06:43.973117
| 2018-07-27T23:39:08
| 2018-07-27T23:39:08
| 134,325,059
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 639
|
h
|
#include <iostream>
#include <cstdio>
using namespace std;
int max_of_four(int a, int b, int c, int d);
/*
Add `int max_of_four(int a, int b, int c, int d)` here.
*/
int main() {
int a, b, c, d;
scanf("%d %d %d %d", &a, &b, &c, &d);
int ans = max_of_four(a, b, c, d);
printf("%d", ans);
return 0;
}
int max_of_four(int a, int b, int c, int d)
{
if(a>=b)
b =a;
else
a =b;
if(c>=d)
d =c;
else
c =d;
if(a>=d)
return a;
else
return d;
}
|
[
"eng.islam.hamdy1992@gmail.com"
] |
eng.islam.hamdy1992@gmail.com
|
0535c5c8b1e1d80cf0c59d2c393f118250c4b566
|
e0bbb262b4b07df2a2da7a71fd5ee1627d826d8b
|
/LanChat/LanChat.h
|
9b16c5dc1641c99bd8727ba745d7bfce3c962411
|
[
"MIT"
] |
permissive
|
songbaoming/LanChat
|
1b32553c5f8ffbdf7609dcf8729ebf89735e75e2
|
8a064039bdc2168c47bf53e48efb004d6f19ed92
|
refs/heads/master
| 2021-01-19T08:11:31.251540
| 2017-11-03T07:28:44
| 2017-11-03T07:28:44
| 32,850,729
| 9
| 3
| null | 2017-11-03T07:26:59
| 2015-03-25T08:05:00
|
C++
|
GB18030
|
C++
| false
| false
| 489
|
h
|
// LanChat.h : PROJECT_NAME 应用程序的主头文件
//
#pragma once
#ifndef __AFXWIN_H__
#error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件"
#endif
#include "resource.h" // 主符号
// CLanChatApp:
// 有关此类的实现,请参阅 LanChat.cpp
//
class CLanChatApp : public CWinApp
{
public:
CLanChatApp();
// 重写
public:
virtual BOOL InitInstance();
// 实现
private:
HANDLE m_hMutex;
DECLARE_MESSAGE_MAP()
};
extern CLanChatApp theApp;
|
[
"songbaoming@yeah.net"
] |
songbaoming@yeah.net
|
186baab335d193a038172c553f4e2d92067f541a
|
f336c286e1d0eed50a8f30ac34ac58c3311d6267
|
/Apuntes/ListaSimplementeEnlazada/lista.h
|
2b8aefef77cf606bd1df828f01a7268115da532e
|
[] |
no_license
|
JoseMPaz87/AlgortmosProgramacion2
|
49fce0be30238b4649eadc92175cee3fb49a55c8
|
689c8f41dfe9165c9ffbec2e85efe34215e5efa0
|
refs/heads/master
| 2022-11-10T06:04:38.411005
| 2020-06-23T19:18:09
| 2020-06-23T19:18:09
| 256,578,548
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,515
|
h
|
#ifndef _LISTA_H_
#define _LISTA_H_
#include "nodo.h"
class Lista
{
private :
// Primer elemento de la lista
Nodo * primero ;
// Tamaño de la lista
unsigned tam ;
public :
// Constructor
// PRE : ninguna
// POST : construye una lista vacia
// - primero apunta a nulo
// - tam = 0
Lista ();
// Destructor
// PRE : lista creada
// POST : Libera todos los recursos de la lista
~Lista ();
// La lista es vacía ?
// PRE : lista creada
// POST : devuelve verdadero si la lista es vacia
// falso de lo contrario
bool listaVacia ();
// Agregar un elemento a la lista
// PRE : lista creada
// POST : agrega un dato en la posicion pos
// incrementa tam en 1
void insertar ( Dato d , unsigned pos );
// Obtener el dato que está en la posición pos
// PRE : - lista creada y no vacia
// - 0 < pos <= tam
// POST : devuelve el dato que esta en la posicion pos
// se toma 1 como el primero
Dato obtenerDato ( unsigned pos );
// Borrado del nodo que está en la posición pos
// PRE : - lista creada y no vacia
// - 0 < pos <= tam
// POST : libera el nodo que esta en la posición pos
// se toma 1 como el primero
void eliminarDato ( unsigned pos );
// Obtener el tamaño de la lista
// PRE : Lista creada
// POST : Devuelve tam ( cantidad de nodos de la lista )
unsigned obtenerTam ();
private :
// Obtiene un puntero al nodo de la posicion pos
// PRE : 0 < pos <= tam
// POST : devuelve un puntero al nodo solicitado
Nodo * obtenerNodo ( unsigned pos );
};
#endif // _LISTA_H_
|
[
"jpaz885@gmail.com"
] |
jpaz885@gmail.com
|
44cb4a5e611cdef1845f6db0e605aabec01cb2e1
|
3a317ef962cece53f2e71d2ed5325f780b0e298e
|
/sketch_may09b/sketch_may09b.ino
|
0c8ede444098cf8908740ebf51eee3bfa90d1ecd
|
[
"MIT"
] |
permissive
|
GeneralMine/Arduino-Collection
|
c983d06b4d3521450854615ffc9642ec4f3e154c
|
89677a8f156dc68f03edae846a4a84d669ca0d17
|
refs/heads/master
| 2020-04-14T04:09:58.981928
| 2019-11-24T00:12:58
| 2019-11-24T00:12:58
| 163,627,464
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 200
|
ino
|
int ledpin = 7;
void setup() {
// put your setup code here, to run once:
pinMode(ledpin, OUTPUT);
}
void loop() {
// put your main code here, to run repeatedly:
digitalWrite(ledpin, HIGH);
}
|
[
"marvin_raiser@web.de"
] |
marvin_raiser@web.de
|
defac77ebec196868302f6f268e60174e437717f
|
711547b37343a20e123fffccf0a0f37c3ac14618
|
/Homework/boilerplate/forwarding.cpp
|
1f71ff81c36a6e2ec58d89f6a2790a51d2e02745
|
[
"LicenseRef-scancode-warranty-disclaimer"
] |
no_license
|
Tokubara/Router-Lab
|
e5f3a24e53bc4c1dbb6891324a6b07699b212b13
|
59385239ee27419cbf59d76d628692ed13aab113
|
refs/heads/master
| 2020-11-30T14:37:18.821944
| 2019-12-27T09:48:38
| 2019-12-27T09:48:38
| 230,416,799
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 39
|
cpp
|
#include "../forwarding/forwarding.cpp"
|
[
"1270802817@qq.com"
] |
1270802817@qq.com
|
55a94d3bd6c8a09af829871e0c1f4a42141b7e9f
|
651bfa60017279d39939fa6eed2bb2ba3fc42b3e
|
/Repos/ProtocoloElGamalRSA/include/LSFR.h
|
5d01cfbe71978a320c5fd4cf78bbac0fe019ba0e
|
[] |
no_license
|
alvarez37/algebra
|
a711d2af3f6e5a263595374dce2564c1691805a3
|
6c370b21799e2f78fc5f02640b4ac65b178f030a
|
refs/heads/master
| 2020-05-25T06:52:05.564774
| 2019-10-08T02:23:20
| 2019-10-08T02:23:20
| 187,673,184
| 0
| 0
| null | 2019-05-28T21:49:10
| 2019-05-20T16:03:59
|
C++
|
UTF-8
|
C++
| false
| false
| 256
|
h
|
#ifndef LSFR_H
#define LSFR_H
#include "RC4.h"
class LFSR
{
public:
LFSR(int,vector<int>,vector<int>);
void fill_seed();
private:
vector<int> our_seed;
int n_bits;
vector<int> tap;
};
#endif // LSFR_H
|
[
"31245828+alvarez37@users.noreply.github.com"
] |
31245828+alvarez37@users.noreply.github.com
|
d133174efde070e29aab65580cef078504507177
|
7df5fae6fc1ebd2c3896361a9eb2feea1f1a73df
|
/obs/src/cpp/Utilities/TestUtilities.cpp
|
25ed7e8ab2acc5f2aa5c180cf3c06ec271820474
|
[] |
no_license
|
jentlestea1/obs_xslt
|
bd7c35a71698a17d4e89c4122fbd8bb450f56ce9
|
d22394be1712f956fccf20e31204b8f961a8ee05
|
refs/heads/master
| 2021-05-11T06:50:25.310161
| 2018-01-18T15:13:28
| 2018-01-18T15:13:28
| 117,998,474
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,328
|
cpp
|
//
// Copyright 2004 P&P Software GmbH - All Rights Reserved
//
// TestUtilities.cpp
//
// Version 1.0
// Date 13.09.02
// Author A. Pasetti (P&P Software)
#include <stdio.h>
#include <time.h>
#include "../GeneralInclude/TestCompilerSwitches.h"
#include "../GeneralInclude/TestConstants.h"
#include "../Utilities/TestUtilities.h"
void printRegressionTestHeader(FILE* outFile) {
#ifdef MS_HOST
time_t ltime;
time( <ime );
fprintf(outFile,"<html><head>\n");
fprintf(outFile,"<title>OBS Framework - Regression Test Report</title>\n");
fprintf(outFile,"</head><body bgcolor=\"#FFFF99\" link=\"#3333FF\">\n");
fprintf(outFile,"<center><h1>Regression Test Report</h1></center>\n");
fprintf(outFile,"<center><h4><i>Test Run Performed on %s</i></h4></center>\n",
ctime( <ime ));
fprintf(outFile,"This report was automatically generated by the regression test program of\n");
fprintf(outFile,"the OBS Framework. The regression test program executes all the test cases\n");
fprintf(outFile,"defined for the OBS Framework. The test cases are executed in sequence.\n");
fprintf(outFile,"Each test cases tests some or all the functionalities of one \n");
fprintf(outFile,"framework component. The tests are performed at component-level only.\n");
fprintf(outFile,"A test case can have two possible outcomes: 'test succeeded' or 'test failed'.\n");
fprintf(outFile,"The test case outcome can be accompanied by an explanatory message.\n");
fprintf(outFile,"The table below reports the outcome of the test case performed in a \n");
fprintf(outFile,"regression test run. The links in the table point to the files documenting the individual test cases. \n");
fprintf(outFile,"The links are active only if this file\n");
fprintf(outFile,"is placed in the directory containing the HTML architectural documentation of \n");
fprintf(outFile,"the OBS Framework.\n");
fprintf(outFile,"There should be one documentation file for each test case. The links assume its \n");
fprintf(outFile,"name to be: 'TEST_FILE_NAME_1'+'test name'+'TEST_FILE_NAME_2'+'.html' where \n");
fprintf(outFile,"'TEST_FILE_NAME_1' and 'TEST_FILE_NAME_2' are string constants defined in\n");
fprintf(outFile,"the 'TestConstants.h' include file.\n");
fprintf(outFile,"<p>\n");
fprintf(outFile,"<p>\n");
fprintf(outFile,"<table BORDER=1 ALIGN=\"center\" CELLPADDING=5%>\n");
fprintf(outFile,"<tr><th>Test Name</th>\n");
fprintf(outFile,"<th>Test Outcome</th></tr>\n");
#else
printf("Regression Test Report");
#endif
}
void printRegressionTestTail(FILE* outFile) {
#ifdef MS_HOST
fprintf(outFile,"</table></body></html>\n");
#endif
}
void printTestSuccess(FILE* outFile, char* testName, char* testMsg) {
#ifdef MS_HOST
fprintf(outFile,"<tr><td><a href=\"%s%s%s.html\">%s</a></td>\n",
TEST_FILE_NAME_1,doubleUnderscore(outFile,testName),TEST_FILE_NAME_2,testName);
fprintf(outFile,"<td>%s</td></tr>\n",testMsg);
#else
printf("Test %s executed successfully. %s\n",testName,testMsg);
#endif
}
void printTestFailed(FILE* outFile, char* testName, char* testMsg) {
#ifdef MS_HOST
fprintf(outFile,"<tr><td><a href=\"%s%s%s.html\">%s</a></td>\n",
TEST_FILE_NAME_1,doubleUnderscore(outFile,testName),TEST_FILE_NAME_2,testName);
fprintf(outFile,"<td><b>%s</b></td></tr>\n",testMsg);
#else
printf("Test %s failed. %s\n",testName,testMsg);
#endif
}
void printErrorMsg(FILE* outFile, char* testName, char* testMsg) {
#ifdef MS_HOST
fprintf(outFile,"<tr><td>%s</td>\n",testName);
fprintf(outFile,"<td><b>%s</b></td></tr>\n",testMsg);
#else
printf("Test %s failed. %s\n",testName,testMsg);
#endif
}
char* doubleUnderscore(FILE* outFile, char* testName) {
int i = 0;
int j = 0;
while ( (testName[j]!='\0') && (i<(MAX_TEST_FILE_NAME_LENGTH-1)) ) {
charBuffer[i] = testName[j];
if (testName[j]=='_') {
i++;
charBuffer[i] = '_';
}
i++;
j++;
}
if (testName[j]!='\0') {
printErrorMsg(outFile,testName,"Test case name is too long");
}
charBuffer[i]='\0';
return charBuffer;
}
|
[
"jentlestea@zju.edu.cn"
] |
jentlestea@zju.edu.cn
|
8fed2bba1cedf88fb5b179647187be642f57c393
|
988742a6fb3b45db6a0c0996c7b968a2268b9e52
|
/ch16/exercises/ex5.cpp
|
269e6dad866c06c5d73546478c5fdf5f6f8c3a49
|
[] |
no_license
|
briansorahan/cplusplus-primer-plus
|
e15e8510bdce5dc2cb4998a0a567d7fac5066fdb
|
5693def87811b30bcc3480ffa3aa6c06bb874c1e
|
refs/heads/master
| 2016-09-05T15:51:11.904042
| 2013-12-16T03:20:09
| 2013-12-16T03:20:09
| 13,820,738
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,428
|
cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
// sorts ar, removes duplicates, then returns the number of
// elements in the result
template <typename T>
int reduce(T ar[], int n);
// would be nice to templatize the show* functions
void showLong(const long l);
void showString(const std::string s);
int main(int argc, char ** argv) {
const int N = 8;
long ar1[N] = { 2, 4, 8, 3, 4, 2, 1, 0 };
int unique1 = reduce(ar1, N);
std::cout << "ar1 = ";
std::for_each(ar1, ar1 + N, showLong);
std::cout << std::endl;
std::cout << "Unique elements in ar1 = " << unique1 << std::endl;
std::string ar2[N] = {
"stanley",
"stanley",
"bo",
"banley",
"banana",
"fana",
"fo",
"fanley"
};
int unique2 = reduce(ar2, N);
std::cout << "ar2 = ";
std::for_each(ar2, ar2 + N, showString);
std::cout << std::endl;
std::cout << "Unique elements in ar2 = " << unique2 << std::endl;
return 0;
}
template <typename T>
int reduce(T ar[], int n) {
std::sort(ar, ar + n);
int unique = 1; // first element is always unique
int i = 0;
for (int i = 0; i < n; i++) {
if (i > 0 && (ar[i] != ar[i - 1])) {
++unique;
}
}
return unique;
}
void showLong(const long l) {
std::cout << l << ' ';
}
void showString(const std::string s) {
std::cout << s << ' ';
}
|
[
"bsorahan@gmail.com"
] |
bsorahan@gmail.com
|
df693b599ce518c2a48ea717994f5451185176b2
|
0c023df5d28b34b37f3f79ac0aec5a1262b8ac02
|
/src/layer/convolutiondepthwisebnrelu.cpp
|
bd94f82b974517719da63cb1da7587c7fd7718bb
|
[
"BSD-3-Clause",
"Zlib",
"BSD-2-Clause"
] |
permissive
|
ahcyd008/ncnn
|
a965424f6f57cc249bc0c412f563452766793110
|
7b67f3c614a7574f8764f2cc28e121a9b7c1a101
|
refs/heads/master
| 2020-04-01T22:52:50.131945
| 2019-05-03T18:34:54
| 2019-05-03T18:34:54
| 153,731,348
| 0
| 0
|
NOASSERTION
| 2018-10-19T05:34:01
| 2018-10-19T05:34:01
| null |
UTF-8
|
C++
| false
| false
| 8,408
|
cpp
|
// Tencent is pleased to support the open source community by making ncnn available.
//
// Copyright (C) 2017 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// https://opensource.org/licenses/BSD-3-Clause
//
// 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 "convolutiondepthwisebnrelu.h"
#include "layer_type.h"
#include <math.h>
namespace ncnn {
DEFINE_LAYER_CREATOR(ConvolutionDepthWiseBNRelu)
ConvolutionDepthWiseBNRelu::ConvolutionDepthWiseBNRelu()
{
one_blob_only = true;
support_inplace = false;
}
ConvolutionDepthWiseBNRelu::~ConvolutionDepthWiseBNRelu()
{
}
int ConvolutionDepthWiseBNRelu::load_param(const ParamDict& pd)
{
num_output = pd.get(0, 0);
kernel_w = pd.get(1, 0);
kernel_h = pd.get(11, kernel_w);
dilation_w = pd.get(2, 1);
dilation_h = pd.get(12, dilation_w);
stride_w = pd.get(3, 1);
stride_h = pd.get(13, stride_w);
pad_w = pd.get(4, 0);
pad_h = pd.get(14, pad_w);
bias_term = pd.get(5, 0);
weight_data_size = pd.get(6, 0);
group = pd.get(7, 1);
if (num_output % group != 0)
{
// reject invalid group
return -100;
}
bn_channels = num_output;
bn_eps = 0.0f;
relu_slope = 0.0f;
return 0;
}
int ConvolutionDepthWiseBNRelu::load_model(const ModelBin& mb)
{
weight_data = mb.load(weight_data_size, 0);
if (weight_data.empty())
return -100;
if (bias_term)
{
bias_data = mb.load(num_output, 1);
if (bias_data.empty())
return -100;
}
//batch noraml
bn_slope_data = mb.load(bn_channels, 1);
if (bn_slope_data.empty())
return -100;
bn_mean_data = mb.load(bn_channels, 1);
if (bn_mean_data.empty())
return -100;
bn_var_data = mb.load(bn_channels, 1);
if (bn_var_data.empty())
return -100;
bn_bias_data = mb.load(bn_channels, 1);
if (bn_bias_data.empty())
return -100;
bn_a_data.create(bn_channels);
if (bn_a_data.empty())
return -100;
bn_b_data.create(bn_channels);
if (bn_b_data.empty())
return -100;
for (int i=0; i<bn_channels; i++)
{
float sqrt_var = sqrt(bn_var_data[i] + bn_eps);
bn_a_data[i] = bn_bias_data[i] - bn_slope_data[i] * bn_mean_data[i] / sqrt_var;
bn_b_data[i] = bn_slope_data[i] / sqrt_var;
}
//relu
//none
return 0;
}
int ConvolutionDepthWiseBNRelu::forward(const Mat& bottom_blob, Mat& top_blob, const Option& opt) const
{
// convolv with NxN kernel
// value = value + bias
int w = bottom_blob.w;
int h = bottom_blob.h;
int channels = bottom_blob.c;
size_t elemsize = bottom_blob.elemsize;
if (channels % group != 0 || num_output % group != 0)
{
// reject invalid group
return -100;
}
// fprintf(stderr, "ConvolutionDepthWise input %d x %d pad = %d %d ksize=%d %d stride=%d %d\n", w, h, pad_w, pad_h, kernel_w, kernel_h, stride_w, stride_h);
const int kernel_extent_w = dilation_w * (kernel_w - 1) + 1;
const int kernel_extent_h = dilation_h * (kernel_h - 1) + 1;
Mat bottom_blob_unbordered = bottom_blob;
Mat bottom_blob_bordered = bottom_blob_unbordered;
if (pad_w > 0 || pad_h > 0)
{
copy_make_border(bottom_blob_unbordered, bottom_blob_bordered, pad_h, pad_h, pad_w, pad_w, BORDER_CONSTANT, 0.f, opt.workspace_allocator, opt.num_threads);
if (bottom_blob_bordered.empty())
return -100;
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
}
else if (pad_w == -233 && pad_h == -233)
{
int wpad = kernel_extent_w + (w - 1) / stride_w * stride_w - w;
int hpad = kernel_extent_h + (h - 1) / stride_h * stride_h - h;
if (wpad > 0 || hpad > 0)
{
copy_make_border(bottom_blob_unbordered, bottom_blob_bordered, hpad / 2, hpad - hpad / 2, wpad / 2, wpad - wpad / 2, BORDER_CONSTANT, 0.f, opt.workspace_allocator, opt.num_threads);
if (bottom_blob_bordered.empty())
return -100;
}
w = bottom_blob_bordered.w;
h = bottom_blob_bordered.h;
}
int outw = (w - kernel_extent_w) / stride_w + 1;
int outh = (h - kernel_extent_h) / stride_h + 1;
top_blob.create(outw, outh, num_output, elemsize, opt.blob_allocator);
if (top_blob.empty())
return -100;
const int maxk = kernel_w * kernel_h;
// kernel offsets
std::vector<int> _space_ofs(maxk);
int* space_ofs = &_space_ofs[0];
{
int p1 = 0;
int p2 = 0;
int gap = w * dilation_h - kernel_w * dilation_w;
for (int i = 0; i < kernel_h; i++)
{
for (int j = 0; j < kernel_w; j++)
{
space_ofs[p1] = p2;
p1++;
p2 += dilation_w;
}
p2 += gap;
}
}
// depth-wise
if (channels == group && group == num_output)
{
#pragma omp parallel for num_threads(opt.num_threads)
for (int g=0; g<group; g++)
{
float* outptr = top_blob.channel(g);
const float* kptr = (const float*)weight_data + maxk * g;
const Mat m = bottom_blob_bordered.channel(g);
float a = bn_a_data[g];
float b = bn_b_data[g];
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
float sum = 0.f;
if (bias_term)
sum = bias_data[g];
const float* sptr = m.row(i*stride_h) + j*stride_w;
for (int k = 0; k < maxk; k++)
{
float val = sptr[ space_ofs[k] ];
float w = kptr[k];
sum += val * w;
}
sum = b*sum+a;
if (sum < 0)
sum = 0;
outptr[j] = sum;
}
outptr += outw;
}
}
return 0;
}
const int channels_g = channels / group;
const int num_output_g = num_output / group;
#ifdef _WIN32
#pragma omp parallel for num_threads(opt.num_threads)
#else // _WIN32
#pragma omp parallel for collapse(2) num_threads(opt.num_threads)
#endif // _WIN32
for (int g=0; g<group; g++)
{
for (int p=0; p<num_output_g; p++)
{
float* outptr = top_blob.channel(g * num_output_g + p);
const float* weight_data_ptr = (const float*)weight_data + maxk * channels_g * num_output_g * g;
float a = bn_a_data[g * num_output_g + p];
float b = bn_b_data[g * num_output_g + p];
for (int i = 0; i < outh; i++)
{
for (int j = 0; j < outw; j++)
{
float sum = 0.f;
if (bias_term)
sum = bias_data[num_output_g * g + p];
const float* kptr = weight_data_ptr + maxk * channels_g * p;
// channels_g
for (int q=0; q<channels_g; q++)
{
const Mat m = bottom_blob_bordered.channel(channels_g * g + q);
const float* sptr = m.row(i*stride_h) + j*stride_w;
for (int k = 0; k < maxk; k++)
{
float val = sptr[ space_ofs[k] ];
float w = kptr[k];
sum += val * w;
}
kptr += maxk;
}
sum = b*sum+a;
if (sum < 0)
sum = 0;
outptr[j] = sum;
}
outptr += outw;
}
}
}
return 0;
}
} // namespace ncnn
|
[
"ahcyd000@gmail.com"
] |
ahcyd000@gmail.com
|
221912188fa1d63d6ccceb7a9f7fc597d5013e37
|
1787588a5ebcaa184f2a067903a653a245d03e9d
|
/diverta2019/a/main.cpp
|
2545a405ee69bdfa97fa88aacd573770fd37881c
|
[] |
no_license
|
ebisenttt/atcoder
|
a3576658eac148372561a6838c081952744f4dee
|
edfb13c4eb240f5650651cd66fd925496f678257
|
refs/heads/main
| 2023-06-17T22:54:20.138588
| 2021-07-16T07:43:03
| 2021-07-16T07:43:03
| 313,921,901
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 413
|
cpp
|
#include <bits/stdc++.h>
using namespace std;
#define REP(i, n) for(int i = 0; i < n; i++)
#define FOR(i, m, n) for(int i = m; i < n; i++)
#define ALL(x) (x).begin(),(x).end()
#define SIZE(x) ((ll)(x).size()
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
#define INF 1e9
typedef long long ll;
typedef long double ld;
int main(){
ll n,k;
cin>>n>>k;
cout<<n-k+1<<endl;
return 0;
}
|
[
"vamos.nippon.2010@gmail.com"
] |
vamos.nippon.2010@gmail.com
|
e068ad71a8e9d3699bf2871109efeea795bf421e
|
ca84d3203dfdd971332621b2e7a6b0e71f308ddf
|
/src/automaton.hpp
|
4a82e66eb0dbe3eade423bb1a168cf788e83eb62
|
[] |
no_license
|
uicus/rbg2gdl
|
7cb5da47ecf301c96079917ef909095426a2d255
|
11457a39b48ea216e6edc9063bc7ad49a6ae3a73
|
refs/heads/master
| 2020-12-30T23:22:26.322219
| 2018-01-22T21:43:01
| 2018-01-22T21:43:01
| 68,704,565
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,465
|
hpp
|
#ifndef AUTOMATON
#define AUTOMATON
#include<vector>
#include"state.hpp"
#include"pure_game_move.hpp"
#include"types.hpp"
class automaton{
std::vector<state> local_register;
uint start_state;
uint accept_state;
std::pair<uint,uint> place_side_by_side(automaton&& rhs);
std::pair<uint,uint> prepare_new_endpoints(void);
void set_endpoints(const std::pair<uint,uint>& new_endpoints);
void concat_automaton(automaton&& concatee);
void concat_automaton_by_epsilon(automaton&& concatee);
void concat_automaton_by_start_state(automaton&& concatee);
public:
void starify_automaton(void);
void repeat_automaton(uint times);
std::string transitions_to_gdl(void);
std::string effects_to_gdl(void);
uint get_start_state(void);
friend automaton pure_letter_automaton(const rbg_parser::pure_game_move* label);
friend automaton modifier_automaton(const rbg_parser::game_move* action);
friend automaton sum_of_automatons(std::vector<automaton>&& elements);
friend automaton concatenation_of_automatons(std::vector<automaton>&& elements);
};
automaton pure_letter_automaton(const rbg_parser::pure_game_move* label);
automaton modifier_automaton(const rbg_parser::game_move* action);
automaton sum_of_automatons(std::vector<automaton>&& elements);
automaton concatenation_of_automatons(std::vector<automaton>&& elements);
#endif
|
[
"jakubsutowicz@gmail.com"
] |
jakubsutowicz@gmail.com
|
ef30588b6e4ff08d56518de48d422eff8bc9748c
|
03f037d0f6371856ede958f0c9d02771d5402baf
|
/graphics/VTK-7.0.0/Examples/Array/Cxx/ArrayBasics.cxx
|
dc0ebd5822b3d0f782abe66a81b7cc0f756b156f
|
[
"BSD-3-Clause"
] |
permissive
|
hlzz/dotfiles
|
b22dc2dc5a9086353ed6dfeee884f7f0a9ddb1eb
|
0591f71230c919c827ba569099eb3b75897e163e
|
refs/heads/master
| 2021-01-10T10:06:31.018179
| 2016-09-27T08:13:18
| 2016-09-27T08:13:18
| 55,040,954
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,487
|
cxx
|
#include <vtkArrayPrint.h>
#include <vtkDenseArray.h>
#include <vtkSparseArray.h>
int main(int vtkNotUsed(argc), char *vtkNotUsed(argv)[])
{
////////////////////////////////////////////////////////
// Creating N-Way Arrays
// Creating a dense array of 10 integers:
vtkDenseArray<vtkIdType>* array = vtkDenseArray<vtkIdType>::New();
array->Resize(10);
// Creating a dense 20 x 30 matrix:
vtkDenseArray<double>* matrix = vtkDenseArray<double>::New();
matrix->Resize(20, 30);
// Creating a sparse 10 x 20 x 30 x 40 tensor:
vtkArrayExtents extents;
extents.SetDimensions(4);
extents[0] = vtkArrayRange(0, 10);
extents[1] = vtkArrayRange(0, 20);
extents[2] = vtkArrayRange(0, 30);
extents[3] = vtkArrayRange(0, 40);
vtkSparseArray<vtkIdType>* tensor = vtkSparseArray<vtkIdType>::New();
tensor->Resize(extents);
////////////////////////////////////////////////////////
// Initializing N-Way Arrays
// Filling a dense array with ones:
array->Fill(1);
// Filling a dense matrix with zeros:
matrix->Fill(0.0);
// There's nothing to do for a sparse array - it's already empty.
////////////////////////////////////////////////////////
// Assigning N-Way Array Values
// Assign array value [5]:
array->SetValue(5, 42);
// Assign matrix value [4, 3]:
matrix->SetValue(4, 3, 1970);
// Assign tensor value [3, 7, 1, 2]:
vtkArrayCoordinates coordinates;
coordinates.SetDimensions(4);
coordinates[0] = 3;
coordinates[1] = 7;
coordinates[2] = 1;
coordinates[3] = 2;
tensor->SetValue(coordinates, 38);
////////////////////////////////////////////////////////
// Accessing N-Way Array Values
// Access array value [5]:
cout << "array[5]: " << array->GetValue(5) << "\n\n";
// Access matrix value [4, 3]:
cout << "matrix[4, 3]: " << matrix->GetValue(4, 3) << "\n\n";
// Access tensor value [3, 7, 1, 2]:
cout << "tensor[3, 7, 1, 2]: " << tensor->GetValue(coordinates) << "\n\n";
////////////////////////////////////////////////////////
// Printing N-Way Arrays
cout << "array:\n";
vtkPrintVectorFormat(cout, array);
cout << "\n";
cout << "matrix:\n";
vtkPrintMatrixFormat(cout, matrix);
cout << "\n";
cout << "tensor:\n";
vtkPrintCoordinateFormat(cout, tensor);
cout << "\n";
// Cleanup array instances ...
tensor->Delete();
matrix->Delete();
array->Delete();
return 0;
}
|
[
"shentianweipku@gmail.com"
] |
shentianweipku@gmail.com
|
a269be15ec50d2c7533c0a24a2d18159b63699f7
|
a42ce2ebd1b659963f5f2e1cb44b852ed5ad8521
|
/src/opengl-window.cc
|
3fde99490a5a33c0070cf13a2466d7a6b08e4485
|
[] |
no_license
|
dev-tp/cs4550
|
dfca46ca5d417bc5e3dfadbf992eda7ad3f50c0e
|
15d6d6c31c1d4634edc6d125b1f3c8d1896ebf50
|
refs/heads/master
| 2021-01-20T09:13:29.754778
| 2017-12-01T07:06:26
| 2017-12-01T07:06:26
| 101,582,335
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 521
|
cc
|
#include "opengl-window.h"
void CreateWindow(std::string title, void (*setup)()) {
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
glutInitWindowSize(SCREEN_WIDTH, SCREEN_HEIGHT);
glutInitWindowPosition(POSITION_X, POSITION_Y);
glutCreateWindow(title.c_str());
setup();
glutMainLoop();
}
void DefaultSetup() {
glClearColor(1.0f, 1.0f, 1.0f, 0.0f);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(2.0f);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, SCREEN_WIDTH, 0.0, SCREEN_HEIGHT);
}
|
[
"rcksorto@yahoo.com"
] |
rcksorto@yahoo.com
|
a9805a8027da7b12d7ca0aa643da3dd5e2fdad2f
|
bea0cf33c8d3d76ca692d390fad9bed6205af274
|
/nowcoder/Fibonacci数列.cpp
|
d4a5b8393ba27a8063464e98c0dd68ac341946c1
|
[] |
no_license
|
rohdea0826/XATU_ACM
|
dd3b29ec141d2f0fd6aa1a17d9a1f28229f06d3b
|
adab6f727a4bcbabc155bcc241866beb4681e317
|
refs/heads/master
| 2021-07-08T10:27:03.931100
| 2019-02-19T09:07:36
| 2019-02-19T09:07:36
| 74,180,655
| 0
| 0
| null | null | null | null |
GB18030
|
C++
| false
| false
| 1,031
|
cpp
|
//题目描述
//Fibonacci数列是这样定义的:
//F[0] = 0
//F[1] = 1
//for each i ≥ 2: F[i] = F[i - 1] + F[i - 2]
//因此,Fibonacci数列就形如:0, 1, 1, 2, 3, 5, 8, 13, ...,在Fibonacci数列中的数我们称为Fibonacci数。给你一个N,你想让其变为一个Fibonacci数,每一步你可以把当前数字X变为X - 1或者X + 1,现在给你一个数N求最少需要多少步可以变为Fibonacci数。
//输入描述 :
//输入为一个正整数N(1 ≤ N ≤ 1, 000, 000)
//输出描述 :
// 输出一个最小的步数变为Fibonacci数"
// 示例1
// 输入
// 复制
// 15
// 输出
// 复制
// 2
#include <iostream>
using namespace std;
int main()
{
int f, f0, f1;
int i, tmp;
f0 = 0; f1 = 1;
cin >> i;
tmp = i;
while(tmp)
{
f = f0 + f1;
f0 = f1; f1 = f;
if (i > f) {
if (i - f < tmp) tmp = i - f;
else if (tmp != i && i - f > tmp) break;
}
else
{
if (f - i < tmp)tmp = f - i;
else if (tmp != i & f - i > tmp) break;
}
}
cout << tmp << endl;
return 0;
}
|
[
"sqg0826@foxmail.com"
] |
sqg0826@foxmail.com
|
609bc12b311797fd836ef236d0393cec8c78f621
|
c792992a5bc2e25fa377c92257eee09d3bbeb65c
|
/Common/Flag_t.hpp
|
44b1de33c186fbe17a7e253b6e911f31b9322fb8
|
[] |
no_license
|
mikemcqueen/CocoaVideoPoker
|
5f4005cd97416f13001338ea1670bbd4d2187adf
|
955845c4f7b24483c7cfac283af0fafb8970e7e0
|
refs/heads/master
| 2020-05-27T21:15:48.241597
| 2017-03-02T07:40:30
| 2017-03-02T07:40:30
| 83,646,841
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,222
|
hpp
|
////////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2008 Mike McQueen. All rights reserved.
//
////////////////////////////////////////////////////////////////////////////////
#pragma once
template<class TFlag>
class FlagBase_t
{
private:
TFlag m_Flags;
public:
typedef TFlag value_type;
// static const FlagBase_t<TFlag> NoFlags;
// FlagBase_t() { Clear(); }
FlagBase_t(value_type flags = 0) : m_Flags(flags) {}
FlagBase_t<TFlag>& operator=(const value_type flags) { m_Flags = flags; }
void Reset() { m_Flags = 0; }
void Clear(TFlag Flags) { m_Flags ^= (m_Flags & Flags); }
void Set(value_type Flags) { *(value_type*)&m_Flags |= Flags; }
bool Test(TFlag Flags) const { return Flags == (Flags & m_Flags); }
bool TestAny(TFlag Flags) const { return 0 != (Flags & m_Flags); }
// value_type value() const { return m_Flags; }
};
typedef FlagBase_t<unsigned> Flag_t;
////////////////////////////////////////////////////////////////////////////////
|
[
"mike.mcqueen@yahoo.com"
] |
mike.mcqueen@yahoo.com
|
89aebd4fbee9d82d4dd24f95fcc2418d5377366c
|
b4660cc8fa3ce045508105fa52228a98fa19a87d
|
/src/win32/base/browser_info.cc
|
27d5561acd7e7f729483993e98ca92cdc67579b3
|
[
"BSD-3-Clause",
"LicenseRef-scancode-unicode",
"LicenseRef-scancode-public-domain"
] |
permissive
|
hnakamur/mozc-deb
|
81e9b561863e57da73aa9ba90d24ff5d0bca480b
|
a0d6db21786ae7fc54806714cbeca6c7c74cbd36
|
refs/heads/master
| 2021-04-15T09:32:03.635220
| 2018-05-04T10:09:23
| 2018-05-04T10:09:23
| 126,575,465
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,084
|
cc
|
// Copyright 2010-2016, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#include "win32/base/browser_info.h"
#define _ATL_NO_AUTOMATIC_NAMESPACE
#define _WTL_NO_AUTOMATIC_NAMESPACE
#include <atlbase.h>
#include <atlcom.h>
#include <string>
#include "base/util.h"
#include "base/win_util.h"
#include "win32/base/accessible_object.h"
#include "win32/base/focus_hierarchy_observer.h"
namespace mozc {
namespace win32 {
namespace {
using ::ATL::CComPtr;
using ::ATL::CComQIPtr;
using ::ATL::CComVariant;
wchar_t g_exe_module_name_[4096];
size_t g_exe_module_name_len_ = 0;
int g_exe_module_ver_major_ = 0;
int g_exe_module_ver_minor_ = 0;
int g_exe_module_ver_build_ = 0;
int g_exe_module_ver_revision_ = 0;
bool g_exe_module_ver_initialized_ = false;
BrowserInfo::BrowserType g_browser_type_ = BrowserInfo::kBrowserTypeUnknown;
bool g_browser_type_initialized_ = false;
wstring GetProcessModuleName() {
if (g_exe_module_name_len_ == 0) {
return L"";
}
return wstring(g_exe_module_name_, g_exe_module_name_len_);
}
} // namespace
// static
BrowserInfo::BrowserType BrowserInfo::GetBrowerType() {
if (!g_browser_type_initialized_) {
bool loder_locked = false;
if (!WinUtil::IsDLLSynchronizationHeld(&loder_locked) ||
loder_locked) {
return kBrowserTypeUnknown;
}
string exe_path_utf8;
Util::WideToUTF8(GetProcessModuleName(), &exe_path_utf8);
Util::LowerString(&exe_path_utf8);
if (Util::EndsWith(exe_path_utf8, "chrome.exe")) {
g_browser_type_ = kBrowserTypeChrome;
} else if (Util::EndsWith(exe_path_utf8, "firefox.exe")) {
g_browser_type_ = kBrowserTypeFirefox;
} else if (Util::EndsWith(exe_path_utf8, "iexplore.exe")) {
g_browser_type_ = kBrowserTypeIE;
} else if (Util::EndsWith(exe_path_utf8, "opera.exe")) {
g_browser_type_ = kBrowserTypeOpera;
} else {
g_browser_type_ = kBrowserTypeUnknown;
}
g_browser_type_initialized_ = true;
}
return g_browser_type_;
}
// static
bool BrowserInfo::IsInIncognitoMode(
const FocusHierarchyObserver &focus_hierarchy_observer) {
if (GetBrowerType() == kBrowserTypeUnknown) {
return false;
}
bool loder_locked = false;
if (!WinUtil::IsDLLSynchronizationHeld(&loder_locked) ||
loder_locked) {
return false;
}
const string root_window_name = focus_hierarchy_observer.GetRootWindowName();
if (root_window_name.empty()) {
return false;
}
const char *sufix_ja = nullptr;
const char *sufix_en = nullptr;
switch (GetBrowerType()) {
case kBrowserTypeChrome:
sufix_ja = "(シークレット モード)";
sufix_en = "(Incognito)";
break;
case kBrowserTypeFirefox:
sufix_ja = " (プライベートブラウジング)";
sufix_en = "(Private Browsing)";
break;
case kBrowserTypeIE:
sufix_ja = "[InPrivate]";
sufix_en = "[InPrivate]";
break;
}
if (sufix_ja != nullptr && Util::EndsWith(root_window_name, sufix_ja)) {
return true;
}
if (sufix_en != nullptr && Util::EndsWith(root_window_name, sufix_en)) {
return true;
}
return false;
}
// static
bool BrowserInfo::IsOnChromeOmnibox(
const FocusHierarchyObserver &focus_hierarchy_observer) {
if (GetBrowerType() != kBrowserTypeChrome) {
return false;
}
bool loder_locked = false;
if (!WinUtil::IsDLLSynchronizationHeld(&loder_locked) ||
loder_locked) {
return false;
}
const auto &ui_hierarchy = focus_hierarchy_observer.GetUIHierarchy();
if (ui_hierarchy.size() == 0) {
return false;
}
const auto ¤t_ui_element = ui_hierarchy.front();
if (!current_ui_element.is_builtin_role ||
current_ui_element.role != "ROLE_SYSTEM_TEXT") {
return false;
}
const char kOmniboxDescJa[] = "アドレス検索バー";
if (current_ui_element.name == kOmniboxDescJa) {
return true;
}
const char kOmniboxDescEn[] = "Address and search bar";
if (current_ui_element.name == kOmniboxDescEn) {
return true;
}
return false;
}
// static
void BrowserInfo::OnDllProcessAttach(HINSTANCE module_handle,
bool static_loading) {
const DWORD copied_len_without_null = ::GetModuleFileName(
nullptr, g_exe_module_name_, arraysize(g_exe_module_name_));
if ((copied_len_without_null + 1) < arraysize(g_exe_module_name_)) {
g_exe_module_name_len_ = copied_len_without_null;
}
}
// static
void BrowserInfo::OnDllProcessDetach(HINSTANCE module_handle,
bool process_shutdown) {
}
} // namespace win32
} // namespace mozc
|
[
"hnakamur@gmail.com"
] |
hnakamur@gmail.com
|
8f15c803f1f2c6d5c57318b0bb3a06d85627ea40
|
1b966edc8337f9c69b4dc986034ea923dd891179
|
/qt/other/canvas/button_canvas_car/mybutton.cpp
|
0304705f4af76bee24adb4be56a1fb6c2a448897
|
[] |
no_license
|
hackerlank/renyang-learn
|
7394f7d387001255e36337b9c30caecbfcc576a6
|
aaf2e1c4ed302558d0e043e4be845c532f00c06b
|
refs/heads/master
| 2020-06-09T09:39:33.744807
| 2009-09-20T16:07:57
| 2009-09-20T16:07:57
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 227
|
cpp
|
#include "mybutton.h"
MyPushButton::MyPushButton(QWidget *parent,const char *name, const char *text):QPushButton(parent,text){
setPixmap(QPixmap("cater2.png"));
setToggleType(Toggle); // 設定按壓後,不會彈起來
}
|
[
"superporter2001@e6a1191f-3756-0410-b840-13f34102b90a"
] |
superporter2001@e6a1191f-3756-0410-b840-13f34102b90a
|
8618bead781a112c1986c05880b144c3427b098c
|
60193311299ad70a697da3a65699fcd8b63bf264
|
/Orge-Study/ogre_src_v1-8-0/OgreMain/src/OgreOverlayContainer.cpp
|
cd3ecf68674406451cc2e3fc969506d8dff0a277
|
[] |
no_license
|
DGHeroin/Mirror-GLSL-Study
|
cd6fac3967173f9bf77d8d32776508fa81a98d86
|
9df468c5d8cc77bd89f4185230fd0b34c3721cad
|
refs/heads/master
| 2021-09-23T23:30:59.336825
| 2017-07-03T16:14:42
| 2017-07-03T16:14:42
| 96,129,238
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 12,784
|
cpp
|
/*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2012 Torus Knot Software Ltd
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 "OgreStableHeaders.h"
#include "OgreOverlayContainer.h"
#include "OgreException.h"
#include "OgreOverlayManager.h"
namespace Ogre {
//---------------------------------------------------------------------
OverlayContainer::OverlayContainer(const String& name)
: OverlayElement(name),
mChildrenProcessEvents(true)
{
}
//---------------------------------------------------------------------
OverlayContainer::~OverlayContainer()
{
// remove from parent overlay if root
if (mOverlay && !mParent)
{
mOverlay->remove2D(this);
}
OverlayContainer::ChildIterator ci = getChildIterator();
while (ci.hasMoreElements())
{
OverlayElement* child = ci.getNext();
child->_notifyParent(0, 0);
}
}
//---------------------------------------------------------------------
void OverlayContainer::addChild(OverlayElement* elem)
{
if (elem->isContainer())
{
addChildImpl(static_cast<OverlayContainer*>(elem));
}
else
{
addChildImpl(elem);
}
}
//---------------------------------------------------------------------
void OverlayContainer::addChildImpl(OverlayElement* elem)
{
String name = elem->getName();
ChildMap::iterator i = mChildren.find(name);
if (i != mChildren.end())
{
OGRE_EXCEPT(Exception::ERR_DUPLICATE_ITEM, "Child with name " + name +
" already defined.", "OverlayContainer::addChild");
}
mChildren.insert(ChildMap::value_type(name, elem));
// tell child about parent & ZOrder
elem->_notifyParent(this, mOverlay);
elem->_notifyZOrder(mZOrder + 1);
elem->_notifyWorldTransforms(mXForm);
elem->_notifyViewport();
}
//---------------------------------------------------------------------
void OverlayContainer::addChildImpl(OverlayContainer* cont)
{
// Add to main map first
// This will pick up duplicates
OverlayElement* pElem = cont;
addChildImpl(pElem);
/*
cont->_notifyParent(this, mOverlay);
cont->_notifyZOrder(mZOrder + 1);
cont->_notifyWorldTransforms(mXForm);
// tell children of new container the current overlay
ChildIterator it = cont->getChildIterator();
while (it.hasMoreElements())
{
// Give children ZOrder 1 higher than this
GuiElement* pElemChild = it.getNext();
pElemChild->_notifyParent(cont, mOverlay);
pElemChild->_notifyZOrder(cont->getZOrder() + 1);
pElemChild->_notifyWorldTransforms(mXForm);
}
*/
// Now add to specific map too
mChildContainers.insert(ChildContainerMap::value_type(cont->getName(), cont));
}
//---------------------------------------------------------------------
void OverlayContainer::removeChild(const String& name)
{
ChildMap::iterator i = mChildren.find(name);
if (i == mChildren.end())
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
" not found.", "OverlayContainer::removeChild");
}
OverlayElement* element = i->second;
mChildren.erase(i);
// remove from container list (if found)
ChildContainerMap::iterator j = mChildContainers.find(name);
if (j != mChildContainers.end())
mChildContainers.erase(j);
element->_setParent(0);
}
//---------------------------------------------------------------------
void OverlayContainer::_addChild(OverlayElement* elem)
{
if (elem->isContainer())
{
addChildImpl(static_cast<OverlayContainer*>(elem));
}
else
{
addChildImpl(elem);
}
}
//---------------------------------------------------------------------
void OverlayContainer::_removeChild(const String& name)
{
ChildMap::iterator i = mChildren.find(name);
if (i == mChildren.end())
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
" not found.", "OverlayContainer::removeChild");
}
OverlayElement* element = i->second;
mChildren.erase(i);
// remove from container list (if found)
ChildContainerMap::iterator j = mChildContainers.find(name);
if (j != mChildContainers.end())
mChildContainers.erase(j);
element->_setParent(0);
}
//---------------------------------------------------------------------
OverlayElement* OverlayContainer::getChild(const String& name)
{
ChildMap::iterator i = mChildren.find(name);
if (i == mChildren.end())
{
OGRE_EXCEPT(Exception::ERR_ITEM_NOT_FOUND, "Child with name " + name +
" not found.", "OverlayContainer::getChild");
}
return i->second;
}
//---------------------------------------------------------------------
OverlayContainer::ChildIterator OverlayContainer::getChildIterator(void)
{
return ChildIterator(mChildren.begin(), mChildren.end());
}
//---------------------------------------------------------------------
OverlayContainer::ChildContainerIterator OverlayContainer::getChildContainerIterator(void)
{
return ChildContainerIterator(mChildContainers.begin(), mChildContainers.end());
}
//---------------------------------------------------------------------
void OverlayContainer::initialise(void)
{
ChildContainerMap::iterator coni;
for (coni = mChildContainers.begin(); coni != mChildContainers.end(); ++coni)
{
coni->second->initialise();
}
ChildMap::iterator ci;
for (ci = mChildren.begin(); ci != mChildren.end(); ++ci)
{
ci->second->initialise();
}
}
//---------------------------------------------------------------------
void OverlayContainer::_positionsOutOfDate(void)
{
OverlayElement::_positionsOutOfDate();
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
it.getNext()->_positionsOutOfDate();
}
}
//---------------------------------------------------------------------
void OverlayContainer::_update(void)
{
// call superclass
OverlayElement::_update();
// Update children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
it.getNext()->_update();
}
}
//---------------------------------------------------------------------
ushort OverlayContainer::_notifyZOrder(ushort newZOrder)
{
OverlayElement::_notifyZOrder(newZOrder);
// One for us
newZOrder++;
// Update children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
// Children "consume" ZOrder values, so keep track of them
newZOrder = it.getNext()->_notifyZOrder(newZOrder);
}
return newZOrder;
}
//---------------------------------------------------------------------
void OverlayContainer::_notifyWorldTransforms(const Matrix4& xform)
{
OverlayElement::_notifyWorldTransforms(xform);
// Update children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
it.getNext()->_notifyWorldTransforms(xform);
}
}
//---------------------------------------------------------------------
void OverlayContainer::_notifyViewport()
{
OverlayElement::_notifyViewport();
// Update children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
it.getNext()->_notifyViewport();
}
}
//---------------------------------------------------------------------
void OverlayContainer::_notifyParent(OverlayContainer* parent, Overlay* overlay)
{
OverlayElement::_notifyParent(parent, overlay);
// Update children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
// Notify the children of the overlay
it.getNext()->_notifyParent(this, overlay);
}
}
//---------------------------------------------------------------------
void OverlayContainer::_updateRenderQueue(RenderQueue* queue)
{
if (mVisible)
{
OverlayElement::_updateRenderQueue(queue);
// Also add children
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
// Give children ZOrder 1 higher than this
it.getNext()->_updateRenderQueue(queue);
}
}
}
OverlayElement* OverlayContainer::findElementAt(Real x, Real y) // relative to parent
{
OverlayElement* ret = NULL;
int currZ = -1;
if (mVisible)
{
ret = OverlayElement::findElementAt(x,y); //default to the current container if no others are found
if (ret && mChildrenProcessEvents)
{
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
OverlayElement* currentOverlayElement = it.getNext();
if (currentOverlayElement->isVisible() && currentOverlayElement->isEnabled())
{
int z = currentOverlayElement->getZOrder();
if (z > currZ)
{
OverlayElement* elementFound = currentOverlayElement->findElementAt(x ,y );
if (elementFound)
{
currZ = z;
ret = elementFound;
}
}
}
}
}
}
return ret;
}
void OverlayContainer::copyFromTemplate(OverlayElement* templateOverlay)
{
OverlayElement::copyFromTemplate(templateOverlay);
if (templateOverlay->isContainer() && isContainer())
{
OverlayContainer::ChildIterator it = static_cast<OverlayContainer*>(templateOverlay)->getChildIterator();
while (it.hasMoreElements())
{
OverlayElement* oldChildElement = it.getNext();
if (oldChildElement->isCloneable())
{
OverlayElement* newChildElement =
OverlayManager::getSingleton().createOverlayElement(
oldChildElement->getTypeName(),
mName+"/"+oldChildElement->getName());
newChildElement->copyFromTemplate(oldChildElement);
addChild((OverlayContainer*)newChildElement);
}
}
}
}
OverlayElement* OverlayContainer::clone(const String& instanceName)
{
OverlayContainer *newContainer;
newContainer = static_cast<OverlayContainer*>(OverlayElement::clone(instanceName));
ChildIterator it = getChildIterator();
while (it.hasMoreElements())
{
OverlayElement* oldChildElement = it.getNext();
if (oldChildElement->isCloneable())
{
OverlayElement* newChildElement = oldChildElement->clone(instanceName);
newContainer->_addChild(newChildElement);
}
}
return newContainer;
}
}
|
[
"ade.li.indie@gmail.com"
] |
ade.li.indie@gmail.com
|
b184f5fa2b22f0cf3796d7f56ac3a955022fed29
|
46d4712c82816290417d611a75b604d51b046ecc
|
/Samples/Win7Samples/begin/sdkdiff/list.cpp
|
4b2c7a2a0fe449618d977749230af9552b4ff700
|
[
"LicenseRef-scancode-warranty-disclaimer",
"MIT"
] |
permissive
|
ennoherr/Windows-classic-samples
|
00edd65e4808c21ca73def0a9bb2af9fa78b4f77
|
a26f029a1385c7bea1c500b7f182d41fb6bcf571
|
refs/heads/master
| 2022-12-09T20:11:56.456977
| 2022-12-04T16:46:55
| 2022-12-04T16:46:55
| 156,835,248
| 1
| 0
|
NOASSERTION
| 2022-12-04T16:46:55
| 2018-11-09T08:50:41
| null |
WINDOWS-1252
|
C++
| false
| false
| 36,063
|
cpp
|
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//
// Copyright (c) Microsoft Corporation. All rights reserved.
/* Storage allocation scheme customised */
#include "precomp.h"
#include "list.h"
// use the standard Trace_Error function, but we have no
// parent window to pass for these errors.
#define TRACE_ERROR(a, b) Trace_Error(NULL, a, b)
char msg[80]; /* a temp for building up StringCchPrintf messages in */
#define BLOCKSIZE 25000
typedef struct blockTag {
struct blockTag * PrevBlock; /* backward link (NULL terminated doubly linked chain of blocks) */
struct blockTag * NextBlock; /* forward link (pCurrent points to last in chain) */
HANDLE hMem; /* memory handle for this block */
int iInUse; /* number of allocations taken out of it. 0 => free it */
SIZE_T iNext; /* next byte to use */
char chData[BLOCKSIZE];
} BLOCK, *PBLOCK;
CRITICAL_SECTION CritSec; /* to protect pCurrent */
PBLOCK pCurrent = NULL; /* block currently in use */
/* must always be either NULL or valid */
/* Allocate storage for List elements. n.b. after a call to this
you MUST record the value of pCurrent as you need to hand that in
to Free. You don't hand in the value of the actual storage.
See screed above.
This function Enters the critical section. The caller must Leave it.
*/
LPVOID
list_Alloc(
SIZE_T size
)
{
LPVOID pRet;
PBLOCK pb;
EnterCriticalSection(&CritSec);
if ((pCurrent==NULL)||(pCurrent->iNext+size>BLOCKSIZE+1)) {
pb = pCurrent;
pCurrent = (struct blockTag*)HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY ,(sizeof(BLOCK)));
if (pCurrent==NULL) {
OutputDebugString("HeapAlloc failed!!\n");
return NULL;
}
pCurrent->PrevBlock = pb;
pCurrent->NextBlock = NULL;
pCurrent->hMem = pCurrent;
pCurrent->iInUse = 0;
pCurrent->iNext = 0;
if (pb==NULL)
;
else
pb->NextBlock = pCurrent;
}
pRet = &(pCurrent->chData[pCurrent->iNext]);
++(pCurrent->iInUse);
pCurrent->iNext += size;
/* for MIPS we must also ensure that the data is aligned 4 byte*/
pCurrent->iNext = ((pCurrent->iNext + (sizeof(void *)-1)) & ~(sizeof(void *) - 1));
return pRet;
}
void
list_Free(
PBLOCK pBlock,
LPVOID p
)
{
HANDLE hMem;
HRESULT hr;
EnterCriticalSection(&CritSec);
--pBlock->iInUse;
if (pBlock->iInUse<=0) {if (pBlock->iInUse<0) {
hr = StringCchPrintf(msg, sizeof(msg),"List block allocation negative (%d)", pBlock->iInUse);
if (FAILED(hr))
OutputError(hr, IDS_SAFE_PRINTF);
TRACE_ERROR(msg, FALSE);
}
if (pCurrent==pBlock) pCurrent = pBlock->PrevBlock; /* defend the invariant */
/* loop it out of the chain */
if (pBlock->PrevBlock!=NULL) pBlock->PrevBlock->NextBlock = pBlock->NextBlock;
if (pBlock->NextBlock!=NULL) pBlock->NextBlock->PrevBlock = pBlock->PrevBlock;
hMem = pBlock->hMem;
HeapFree(GetProcessHeap(), NULL, hMem);
}
LeaveCriticalSection(&CritSec);
}
/* The following definition tells the truth about what an ITEM is. The
| header file says only that there's a structure with the tag item_tag and
| that a LIST is a pointer to one. Here we spell out what that structure
| is (and a LIST is still a pointer to one). A PLIST is defined as a
| pointer to one of those, but is only really used because the C
| parameter mechanism demands an extra level of indirection for a
| parameter that can be updated. (Modula-2 VAR parameter).
*/
typedef struct item_tag {
struct item_tag *pitNext; /* to next in circular list */
struct item_tag *pitPrev; /* to prev in circular list */
PBLOCK pBlock; /* to memory block */
BOOL bAnchor; /* TRUE iff an anchor block */
BOOL bOK; /* true unless a list op has failed */
int iLen; /* length of data only */
char *Data[1]; /* the caller's data. The '1' is a lie */
} ITEM;
/* For an anchor block, only the fields pitNext thru bAnchor are allocated.
| For a normal list element, Data may well be longer than 1 byte.
| The bOK flag is to support a style of programming where several
| successive operations can be done without having to check the return
| code at each stage. At the end, the list can be examined to see if
| the data in it is valid or if it has been made invalid by the failure
| of any of the previous operations. Certain operations may result in
| having no list at all if they fail (e.g. create) and for these, you'd
| better check the result at once!
*/
static SIZE_T iAnchorSize; /* Size of anchor block (no data, no dummy) */
static SIZE_T iHeaderSize; /* Size of data block not counting Data
and offset from cursor back to item.
*/
static BOOL bInited = FALSE; /* TRUE <=> iAnchorSize and iHeaderSize are OK*/
#define MOVEBACK(Curs) \
{ Curs = ((char *)Curs-iHeaderSize); } /*move from Data to pitNext*/
/*==================================================================
|| Lists are circular, doubly linked with an anchor block which holds
|| pointers to both ends. Every block has a flag which shows whether
|| it's an anchor or not.
||
|| Empty list:
||
|| -------------
|| | |
|| | Anchor |
|| v ------- |
|| Ul--->| Next--+--|
|| |-------| |
|| | Prev--+--
|| -------
||
|| One entry list:
||
|| ------------------------------------
|| | |
|| | Anchor |
|| v ------- ------ |
|| Ul--->| Next--+------------->| Next-+---|
|| |-------| | |------| |
|| | Prev--+---- | Prev-+---
|| ------- |------|
|| | Len |
|| |------|
|| | Data |
|| ------
|| Two entry list:
||
|| -------------------------------------------------
|| | --------------- --------------- |
|| || | | | |
|| || Anchor | | | |
|| vv -------- | v ------ | ------ |
|| Ul--->| Next--+-----+----->| Next-+----+-->| Next-+--
|| |-------| | |------| | | |------|
|| | Prev--+-- ------+-Prev | | ---+-Prev |
|| ------- | |------| | |------|
|| | | Len | | | Len |
|| | |------| | |------|<----Cursor
|| | | Data | | | Data |
|| | ------ | ------
|| | |
|| -------------------
||
|| etc.
||
|| Note that an external cursor (i.e one which is seen by the caller)
|| points to the Data field, not to the start of the structure.
|| This allows easy access to the data by the user at the cost of a
|| slightly slower traverse.
|| Within this module, we may sometimes traverse a list with a cursor
|| that points to the start of an item. This is called an item cursor.
È===================================================================*/
/*------------------------------------------------------------------
| Set iAnchorSize and iHeaderSize. Implementation independent!
-------------------------------------------------------------------*/
void
APIENTRY
List_Init(
void
)
{
LIST P;
P = (LIST)&P; /* really any old address will do */
iAnchorSize = (char *)&(P->iLen) - (char *)&(P->pitNext);
iHeaderSize = (char *)&(P->Data) - (char *)&(P->pitNext);
InitializeCriticalSection(&CritSec);
bInited = TRUE;
/* assumes layout in storage is linear */
}
void
APIENTRY
List_Term(
void
)
{
if (pCurrent!=NULL)
TRACE_ERROR("List storage not cleared out properly", FALSE);
}
/* Dump the internals to the debugger. */
void
APIENTRY
List_Dump(
LPSTR Header,
LIST lst
)
{
LIST pit;
HRESULT hr;
char X_msg[250] = {0};
OutputDebugString(Header); OutputDebugString("\n");
pit = lst;
do {
hr = StringCchPrintf(X_msg, sizeof(X_msg)-1, "%8p %8p %8p %ld %s "
, pit, pit->pitNext, pit->pitPrev, pit->iLen
, (pit->bAnchor ? "Anchor" : "Data")
);
if (FAILED(hr))
OutputError(hr, IDS_SAFE_PRINTF);
OutputDebugString(X_msg);
if (pit->pitNext->pitPrev != pit)
OutputDebugString(" Next Prev error!!");
if (pit->pitPrev->pitNext != pit)
OutputDebugString(" Prev Next error!!");
OutputDebugString("\n");
pit = pit->pitNext;
} while (pit!=lst);
OutputDebugString("End of list dump\n");
}
/* Dump hex representation of handle to debugger */
void
APIENTRY
List_Show(
LIST lst
)
{
char X_msg[50] = {0};
HRESULT hr = StringCchPrintf(X_msg, sizeof(X_msg)-1, "%p", lst);
if (FAILED(hr))
OutputError(hr, IDS_SAFE_PRINTF);
OutputDebugString(X_msg);
}
/*------------------------------------------------------------------
| Create a list. It will be initially empty
-------------------------------------------------------------------*/
LIST
APIENTRY
List_Create(
void
)
{
LIST lst;
if (!bInited) {
List_Init(); /* prevent some strange errors */
}
lst = (LIST)list_Alloc(iAnchorSize);
if (lst==NULL) {
return NULL;
}
lst->pBlock = pCurrent;
LeaveCriticalSection(&CritSec);
lst->bOK = TRUE;
lst->pitNext = lst;
lst->pitPrev = lst;
lst->bAnchor = TRUE;
/* no length field set in an anchor block */
return lst;
}
/*------------------------------------------------------------------
| Destroy *plst. It does not need to be empty first
-------------------------------------------------------------------*/
void
APIENTRY
List_Destroy(
PLIST plst
)
{
LIST pitP; /* item cursor on * plst */
LIST pitQ; /* item cursor runs one step ahead of pitQ */
if (plst==NULL) {
TRACE_ERROR("Bug:Attempt to destroy NULL list. Continuing...", FALSE);
return;
}
/* There is at least an anchor block to destroy */
pitP = *plst;
do {
pitQ = pitP->pitNext;
list_Free(pitP->pBlock, pitP);
pitP = pitQ;
}while (pitP != *plst);
*plst = NULL;
}
/*------------------------------------------------------------------
| Return the address of the place for Len bytes of data in a new
| item at the start of lst
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_NewFirst(
LIST lst,
UINT uLen
)
{
LIST pit;
if (lst==NULL) {
TRACE_ERROR("Bug: List_NewFirst to bogus list. Continuing...", FALSE);
return NULL;
}
pit = (LIST)list_Alloc(iHeaderSize+uLen);
if (pit==NULL) {
lst->bOK = FALSE;
return NULL;
}
pit->pBlock = pCurrent;
LeaveCriticalSection(&CritSec);
pit->iLen = uLen;
pit->pitPrev = lst;
pit->pitNext = lst->pitNext;
lst->pitNext->pitPrev = pit; /* for empty list that set lst->pitPrev */
lst->pitNext = pit;
pit->bAnchor = FALSE;
return (char *)&(pit->Data);
}
/*------------------------------------------------------------------
| Delete the first item in lst. Error if lst is empty
-------------------------------------------------------------------*/
void
APIENTRY
List_DeleteFirst(
LIST lst
)
{
LIST pit;
if (lst==NULL) {TRACE_ERROR("Bug: List_DeleteFirst from bogus list. Continuing...", FALSE);
return;
}
/* attempting to delete the anchor block! */
if (lst->pitNext==lst) {
lst->bOK = FALSE;
} else {
pit = lst->pitNext;
pit->pitNext->pitPrev = pit->pitPrev;
pit->pitPrev->pitNext = pit->pitNext;
list_Free(pit->pBlock, pit);
}
}
/*------------------------------------------------------------------
| Return the address of the place for uLen bytes of data in a new
| item at the end of lst
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_NewLast(
LIST lst,
UINT uLen
)
{
LIST pit;
if (lst==NULL) {
TRACE_ERROR("Bug: List_NewLast in bogus list. Continuing...", FALSE);
return NULL;
}
pit = (LIST)list_Alloc(iHeaderSize+uLen);
if (pit==NULL) {
lst->bOK = FALSE;
return NULL;
}
pit->pBlock = pCurrent;
LeaveCriticalSection(&CritSec);
pit->iLen = uLen;
pit->pitNext = lst;
pit->pitPrev = lst->pitPrev;
lst->pitPrev->pitNext = pit; /* for empty list that set lst->pitNext */
lst->pitPrev = pit;
pit->bAnchor = FALSE;
return (char *)&(pit->Data);
}
/*------------------------------------------------------------------
| Delete the last item in lst. Error if lst is empty
-------------------------------------------------------------------*/
void
APIENTRY
List_DeleteLast(
LIST lst
)
{
LIST pit;
if (lst==NULL) {
TRACE_ERROR("Bug: List_DeleteLast from bogus list. Continuing...", FALSE);
return;
}
/* attempting to delete the anchor block! */
if (lst->pitNext==lst) {
lst->bOK = FALSE;
} else {
pit = lst->pitPrev;
pit->pitNext->pitPrev = pit->pitPrev;
pit->pitPrev->pitNext = pit->pitNext;
list_Free(pit->pBlock, pit);
}
}
/*--------------------------------------------------------------------
| Return the address of the place for uLen bytes of data in a new
| item immediately after Curs.
| List_NewAfter(Lst,NULL,uLen) returns a pointer
| to space for uLen bytes in a new first element.
---------------------------------------------------------------------*/
LPVOID
APIENTRY
List_NewAfter(
LIST lst,
LPVOID Curs,
UINT uLen
)
{
LIST pitNew;
LIST pitAfter;
if (lst==NULL) {
TRACE_ERROR("Bug: List_NewAfter in bogus list. Continuing...", FALSE);
return NULL;
}
if (Curs==NULL) {
return List_NewFirst(lst, uLen);
} else {
MOVEBACK(Curs);
pitAfter = (LIST)Curs;
pitNew = (LIST)list_Alloc(iHeaderSize+uLen);
if (pitNew==NULL) {
lst->bOK = FALSE;
return NULL;
}
pitNew->pBlock = pCurrent;
LeaveCriticalSection(&CritSec);
pitNew->iLen = uLen;
pitNew->pitPrev = pitAfter;
pitNew->pitNext = pitAfter->pitNext;
pitAfter->pitNext->pitPrev = pitNew;
pitAfter->pitNext = pitNew;
pitNew->bAnchor = FALSE;
return (char *)&(pitNew->Data);
}
}
/*--------------------------------------------------------------------
| Return the address of the place for uLen bytes of data in a new
| item immediately before Curs.
| List_NewBefore(Lst,NULL,uLen) returns a pointer
| to space for uLen bytes in a new last element.
---------------------------------------------------------------------*/
LPVOID
APIENTRY
List_NewBefore(
LIST lst,
LPVOID Curs,
UINT uLen
)
{
LIST pitNew;
LIST pitBefore;
if (lst==NULL) {
TRACE_ERROR("Bug: List_NewBefore in bogus list. Continuing...", FALSE);
return NULL;
}
if (Curs==NULL) {
return List_NewLast(lst, uLen);
} else {
MOVEBACK(Curs);
pitBefore = (LIST)Curs;
pitNew = (LIST)list_Alloc(iHeaderSize+uLen);
if (pitNew==NULL) {
lst->bOK = FALSE;
return NULL;
}
pitNew->pBlock = pCurrent;
LeaveCriticalSection(&CritSec);
pitNew->iLen = uLen;
pitNew->pitNext = pitBefore;
pitNew->pitPrev = pitBefore->pitPrev;
pitBefore->pitPrev->pitNext = pitNew;
pitBefore->pitPrev = pitNew;
pitNew->bAnchor = FALSE;
return (char *) &(pitNew->Data);
}
}
/*------------------------------------------------------------------
| Delete the item that Curs identifies.
| This will be only a few (maybe as little as 3) machine instructions
| quicker than DeleteForwards or DeleteBackwards but leaves Curs dangling.
| It is therefore NOT usually to be preferred.
| It may be useful when you have a function which returns an LPVOID
| since the argument does not need to be a variable.
| Trivial example: List_Delete(List_First(L));
-------------------------------------------------------------------*/
void
APIENTRY
List_Delete(
LPVOID Curs
)
{
LIST pit;
if (Curs==NULL) {
TRACE_ERROR("Bug: List_Delete NULL item", FALSE);
return;
}
MOVEBACK(Curs)
pit = (LIST)Curs;
pit->pitNext->pitPrev = pit->pitPrev;
pit->pitPrev->pitNext = pit->pitNext;
list_Free(pit->pBlock, pit);
}
/*-----------------------------------------------------------------------
| Delete the item that Curs identifies and return a cursor that
| identifies the next item (NULL if already on last)
------------------------------------------------------------------------*/
LPVOID
APIENTRY
List_DeleteForwards(
LPVOID Curs
)
{
LIST pitDel; /* the item to delete */
LIST pitN; /* the item after (could be anchor) */
if (Curs==NULL) {
TRACE_ERROR("Bug: List_DeleteForwards NULL cursor. Continuing...", FALSE);
return NULL;
}
MOVEBACK(Curs)
pitDel = (LIST)Curs;
pitN = pitDel->pitNext;
pitN->pitPrev = pitDel->pitPrev;
pitDel->pitPrev->pitNext = pitN;
list_Free(pitDel->pBlock, pitDel);
if (pitN->bAnchor)
return NULL;
else
return (char *)&(pitN->Data);
}
/*-----------------------------------------------------------------------
| Delete the item that Curs identifies and return a cursor that
| identifies the previous item (NULL if already on first)
------------------------------------------------------------------------*/
LPVOID
APIENTRY
List_DeleteBackwards(
LPVOID Curs
)
{
LIST pitDel; /* the one to delete */
LIST pitB; /* the one before */
if (Curs==NULL) {
TRACE_ERROR("List_DeleteBackwards NULL cursor. Continuing...", FALSE);
return NULL;
}
MOVEBACK(Curs)
pitDel = (LIST)Curs;
pitB = pitDel->pitPrev;
pitDel->pitNext->pitPrev = pitB;
pitB->pitNext = pitDel->pitNext;
list_Free(pitDel->pBlock, pitDel);
if (pitB->bAnchor)
return NULL;
else
return (char *)&(pitB->Data);
}
/*-------------------------------------------------------------------
| Return the length of the object identified by the cursor Curs
-------------------------------------------------------------------*/
int
APIENTRY
List_ItemLength(
LPVOID Curs
)
{
LIST pit;
if (Curs==NULL) {
TRACE_ERROR("Bug: List_ItemLength NULL cursor. Continuing...", FALSE);
return 0;
}
MOVEBACK(Curs)
pit = (LIST)Curs;
return pit->iLen;
}
/*------------------------------------------------------------------
| Return the address of the first object in lst
| If lst is empty then Return NULL.
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_First(
LIST lst
)
{
if (lst==NULL) {
TRACE_ERROR("Bug: List_First of bogus list. Continuing...", FALSE);
return NULL;
}
if (lst->pitNext==lst) {
return NULL;
}
return &(lst->pitNext->Data);
}
/*------------------------------------------------------------------
| Return the address of the last object in lst
| If lst is empty then return NULL.
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_Last(
LIST lst
)
{
if (lst==NULL) {
TRACE_ERROR("Bug: List_Last of bogus list. Continuing...", FALSE);
return NULL;
}
if (lst->pitNext==lst) {
return NULL;
}
return &(lst->pitPrev->Data);
}
/*------------------------------------------------------------------
| Return the address of the object after Curs^.
| List_Next(List_Last(lst)) == NULL; List_Next(NULL) is an error.
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_Next(
LPVOID Curs
)
{
LIST pit;
if (Curs==NULL) {
TRACE_ERROR("Bug: List_Next of NULL cursor. Continuing...", FALSE);
return NULL;
}
MOVEBACK(Curs)
pit = (LIST)Curs;
pit = pit->pitNext;
if (pit->bAnchor) {
return NULL;
} else {
return &(pit->Data);
}
}
/*------------------------------------------------------------------
| Return the address of the object after Curs^.
| List_Prev(List_First(L)) == NULL; List_Prev(NULL) is an error.
-------------------------------------------------------------------*/
LPVOID
APIENTRY
List_Prev(
LPVOID Curs
)
{
LIST pit;
if (Curs==NULL) {
TRACE_ERROR("Bug: List_Prev of NULL cursor. Continuing...", FALSE);
return NULL;
}
MOVEBACK(Curs)
pit = (LIST)Curs;
pit = pit->pitPrev;
if (pit->bAnchor) {
return NULL;
} else {
return &(pit->Data);
}
}
/*-------------------------------------------------------------------
| Arrange that lst is empty after this call
--------------------------------------------------------------------*/
void
APIENTRY
List_Clear(
LIST lst
)
{
LIST pitP; /* item cursor on List, points to element starts */
LIST pitQ; /* runs one step ahead of pitP */
if (lst==NULL) {
TRACE_ERROR("Bug: List_Clear of bogus list. Continuing...", FALSE);
return;
}
pitP = lst->pitNext; /* first element of list proper */
while (pitP!=lst) { /* while not wrapped onto anchor */pitQ = pitP->pitNext;
list_Free(pitP->pBlock, pitP);
pitP = pitQ;
}
lst->bOK = TRUE;
lst->pitNext = lst;
lst->pitPrev = lst;
}
/*---------------------------------------------------------------------
| Return TRUE if and only if lst is empty
----------------------------------------------------------------------*/
BOOL
APIENTRY
List_IsEmpty(
LIST lst
)
{ if (lst==NULL) {TRACE_ERROR("Bug: List_IsEmpty of bogus list. Continuing...", FALSE);
return TRUE; /* well it's sort of true isn't it? */
}
return lst->pitNext ==lst;
} /* List_IsEmpty */
/*------------------------------------------------------------------
| l1 had better be empty. l1 then acquires all the elements from l2
-------------------------------------------------------------------*/
void
APIENTRY
SwitchLists(
LIST l1,
LIST l2
)
{
/* connect l1 to l2's elements, l1 had better be initially empty */
l1->pitPrev = l2->pitPrev;
l1->pitNext = l2->pitNext;
/* connect the elements to l1 anchor block. */
l1->pitPrev->pitNext = l1;
l1->pitNext->pitPrev = l1;
/* make l2 empty */
l2->pitPrev = l2;
l2->pitNext = l2;
}
/*-----------------------------------------------------------------------
| l1 := l1||l2; l2 := empty
| The elements themselves are not moved, so pointers to them remain valid.
|
| l1 gets all the elements of l1 in their original order followed by
| all the elements of l2 in the order they were in in l2.
| l2 becomes empty.
------------------------------------------------------------------------*/
void
APIENTRY
List_Join(
LIST l1,
LIST l2
)
{
if ((l1==NULL)||(l2==NULL)) {
TRACE_ERROR("Bug: List_Join of bogus list. Continuing...", FALSE);
return;
}
l1->bOK = l1->bOK &&l2->bOK; /* result OK if both inputs OK */
l2->bOK = TRUE; /* as l2 always becomes empty */
if (l2->pitNext==l2) {
/* no elements need moving */
} else if (l2->pitNext==l2) {
SwitchLists(l1,l2);
return;
} else {
l2->pitNext->pitPrev = l1->pitPrev;
l1->pitPrev->pitNext = l2->pitNext;
l1->pitPrev = l2->pitPrev;
l1->pitPrev->pitNext = l1;
l2->pitNext = l2;
l2->pitPrev = l2;
}
}
/*-----------------------------------------------------------------------
| Let L1 be *pl1 and L2 be *pl2
| L1 := L1[...Curs] || L2 || L1[Curs+1...]; L2 := empty
| Curs=NULL means insert L2 at the start of L1
| The elements themselves are not moved, so pointers to them remain valid.
|
| L1 gets the elements of L1 from the start up to and including the element
| that Curs points at, in their original order,
| followed by all the elements that were in L2, in their original order,
| followed by the rest of L1
------------------------------------------------------------------------*/
void
APIENTRY
List_InsertListAfter(
LIST l1,
LIST l2,
LPVOID Curs
)
{
LIST pitA; /* The element after Curs, could be anchor */
LIST pit; /* The start of the element that Curs points at
| or the anchor block if Curs==NULL
*/
if ( (l1==NULL) || (l2==NULL)) {
TRACE_ERROR("Bug: List_InsertListAfter with bogus list. Continuing...", FALSE);
return;
}
l1->bOK = l1->bOK && l2->bOK;
l2->bOK = TRUE;
if (l2->pitNext==l2) {
/* no elements need moving */
} else if ( l1->pitNext==l1) {
/* the easy way to code this would be simply to switch the two
| pointers l1 and l2, but they are value parameters and we don't
| want to change that.
*/
SwitchLists(l1,l2);
return;
} else {
if (Curs==NULL) {
pit = l1;
} else {
MOVEBACK(Curs)
pit = (LIST)Curs;
}
/* pit points to a block to insert after, could be anchor */
pitA = pit->pitNext; /* Cannot be same as P, already checked */
l2->pitNext->pitPrev = pit; /* P<-- elems-of-l2 A */
l2->pitPrev->pitNext = pitA; /* P<-- elems-of-l2 -->A */
pit->pitNext = l2->pitNext; /* P<-->elems-of-l2 -->A */
pitA->pitPrev = l2->pitPrev; /* P<-->elems-of-l2<-->A */
l2->pitNext = l2;
l2->pitPrev = l2;
}
}
/*-----------------------------------------------------------------------
| l1 := l1[...Curs-1] || l2 || l1[Curs...]; l2 := empty
| Curs=NULL means insert l2 at the end of l1
| The elements themselves are not moved, so pointers to them remain valid.
|
| l1 gets the elements of l1 from the start up to but not including the
| element that Curs points at, in their original order,
| followed by all the elements that were in l2, in their original order,
| followed by the rest of l1.
------------------------------------------------------------------------*/
void
APIENTRY
List_InsertListBefore(
LIST l1,
LIST l2,
LPVOID Curs
)
{
LIST pitB; /* The element before Curs, could be anchor */
LIST pit; /* The start of the element that Curs points at
| or the anchor block if Curs==NULL
*/
if ((l1==NULL) || (l2==NULL)) {
TRACE_ERROR("Bug: List_InsertListBefore with bogus list. Continuing...", FALSE);
return;
}
l1->bOK = l1->bOK && l2->bOK;
l2 ->bOK = TRUE;
if (l1->pitNext==l1) {
/* the easy way to code this would be simply to switch the two
| pointers l1 and l2, but they are value parameters and we don't
| want to change that.
*/
SwitchLists(l1,l2);
return;
} else {
if (Curs==NULL) {
pit = l1;
} else {
MOVEBACK(Curs)
pit = (LIST)Curs;
}
/* P points to a block to insert before, could be anchor */
pitB = pit->pitPrev; /* Cannot be same as P, already checked */
l2->pitNext->pitPrev = pitB; /* B<-- elems-of-L2 P */
l2->pitPrev->pitNext = pit; /* B<-- elems-of-L2 -->P */
pitB->pitNext = l2->pitNext; /* B<-->elems-of-L2 -->P */
pit->pitPrev = l2->pitPrev; /* B<-->elems-of-L2<-->P */
l2->pitNext = l2;
l2->pitPrev = l2;
}
}
/*-----------------------------------------------------------------------
| Let l1 be l1 and l2 be l2
| Split l2 off from the front of l1: final l2,l1 = original l1
|
| Split l1 into l2: objects of l1 up to and including Curs object
| l1: objects of l1 after Curs
| Any original contents of l2 are freed.
| List_Spilt(l1, l2, NULL) splits l1 before the first object so l1 gets all.
| The elements themselves are not moved.
------------------------------------------------------------------------*/
void
APIENTRY
List_SplitAfter(
LIST l1,
LIST l2,
LPVOID Curs
)
{
LIST pit;
if ((l1==NULL) || (l2==NULL)) {
TRACE_ERROR("Bug: List_SplitAfter bogus list. Continuing...", FALSE);
return;
}
if (l2->pitNext!=l2) {
List_Clear(l2);
};
if (Curs!=NULL) {
MOVEBACK(Curs)
pit = (LIST)Curs;
/* Curs had better be an item in l1! l2 had better be created! */
if (pit==l1) {
l1->bOK = FALSE;
l2->bOK = FALSE;
return;
}
if (pit->pitNext==l1) {
/* transfer whole of l2 to l1 */
SwitchLists(l2,l1);
return;
}
l2->pitPrev = pit;
l2->pitNext = l1->pitNext;
l1->pitNext = pit->pitNext;
pit->pitNext = l2;
l2->pitNext->pitPrev = l2;
l1->pitNext->pitPrev = l1;
}
}
/*----------------------------------------------------------------------
| Split l2 off from the back of l1: final l1,l2 = original l1
|
| Split l1 into l1: objects of l1 up to but not including Curs object
| l2: objects of l1 from Curs onwards
| Any original contants of l2 are freed.
| List_Spilt(l1, l2, NULL) splits l1 after the last object so l1 gets all.
| The elements themselves are not moved.
-----------------------------------------------------------------------*/
void
APIENTRY
List_SplitBefore(
LIST l1,
LIST l2,
LPVOID Curs
)
{
LIST pit;
if ((l1==NULL) || (l2==NULL)) {
TRACE_ERROR("Bug: List_SplitBefore bogus list. Continuing...", FALSE);
return;
}
if (l2->pitNext!=l2) {
List_Clear(l2);
}
if (Curs!=NULL) {
MOVEBACK(Curs)
pit = (LIST)Curs;
/* Curs had better be an item in L1! L2 had better be created! */
if (pit==l1) {
l1->bOK = FALSE;
l2->bOK = FALSE;
return;
}
if (pit->pitPrev==l1) {
SwitchLists(l2,l1);
return;
}
l2->pitNext = pit;
l2->pitPrev = l1->pitPrev;
l1->pitPrev = pit->pitPrev;
pit->pitPrev = l2;
l2->pitPrev->pitNext = l2;
l1->pitPrev->pitNext = l1;
}
}
/*------------------------------------------------------------------
| Return the number of items in L
-------------------------------------------------------------------*/
int
APIENTRY
List_Card(
LIST lst
)
{
LIST pit; /* item cursor on lst */
int cit;
if (lst==NULL) {
TRACE_ERROR("Bug: List_Card of bogus list. Continuing...", FALSE);
return 0; /* well it is sort of 0 */
}
pit = lst->pitNext;
cit = 0;
while (pit!=lst) {
cit++;
pit = pit->pitNext;
}
return cit;
}
/*------------------------------------------------------------------
| Check return code
-------------------------------------------------------------------*/
BOOL
APIENTRY
List_IsOK(
LIST lst
)
{
if (lst==NULL) {
TRACE_ERROR("Bug: List_IsOK of bogus list. Continuing...", FALSE);
return FALSE; /* well it is sick ain't it! */
}
return lst->bOK;
}
/*------------------------------------------------------------------
| Set return code to good
-------------------------------------------------------------------*/
void
APIENTRY
List_MakeOK(
LIST lst
)
{
if (lst==NULL) {
TRACE_ERROR("Bug: List_MakeOK of bogus list. Continuing...", FALSE);
return;
}
lst->bOK = TRUE;
}
BOOL
APIENTRY
List_Check(
LIST lst
)
{
LIST pel;
BOOL bOK;
/*-----------------------------------------------------------------
| Check the anchor block has the Anchor flag set.
| Run through the LIST using the Anchor flag (which should be FALSE)
| to mark where we have been (to test for loops in the chain)
| and carry on until we see the Anchor flag again. Check that this
| is the anchor block that we started from. Now do another pass
| turning the Anchor flags off again and checking the Prev pointers.
-------------------------------------------------------------------*/
if (lst==NULL)
return FALSE;
bOK = lst->bAnchor;
pel = lst->pitNext;
while (! pel->bAnchor) {
pel->bAnchor = TRUE;
pel = pel->pitNext;
}
bOK = bOK && (pel==lst);
if (bOK) {
/* Turn all the bAnchor flags off */
pel = lst;
do {pel->bAnchor = FALSE;
bOK = bOK & (pel->pitNext->pitPrev==pel);
pel = pel->pitNext;
} while (pel!=lst);
lst->bAnchor = TRUE; /* except the real one */
} else { /* just turn off those that we set on */
pel = lst->pitNext;
while (pel->bAnchor) {
pel->bAnchor = FALSE;
pel = pel->pitNext;
}
lst->bAnchor = TRUE;
}
return bOK;
}
void
APIENTRY
List_Recover(
PLIST plst
)
{
LIST Last, P,Q;
BOOL OK;
/* For no particular reason we presume that the forward chain
is good and reconstruct the back chain from it. A better
algorithm would do the kind of things that List_Check does
to figure out where the problems lie. This just steps along
until it sees either an address that it has already seen or
else the anchor block. (It's an n-squared algorithm).
It links the last good block found back to the anchor and
fixes all the Anchor flags.
*/
if (plst==NULL)
return;
if (*plst==NULL) {
*plst = List_Create();
return;
}
(*plst)->bAnchor = TRUE;
P = (*plst)->pitNext;
Last = *plst;
for (; ; ) {if (P==*plst) break;
Last = P;
if (P->pitNext!=*plst) {OK = TRUE;
Q = *plst;
for (; ; ) {
OK &= (P->pitNext!=Q);
if (Q==P) break;
Q = Q->pitNext;
}
if (!OK) break;
}
P = P->pitNext;
}
P = *plst;
while (P!=Last) {P->pitNext->pitPrev = P;
P->bAnchor = FALSE;
P = P->pitNext;
}
Last->pitNext = *plst;
(*plst)->pitPrev = Last;
(*plst)->bAnchor = TRUE;
(*plst)->bOK = TRUE;
}
|
[
"chrisg@microsoft.com"
] |
chrisg@microsoft.com
|
5dd7cc3a9b8b3cc7de1f435578e8a6f637eb7c38
|
20a4df8d7a9ccbdc8c2695d2837d179dad94e3ee
|
/demo/interactive_compounds.cpp
|
8709e85033bc76303fb481cfd190c53a06980f70
|
[] |
no_license
|
poftwaresatent/kinematic_objectives
|
6cfcc3f5894cf42436bd30a11e37e29ac28a55d1
|
64928016fdcc7db0475fcdb2b1c02e71d92695c2
|
refs/heads/master
| 2016-09-05T19:06:45.841098
| 2013-04-14T18:04:33
| 2013-04-14T18:04:33
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 19,537
|
cpp
|
/*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2013, Willow Garage, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of the Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Roland Philippsen */
#include <kinematic_objectives/print.h>
#include <kinematic_objectives/util.h>
#include "interactive_compounds.h"
#include <err.h>
namespace kinematic_objectives {
namespace demo {
InteractiveCompound::
InteractiveCompound(PlanarRobot & robot)
: robot_(robot)
{
}
TestOne::
TestOne(PlanarRobot & robot)
: InteractiveCompound(robot),
h_ee_ (0.2, 0.0, 1.0, 0.0, 0.5),
h_ee_ori_ (0.1, 0.0, 1.0, 0.0, 0.3),
h_base_ (0.2, 0.0, 1.0, 0.5, 0.5),
orient_ee_ ("orient_ee", 3),
attract_ee_ ("attract_ee", 3, robot_.len_c_, 0.0, 0.0, -1.0),
attract_base_ ("attract_base", 0, 0.0, 0.0, 0.0, -1.0),
pd_orient_ee_ ("pd_orient_ee", &orient_ee_, false, 100.0, 20.0),
pd_attract_ee_ ("pd_attract_ee", &attract_ee_, false, 100.0, 20.0),
pd_attract_base_("pd_attract_base", &attract_base_, false, 100.0, 20.0),
damping_ ("damping", 20.0)
{
handles_.push_back(&h_ee_);
handles_.push_back(&h_ee_ori_);
handles_.push_back(&h_base_);
compound_objective_.hard_objectives_.push_back(&pd_orient_ee_);
compound_objective_.hard_objectives_.push_back(&pd_attract_ee_);
compound_objective_.hard_objectives_.push_back(&pd_attract_base_);
compound_objective_.hard_objectives_.push_back(&damping_);
}
void TestOne::
init(double gui_dimx, double gui_dimy)
{
h_ee_.point_ << gui_dimx / 2.0 - 1.0, gui_dimy / 2.0 , 0.0;
h_ee_ori_.point_ << gui_dimx / 2.0 + 1.0, gui_dimy / 2.0 + 1.0, 0.0;
h_base_.point_ << gui_dimx / 2.0 , 1.0, 0.0;
Vector posture(5);
posture <<
gui_dimx / 2.0,
gui_dimy / 2.0,
80.0 * deg,
- 40.0 * deg,
25.0 * deg;
robot_.update(posture, Vector::Zero(posture.size()));
compound_objective_.init(robot_);
}
void TestOne::
draw(cairo_t * cr, double weight, double pixelsize) const
{
cairo_save(cr);
// handles
for (size_t ii(0); ii < handles_.size(); ++ii) {
handles_[ii]->draw(cr, weight, pixelsize);
}
cairo_set_source_rgba(cr, 0.0, 1.0, 0.0, 0.5);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, h_ee_.point_[0], h_ee_.point_[1]);
cairo_line_to(cr, h_ee_ori_.point_[0], h_ee_ori_.point_[1]);
cairo_stroke(cr);
// orientation objective
cairo_set_source_rgba(cr, 0.0, 1.0, 0.5, 0.3);
cairo_set_line_width(cr, weight * 6.0 / pixelsize);
static double const len(0.5);
double const dx(len * cos(orient_ee_.goal_));
double const dy(len * sin(orient_ee_.goal_));
cairo_move_to(cr, robot_.pos_b_[0], robot_.pos_b_[1]);
cairo_line_to(cr, robot_.pos_b_[0] + dx, robot_.pos_b_[1] + dy);
cairo_stroke(cr);
// thin line for end effector objective
cairo_set_source_rgb(cr, 1.0, 0.4, 0.4);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, attract_ee_.gpoint_[0], attract_ee_.gpoint_[1]);
cairo_line_to(cr, attract_ee_.attractor_[0], attract_ee_.attractor_[1]);
cairo_stroke(cr);
// base attraction
cairo_set_source_rgb(cr, 0.4, 1.0, 0.4);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, attract_base_.gpoint_[0], attract_base_.gpoint_[1]);
cairo_line_to(cr,
attract_base_.gpoint_[0] + attract_base_.getBias()[0],
attract_base_.gpoint_[1] + attract_base_.getBias()[1]);
cairo_stroke(cr);
cairo_restore(cr);
}
void TestOne::
update()
{
orient_ee_.goal_ = atan2(h_ee_ori_.point_[1] - h_ee_.point_[1], h_ee_ori_.point_[0] - h_ee_.point_[0]);
attract_ee_.attractor_ = h_ee_.point_;
attract_base_.attractor_ = h_base_.point_;
}
FirstInteractiveCompound::
FirstInteractiveCompound(PlanarRobot & robot)
: InteractiveCompound(robot),
h_ee_ (0.2, 0.0, 1.0, 0.0, 0.5),
h_ee_ori_ (0.1, 0.0, 1.0, 0.0, 0.3),
h_base_ (0.2, 0.0, 1.0, 0.5, 0.5),
h_repulsor_(1.5, 1.0, 0.5, 0.0, 0.2),
h_obstacle_(1.5, 0.7, 0.0, 0.2, 0.5),
distance_api_(robot_, &h_obstacle_),
joint_limits_ ("joint_limits"),
avoid_base_ ("avoid_base", distance_api_, 0, 0.0),
avoid_ellbow_ ("avoid_ellbow", distance_api_, 1, 0.0),
avoid_wrist_ ("avoid_wrist", distance_api_, 2, 0.0),
avoid_ee_ ("avoid_ee", distance_api_, 3, 0.0),
orient_ee_ ("orient_ee", 3),
repulse_base_ ("repulse_base", 0, 0.0, 0.0, 0.0, h_repulsor_.radius_),
repulse_ellbow_("repulse_ellbow", 1, robot_.len_a_, 0.0, 0.0, h_repulsor_.radius_),
repulse_wrist_ ("repulse_wrist", 2, robot_.len_b_, 0.0, 0.0, h_repulsor_.radius_),
repulse_ee_ ("repulse_ee", 3, robot_.len_c_, 0.0, 0.0, h_repulsor_.radius_)
{
handles_.push_back(&h_ee_);
handles_.push_back(&h_ee_ori_);
handles_.push_back(&h_base_);
handles_.push_back(&h_repulsor_);
handles_.push_back(&h_obstacle_);
joint_limits_.init(5);
joint_limits_.limits_(3, 0) = -120.0 * deg;
joint_limits_.limits_(3, 1) = -119.999 * deg;
joint_limits_.limits_(3, 2) = 119.999 * deg;
joint_limits_.limits_(3, 3) = 120.0 * deg;
joint_limits_.limits_(4, 0) = -120.0 * deg;
joint_limits_.limits_(4, 1) = -119.999 * deg;
joint_limits_.limits_(4, 2) = 119.999 * deg;
joint_limits_.limits_(4, 3) = 120.0 * deg;
compound_objective_.unilateral_constraints_.push_back(&joint_limits_);
compound_objective_.unilateral_constraints_.push_back(&avoid_ee_);
compound_objective_.unilateral_constraints_.push_back(&avoid_wrist_);
compound_objective_.unilateral_constraints_.push_back(&avoid_ellbow_);
compound_objective_.unilateral_constraints_.push_back(&avoid_base_);
compound_objective_.hard_objectives_.push_back(&orient_ee_);
compound_objective_.soft_objectives_.push_back(&repulse_base_);
compound_objective_.soft_objectives_.push_back(&repulse_ellbow_);
compound_objective_.soft_objectives_.push_back(&repulse_wrist_);
compound_objective_.soft_objectives_.push_back(&repulse_ee_);
}
void FirstInteractiveCompound::
init(double gui_dimx, double gui_dimy)
{
h_ee_.point_ << 1.0, gui_dimy / 2.0 , 0.0;
h_ee_ori_.point_ << 2.0, gui_dimy / 2.0 + 1.0, 0.0;
h_base_.point_ << 1.0, 1.0, 0.0;
h_repulsor_.point_ << gui_dimx / 2.0, 1.0, 0.0;
h_obstacle_.point_ << gui_dimx / 2.0, gui_dimy - 1.0, 0.0;
Vector posture(5);
posture <<
gui_dimx / 2.0,
gui_dimy / 2.0,
80.0 * deg,
- 40.0 * deg,
25.0 * deg;
robot_.update(posture, Vector::Zero(posture.size()));
compound_objective_.init(robot_);
}
void FirstInteractiveCompound::
draw(cairo_t * cr, double weight, double pixelsize)
const
{
cairo_save(cr);
// handles
for (size_t ii(0); ii < handles_.size(); ++ii) {
handles_[ii]->draw(cr, weight, pixelsize);
}
cairo_set_source_rgba(cr, 0.0, 1.0, 0.0, 0.5);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, h_ee_.point_[0], h_ee_.point_[1]);
cairo_line_to(cr, h_ee_ori_.point_[0], h_ee_ori_.point_[1]);
cairo_stroke(cr);
// orientation objective
cairo_set_source_rgba(cr, 0.0, 1.0, 0.5, 0.3);
cairo_set_line_width(cr, weight * 6.0 / pixelsize);
static double const len(0.5);
double const dx(len * cos(orient_ee_.goal_));
double const dy(len * sin(orient_ee_.goal_));
cairo_move_to(cr, robot_.pos_b_[0], robot_.pos_b_[1]);
cairo_line_to(cr, robot_.pos_b_[0] + dx, robot_.pos_b_[1] + dy);
cairo_stroke(cr);
// joint limits
if (joint_limits_.isActive()) {
cairo_set_source_rgba(cr, 1.0, 0.2, 0.8, 0.8);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
for (ssize_t ii(0); ii < joint_limits_.getJacobian().rows(); ++ii) {
if (0.0 < joint_limits_.getJacobian()(ii, 3)) {
cairo_move_to(cr, robot_.pos_a_[0], robot_.pos_a_[1]);
cairo_arc(cr, robot_.pos_a_[0], robot_.pos_a_[1], 0.1,
normangle(normangle(robot_.position_[2]) + joint_limits_.limits_(3, 0)),
normangle(normangle(robot_.position_[2]) + joint_limits_.limits_(3, 3)));
cairo_line_to(cr, robot_.pos_a_[0], robot_.pos_a_[1]);
cairo_fill(cr);
}
if (0.0 < joint_limits_.getJacobian()(ii, 4)) {
cairo_move_to(cr, robot_.pos_b_[0], robot_.pos_b_[1]);
cairo_arc(cr, robot_.pos_b_[0], robot_.pos_b_[1], 0.1,
normangle(normangle(robot_.q23_) + joint_limits_.limits_(4, 0)),
normangle(normangle(robot_.q23_) + joint_limits_.limits_(4, 3)));
cairo_line_to(cr, robot_.pos_b_[0], robot_.pos_b_[1]);
cairo_fill(cr);
}
}
}
// avoidance points
cairo_set_source_rgb(cr, 1.0, 0.4, 1.0);
cairo_set_line_width(cr, weight * 5.0 / pixelsize);
if (avoid_base_.isActive()) {
cairo_move_to(cr, avoid_base_.gpoint_[0], avoid_base_.gpoint_[1]);
cairo_line_to(cr, avoid_base_.gpoint_[0], avoid_base_.gpoint_[1]);
cairo_stroke(cr);
}
if (avoid_ellbow_.isActive()) {
cairo_move_to(cr, avoid_ellbow_.gpoint_[0], avoid_ellbow_.gpoint_[1]);
cairo_line_to(cr, avoid_ellbow_.gpoint_[0], avoid_ellbow_.gpoint_[1]);
cairo_stroke(cr);
}
if (avoid_wrist_.isActive()) {
cairo_move_to(cr, avoid_wrist_.gpoint_[0], avoid_wrist_.gpoint_[1]);
cairo_line_to(cr, avoid_wrist_.gpoint_[0], avoid_wrist_.gpoint_[1]);
cairo_stroke(cr);
}
if (avoid_ee_.isActive()) {
cairo_move_to(cr, avoid_ee_.gpoint_[0], avoid_ee_.gpoint_[1]);
cairo_line_to(cr, avoid_ee_.gpoint_[0], avoid_ee_.gpoint_[1]);
cairo_stroke(cr);
}
// repulsion vectors
cairo_set_source_rgb(cr, 0.4, 0.4, 1.0);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
if (repulse_base_.isActive()) {
cairo_move_to(cr, repulse_base_.gpoint_[0], repulse_base_.gpoint_[1]);
cairo_line_to(cr,
repulse_base_.gpoint_[0] + repulse_base_.getBias()[0],
repulse_base_.gpoint_[1] + repulse_base_.getBias()[1]);
cairo_stroke(cr);
}
if (repulse_ellbow_.isActive()) {
cairo_move_to(cr, repulse_ellbow_.gpoint_[0], repulse_ellbow_.gpoint_[1]);
cairo_line_to(cr,
repulse_ellbow_.gpoint_[0] + repulse_ellbow_.getBias()[0],
repulse_ellbow_.gpoint_[1] + repulse_ellbow_.getBias()[1]);
cairo_stroke(cr);
}
if (repulse_wrist_.isActive()) {
cairo_move_to(cr, repulse_wrist_.gpoint_[0], repulse_wrist_.gpoint_[1]);
cairo_line_to(cr,
repulse_wrist_.gpoint_[0] + repulse_wrist_.getBias()[0],
repulse_wrist_.gpoint_[1] + repulse_wrist_.getBias()[1]);
cairo_stroke(cr);
}
if (repulse_ee_.isActive()) {
cairo_move_to(cr, repulse_ee_.gpoint_[0], repulse_ee_.gpoint_[1]);
cairo_line_to(cr,
repulse_ee_.gpoint_[0] + repulse_ee_.getBias()[0],
repulse_ee_.gpoint_[1] + repulse_ee_.getBias()[1]);
cairo_stroke(cr);
}
cairo_restore(cr);
}
void FirstInteractiveCompound::
update()
{
orient_ee_.goal_ = atan2(h_ee_ori_.point_[1] - h_ee_.point_[1], h_ee_ori_.point_[0] - h_ee_.point_[0]);
repulse_base_.repulsor_ = h_repulsor_.point_;
repulse_ellbow_.repulsor_ = h_repulsor_.point_;
repulse_wrist_.repulsor_ = h_repulsor_.point_;
repulse_ee_.repulsor_ = h_repulsor_.point_;
}
ElasticLinksCompound::
ElasticLinksCompound(PlanarRobot & robot)
: FirstInteractiveCompound(robot),
h2_ee_ (0.2, 0.0, 0.6, 0.0, 0.5),
h1_wrist_ (0.2, 0.0, 0.5, 0.5, 0.5),
h2_wrist_ (0.2, 0.0, 0.3, 0.3, 0.5),
h1_ellbow_(0.2, 0.0, 0.8, 0.8, 0.5),
h2_ellbow_(0.2, 0.0, 0.4, 0.4, 0.5),
h2_base_ (0.2, 0.0, 0.6, 0.3, 0.5),
ee_left_ ("ee_left", 3, robot_.len_c_, 0.0, 0.0, -10.0),
ee_right_ ("ee_right", 3, robot_.len_c_, 0.0, 0.0, -10.0),
wrist_left_ ("wrist_left", 2, robot_.len_b_, 0.0, 0.0, -10.0),
wrist_right_ ("wrist_right", 2, robot_.len_b_, 0.0, 0.0, -10.0),
ellbow_left_ ("ellbow_left", 1, robot_.len_a_, 0.0, 0.0, -10.0),
ellbow_right_("ellbow_right", 1, robot_.len_a_, 0.0, 0.0, -10.0),
base_left_ ("base_left", 0, 0.0, 0.0, 0.0, -10.0),
base_right_ ("base_right", 0, 0.0, 0.0, 0.0, -10.0)
{
handles_.push_back(&h2_ee_);
handles_.push_back(&h1_wrist_);
handles_.push_back(&h2_wrist_);
handles_.push_back(&h1_ellbow_);
handles_.push_back(&h2_ellbow_);
handles_.push_back(&h2_base_);
compound_objective_.soft_objectives_.push_back(&ee_left_);
compound_objective_.soft_objectives_.push_back(&ee_right_);
compound_objective_.soft_objectives_.push_back(&wrist_left_);
compound_objective_.soft_objectives_.push_back(&wrist_right_);
compound_objective_.soft_objectives_.push_back(&ellbow_left_);
compound_objective_.soft_objectives_.push_back(&ellbow_right_);
compound_objective_.soft_objectives_.push_back(&base_left_);
compound_objective_.soft_objectives_.push_back(&base_right_);
}
void ElasticLinksCompound::
init(double gui_dimx, double gui_dimy)
{
h2_ee_.point_ << 3.0, gui_dimy / 2.0 , 0.0;
h1_wrist_.point_ << 1.0, gui_dimy / 2.0 - 0.5, 0.0;
h2_wrist_.point_ << 3.0, gui_dimy / 2.0 - 0.5, 0.0;
h1_ellbow_.point_ << 1.0, gui_dimy / 2.0 - 1.0, 0.0;
h2_ellbow_.point_ << 3.0, gui_dimy / 2.0 - 1.0, 0.0;
h2_base_.point_ << 3.0, 1.0, 0.0;
FirstInteractiveCompound::init(gui_dimx, gui_dimy);
}
static void draw_elastic(cairo_t * cr, double weight, double pixelsize,
InteractionHandle const & handle,
PointAttractionObjective const & objective)
{
cairo_set_source_rgba(cr, handle.red_, handle.green_, handle.blue_, 0.5);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr,
objective.gpoint_[0],
objective.gpoint_[1]);
cairo_line_to(cr,
handle.point_[0],
handle.point_[1]);
cairo_stroke(cr);
if (objective.isActive()) {
cairo_set_source_rgba(cr, handle.red_, handle.green_, handle.blue_, 0.8);
cairo_set_line_width(cr, weight * 3.0 / pixelsize);
cairo_move_to(cr,
objective.gpoint_[0],
objective.gpoint_[1]);
cairo_line_to(cr,
objective.gpoint_[0] + objective.getBias()[0],
objective.gpoint_[1] + objective.getBias()[1]);
cairo_stroke(cr);
}
}
void ElasticLinksCompound::
draw(cairo_t * cr, double weight, double pixelsize)
const
{
FirstInteractiveCompound::draw(cr, weight, pixelsize);
draw_elastic(cr, weight, pixelsize, h_ee_, ee_left_);
draw_elastic(cr, weight, pixelsize, h2_ee_, ee_right_);
draw_elastic(cr, weight, pixelsize, h1_wrist_, wrist_left_);
draw_elastic(cr, weight, pixelsize, h2_wrist_, wrist_right_);
draw_elastic(cr, weight, pixelsize, h1_ellbow_, ellbow_left_);
draw_elastic(cr, weight, pixelsize, h2_ellbow_, ellbow_right_);
draw_elastic(cr, weight, pixelsize, h_base_, base_left_);
draw_elastic(cr, weight, pixelsize, h2_base_, base_right_);
}
void ElasticLinksCompound::
update()
{
ee_left_.attractor_ = h_ee_.point_;
ee_right_.attractor_ = h2_ee_.point_;
wrist_left_.attractor_ = h1_wrist_.point_;
wrist_right_.attractor_ = h2_wrist_.point_;
ellbow_left_.attractor_ = h1_ellbow_.point_;
ellbow_right_.attractor_ = h2_ellbow_.point_;
base_left_.attractor_ = h_base_.point_;
base_right_.attractor_ = h2_base_.point_;
FirstInteractiveCompound::update();
}
EEGoalCompound::
EEGoalCompound(PlanarRobot & robot)
: FirstInteractiveCompound(robot),
attract_ee_ ("attract_ee", 3, robot_.len_c_, 0.0, 0.0, -1.0),
attract_base_ ("attract_base", 0, 0.0, 0.0, 0.0, -1.0)
{
compound_objective_.hard_objectives_.push_back(&attract_ee_);
compound_objective_.soft_objectives_.push_back(&attract_base_);
}
void EEGoalCompound::
draw(cairo_t * cr, double weight, double pixelsize)
const
{
FirstInteractiveCompound::draw(cr, weight, pixelsize);
// thin line for end effector objective
cairo_set_source_rgb(cr, 1.0, 0.4, 0.4);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, attract_ee_.gpoint_[0], attract_ee_.gpoint_[1]);
cairo_line_to(cr, attract_ee_.attractor_[0], attract_ee_.attractor_[1]);
cairo_stroke(cr);
// base attraction
if (attract_base_.isActive()) {
cairo_set_source_rgb(cr, 0.4, 1.0, 0.4);
cairo_set_line_width(cr, weight * 1.0 / pixelsize);
cairo_move_to(cr, attract_base_.gpoint_[0], attract_base_.gpoint_[1]);
cairo_line_to(cr,
attract_base_.gpoint_[0] + attract_base_.getBias()[0],
attract_base_.gpoint_[1] + attract_base_.getBias()[1]);
cairo_stroke(cr);
}
}
void EEGoalCompound::
update()
{
attract_ee_.attractor_ = h_ee_.point_;
attract_base_.attractor_ = h_base_.point_;
FirstInteractiveCompound::update();
}
}
}
|
[
"poftwaresatent@gmail.com"
] |
poftwaresatent@gmail.com
|
3c40b38ca651974ba98573879f4a2e0a87a08fb0
|
85e5e67b0ddb32701b6aad5c3d2a428c768bb41c
|
/Engine/PackTest.cpp
|
e92f8c58e7ee7d43e7ffa9c7e5008a51407b97cd
|
[] |
no_license
|
lim-james/Allure
|
a6ebca6b2ca1c70bc2108f8ae710c2a88117657d
|
6d837a49254d181babf546d829fc871e468d66db
|
refs/heads/master
| 2021-07-18T04:31:08.130059
| 2020-08-21T03:30:54
| 2020-08-21T03:30:54
| 205,639,206
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 5,298
|
cpp
|
#include "PackTest.h"
#include "Camera.h"
#include "Light2D.h"
#include "TilemapRender.h"
#include "SpriteRender.h"
#include "SpriteAnimationSystem.h"
#include "AnimationSystem.h"
// scripts
#include "CameraFollow.h"
#include "CrosshairController.h"
// utilities
#include "LoadTilemap.h"
#include "LoadTexture.h"
void PackTest::Awake() {
Scene::Awake();
systems->Subscribe<SpriteAnimationSystem>(1);
systems->Subscribe<AnimationSystem>(1);
// Materials
spriteLit = new Material::SpriteLit;
tilemapLit = new Material::TilemapLit;
circle = new Material::Circle;
circle->borderWeight = 0.25f;
// Prefab
coinPrefab = new CoinPrefab;
coinPrefab->Initialize(entities);
flyingEnemyPrefab = new FlyingEnemyPrefab;
flyingEnemyPrefab->Initialize(entities);
skeletonArcherPrefab = new SkeletonArcherPrefab;
skeletonArcherPrefab->Initialize(entities);
slimePrefab = new SlimePrefab;
slimePrefab->Initialize(entities);
golemMidPrefab = new GolemMidPrefab;
golemMidPrefab->Initialize(entities);
golemLittlePrefab = new GolemLittlePrefab;
golemLittlePrefab->Initialize(entities);
magePrefab = new MagePrefab;
magePrefab->Initialize(entities);
spawnerPrefab = new SpawnerPrefab;
spawnerPrefab->Initialize(entities);
stoneShieldPrefab = new StoneShieldPrefab;
stoneShieldPrefab->Initialize(entities);
castingCirclePrefab = new CastingCirclePrefab;
castingCirclePrefab->Initialize(entities);
spikesPrefab = new SpikesPrefab;
spikesPrefab->Initialize(entities);
chestPrefab = new ChestPrefab;
chestPrefab->Initialize(entities);
altarCandlePrefab = new AltarCandlePrefab;
altarCandlePrefab->Initialize(entities);
candle1Prefab = new Candle1Prefab;
candle1Prefab->Initialize(entities);
candle2Prefab = new Candle2Prefab;
candle2Prefab->Initialize(entities);
}
void PackTest::Create() {
Scene::Create();
Camera* const camera = entities->GetComponent<Camera>(mainCamera);
camera->clearColor = 1.f;
camera->SetSize(5.f);
camera->projection = ORTHOGRAPHIC;
camera->captureDepth = true;
CameraFollow* const follow = entities->AddComponent<CameraFollow>(mainCamera);
follow->SetActive(true);
follow->offset.z = 10.f;
follow->stick = false;
follow->speed = 10.f;
follow->jutDistance = 1.f;
{
const unsigned entity = entities->Create();
Transform* const transform = entities->GetComponent<Transform>(entity);
transform->SetLocalTranslation(vec3f(-5.f, 6.f, 0.f));
TilemapRender* const render = entities->AddComponent<TilemapRender>(entity);
render->SetPalette(Load::TMP("Files/Data/Palettes/world.tmp"));
render->layout = Load::TML("Files/Data/Levels/levels-(0).csv");
render->SetActive(true);
render->SetMaterial(tilemapLit);
}
{
const unsigned entity = entities->Create();
Transform* const transform = entities->GetComponent<Transform>(entity);
transform->SetLocalTranslation(vec3f(-5.f, 7.f, 1.f));
TilemapRender* const render = entities->AddComponent<TilemapRender>(entity);
render->SetPalette(Load::TMP("Files/Data/Palettes/world.tmp"));
render->layout = Load::TML("Files/Data/Levels/levels-(1).csv");
render->SetActive(true);
render->SetMaterial(tilemapLit);
}
//coinPrefab->Create();
//slimePrefab->CreateAt(vec3f(1.f, 0.f, 0.f));
//flyingEnemyPrefab->CreateAt(vec3f(2.f, 0.f, 0.f));
//skeletonArcherPrefab->CreateAt(vec3f(3.f, 0.f, 0.f));
//golemMidPrefab->CreateAt(vec3f(-1.f, 0.f, 0.f));
//golemLittlePrefab->CreateAt(vec3f(-2.f, 0.f, 0.f));
// crosshair
{
const unsigned entity = entities->Create();
Transform* const transform = entities->GetComponent<Transform>(entity);
transform->SetLocalTranslation(vec3f(0.f, 0.f, 5.f));
transform->SetScale(0.5f);
follow->crosshair = transform;
TransformAnimator* const animator = entities->AddComponent<TransformAnimator>(entity);
animator->SetActive(true);
SpriteRender* const render = entities->AddComponent<SpriteRender>(entity);
render->SetActive(true);
render->SetMaterial(circle);
CrosshairController* const controller = entities->AddComponent<CrosshairController>(entity);
controller->SetActive(true);
controller->view = camera;
}
{
Transform * const transform = magePrefab->CreateAt(vec3f(-3.f, 0.f, 0.1f));
follow->player = transform;
const unsigned entity = transform->entity;
Light2D* const light = entities->AddComponent<Light2D>(entity);
light->SetActive(true);
light->type = LIGHT_POINT;
light->intensity = 100.f;
light->strength = 0.5f;
}
//spawnerPrefab->CreateAt(vec3f(0.f, -1.f, 0.f));
//stoneShieldPrefab->CreateAt(vec3f(-1.f, -1.f, 0.f));
//castingCirclePrefab->CreateAt(vec3f(-3.f, -1.f, 0.f));
//spikesPrefab->CreateAt(vec3f(0.f, -2.f, 0.f));
//chestPrefab->CreateAt(vec3f(1.f, -2.f, 0.f));
//altarCandlePrefab->CreateAt(vec3f(0.f, -3.f, 0.f));
//candle1Prefab->CreateAt(vec3f(1.f, -3.f, 0.f));
//candle2Prefab->CreateAt(vec3f(2.f, -3.f, 0.f));
}
void PackTest::Destroy() {
Scene::Destroy();
delete coinPrefab;
delete flyingEnemyPrefab;
delete skeletonArcherPrefab;
delete slimePrefab;
delete golemMidPrefab;
delete golemLittlePrefab;
delete magePrefab;
delete spawnerPrefab;
delete stoneShieldPrefab;
delete castingCirclePrefab;
delete spikesPrefab;
delete chestPrefab;
delete altarCandlePrefab;
delete candle1Prefab;
delete candle2Prefab;
}
|
[
"jameslimbj@gmail.com"
] |
jameslimbj@gmail.com
|
a14650f078cd2a2f5f30b9f509988c413398bbac
|
218297c214d543e25cd67e95a2e871f49acb797b
|
/src/service/WifiConnectionService.cpp
|
f817d34bb5459efefea35268b05f50880004cc7e
|
[] |
no_license
|
ulvestuen/lunsjregistrering-iot
|
45c3b791d679bd277606634f4d48d925b3bb2bf3
|
4414e1d325eff84d14700f183c7f6f84e779b4d8
|
refs/heads/master
| 2020-07-21T21:38:10.604097
| 2019-10-14T20:29:10
| 2019-10-14T20:29:10
| 206,979,691
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 608
|
cpp
|
#include <service/WifiConnectionService.h>
WifiConnectionService::WifiConnectionService() {}
void WifiConnectionService::connect()
{
Serial.begin(115200);
WiFi.disconnect(true);
WiFi.persistent(false);
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED)
{
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.print("Connected to ");
Serial.println(ssid);
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
|
[
"idaruh@gmail.com"
] |
idaruh@gmail.com
|
21953e951cd8ffead8703c929309fdeb96635669
|
664534cb02d1b7fa43b2b84b27dd17d52f1b8b84
|
/꼬인 전깃줄.cpp
|
3d1cfac3b0e849c8f8c0f871b3efaabaa12a026a
|
[] |
no_license
|
chaeyeonhan1225/BOJ
|
b3b6a50418da902c7e69b6018e93e3ee6fa8017d
|
4c733b33fd58d2311ce768298b974f6473887838
|
refs/heads/master
| 2022-12-16T14:03:35.647699
| 2020-09-20T13:36:47
| 2020-09-20T13:36:47
| 270,011,093
| 0
| 0
| null | null | null | null |
WINDOWS-1252
|
C++
| false
| false
| 597
|
cpp
|
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main(void)
{
// LIS ±¸Çϱâ
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int N;
cin >> N;
vector<int> a(N+1);
for (int i = 1; i <= N; ++i) {
int k;
cin >> k;
a[i] = k;
}
vector<int> s;
for (int i = 1; i <= N; ++i) {
if (s.empty()) {
s.push_back(a[i]);
continue;
}
if (s.back() < a[i]) {
s.push_back(a[i]);
}
else {
vector<int>::iterator it = lower_bound(s.begin(), s.end(), a[i]);
*it = a[i];
}
}
cout << N - s.size() << "\n";
return 0;
}
|
[
"gkscodus11@gmail.com"
] |
gkscodus11@gmail.com
|
aa6975e63a648eebd532d5b612866e023dba5622
|
d0c44dd3da2ef8c0ff835982a437946cbf4d2940
|
/cmake-build-debug/programs_tiling/function13927/function13927_schedule_4/function13927_schedule_4_wrapper.cpp
|
ef49abd3c9e452461d500e9c9547b81d260e741d
|
[] |
no_license
|
IsraMekki/tiramisu_code_generator
|
8b3f1d63cff62ba9f5242c019058d5a3119184a3
|
5a259d8e244af452e5301126683fa4320c2047a3
|
refs/heads/master
| 2020-04-29T17:27:57.987172
| 2019-04-23T16:50:32
| 2019-04-23T16:50:32
| 176,297,755
| 1
| 2
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,257
|
cpp
|
#include "Halide.h"
#include "function13927_schedule_4_wrapper.h"
#include "tiramisu/utils.h"
#include <cstdlib>
#include <iostream>
#include <time.h>
#include <fstream>
#include <chrono>
#define MAX_RAND 200
int main(int, char **){
Halide::Buffer<int32_t> buf00(2048);
Halide::Buffer<int32_t> buf01(32768);
Halide::Buffer<int32_t> buf02(2048);
Halide::Buffer<int32_t> buf03(2048);
Halide::Buffer<int32_t> buf04(32768);
Halide::Buffer<int32_t> buf05(32768);
Halide::Buffer<int32_t> buf0(2048, 32768);
init_buffer(buf0, (int32_t)0);
auto t1 = std::chrono::high_resolution_clock::now();
function13927_schedule_4(buf00.raw_buffer(), buf01.raw_buffer(), buf02.raw_buffer(), buf03.raw_buffer(), buf04.raw_buffer(), buf05.raw_buffer(), buf0.raw_buffer());
auto t2 = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diff = t2 - t1;
std::ofstream exec_times_file;
exec_times_file.open("../data/programs/function13927/function13927_schedule_4/exec_times.txt", std::ios_base::app);
if (exec_times_file.is_open()){
exec_times_file << diff.count() * 1000000 << "us" <<std::endl;
exec_times_file.close();
}
return 0;
}
|
[
"ei_mekki@esi.dz"
] |
ei_mekki@esi.dz
|
a582923fb7afd48ef6fb39b335d4970c1c3ad989
|
45ba0b455464fe8db168865e2e95d171bba1a3c6
|
/website/domain/manager.cpp
|
5619b7ec3c3a83186575c491e3cfa9e03651b3df
|
[] |
no_license
|
sepiosky/Jom-e-Bazar
|
45c29608863ea496dbdc4bc7c4824cb096c75708
|
004460b039d12de187178d7bbd532c3812e06025
|
refs/heads/master
| 2023-01-13T13:26:31.103846
| 2020-11-22T16:52:18
| 2020-11-22T16:52:18
| 315,084,586
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 4,331
|
cpp
|
#include"manager.h"
using namespace std;
Manager* Manager::signup_manager(string username, string mail, unsigned long password)
{
if(site_manager!=0)
return site_manager;
site_manager=new Manager(username,mail,password);
return site_manager;
}
void Manager::add_car_csv(vector<Product*>& products, string line)
{
istringstream csv(line);
string data;
getline(csv,data,','); string Name=data;
getline(csv,data,','); int Weight=stoi(data);
getline(csv,data,','); int Seats=stoi(data);
getline(csv,data,','); int Cylinders=stoi(data);
getline(csv,data,','); int EngineCapacity=stoi(data);
getline(csv,data,','); int ReverseParkingSensors=stoi(data);
products.push_back( new Car(Name, Weight, Seats, Cylinders, EngineCapacity,
ReverseParkingSensors) );
return;
}
void Manager::add_tv_csv(vector<Product*>& products, string line)
{
istringstream csv(line);
string data;
getline(csv,data,','); string Name=data;
getline(csv,data,','); int ScreenSize=stoi(data);
getline(csv,data,','); string ScreenType=data;
getline(csv,data,','); string Resolution=data;
getline(csv,data,','); int ThreeD=stoi(data);
getline(csv,data,','); int HDR=stoi(data);
products.push_back( new TV(Name, ScreenSize, ScreenType, Resolution, ThreeD, HDR) );
return;
}
void Manager::add_mobile_csv(vector<Product*>& products, string line)
{
istringstream csv(line);
string data;
getline(csv,data,','); string Name=data;
getline(csv,data,','); int Weight=stoi(data);
getline(csv,data,','); double Frequency=stod(data);
getline(csv,data,','); double BMemory=stod(data);
getline(csv,data,','); int RAM=stoi(data);
getline(csv,data,','); double DisplaySize=stod(data);
getline(csv,data,','); double CameraResolution=stod(data);
getline(csv,data,','); string OS=data;
products.push_back( new Mobile(Name, Weight, Frequency, BMemory, RAM,
DisplaySize, CameraResolution, OS) );
return;
}
bool Manager::sort_offer_by_price_ascend(Offer*& offer1, Offer*& offer2)
{
if(offer1->get_unit_price() == offer2->get_unit_price())
return offer1->get_offer_id() < offer2->get_offer_id();
return offer1->get_unit_price() < offer2->get_unit_price();
}
bool Manager::sort_offer_by_price_descend(Offer*& offer1, Offer*& offer2)
{
if(offer1->get_unit_price() == offer2->get_unit_price())
return offer1->get_offer_id() < offer2->get_offer_id();
return offer1->get_unit_price() > offer2->get_unit_price();
}
void Manager::import_products(vector<Product*>& products, string type, string path)
{
ifstream fread;
fread.open(path);
if(!fread.good())
throw NotFound();
string line;
bool is_first_line=1;
while(getline(fread,line))
{
if(is_first_line) {
is_first_line=false;
continue;
}
if(type=="car")
add_car_csv(products,line);
if(type=="tv")
add_tv_csv(products,line);
if(type=="mobile")
add_mobile_csv(products,line);
}
}
string Manager::print_offers(vector<Offer*> offers, string order, string field)
{
string result="productId | offerId | offerUnitPrice | offerAmount\n";
if(field=="offerId" && order=="ASCEND")
sort(offers.begin(), offers.end(), sort_offer_by_id_ascend);
if(field=="offerId" && order=="DESCEND")
sort(offers.begin(), offers.end(), sort_offer_by_id_descend);
if(field=="offerPrice" && order=="ASCEND")
sort(offers.begin(), offers.end(), sort_offer_by_price_ascend);
if(field=="offerPrice" && order=="DESCEND")
sort(offers.begin(), offers.end(), sort_offer_by_price_descend);
for(int i=0;i<offers.size();i++)
{
string s_unit_price=to_string(offers[i]->get_unit_price());
s_unit_price.erase ( s_unit_price.find_last_not_of('0') + 1, std::string::npos );
if(s_unit_price[s_unit_price.size()-1]=='.')
s_unit_price.resize(s_unit_price.size()-1);
result+=to_string(offers[i]->get_product_id()) +" | " + to_string(offers[i]->get_offer_id())
+" | "+s_unit_price+" | "+to_string(offers[i]->get_amount())+'\n';
}
return result;
}
Manager* Manager::site_manager=0;
|
[
"sepehr1377.sg@gmail.com"
] |
sepehr1377.sg@gmail.com
|
3e21b0fae404bc65ae13f9a6b985c3f72ee2c7c3
|
1c925e0bc4bd0967f77e4c1c60b9130b6bd8edd0
|
/Src/Utility/MessagedException.h
|
a9da7c05e997e7e15289c12fb3ba9c95b0e7e77d
|
[] |
no_license
|
d909b/CGE-Piano
|
ed7ff2184fc6ccb9626e9599ff273667293c1605
|
3d9525cdd8493c26e168badc2363b7aecd635297
|
refs/heads/master
| 2020-04-05T22:59:32.686324
| 2013-01-10T09:42:49
| 2013-01-10T09:42:49
| 4,771,550
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 418
|
h
|
/*
* MessagedException.h
*
* @date: Jun 24, 2012
* @author: patrick
*/
#pragma once
#include <exception>
#include <string>
class MessagedException: public std::exception
{
public:
MessagedException(std::string message) throw() :
message_(message)
{;}
virtual ~MessagedException() throw() {;}
virtual const char* what() const throw()
{
return message_.c_str();
}
private:
std::string message_;
};
|
[
"patrick.schwab@technikum-wien.at"
] |
patrick.schwab@technikum-wien.at
|
92b6b6fb357a64b785434d4accf4ec010bff1c83
|
5f1b3d3e8d9e38b5db3d490487556e2858c3cace
|
/_Include/SerialSettings.h
|
c019572b95c0b545db68944721db1f0d2996e60c
|
[] |
no_license
|
NicolaDemers/QtSerialCommands
|
ff7e986b81f3b13739194389111bd4e54330344f
|
65717bfe4855c93f4f05376abdc6f339842d1e01
|
refs/heads/master
| 2021-08-19T03:24:29.417213
| 2018-08-23T17:33:40
| 2018-08-23T17:33:40
| 165,329,828
| 0
| 1
| null | null | null | null |
ISO-8859-1
|
C++
| false
| false
| 1,072
|
h
|
#pragma once
#include "QAsyncSerialPort.h"
/*! \class QSerialSettings
*
* \brief Conteneur des paramètres d'un appareil de communication série. Permet la sauvegarde et le chargement de fichier ini.
*
* save() pour sauvegarder et load() pour charger.
*
*/
class SerialSettings
{
public:
SerialSettings(QAsyncSerialPort::BaudRate baudRate = QAsyncSerialPort::BaudRate::BR9600);
SerialSettings(int port, QAsyncSerialPort::BaudRate baudRate = QAsyncSerialPort::BaudRate::BR9600);
~SerialSettings();
// Cles pour fichier INI
static QString const KEY_PORT;
static QString const KEY_BAUDRATE;
static QString const KEY_STOPBITS;
static QString const KEY_DATABITS;
static QString const KEY_PARITY;
static QString const KEY_FLOWCONTROL;
// Serial Port
int m_Port;
QAsyncSerialPort::BaudRate m_BaudRate;
QSerialPort::StopBits m_StopBits;
QSerialPort::DataBits m_DataBits;
QSerialPort::Parity m_Parity;
QSerialPort::FlowControl m_FlowControl;
void save(QString fileName);
void load(QString fileName);
void loadGeneric();
private:
bool isValid();
};
|
[
"nicola.demers93@gmail.com"
] |
nicola.demers93@gmail.com
|
377e09a09ae44dcd5b2673e607e8f236fb44d6c8
|
41823c261082cc74037f56be62996600422fe518
|
/ world-opponent-network/wonapi/WONInternal/ActivatePatchOp.cpp
|
ad5ed9a877f84b748a0eaa7230ec8a25587542a1
|
[] |
no_license
|
ECToo/world-opponent-network
|
90adf14ca8b324898a1f0b2202c1cfb2b4bdeb03
|
fbb35876ae26006606d07b6297d557bd53234066
|
refs/heads/master
| 2021-01-25T07:40:21.063935
| 2014-05-16T16:02:54
| 2014-05-16T16:02:54
| 32,217,407
| 0
| 1
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,216
|
cpp
|
#include "ActivatePatchOp.h"
using namespace WONAPI;
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
ActivatePatchOp::ActivatePatchOp(ServerContext* theContext)
: DBProxyOp(theContext),
mMsgType(15)
{
Init();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
ActivatePatchOp::ActivatePatchOp(const IPAddr& theAddr)
: DBProxyOp(theAddr),
mMsgType(15)
{
Init();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
WONStatus ActivatePatchOp::CheckResponse()
{
// Call the base class implementation
WONStatus result = DBProxyOp::CheckResponse();
if (result != WS_Success)
return result;
if (mSubMessageReplyType != mMsgType+1)
return InvalidReplyHeader();
// Do extended unpack
// Finished
return WS_Success;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void ActivatePatchOp::RunHook()
{
SetMessageType(DBProxyPatchServer);
SetSubMessageType(mMsgType);
// Pack the message data
WriteBuffer requestData;
requestData.AppendString(mProductName);
requestData.AppendString(mConfigName);
requestData.AppendString(mFromVersion);
requestData.AppendString(mToVersion);
requestData.AppendString(mNetAddress); // patch url
requestData.AppendByte(mIsActive);
// Pack and call base class implementation
SetProxyRequestData(requestData.ToByteBuffer());
DBProxyOp::RunHook();
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void ActivatePatchOp::Init()
{
Reset();
ServerRequestOp::mLengthFieldSize = 4;
mProductName = "";
mConfigName = "";
mFromVersion = "";
mToVersion = "";
mNetAddress = ""; // patch url
mIsActive = FALSE;
}
|
[
"shefben@gmail.com@248fbcc8-4fec-2078-69e5-adb693b6ed4e"
] |
shefben@gmail.com@248fbcc8-4fec-2078-69e5-adb693b6ed4e
|
8c0b7c62a47a7d6938019f4b215ee99dc95bed29
|
9a3b9d80afd88e1fa9a24303877d6e130ce22702
|
/src/Providers/UNIXProviders/AuthorizedUse/UNIX_AuthorizedUse_ZOS.hxx
|
c814bed376c679fddf8db1b6c9534f2321261188
|
[
"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
| 1,809
|
hxx
|
//%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.
//
//////////////////////////////////////////////////////////////////////////
//
//%/////////////////////////////////////////////////////////////////////////
#ifdef PEGASUS_OS_ZOS
#ifndef __UNIX_AUTHORIZEDUSE_PRIVATE_H
#define __UNIX_AUTHORIZEDUSE_PRIVATE_H
#endif
#endif
|
[
"brunolauze@msn.com"
] |
brunolauze@msn.com
|
e7a6b76deb29f7cf0ce1d69ffd3002b644712d6b
|
3a35b302ac0355dd5911bdd5f93546fd22766ed2
|
/Class/Object/Bullet/BulletFactory.cpp
|
6cdaf76b0863275ee657a0b8af9c1045cd67bcdb
|
[] |
no_license
|
kyoichi001/sarashina-yako
|
86ec8e66e6a8d1b0751baf52bcdc29b9785b7419
|
bcf25a24bc21bff1b450d69e94376e3e2d7170ab
|
refs/heads/master
| 2023-02-01T21:08:27.135547
| 2020-12-16T02:36:52
| 2020-12-16T02:36:52
| 321,843,299
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 8,918
|
cpp
|
#include "BulletFactory.h"
#include "IBullet.h"
#include "../../../Library/Func.h"
#include "../../../Library/Renderer.h"
#include "../../../Library/Math/Constant.h"
#include "../../../Library/Easing/InterpolationMethod.h"
#include "../../MediatorClass/ObjectAdaptor.h"
#include "RenewManager.h"
#include <cmath>
inline float getCirAngle(int num, int many) noexcept {return float(num) * PI2 / float(many);}
inline float getFanAngle(int num, float open, int many)noexcept {
return open * (float(num) - float(many - 1) / 2.0f);//-open * (float(many - 1) / 2.0f) + num * open;
}
inline float getFanAngleOpen(int num, float open, int many) noexcept {
return -(open *0.5f) + open * num / (many - 1);
}
inline float getCirFanAngle(int num, float open, int cirmany, int fanmany) noexcept {
return getCirAngle(num / fanmany, cirmany) + getFanAngle(num%fanmany, open, fanmany);
}
inline float getCirFanAngle(int cirnum,int fannum, float open, int cirmany, int fanmany) noexcept {
return getCirAngle(cirnum, cirmany) + getFanAngle(fannum, open, fanmany);
}
inline float getPolygonRadiusRv(int VartexMany, float Angle)noexcept {
return cosf(fmodf(Angle, PI2 / float(VartexMany)) - PI / float(VartexMany));
}
inline float getPolygonStarRadiusRv(int VartexMany, float Angle) noexcept {
return cosf(fmodf(Angle, PI4 / VartexMany) - PI2 / VartexMany);
}
int SmallBHdl[10], MidiumBHdl[10], BigBHdl[10], ArrowBHdl[10], FudaBHdl[10], VeryBigBHdl[10];
int PetalHdl[10], WaterHdl[10];
int SmallOvalHdl[10], BigOvalHdl[10], LeafHdl[10],TrumpHdl[10];
int FireHdl[4],GemHdl[10];
BulletData BVoid { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {},-1,-1 };
BulletData BSmall { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawGraph(XY.x - 6, XY.y - 6, SmallBHdl[Color]); },1,4 };
BulletData BMidium { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawGraph(XY.x - 8, XY.y - 8, MidiumBHdl[Color]); },2,8 };
BulletData BBig { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawGraph(XY.x - 16,XY.y - 16, BigBHdl[Color]); },8,14 };
BulletData BArrow { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() + HALF_PI, ArrowBHdl[Color]); },4,10 };
BulletData BFuda { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() - HALF_PI, FudaBHdl[Color]); },2,10 };
BulletData BHuge { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,lerp(0.0f,1.0f,0,5,t,Ease<Liner>::In),IBullet::getTurnAngle() , VeryBigBHdl[Color]); },18,30 };
BulletData BWater { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() +HALF_PI, WaterHdl[Color]); },3,10 };
BulletData BLeaf { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() +HALF_PI, LeafHdl[Color]); },3 ,10};
BulletData BSOval { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() +HALF_PI, SmallOvalHdl[Color]); },4,6 };
BulletData BLOval { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.8f, Speed.Angle() +HALF_PI, SmallOvalHdl[Color]); },4,6 };
BulletData BFire { [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {
DxWrp::SetDrawBlendMode(BLEND_ADD,255);
DxWrp::DrawRotaGraph(XY- Speed.normed()*37.0f,lerp(0.0f,1.0f,0,10,t,Ease<Liner>::In), Speed.Angle() - HALF_PI, FireHdl[(t / 6) % 3 + 1]);
DxWrp::ResetBlendModeAdd();
DxWrp::DrawRotaGraph(XY - Speed.normed()*37.0f, lerp(0.0f, 1.0f, 0, 10, t, Ease<Liner>::In), Speed.Angle() - HALF_PI, FireHdl[0]);
},50,64 };
BulletData BTrump{ [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f, Speed.Angle() + HALF_PI, TrumpHdl[Color]); },2,6 };
BulletData BGem{ [](const Point& XY,const Vec2& Speed, BulletColor Color,int t) {DxWrp::DrawRotaGraph(XY ,1.0f,IBullet::getTurnAngle(), GemHdl[Color]); },50,80 };
BulletData* DataArray[] = {&BVoid ,&BSmall ,&BMidium ,&BBig ,&BHuge,&BArrow,&BFuda,&BWater, &BLeaf,&BSOval,&BLOval,&BFire,&BTrump,&BGem };
BulletFactory::BulletFactory(ObjectAdaptor* Adaptor) noexcept:mAddFlag(true), mObj(Adaptor), mEmi(Adaptor->ObjEmi()) {
BEmitter::SetSplitBList(this);
DxWrp::LoadDivGraph("Picture/Bullet/SmallBullet.png", 10, 10, 1, 12, 12, SmallBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/MidiumBullet.png", 10, 10, 1, 16, 16, MidiumBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/BigBullet.png", 10, 10, 1, 32, 32, BigBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/ArrowBullet.png", 10, 10, 1, 32, 32, ArrowBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/FudaBullet.png", 10, 10, 1, 32, 32, FudaBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/VeryBigBullet.png", 10, 10, 1, 96, 96, VeryBigBHdl);
DxWrp::LoadDivGraph("Picture/Bullet/waterBullet.png", 10, 10, 1, 32, 32, WaterHdl);
DxWrp::LoadDivGraph("Picture/Bullet/LeafBullet.png", 10, 10, 1, 32, 32, LeafHdl);
DxWrp::LoadDivGraph("Picture/Bullet/SmallOvalBullet.png", 10, 10, 1, 24, 24, SmallOvalHdl);
DxWrp::LoadDivGraph("Picture/Bullet/fireBullet.png", 4, 4, 1, 256, 256, FireHdl);
DxWrp::LoadDivGraph("Picture/Bullet/TrumpBullet.png", 10, 10, 1, 32, 32, TrumpHdl);
DxWrp::LoadDivGraph("Picture/Bullet/gembullet.png", 10, 10, 1, 128, 128, GemHdl);
}
BulletFactory::~BulletFactory()noexcept{}
void BulletFactory::Bullet(uchar ID, uchar renewID, const Point& XY, uchar FanMany, float Angle, float Speed, float open, short radius) noexcept {
DammakuData& data = mDataBase.mBullet[ID];
auto& bList = mObj->ObjBul();
Angle += data.mAngleState == Aiming ? XY.Angle(mObj->GetPlayer()->p) : 0.0f;
if (data.mPolygon == 0) {
for (int i = 0; i < data.mCirMany; ++i) {
for (int j = 0; j < FanMany; ++j) {
Vec2 p{ getCirFanAngle(i, j,open, data.mCirMany, FanMany) + Angle ,1.0f,0 };
bList.Emplace(ID, renewID, XY + p * radius, p*Speed, data.mColor, nullptr, DataArray[data.mShape]);
}
}
}else{
for (int i = 0; i < data.mCirMany; ++i) {
for (int j = 0; j < FanMany; ++j) {
float an = getCirFanAngle(i, j, open, data.mCirMany, FanMany) ;
Vec2 p{ an+ Angle ,1.0f/getPolygonRadiusRv(data.mPolygon,an),0 };
bList.Emplace(ID, renewID, XY + p * radius, p*Speed, data.mColor, nullptr, DataArray[data.mShape]);
}
}
}
//PLAY_SE(2);
}
/*void BulletFactory::Bullet(uchar ID, const Point& XY, uchar fanMany, float Angle, float Speed, float open, BulletShape shape, BulletColor color, short radius = 0)noexcept {
DammakuData& data = mDataBase.mBullet[ID];
auto& bList = mObj->ObjBul();
Angle += data.mAngleState == Aiming ? XY.Angle(mObj->GetPlayer().p) : 0.0f;
for (int i = 0; i < data.mCirMany*fanMany; ++i) {
Vec2 p{ Decide_CirFan_Angle(i, open, data.mCirMany, fanMany) + Angle ,1.0f,0 };
bList.Emplace(ID, XY + p * radius, p*Speed, color, data.mTill, nullptr, DataArray[shape], data.mDrawBlend);
}
//PLAY_SE(2);
}*/
/*void BulletFactory::Bullet(uchar ID, const Point& XY, uchar FanMany, float Angle, float Speed, float open, float(*f)(float), short radius)noexcept {
DammakuData& data = mDataBase.mBullet[ID];
auto& bList = mObj->ObjBul();
Angle += data.mAngleState == Aiming ? XY.Angle(mObj->GetPlayer().p) : 0.0f;
for (int i = 0; i < data.mCirMany*FanMany; ++i) {
float angle = Decide_CirFan_Angle(i, open, data.mCirMany, FanMany) + Angle;
Vec2 p{ angle ,f(angle),0 };
bList.Emplace(ID, XY + p * radius, p*Speed, data.mColor, data.mTill, nullptr, DataArray[data.mShape], data.mDrawBlend);
}
//PLAY_SE(2);
}
void BulletFactory::Bullet(uchar ID, const Point& XY, uchar Many, float Angle, float Speed, float(*f)(int, int), short radius )noexcept {
Angle += mBulletAngleState == Player ? XY.Angle(mObj->GetPlayer().p) : 0.0f;
auto bList = mObj->ObjBul();
for (int i = 0; i <Many; ++i) {
float angle = Decide_CirFan_Angle(i, open, CirMany, FanMany) + Angle;
Vec2 p{ angle ,f(angle),0 };
bList.Emplace(ID, XY + p*radius, p*Speed, Color, Till, nullptr, DataArray[Shape], mBulletDrawType);
}
PLAY_SE(2);
}*/
float BulletFactory::GetBullettoPlayerAngle(const Point& XY)const noexcept { return XY.Angle(mObj->GetPlayer()->p); }
void BulletFactory::clear_emi() noexcept { mObj->ObjEmi().Kill(); }
void BulletFactory::setDammakuData(uchar ID, int cirMany, BulletColor color, BulletShape shape, int till, char AngleState, char drawBlend,char polygon) noexcept {
mDataBase.set(ID, cirMany, color, shape, till, AngleState, drawBlend,polygon);
}
void BulletFactory::clearDammakuData()noexcept {
mDataBase.clear();
}
void BulletFactory::BulletForeach(int ID, func Func)noexcept {
for (auto& Bul : mObj->ObjBul()) {
if (Bul.GetID() == ID)Func(Bul, Bul.GetTime(), *mObj);
}
}
BulletData* BulletFactory::getBulletData(BulletShape shape)noexcept {
return DataArray[shape];
}
|
[
"40378788+kyoichi001@users.noreply.github.com"
] |
40378788+kyoichi001@users.noreply.github.com
|
a26227ca9023716758309002271073b85130bb67
|
d64737d31ae9caba2820ea1048be3f9bce708b42
|
/cpp/number-of-rectangles-that-can-form-the-largest-square.cpp
|
3c50f388e293259f6fa044c8c0d9e85cd2352fc2
|
[] |
no_license
|
ldcduc/leetcode-training
|
2453ec13e69160bc29e8e516e19544c2b25bf945
|
40db37375372f14dd45d0a069c8b86fe36221f09
|
refs/heads/master
| 2023-08-05T01:46:52.993542
| 2021-09-18T16:47:54
| 2021-09-18T16:47:54
| 271,736,046
| 9
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 685
|
cpp
|
/* Problem url: https://leetcode.com/problems/number-of-rectangles-that-can-form-the-largest-square
* Code by: ldcduc
* */
/* Begin of Solution */
class Solution {
public:
int countGoodRectangles(vector<vector<int>>& rectangles) {
int side = 0, result = 0;
for (int i = 0; i < rectangles.size(); ++ i) {
if (min(rectangles[i][0], rectangles[i][1]) >= side) {
result = min(rectangles[i][0], rectangles[i][1]) == side ? result + 1 : 1;
side = min(rectangles[i][0], rectangles[i][1]);
}
}
return result;
}
};
/* End of Solution */
/*
* Comment by ldcduc
* Suggested tags: array
*
* */
|
[
"ldcduc@apcs.vn"
] |
ldcduc@apcs.vn
|
056fcab0b22abd311cd88f6eb8eca707d8df6251
|
f6408fa4d36915390024275dc69cb8a4427074f9
|
/sprout/algorithm/fixed/transform.hpp
|
e120f0d909df762ccee461b0e9760261d327ed26
|
[
"BSL-1.0"
] |
permissive
|
nekko1119/Sprout
|
72dcc643536e595832be7d05151a1444e072980c
|
3e33de25ebbf4043f86a56f58459e3e45fcbe746
|
refs/heads/master
| 2021-01-15T18:04:36.229085
| 2013-09-20T07:38:27
| 2013-09-20T07:38:27
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 11,918
|
hpp
|
/*=============================================================================
Copyright (c) 2011-2013 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprout
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)
=============================================================================*/
#ifndef SPROUT_ALGORITHM_FIXED_TRANSFORM_HPP
#define SPROUT_ALGORITHM_FIXED_TRANSFORM_HPP
#include <iterator>
#include <type_traits>
#include <sprout/config.hpp>
#include <sprout/index_tuple/metafunction.hpp>
#include <sprout/container/traits.hpp>
#include <sprout/container/functions.hpp>
#include <sprout/container/indexes.hpp>
#include <sprout/iterator/operation.hpp>
#include <sprout/iterator/transform_iterator.hpp>
#include <sprout/iterator/type_traits/common.hpp>
#include <sprout/algorithm/fixed/result_of.hpp>
#include <sprout/pit/pit.hpp>
#include <sprout/detail/container_complate.hpp>
namespace sprout {
namespace fixed {
namespace detail {
template<typename RandomAccessIterator, typename Result, typename UnaryOperation, sprout::index_t... Indexes>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform_impl_ra(
RandomAccessIterator first, RandomAccessIterator,
Result const& result, UnaryOperation op,
sprout::index_tuple<Indexes...>,
typename sprout::container_traits<Result>::difference_type offset,
typename sprout::container_traits<Result>::size_type size,
typename sprout::container_traits<Result>::size_type input_size
)
{
return sprout::remake<Result>(
result, sprout::size(result),
(Indexes >= offset && Indexes < offset + size && Indexes < offset + input_size
? op(first[Indexes - offset])
: *sprout::next(sprout::internal_begin(result), Indexes)
)...
);
}
template<typename RandomAccessIterator, typename Result, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(
RandomAccessIterator first, RandomAccessIterator last,
Result const& result, UnaryOperation op,
std::random_access_iterator_tag*
)
{
return sprout::fixed::detail::transform_impl_ra(
first, last,
result, op,
sprout::container_indexes<Result>::make(),
sprout::internal_begin_offset(result),
sprout::size(result),
sprout::distance(first, last)
);
}
template<typename InputIterator, typename Result, typename UnaryOperation, typename... Args>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::container_traits<Result>::static_size == sizeof...(Args),
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform_impl(
InputIterator, InputIterator,
Result const& result, UnaryOperation,
typename sprout::container_traits<Result>::size_type,
Args const&... args
)
{
return sprout::remake<Result>(result, sprout::size(result), args...);
}
template<typename InputIterator, typename Result, typename UnaryOperation, typename... Args>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::container_traits<Result>::static_size != sizeof...(Args),
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform_impl(
InputIterator first, InputIterator last,
Result const& result, UnaryOperation op,
typename sprout::container_traits<Result>::size_type size,
Args const&... args
)
{
return first != last && sizeof...(Args) < size
? sprout::fixed::detail::transform_impl(sprout::next(first), last, result, op, size, args..., op(*first))
: sprout::detail::container_complate(result, args...)
;
}
template<typename InputIterator, typename Result, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(
InputIterator first, InputIterator last,
Result const& result, UnaryOperation op,
std::input_iterator_tag*
)
{
return sprout::fixed::detail::transform_impl(first, last, result, op, sprout::size(result));
}
template<typename InputIterator, typename Result, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::is_fixed_container<Result>::value,
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform(InputIterator first, InputIterator last, Result const& result, UnaryOperation op) {
typedef typename std::iterator_traits<InputIterator>::iterator_category* category;
return sprout::fixed::detail::transform(first, last, result, op, category());
}
template<typename InputIterator, typename Result, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename std::enable_if<
!sprout::is_fixed_container<Result>::value,
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform(InputIterator first, InputIterator last, Result const& result, UnaryOperation op) {
return sprout::remake<Result>(
result, sprout::size(result),
sprout::make_transform_iterator(first, op),
sprout::make_transform_iterator(last, op)
);
}
} // namespace detail
//
// transform
//
template<typename InputIterator, typename Result, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(InputIterator first, InputIterator last, Result const& result, UnaryOperation op) {
return sprout::fixed::detail::transform(first, last, result, op);
}
template<typename Result, typename InputIterator, typename UnaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(InputIterator first, InputIterator last, UnaryOperation op) {
return sprout::fixed::transform(first, last, sprout::pit<Result>(), op);
}
namespace detail {
template<typename RandomAccessIterator1, typename RandomAccessIterator2, typename Result, typename BinaryOperation, sprout::index_t... Indexes>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform_impl_ra(
RandomAccessIterator1 first1, RandomAccessIterator1, RandomAccessIterator2 first2,
Result const& result, BinaryOperation op,
sprout::index_tuple<Indexes...>,
typename sprout::container_traits<Result>::difference_type offset,
typename sprout::container_traits<Result>::size_type size,
typename sprout::container_traits<Result>::size_type input_size
)
{
return sprout::remake<Result>(
result, sprout::size(result),
(Indexes >= offset && Indexes < offset + size && Indexes < offset + input_size
? op(first1[Indexes - offset], first2[Indexes - offset])
: *sprout::next(sprout::internal_begin(result), Indexes)
)...
);
}
template<typename RandomAccessIterator1, typename RandomAccessIterator2, typename Result, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(
RandomAccessIterator1 first1, RandomAccessIterator1 last1, RandomAccessIterator2 first2,
Result const& result, BinaryOperation op,
std::random_access_iterator_tag*
)
{
return sprout::fixed::detail::transform_impl_ra(
first1, last1, first2,
result, op,
sprout::container_indexes<Result>::make(),
sprout::internal_begin_offset(result),
sprout::size(result),
sprout::distance(first1, last1)
);
}
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation, typename... Args>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::container_traits<Result>::static_size == sizeof...(Args),
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform_impl(
InputIterator1, InputIterator1, InputIterator2,
Result const& result, BinaryOperation,
typename sprout::container_traits<Result>::size_type,
Args const&... args
)
{
return sprout::remake<Result>(result, sprout::size(result), args...);
}
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation, typename... Args>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::container_traits<Result>::static_size != sizeof...(Args),
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform_impl(
InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
Result const& result, BinaryOperation op,
typename sprout::container_traits<Result>::size_type size,
Args const&... args
)
{
return first1 != last1 && sizeof...(Args) < size
? sprout::fixed::detail::transform_impl(sprout::next(first1), last1, sprout::next(first2), result, op, size, args..., op(*first1, *first2))
: sprout::detail::container_complate(result, args...)
;
}
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(
InputIterator1 first1, InputIterator1 last1, InputIterator2 first2,
Result const& result, BinaryOperation op,
std::input_iterator_tag*
)
{
return sprout::fixed::detail::transform_impl(first1, last1, first2, result, op, sprout::size(result));
}
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename std::enable_if<
sprout::is_fixed_container<Result>::value,
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, Result const& result, BinaryOperation op) {
typedef typename sprout::common_iterator_category<InputIterator1, InputIterator2>::type* category;
return sprout::fixed::detail::transform(first1, last1, first2, result, op, category());
}
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename std::enable_if<
!sprout::is_fixed_container<Result>::value,
typename sprout::fixed::result_of::algorithm<Result>::type
>::type
transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, Result const& result, BinaryOperation op) {
return sprout::remake<Result>(
result, sprout::size(result),
sprout::make_transform_iterator(first1, first2, op),
sprout::make_transform_iterator(last1, first2, op)
);
}
} // namespace detail
//
// transform
//
template<typename InputIterator1, typename InputIterator2, typename Result, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, Result const& result, BinaryOperation op) {
return sprout::fixed::detail::transform(first1, last1, first2, result, op);
}
template<typename Result, typename InputIterator1, typename InputIterator2, typename BinaryOperation>
inline SPROUT_CONSTEXPR typename sprout::fixed::result_of::algorithm<Result>::type
transform(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, BinaryOperation op) {
return sprout::fixed::transform(first1, last1, first2, sprout::pit<Result>(), op);
}
} // namespace fixed
using sprout::fixed::transform;
} // namespace sprout
#endif // #ifndef SPROUT_ALGORITHM_FIXED_TRANSFORM_HPP
|
[
"bolero.murakami@gmail.com"
] |
bolero.murakami@gmail.com
|
396bf6e3f152e4b4dc03ac9de9d32961d3c6ac15
|
5de7df0be411b4bad61f927cae845bdb8223308f
|
/src/tests/ascent/t_ascent_mpi_derived.cpp
|
6ebae0c6c0bcd52b62e777b24a70fe851948f0ef
|
[
"BSD-3-Clause",
"Zlib"
] |
permissive
|
Alpine-DAV/ascent
|
cb40429167a93c62f78fe650a0121258be279162
|
e52b7bb8c9fd131f2fd49edf58037cc5ef77a166
|
refs/heads/develop
| 2023-09-06T07:57:11.558238
| 2023-08-25T16:05:31
| 2023-08-25T16:05:31
| 81,366,855
| 151
| 61
|
NOASSERTION
| 2023-09-13T19:31:09
| 2017-02-08T19:21:22
|
C++
|
UTF-8
|
C++
| false
| false
| 3,809
|
cpp
|
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
// Copyright (c) Lawrence Livermore National Security, LLC and other Ascent
// Project developers. See top-level LICENSE AND COPYRIGHT files for dates and
// other details. No copyright assignment is required to contribute to Ascent.
//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~//
//-----------------------------------------------------------------------------
///
/// file: ascent_mpi_derived.cpp
///
//-----------------------------------------------------------------------------
#include "gtest/gtest.h"
#include <ascent.hpp>
#include <iostream>
#include <math.h>
#include <ascent_expression_eval.hpp>
#include <flow_workspace.hpp>
#include <mpi.h>
#include <conduit_blueprint.hpp>
#include "t_config.hpp"
#include "t_utils.hpp"
using namespace std;
using namespace conduit;
using namespace ascent;
index_t EXAMPLE_MESH_SIDE_DIM = 20;
void create_test_data(Node &data)
{
int par_rank;
int par_size;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm, &par_rank);
MPI_Comm_size(comm, &par_size);
data.reset();
if(par_rank == 0)
{
Node &mesh = data.append();
conduit::blueprint::mesh::examples::braid("uniform",
EXAMPLE_MESH_SIDE_DIM,
EXAMPLE_MESH_SIDE_DIM,
EXAMPLE_MESH_SIDE_DIM,
mesh);
mesh["state/domain_id"] = 0;
}
else
{
Node &mesh = data.append();
conduit::blueprint::mesh::examples::braid("points",
EXAMPLE_MESH_SIDE_DIM,
EXAMPLE_MESH_SIDE_DIM,
EXAMPLE_MESH_SIDE_DIM,
mesh);
// add a field that wont exist on both domains
mesh["fields/bananas"] = mesh["fields/braid"];
mesh["state/domain_id"] = 1;
//std::cout<<mesh.to_summary_string()<<"\n";
}
}
//-----------------------------------------------------------------------------
TEST(ascent_mpi_derived, mpi_derived)
{
Node n;
ascent::about(n);
// only run this test if ascent was built with jit support
if(n["runtimes/ascent/jit/status"].as_string() == "disabled")
{
ASCENT_INFO("Ascent JIT support disabled, skipping test\n");
return;
}
//
// Set Up MPI
//
int par_rank;
int par_size;
MPI_Comm comm = MPI_COMM_WORLD;
MPI_Comm_rank(comm, &par_rank);
MPI_Comm_size(comm, &par_size);
ASCENT_INFO("Rank "
<< par_rank
<< " of "
<< par_size
<< " reporting");
//
// Create the data.
//
Node data, verify_info;
create_test_data(data);
conduit::blueprint::mesh::verify(data,verify_info);
flow::Workspace::set_default_mpi_comm(MPI_Comm_c2f(comm));
runtime::expressions::register_builtin();
runtime::expressions::ExpressionEval eval(&data);
std::string expr = "magnitude(max(field('bananas')).position)";
conduit::Node res = eval.evaluate(expr);
EXPECT_EQ(res["type"].as_string(), "double");
if(par_rank == 0)
{
res.print();
}
// create an expression that will throw an exception (points volume)
// and do an MPI reduction that will hang (reduce) if exceptions aren't
// handled correctly
expr = "sum(topo('mesh').cell.volume)";
// normally the ascent runtime would catch this so we have to catch
EXPECT_ANY_THROW(res = eval.evaluate(expr));
}
int main(int argc, char* argv[])
{
int result = 0;
::testing::InitGoogleTest(&argc, argv);
MPI_Init(&argc, &argv);
result = RUN_ALL_TESTS();
MPI_Finalize();
return result;
}
|
[
"noreply@github.com"
] |
Alpine-DAV.noreply@github.com
|
bafe56a854e97d6245cc37c0a18de8c4a0b97280
|
b7e97047616d9343be5b9bbe03fc0d79ba5a6143
|
/src/core/chemical/ResConnID.hh
|
05ac578fc198057eb8d65030dc6ea6f3712573ac
|
[] |
no_license
|
achitturi/ROSETTA-main-source
|
2772623a78e33e7883a453f051d53ea6cc53ffa5
|
fe11c7e7cb68644f404f4c0629b64da4bb73b8f9
|
refs/heads/master
| 2021-05-09T15:04:34.006421
| 2018-01-26T17:10:33
| 2018-01-26T17:10:33
| 119,081,547
| 1
| 3
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,253
|
hh
|
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*-
// vi: set ts=2 noet:
//
// (c) Copyright Rosetta Commons Member Institutions.
// (c) This file is part of the Rosetta software suite and is made available under license.
// (c) The Rosetta software is developed by the contributing members of the Rosetta Commons.
// (c) For more information, see http://www.rosettacommons.org. Questions about this can be
// (c) addressed to University of Washington CoMotion, email: license@uw.edu.
/// @file src/core/chemica/ResConnID.hh
/// @brief Declaration of class to represent the chemical bond between two
/// ResidueConnections from one conformation::Residue to another.
/// @author Andrew Leaver-Fay
#ifndef INCLUDED_core_chemical_ResConnID_hh
#define INCLUDED_core_chemical_ResConnID_hh
// Unit Headers
#include <core/chemical/ResConnID.fwd.hh>
// Project Headers
#include <core/types.hh>
namespace core {
namespace chemical {
/// @brief The ResConnID could more properly be called the ResidueConnector. It stores the
/// data necessary to describe how one ResidueConnection on a conformation::Residue is connected
/// to the rest of the structure (Pose), by listing the other Residue's index and the ResidueConnection
/// index.
class ResConnID {
public:
ResConnID();
ResConnID( ResConnID const & );
ResConnID( Size resid, Size connid );
ResConnID & operator = ( ResConnID const & );
friend bool operator < ( ResConnID const & lhs, ResConnID const & rhs );
friend bool operator == ( ResConnID const & lhs, ResConnID const & rhs );
friend bool operator != ( ResConnID const & lhs, ResConnID const & rhs );
Size resid() const;
void resid( Size );
Size connid() const;
void connid( Size );
bool incomplete() const;
void mark_incomplete();
#ifdef SERIALIZATION
template < class Archive >
void
save( Archive & arch ) const;
template < class Archive >
void
load( Archive & arch );
#endif // SERIALIZATION
private:
Size res_id_;
Size conn_id_;
};
bool operator < ( ResConnID const & lhs, ResConnID const & rhs );
bool operator == ( ResConnID const & lhs, ResConnID const & rhs );
bool operator != ( ResConnID const & lhs, ResConnID const & rhs );
}
}
#endif
|
[
"achitturi17059@gmail.com"
] |
achitturi17059@gmail.com
|
0e4f44160e0437bef76dbd813086e2b691d8b771
|
12ea44ea5a8fc9a7451d52dccb1689ebd2c5e71d
|
/main.cpp
|
9e739eece1234e82f637d5264721762cc4a78514
|
[] |
no_license
|
aadebuger/jsonlr
|
4ce38cb110de4e9c0afcce055a78b798b9f9afee
|
f67f06b807ac606616637470e16469b21f743a1b
|
refs/heads/master
| 2021-01-19T09:36:48.907137
| 2017-02-16T02:23:38
| 2017-02-16T02:23:38
| 82,129,487
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 455
|
cpp
|
#include "json.hpp"
#include <iostream>
// for convenience
using json = nlohmann::json;
int main()
{
json j = "{ \"happy\": true, \"pi\": 3.141 }"_json;
for (json::iterator it = j.begin(); it != j.end(); ++it) {
std::cout << *it << '\n';
std::cout << it.key() << " : " << it.value() << "\n";
}
for (auto& element : j) {
std::cout << element << element.is_<<'\n';
}
std::cout<< j<< std::endl;
}
|
[
"zh@zqf.com.cn"
] |
zh@zqf.com.cn
|
d298282c6a37cf1b1750ae490e29871d442e095b
|
fa29e2bce27a561808c8540842ea65339c8cf8f1
|
/tests/octree/src/ModelTests.cpp
|
b91963726f29d1b769cbdd3c194fb7e3a3e91bb5
|
[
"Apache-2.0"
] |
permissive
|
tachyonbrush/hifi
|
3f75973e5fcc782b800b49bb31663eab90902dc7
|
8428b1a4ba355c4593a7ebff58ee1686b0069a9c
|
refs/heads/master
| 2021-01-16T18:02:10.823015
| 2014-09-12T00:53:55
| 2014-09-12T00:53:55
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 22,758
|
cpp
|
//
// EntityTests.h
// tests/octree/src
//
// Created by Brad Hefta-Gaub on 06/04/2014.
// Copyright 2014 High Fidelity, Inc.
//
// Distributed under the Apache License, Version 2.0.
// See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html
//
// TODO:
// * need to add expected results and accumulation of test success/failure
//
#include <QDebug>
#include <EntityItem.h>
#include <EntityTree.h>
#include <EntityTreeElement.h>
#include <Octree.h>
#include <OctreeConstants.h>
#include <PropertyFlags.h>
#include <SharedUtil.h>
//#include "EntityTests.h"
#include "ModelTests.h" // needs to be EntityTests.h soon
void EntityTests::entityTreeTests(bool verbose) {
bool extraVerbose = false;
int testsTaken = 0;
int testsPassed = 0;
int testsFailed = 0;
if (verbose) {
qDebug() << "******************************************************************************************";
}
qDebug() << "EntityTests::entityTreeTests()";
// Tree, id, and entity properties used in many tests below...
EntityTree tree;
QUuid id = QUuid::createUuid();
EntityItemID entityID(id);
entityID.isKnownID = false; // this is a temporary workaround to allow local tree entities to be added with known IDs
EntityItemProperties properties;
float oneMeter = 1.0f;
float halfMeter = oneMeter / 2.0f;
float halfOfDomain = TREE_SCALE * 0.5f;
glm::vec3 positionNearOriginInMeters(oneMeter, oneMeter, oneMeter); // when using properties, these are in meter not tree units
glm::vec3 positionAtCenterInMeters(halfOfDomain, halfOfDomain, halfOfDomain);
glm::vec3 positionNearOriginInTreeUnits = positionNearOriginInMeters / (float)TREE_SCALE;
glm::vec3 positionAtCenterInTreeUnits = positionAtCenterInMeters / (float)TREE_SCALE;
{
testsTaken++;
QString testName = "add entity to tree and search";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
properties.setPosition(positionAtCenterInMeters);
properties.setRadius(halfMeter);
//properties.setModelURL("https://s3-us-west-1.amazonaws.com/highfidelity-public/ozan/theater.fbx");
tree.addEntity(entityID, properties);
float targetRadius = oneMeter * 2.0 / (float)TREE_SCALE; // in tree units
const EntityItem* foundEntityByRadius = tree.findClosestEntity(positionAtCenterInTreeUnits, targetRadius);
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
AACube elementCube = containingElement ? containingElement->getAACube() : AACube();
if (verbose) {
qDebug() << "foundEntityByRadius=" << foundEntityByRadius;
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
qDebug() << "containingElement.box="
<< elementCube.getCorner().x * TREE_SCALE << ","
<< elementCube.getCorner().y * TREE_SCALE << ","
<< elementCube.getCorner().z * TREE_SCALE << ":"
<< elementCube.getScale() * TREE_SCALE;
qDebug() << "elementCube.getScale()=" << elementCube.getScale();
//containingElement->printDebugDetails("containingElement");
}
bool passed = foundEntityByRadius && foundEntityByID && (foundEntityByRadius == foundEntityByID);
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
}
entityID.isKnownID = true; // this is a temporary workaround to allow local tree entities to be added with known IDs
{
testsTaken++;
QString testName = "change position of entity in tree";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
glm::vec3 newPosition = positionNearOriginInMeters;
properties.setPosition(newPosition);
tree.updateEntity(entityID, properties);
float targetRadius = oneMeter * 2.0 / (float)TREE_SCALE; // in tree units
const EntityItem* foundEntityByRadius = tree.findClosestEntity(positionNearOriginInTreeUnits, targetRadius);
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
AACube elementCube = containingElement ? containingElement->getAACube() : AACube();
if (verbose) {
qDebug() << "foundEntityByRadius=" << foundEntityByRadius;
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
qDebug() << "containingElement.box="
<< elementCube.getCorner().x * TREE_SCALE << ","
<< elementCube.getCorner().y * TREE_SCALE << ","
<< elementCube.getCorner().z * TREE_SCALE << ":"
<< elementCube.getScale() * TREE_SCALE;
//containingElement->printDebugDetails("containingElement");
}
bool passed = foundEntityByRadius && foundEntityByID && (foundEntityByRadius == foundEntityByID);
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
}
{
testsTaken++;
QString testName = "change position of entity in tree back to center";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
glm::vec3 newPosition = positionAtCenterInMeters;
properties.setPosition(newPosition);
tree.updateEntity(entityID, properties);
float targetRadius = oneMeter * 2.0 / (float)TREE_SCALE; // in tree units
const EntityItem* foundEntityByRadius = tree.findClosestEntity(positionAtCenterInTreeUnits, targetRadius);
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
AACube elementCube = containingElement ? containingElement->getAACube() : AACube();
if (verbose) {
qDebug() << "foundEntityByRadius=" << foundEntityByRadius;
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
qDebug() << "containingElement.box="
<< elementCube.getCorner().x * TREE_SCALE << ","
<< elementCube.getCorner().y * TREE_SCALE << ","
<< elementCube.getCorner().z * TREE_SCALE << ":"
<< elementCube.getScale() * TREE_SCALE;
//containingElement->printDebugDetails("containingElement");
}
bool passed = foundEntityByRadius && foundEntityByID && (foundEntityByRadius == foundEntityByID);
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
}
{
testsTaken++;
const int TEST_ITERATIONS = 1000;
QString testName = "Performance - findClosestEntity() "+ QString::number(TEST_ITERATIONS) + " times";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
float targetRadius = oneMeter * 2.0 / (float)TREE_SCALE; // in tree units
quint64 start = usecTimestampNow();
const EntityItem* foundEntityByRadius = NULL;
for (int i = 0; i < TEST_ITERATIONS; i++) {
foundEntityByRadius = tree.findClosestEntity(positionAtCenterInTreeUnits, targetRadius);
}
quint64 end = usecTimestampNow();
if (verbose) {
qDebug() << "foundEntityByRadius=" << foundEntityByRadius;
}
bool passed = foundEntityByRadius;
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
float USECS_PER_MSECS = 1000.0f;
float elapsedInMSecs = (float)(end - start) / USECS_PER_MSECS;
qDebug() << "TIME - Test" << testsTaken <<":" << qPrintable(testName) << "elapsed=" << elapsedInMSecs << "msecs";
}
{
testsTaken++;
const int TEST_ITERATIONS = 1000;
QString testName = "Performance - findEntityByID() "+ QString::number(TEST_ITERATIONS) + " times";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
quint64 start = usecTimestampNow();
const EntityItem* foundEntityByID = NULL;
for (int i = 0; i < TEST_ITERATIONS; i++) {
// TODO: does this need to be updated??
foundEntityByID = tree.findEntityByEntityItemID(entityID);
}
quint64 end = usecTimestampNow();
if (verbose) {
qDebug() << "foundEntityByID=" << foundEntityByID;
}
bool passed = foundEntityByID;
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
float USECS_PER_MSECS = 1000.0f;
float elapsedInMSecs = (float)(end - start) / USECS_PER_MSECS;
qDebug() << "TIME - Test" << testsTaken <<":" << qPrintable(testName) << "elapsed=" << elapsedInMSecs << "msecs";
}
{
// seed the random number generator so that our tests are reproducible
srand(0xFEEDBEEF);
testsTaken++;
const int TEST_ITERATIONS = 1000;
QString testName = "Performance - add entity to tree " + QString::number(TEST_ITERATIONS) + " times";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
int iterationsPassed = 0;
quint64 totalElapsedAdd = 0;
quint64 totalElapsedFind = 0;
for (int i = 0; i < TEST_ITERATIONS; i++) {
QUuid id = QUuid::createUuid();// make sure it doesn't collide with previous entity ids
EntityItemID entityID(id);
entityID.isKnownID = false; // this is a temporary workaround to allow local tree entities to be added with known IDs
float randomX = randFloatInRange(1.0f ,(float)TREE_SCALE - 1.0f);
float randomY = randFloatInRange(1.0f ,(float)TREE_SCALE - 1.0f);
float randomZ = randFloatInRange(1.0f ,(float)TREE_SCALE - 1.0f);
glm::vec3 randomPositionInMeters(randomX,randomY,randomZ);
glm::vec3 randomPositionInTreeUnits = randomPositionInMeters / (float)TREE_SCALE;
properties.setPosition(randomPositionInMeters);
properties.setRadius(halfMeter);
//properties.setModelURL("https://s3-us-west-1.amazonaws.com/highfidelity-public/ozan/theater.fbx");
if (extraVerbose) {
qDebug() << "iteration:" << i
<< "ading entity at x/y/z=" << randomX << "," << randomY << "," << randomZ;
qDebug() << "before:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startAdd = usecTimestampNow();
tree.addEntity(entityID, properties);
quint64 endAdd = usecTimestampNow();
totalElapsedAdd += (endAdd - startAdd);
if (extraVerbose) {
qDebug() << "after:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startFind = usecTimestampNow();
float targetRadius = oneMeter * 2.0 / (float)TREE_SCALE; // in tree units
const EntityItem* foundEntityByRadius = tree.findClosestEntity(randomPositionInTreeUnits, targetRadius);
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
quint64 endFind = usecTimestampNow();
totalElapsedFind += (endFind - startFind);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
AACube elementCube = containingElement ? containingElement->getAACube() : AACube();
bool elementIsBestFit = containingElement->bestFitEntityBounds(foundEntityByID);
if (extraVerbose) {
qDebug() << "foundEntityByRadius=" << foundEntityByRadius;
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
qDebug() << "containingElement.box="
<< elementCube.getCorner().x * TREE_SCALE << ","
<< elementCube.getCorner().y * TREE_SCALE << ","
<< elementCube.getCorner().z * TREE_SCALE << ":"
<< elementCube.getScale() * TREE_SCALE;
qDebug() << "elementCube.getScale()=" << elementCube.getScale();
//containingElement->printDebugDetails("containingElement");
qDebug() << "elementIsBestFit=" << elementIsBestFit;
}
// Every 1000th test, show the size of the tree...
if (extraVerbose && (i % 1000 == 0)) {
qDebug() << "after test:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
bool passed = foundEntityByRadius && foundEntityByID && (foundEntityByRadius == foundEntityByID) && elementIsBestFit;
if (passed) {
iterationsPassed++;
} else {
if (extraVerbose) {
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName) << "iteration:" << i
<< "foundEntityByRadius=" << foundEntityByRadius << "foundEntityByID=" << foundEntityByID
<< "x/y/z=" << randomX << "," << randomY << "," << randomZ
<< "elementIsBestFit=" << elementIsBestFit;
}
}
}
if (extraVerbose) {
qDebug() << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
bool passed = iterationsPassed == TEST_ITERATIONS;
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
float USECS_PER_MSECS = 1000.0f;
float elapsedInMSecsAdd = (float)(totalElapsedAdd) / USECS_PER_MSECS;
float elapsedInMSecsFind = (float)(totalElapsedFind) / USECS_PER_MSECS;
qDebug() << "TIME - Test" << testsTaken <<":" << qPrintable(testName)
<< "elapsed Add=" << elapsedInMSecsAdd << "msecs"
<< "elapsed Find=" << elapsedInMSecsFind << "msecs";
}
{
testsTaken++;
const int TEST_ITERATIONS = 1000;
QString testName = "Performance - delete entity from tree " + QString::number(TEST_ITERATIONS) + " times";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
int iterationsPassed = 0;
quint64 totalElapsedDelete = 0;
quint64 totalElapsedFind = 0;
for (int i = 0; i < TEST_ITERATIONS; i++) {
QUuid id = QUuid::createUuid();// make sure it doesn't collide with previous entity ids
EntityItemID entityID(id);
entityID.isKnownID = true; // this is a temporary workaround to allow local tree entities to be added with known IDs
if (extraVerbose) {
qDebug() << "before:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startDelete = usecTimestampNow();
tree.deleteEntity(entityID);
quint64 endDelete = usecTimestampNow();
totalElapsedDelete += (endDelete - startDelete);
if (extraVerbose) {
qDebug() << "after:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startFind = usecTimestampNow();
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
quint64 endFind = usecTimestampNow();
totalElapsedFind += (endFind - startFind);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
if (extraVerbose) {
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
}
// Every 1000th test, show the size of the tree...
if (extraVerbose && (i % 1000 == 0)) {
qDebug() << "after test:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
bool passed = foundEntityByID == NULL && containingElement == NULL;
if (passed) {
iterationsPassed++;
} else {
if (extraVerbose) {
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName) << "iteration:" << i
<< "foundEntityByID=" << foundEntityByID
<< "containingElement=" << containingElement;
}
}
}
if (extraVerbose) {
qDebug() << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
bool passed = iterationsPassed == TEST_ITERATIONS;
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
float USECS_PER_MSECS = 1000.0f;
float elapsedInMSecsDelete = (float)(totalElapsedDelete) / USECS_PER_MSECS;
float elapsedInMSecsFind = (float)(totalElapsedFind) / USECS_PER_MSECS;
qDebug() << "TIME - Test" << testsTaken <<":" << qPrintable(testName)
<< "elapsed Delete=" << elapsedInMSecsDelete << "msecs"
<< "elapsed Find=" << elapsedInMSecsFind << "msecs";
}
{
testsTaken++;
const int TEST_ITERATIONS = 100;
const int ENTITIES_PER_ITERATION = 10;
QString testName = "Performance - delete " + QString::number(ENTITIES_PER_ITERATION)
+ " entities from tree " + QString::number(TEST_ITERATIONS) + " times";
if (verbose) {
qDebug() << "Test" << testsTaken <<":" << qPrintable(testName);
}
int iterationsPassed = 0;
quint64 totalElapsedDelete = 0;
quint64 totalElapsedFind = 0;
for (int i = 0; i < TEST_ITERATIONS; i++) {
QSet<EntityItemID> entitiesToDelete;
for (int j = 0; j < ENTITIES_PER_ITERATION; j++) {
//uint32_t id = 2 + (i * ENTITIES_PER_ITERATION) + j; // These are the entities we added above
QUuid id = QUuid::createUuid();// make sure it doesn't collide with previous entity ids
EntityItemID entityID(id);
entitiesToDelete << entityID;
}
if (extraVerbose) {
qDebug() << "before:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startDelete = usecTimestampNow();
tree.deleteEntities(entitiesToDelete);
quint64 endDelete = usecTimestampNow();
totalElapsedDelete += (endDelete - startDelete);
if (extraVerbose) {
qDebug() << "after:" << i << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
quint64 startFind = usecTimestampNow();
for (int j = 0; j < ENTITIES_PER_ITERATION; j++) {
//uint32_t id = 2 + (i * ENTITIES_PER_ITERATION) + j; // These are the entities we added above
QUuid id = QUuid::createUuid();// make sure it doesn't collide with previous entity ids
EntityItemID entityID(id);
const EntityItem* foundEntityByID = tree.findEntityByEntityItemID(entityID);
EntityTreeElement* containingElement = tree.getContainingElement(entityID);
if (extraVerbose) {
qDebug() << "foundEntityByID=" << foundEntityByID;
qDebug() << "containingElement=" << containingElement;
}
bool passed = foundEntityByID == NULL && containingElement == NULL;
if (passed) {
iterationsPassed++;
} else {
if (extraVerbose) {
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName) << "iteration:" << i
<< "foundEntityByID=" << foundEntityByID
<< "containingElement=" << containingElement;
}
}
}
quint64 endFind = usecTimestampNow();
totalElapsedFind += (endFind - startFind);
}
if (extraVerbose) {
qDebug() << "getOctreeElementsCount()=" << tree.getOctreeElementsCount();
}
bool passed = iterationsPassed == (TEST_ITERATIONS * ENTITIES_PER_ITERATION);
if (passed) {
testsPassed++;
} else {
testsFailed++;
qDebug() << "FAILED - Test" << testsTaken <<":" << qPrintable(testName);
}
float USECS_PER_MSECS = 1000.0f;
float elapsedInMSecsDelete = (float)(totalElapsedDelete) / USECS_PER_MSECS;
float elapsedInMSecsFind = (float)(totalElapsedFind) / USECS_PER_MSECS;
qDebug() << "TIME - Test" << testsTaken <<":" << qPrintable(testName)
<< "elapsed Delete=" << elapsedInMSecsDelete << "msecs"
<< "elapsed Find=" << elapsedInMSecsFind << "msecs";
}
qDebug() << " tests passed:" << testsPassed << "out of" << testsTaken;
if (verbose) {
qDebug() << "******************************************************************************************";
}
}
void EntityTests::runAllTests(bool verbose) {
entityTreeTests(verbose);
}
|
[
"bradh@konamoxt.com"
] |
bradh@konamoxt.com
|
beb1a69135066d939f53007ef668df869eb44a77
|
0d773b5491e0b2a5c02c1ff633b0b27c141e6481
|
/Native/ScannerDriver.h
|
e211b2b44e552b7e6642d91d59a18d8f7e7663b2
|
[
"Apache-2.0"
] |
permissive
|
pravets/AndroidScannerDriverFor1C
|
3528487bac407f80a3ed76e916c0d1b244b27bb5
|
5be1b714ed91ec7ef616ea4336e1a750c234a12f
|
refs/heads/master
| 2023-08-30T12:05:57.763427
| 2021-05-25T14:54:36
| 2021-05-25T14:54:36
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 120
|
h
|
#pragma once
class ScannerDriver
{
public:
const char * getPlatformABI();
ScannerDriver();
~ScannerDriver();
};
|
[
"p.tolkachev@hotmail.com"
] |
p.tolkachev@hotmail.com
|
b827d445176b7f82187eef7b310a94e45539c629
|
1373eaa72803b4425ca91cfd54d0708dafcb62e7
|
/LinkedBinaryTree/LinkedBinaryTree.cpp
|
7f31b8daf03cfa2772a31e47e9f67328c83697b2
|
[] |
no_license
|
aadeaina2014/BinaryTrees
|
0e35aaa83911f4fc3f904c3cd84a325600f564d8
|
87888f76702d1e5e078004c111bc3c7fc5efe8e4
|
refs/heads/master
| 2021-01-18T21:22:46.057883
| 2016-10-19T20:50:32
| 2016-10-19T20:50:32
| 55,170,071
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 2,296
|
cpp
|
/********************************************************************
Florida Institute of Technology
College of Engineering
Electrical and Computer Engineering Department
ECE 2552: Software Hardware Integration
FileName : LinkedBinaryTree.cpp
Code Author : Ayokunle Ade-Aina [aadeaina2014@my.fit.edu] (c)2016
********************************************************************/
#include "LinkedBinaryTree.h"
LinkedBinaryTree::LinkedBinaryTree() // constructor
: _root(NULL), n(0) { }
int LinkedBinaryTree::size() const // number of nodes
{
return n;
}
bool LinkedBinaryTree::empty() const // is tree empty?
{
return size() == 0;
}
LinkedBinaryTree::Position LinkedBinaryTree::root() const // get the root
{
return Position(_root);
}
void LinkedBinaryTree::addRoot() // add root to empty tree
{
_root = new Node; n = 1;
}
// list of all nodes
LinkedBinaryTree::PositionList LinkedBinaryTree::positions() const {
PositionList pl;
preorder(_root, pl); // preorder traversal
return PositionList(pl); // return resulting list
}
// preorder traversal
void LinkedBinaryTree::preorder(Node* v, PositionList& pl) const {
pl.push_back(Position(v)); // add this node
if (v->left != NULL) // traverse left subtree
preorder(v->left, pl);
if (v->right != NULL) // traverse right subtree
preorder(v->right, pl);
}
LinkedBinaryTree::Position // remove p and parent
LinkedBinaryTree::removeAboveExternal(const Position& p) {
Node* w = p.v; Node* v = w->par; // get p's node and parent
Node* sib = (w == v->left ? v->right : v->left);
if (v == _root) { // child of root?
_root = sib; // ...make sibling root
sib->par = NULL;
}
else {
Node* gpar = v->par; // w's grandparent
if (v == gpar->left) gpar->left = sib; // replace parent by sib
else gpar->right = sib;
sib->par = gpar;
}
delete w; delete v; // delete removed nodes
n -= 2; // two fewer nodes
return Position(sib);
}
// expand external node
void LinkedBinaryTree::expandExternal(const Position& p) {
Node* v = p.v; // p's node
v->left = new Node; // add a new left child
v->left->par = v; // v is its parent
v->right = new Node; // and a new right child
v->right->par = v; // v is its parent
n += 2; // two more nodes
}
|
[
"aadeaina2014@my.fit.edu"
] |
aadeaina2014@my.fit.edu
|
f2a0d6b25b117ae8281d61bbeb67efafb3e07c9c
|
45f7454de8cc4e5428ea16e77745ef32e0e4c8d8
|
/elements/standard/firewalltable.cc
|
fb16aeb0b783f4203e42d8c2d8181a94f9793197
|
[
"LicenseRef-scancode-click-license",
"W3C",
"MIT"
] |
permissive
|
hongdal/vNIDS_Ramcloud
|
376c80c899613091fe13d97570c83f2132ebdc45
|
583b55f84ab1ae9ff8c12b2d815d8b1b2afd6516
|
refs/heads/master
| 2020-04-11T05:03:35.863203
| 2018-12-11T04:49:03
| 2018-12-11T04:49:03
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 53,245
|
cc
|
#include <click/config.h>
#include <stdio.h>
#include <stdlib.h>
#include "firewalltable.hh"
CLICK_DECLS
#define UNUSED(expr) \
do \
{ \
(void)(expr); \
} while (0)
// comment this out when release.
#define FIREWALLTABLE_EVAL 1
//#define FIREWALLSTATE_EVAL 1
extern class firewalltable* g_ft;
const char* readable_state[8] = {
"CLOSE___",
"SYN_1___",
"SYN_2___",
"EST_____",
"FIN_1___",
"FIN_2___",
"CLOSE_W_",
"LAST_ACK"
};
/*******************************************************************/
// Definition of functions of ipchain.
//
int getChainSize(const struct ipchain* c)
{
return c->size;
}
struct entry* allocEntry()
{
entry *e = new entry();
if ( NULL == e ) {
fprintf(stderr, "[fetal] allocEntry: out of memory!\n");
fflush(stderr);
while (1);
}
e->delete_pre = NULL;
e->delete_next = NULL;
e->append_pre = NULL;
e->append_next = NULL;
e->connection = NULL;
e->d_a = 0;
e->seq = 0;
e->active_time = 0;
return e;
}
/**
* It's very dangerous to invoke this function
* When the first parameter, e1, is in the real
* firewall table.
*
* overwrite e1, with e2 directly and without any
* other initialization is dangerous.
*
* USE THIS FUNCTION AT YOUR OWN RISTK.
*
**/
bool copyEntry(struct entry* e1, const struct entry* e2)
{
if (!(e1 && e2))
return false;
e1->src_ip = e2->src_ip;
e1->src_ip_mask = e2->src_ip_mask;
e1->des_ip = e2->des_ip;
e1->des_ip_mask = e2->des_ip_mask;
e1->src_port_min = e2->src_port_min;
e1->src_port_max = e2->src_port_max;
e1->des_port_min = e2->des_port_min;
e1->des_port_max = e2->des_port_max;
e1->protocol = e2->protocol;
e1->action = e2->action;
return true;
}
struct ipchain* allocChain()
{
ipchain *c = new ipchain();
struct entry* head = allocEntry();
struct entry* tail = allocEntry();
head->pre = NULL;
head->next = tail;
tail->pre = head;
tail->next = NULL;
c->head = head;
c->tail = tail;
c->size = 0;
c->_delete_ = NULL;
c->_delete_size_ = 0;
c->_append_ = NULL;
c->_append_size_ = 0;
c->delete_refs = 0;
c->delete_seq = 0;
return c;
}
struct entry* getEntryByIndex(const struct ipchain* c, int index)
{
// improve: can make a bit optimization!
if (index > c->size - 1)
{
printf("ERROR: Index is out of bound");
return NULL;
}
struct entry *cur = c->head->next;
while(cur) {
if (index == 0)
return cur;
else{
cur = cur->next;
index--;
}
}
return NULL;
}
void printEntry(const struct entry* e)
{
printf("-------------------------------------------------------------\n");
printf("source ip : %u\n", ntohl(e->src_ip));
printf("source ip mask : %u\n", ntohl(e->src_ip_mask));
printf("destination ip : %u\n", ntohl(e->des_ip));
printf("destination ip mask: %u\n", ntohl(e->des_ip_mask));
printf("srouce port : %hu - %hu\n", e->src_port_min, e->src_port_max);
printf("destination port : %hu - %hu\n", e->des_port_min, e->des_port_max);
printf("protocol : %hhu\n", e->protocol);
printf("action : %d\n", int(e->action));
printf("-------------------------------------------------------------\n");
}
static bool addEntryAtTail(struct ipchain* c, struct entry* e)
{
if (!(c && e)) {
return false;
}
struct entry* tmp = c->tail->pre;
e->next = c->tail;
e->pre = tmp;
tmp->next = e;
c->tail->pre = e;
c->size++;
return true;
}
bool addEntryAtHead(struct ipchain* c, struct entry* e)
{
if (!(c && e))
return false;
struct entry* tmp = c->head->next;
e->next = tmp;
e->pre = c->head;
tmp->pre = e;
c->head->next = e;
c->size++;
return true;
}
bool delEntryByIndex(struct ipchain* c, int index)
{
if (!c)
return false;
if (index > c->size - 1)
{
printf("ERROR: Index is out of bound");
return false;
}
struct entry* tmp = getEntryByIndex(c, index);
tmp->pre->next = tmp->next;
tmp->next->pre = tmp->pre;
free(tmp);
c->size--;
return true;
}
void printChain(const struct ipchain* c) {
struct entry* en = c->head->next;
while(en->next) {
printEntry(en);
en = en->next;
}
}
inline struct entry* nextEntry(const struct ipchain* c, const struct entry* e){
UNUSED(c);
return e->next;
}
inline bool isEntryEqual(const struct ipchain* c, const struct entry* e1, const struct entry* e2){
UNUSED(c);
if (e1->src_ip == e2->src_ip &&
e1->src_ip_mask == e2->src_ip_mask &&
e1->des_ip == e2->des_ip &&
e1->des_ip_mask == e2->des_ip_mask &&
e1->src_port_min == e2->src_port_min &&
e1->src_port_max == e2->src_port_max &&
e1->des_port_min == e2->des_port_min &&
e1->des_port_max == e2->des_port_max &&
e1->protocol == e2->protocol &&
e1->action == e2->action)
return true;
else
return false;
}
/**
* This function receives three parameters.
*
* c : ipchain.
* e1 : rule entry that will be matched against.
* e2 : entry generated from a packet.
*
* e2 will be compared with e1. e1 is one of the rule entries that is in the given ipchain, c.
* If e2 can matche e1, then returns `true`, otherwise returns `false`.
*
* e1 can be a wildcard rule entry.
* e2 must be a specific rule entry, no wildcard is allowed for e2.
*
**/
inline bool isEntryMatch(const struct ipchain* c, const struct entry* e1, const struct entry* e2){
//check port
UNUSED(c);
if (e2->src_port_min < e1->src_port_min ||
e2->src_port_max > e1->src_port_max ||
e2->des_port_min < e1->des_port_min ||
e2->des_port_max > e1->des_port_max)
return false;
//check ip address is or not matched
if (ntohl(e2->des_ip) < ntohl(e1->des_ip) || (ntohl(e2->des_ip) > ntohl(e1->des_ip | e1->des_ip_mask)) ||
ntohl(e2->src_ip) < ntohl(e1->src_ip) || (ntohl(e2->src_ip) > ntohl(e1->src_ip | e1->src_ip_mask)))
return false;
// check protocol
if (e1->protocol != e2->protocol)
return false;
return true;
}
// for stateful firewall migration.
/**
* Add the given entry to _delete_, set delete_refs and _delete_size_ correspondingly
* return
* 0-fail,
* 1-successful.
* */
static int add_to_delete(struct ipchain* c, struct entry* e) {
e->delete_pre = NULL;
e->delete_next = c->_delete_;
if ( NULL != c->_delete_ ) {
c->_delete_->delete_pre = e;
}
c->_delete_ = e;
c->_delete_size_++;
// It's not TCP and it's currently active.
if ( 0x06 != e->protocol && NULL != e->connection ) {
c->delete_refs++;
}
e->d_a = 1;
c->delete_seq++;
e->seq = c->delete_seq;
return 1;
}
static inline uint32_t get_delete_size(const struct ipchain* c) {
return c->_delete_size_;
}
static inline uint16_t get_delete_seq(const struct ipchain* c) {
return c->delete_seq;
}
/**
* return
* NULL - not found.
* pointer to the entry - found.
***/
static struct entry* find_appended_entry_by_seq(struct ipchain* c, uint16_t seq) {
struct entry* ret = c->_append_;
if ( NULL != ret ) {
while ( NULL != ret->append_next ) {
// found it.
if ( seq == ret->seq ) {
return ret;
} else {
ret = ret->append_next;
}
}
if ( seq == ret->seq ) {
return ret;
}
}
return NULL;
}
/**
* Pop the head of the _delete_ link.
* And detach all pointer connections from ipchain.
*
* return:
* NULL-link is empty
* point to entry - successful.
* */
static struct entry* pop_from_delete(struct ipchain* c) {
struct entry* ret = NULL;
if ( c->_delete_size_ > 0 && NULL != c->_delete_) {
// pop from _delete_.
ret = c->_delete_;
c->_delete_ = ret->delete_next;
ret->delete_next = NULL;
ret->delete_pre = NULL;
if ( NULL != c->_delete_ ) {
c->_delete_->delete_pre = NULL;
}
c->_delete_size_--;
// pop from ipchain.
ret->pre->next = ret->next;
ret->next->pre = ret->pre;
c->size--;
ret->next = NULL;
ret->pre = NULL;
}
return ret;
}
/**
* Append the given entry at the head of _append_ link.
* Also, append the given entry at the end of ipchain.
*
* return
* 0 - fail.
* otherwise - successful.
**/
static int add_to_append(struct ipchain* c, struct entry* e) {
// append at the tail of c->_append_;
e->append_pre = NULL;
e->append_next = c->_append_;
if ( NULL != c->_append_ ) {
c->_append_->append_pre = e;
}
c->_append_ = e;
c->_append_size_++;
// append at the end of ipchain.
if ( addEntryAtTail(c, e) != false ) {
return 1;
} else {
return 0;
}
}
/*******************************************************************/
// Definition of class firewallstate.
//
firewallstate::firewallstate():
_free(NULL),
_use(NULL),
// Note, firewallstate should be initiated after firewalltable.
_fwt(g_ft),
_deleted_state_count(0),
_delete_(NULL),
_suspend_(NULL)
{
int index = 0;
struct state_entry* tmp;
while ( index < (int)init_state_size ) {
tmp = new state_entry();
tmp->sib_pre = NULL;
tmp->sib_next = NULL;
tmp->rule = NULL;
// append at the head of free link.
tmp->store_pre = NULL;
tmp->store_next = _free;
if ( NULL != _free ) {
_free->store_pre = tmp;
}
_free = tmp;
index++;
}
}
firewallstate::~firewallstate()
{
struct state_entry* tmp;
struct state_entry* kill;
tmp = _use;
while ( NULL != tmp ) {
kill = tmp;
tmp = tmp->store_next;
delete kill;
}
tmp = _free;
while ( NULL != tmp ) {
kill = tmp;
tmp = tmp->store_next;
delete kill;
}
}
/***
* This function add the given entry's all states to the _delete_
* link. Other properties of the states remain the same.
* Also, the ipt->delete_refs will be increased appropriately.
*
* return
* 0 - fail.
* 1 - successful.
***/
int
firewallstate::fs_add_state_to_delete(struct entry* e) {
if ( NULL != e->connection ) {
struct ipchain* c = _fwt->ft_get_ipt();
struct state_entry *last = e->connection;
// append all states to _delete_
while ( NULL != last ) {
last->seq = e->seq;
last->delete_pre = NULL;
last->delete_next = _delete_;
if ( NULL != _delete_ ) {
_delete_->delete_pre = last;
}
_delete_ = last;
_deleted_state_count++;
// update delete_refs
if ( 0 != last->active ) {
c->delete_refs++;
}
last = last->sib_next;
}
}
return 1;
}
/**
* Once the fwmanager receives a tagged packet, fwmanager may
* call this functions if the packet is TCP.
* This functions will update
* `delete_refs`
*
* return
* 0 - fail.
* 1 - successful.
***/
int
firewallstate::fs_update_state_by_tag(Packet* p) {
const struct click_ip *iph = p->ip_header();
const struct click_tcp *thd = p->tcp_header();
uint32_t src_ip = (uint32_t)(iph->ip_src.s_addr);
uint32_t dst_ip = (uint32_t)(iph->ip_dst.s_addr);
uint16_t src_port = ntohs(thd->th_sport);
uint16_t dst_port = ntohs(thd->th_dport);
struct state_entry* s;
s = _delete_;
while ( NULL != s ) {
if ( ((src_ip == s->src_ip)&&
(dst_ip == s->dst_ip)&&
(src_port == s->src_port)&&
(dst_port == s->dst_port)) ||
((src_ip == s->dst_ip)&&
(dst_ip == s->src_ip)&&
(src_port == s->src_port)&&
(dst_port == s->dst_port)) ||
((src_ip == s->src_ip)&&
(dst_ip == s->dst_ip)&&
(src_port == s->dst_port)&&
(dst_port == s->src_port)) ||
((src_ip == s->dst_ip)&&
(dst_ip == s->src_ip)&&
(src_port == s->dst_port)&&
(dst_port == s->src_port))
) {
// If the matched state is active, then turn it off
// and decrease delete_refs.
if ( 0 != s->active ) {
s->active = 0;
_fwt->ft_get_ipt()->delete_refs--;
return 1;
}
}
s = s->sib_next;
}
return 1;
}
/***
* This function returns the first state_entry from the _delete_ link.
* And set the pointers appropriately.
*
* return
* NULL - fail.
* pointer to state_entry - successful.
*
****/
struct state_entry*
firewallstate::fs_pop_from_deleted_state() {
struct state_entry* ret = _delete_;
// pop from _delete_ link.
if ( 0 == _deleted_state_count || NULL == _delete_ ) {
return NULL;
}
_delete_ = ret->sib_next;
ret->sib_next = NULL;
if ( NULL != _delete_ ) {
_delete_->sib_pre = NULL;
}
// pop from _use link.
if ( NULL != ret->store_pre ) {
ret->store_pre->store_next = ret->store_next;
} else {
_use = ret->store_next;
}
if ( NULL != ret->store_next ) {
ret->store_next->store_pre = ret->store_pre;
}
return ret;
}
int
firewallstate::initialize(ErrorHandler * errh) {
UNUSED(errh);
return 0;
}
int
firewallstate::fs_flush_timers() {
// update timers in each state entry and delete if necessarry.
struct state_entry* tmp;
struct state_entry* kill;
int ret = 1;
tmp = _use;
while ( NULL != tmp ) {
tmp->life_time--;
if ( static_cast<signed int>(tmp->life_time) <= 0 ) {
kill = tmp;
tmp = tmp->store_next;
kill->state = CLOSE;
ret = fs_delete_entry(kill);
#ifdef FIREWALLSTATE_EVAL
fs_print_state(kill, NULL, 2);
#endif
} else {
tmp = tmp->store_next;
}
}
return ret;
}
inline uint8_t
firewallstate::fs_get_flag_by_packet(Packet* p) const {
return static_cast<uint8_t>((p->tcp_header())->th_flags);
}
/***
* This function updates the state of a given state entry,
* according to the given packet, including life_time.
*
* If it's a valid, legitimate packet, then update the entry.
* However, if it fails to update the entry (e.g., due to lack
* of memory), then this function may return 0. In this failed
* case, the packet should be denied.
*
* If the given packet is not a legitimate or valid packet,
* this function will return 0. In this failed case, the packet
* should be denied.
*
* In summary, if this function returns 0, which means failure,
* then the caller should interpreter it as 'deny' this packet.
*
* Input:
* p : the packet to check against.
* s : the state entry to be updated.
*
***/
int
firewallstate::fs_update_state(Packet* p, struct state_entry* s) {
// get tcp header pointer.
const struct click_tcp* thd = p->tcp_header();
// look packet's flags.
uint8_t th_flags = thd->th_flags;
// return value. default as successful.
int ret = 1;
// mask should be: 00010111
uint8_t mask = (TH_FIN) | (TH_SYN) | (TH_ACK) | (TH_RST);
switch ( th_flags & mask ) {
// fin.
case 0x01: {
// check.
if ( s->state == ESTABLISHED ) {
s->fin1_ack = ntohl(thd->th_seq);
s->state = FIN_1;
s->life_time = tcp_expiration;
} else if ( s->state == FIN_1 ) {
s->fin2_ack = ntohl(thd->th_seq);
s->state = FIN_2;
s->life_time = tcp_expiration;
} else if ( s->state == CLOSING_WAIT ) {
s->fin2_ack = ntohl(thd->th_seq);
s->state = LAST_ACK;
s->life_time = syn_expiration;
} else {
// invalid fin.
ret = 0;
}
break;
}
// syn.
case 0x02: {
// check.
if ( s->state == CLOSE ) {
s->syn1_ack = ntohl(thd->th_seq);
s->state = SYN_1;
s->life_time = syn_expiration;
} else {
// invalid syn.
ret = 0;
}
break;
}
// ack.
case 0x10: {
// check.
if ( s->state == ESTABLISHED ) {
// pass this packet.
s->life_time = tcp_expiration;
} else if ( s->state == SYN_2 && (ntohl(thd->th_ack) == s->syn2_ack+1) ) {
s->state = ESTABLISHED;
s->life_time = tcp_expiration;
} else if ( s->state == FIN_1 ) {
// This ack is for the first FIN.
if ( ntohl(thd->th_ack) == s->fin1_ack+1 ) {
s->state = CLOSING_WAIT;
s->life_time = tcp_expiration;
}
} else if ( s->state == FIN_2 ) {
// This ack is for the second FIN.
if ( ntohl(thd->th_ack) == s->fin2_ack+1 ) {
s->state = LAST_ACK;
s->life_time = syn_expiration;
}
} else if ( s->state == LAST_ACK && (ntohl(thd->th_ack) == s->fin2_ack+1) ) {
s->state = CLOSE;
ret = fs_delete_entry(s);
} else {
// invalid ack.
ret = 0;
}
break;
}
// fin + ack
case 0x11: {
// check.
if ( s->state == ESTABLISHED ) {
s->fin1_ack = ntohl(thd->th_seq);
s->state = FIN_1;
s->life_time = tcp_expiration;
} else if ( s->state == FIN_1 ) {
// reply to the previous fin.
if ( ntohl(thd->th_ack) == s->syn1_ack+1 ) {
s->state = LAST_ACK;
s->life_time = syn_expiration;
// this ack reply to other data segments, not previous fin.
} else {
s->state = FIN_2;
s->life_time = tcp_expiration;
}
s->fin2_ack = ntohl(thd->th_seq);
// this case, ack must reply to a data segment.
} else if ( s->state == CLOSING_WAIT ) {
s->state = LAST_ACK;
s->fin2_ack = ntohl(thd->th_seq);
s->life_time = syn_expiration;
} else {
// invalid fin + ack.
ret = 0;
}
break;
}
// syn + ack
case 0x12: {
// check.
if ( s->state == SYN_1 && (ntohl(thd->th_ack) == s->syn1_ack+1)) {
s->syn2_ack = ntohl(thd->th_seq);
s->state = SYN_2;
s->life_time = syn_expiration;
} else {
// invalid syn+ack.
ret = 0;
}
break;
}
// rst (+ack)
case 0x14: case 0x04: {
// check.
s->state = CLOSE;
// should delete this node.
ret = fs_delete_entry(s);
// reset this connection.
break;
}
// None of the above.
default: {
// invalid tcp flag.
ret = 0;
}
}
//
// Here I print the latest state.
// Although, the state entry may have been 'deleted',
// the content is still valid.
// If it's in multi-core context, this should be adjusted appropriately.
//
#ifdef FIREWALLSTATE_EVAL
if ( ret > 0 ) {
fs_print_state(s, p, 0);
} else {
fs_print_state(s, p, 1);
}
#endif
return ret;
}
/**
* This function adds a new state entry.
* The new state entry is appended at the front of the link of
* a given firewall rule (specified by parameter rule).
*
* Only tcp syn packet can trigger this function.
*
* If it's not a valid syn, then fs_update_state(), which is called by this
* function, will return a failure. The failure will prevent the state
* entry from being appended to the 'use' link. Instead, the state entry will
* be appended back to the 'free' link.
*
* p : raw packet.
* e : entry that derives from p.
* rule: which rule introduce this state.
*
**/
int
firewallstate::fs_add_entry(Packet* p, struct entry* e, struct entry* rule) {
struct state_entry *tmp = NULL;
// If free is not empty, grab a node from 'free'
if ( NULL != _free ) {
tmp = _free;
_free = _free->store_next;
if ( NULL != _free ) {
_free->store_pre = NULL;
}
// free is empty.
} else {
tmp = new state_entry();
if ( NULL == tmp ) {
fprintf(stderr, "Could not allocate state entry: out of memory!\n");
fflush(stderr);
return 0;
}
}
// fill up new state node.
tmp->src_ip = e->src_ip;
tmp->dst_ip = e->des_ip;
tmp->src_port = e->src_port_min;
tmp->dst_port = e->des_port_min;
tmp->protocol = e->protocol;
// initial state is set to CLOSE
tmp->state = CLOSE;
// Try to update the state of this state entry.
int ret = fs_update_state(p, tmp);
// If updated successfully.
if ( 0 != ret ) {
// mark this state_entry as active.
tmp->active = 1;
#ifdef DEBUGTIMER_ACTIVE
_fwt->_ActiveTCP++;
#endif
// append to 'use'
tmp->store_pre = NULL;
tmp->store_next = _use;
if ( NULL != _use ) {
_use->store_pre = tmp;
}
_use = tmp;
// append to 'rule'
tmp->rule = rule;
tmp->sib_pre = NULL;
tmp->sib_next = rule->connection;
if ( NULL != rule->connection ) {
rule->connection->sib_pre = tmp;
}
rule->connection = tmp;
// if this rule is in '_delete_' link,
// add to _delete_, increase 'delete_refs'.
if ( 1 == rule->d_a ) {
tmp->delete_pre = NULL;
tmp->delete_next = _delete_;
if ( NULL != _delete_ ) {
_delete_->delete_pre = tmp;
}
_delete_ = tmp;
_deleted_state_count++;
_fwt->ft_get_ipt()->delete_refs++;
}
// Otherwise, append it back to 'free'
} else {
tmp->active = 0;
// append it to 'free' link.
tmp->rule = NULL;
tmp->sib_pre = NULL;
tmp->sib_next = NULL;
tmp->store_pre = NULL;
tmp->store_next = _free;
tmp->delete_pre = NULL;
tmp->delete_next = NULL;
if ( NULL != _free ) {
_free->store_pre = tmp;
}
_free = tmp;
}
return ret;
}
/**
* Delete a given state entry.
* Delete from 'use' link and append to the head of 'free' link.
*
* This function can be called by:
* 'fs_update_state'. fs_update_state can delete a state entry
* due to the closure/reset of a connection.
*
* s : state entry to be deleted.
*
* */
int
firewallstate::fs_delete_entry(struct state_entry* s) {
// This node is not in use or an error may occur to this node,
// It's illegal that a state entry is associated to none of the rules.
if ( NULL == s->rule ) {
return 0;
}
// if it's the first node. update rule->connection.
if ( NULL == s->sib_pre ) {
s->rule->connection = s->sib_next;
// else it's not first node. update its previous node.
} else {
s->sib_pre->sib_next = s->sib_next;
}
// if it's not the last node. update its next node.
if ( NULL != s->sib_next ) {
s->sib_next->sib_pre = s->sib_pre;
}
// garuantee it move clear from rule links.
s->sib_pre = s->sib_next = NULL;
// if it's the first one, the update _use.
if ( NULL == s->store_pre ) {
_use = s->store_next;
// else it's not the first one. update its previous node.
} else {
s->store_pre->store_next = s->store_next;
}
// if it's not the last one, update its next node.
if ( NULL != s->store_next ) {
s->store_next->store_pre = s->store_pre;
}
// If the related TCP rule is in '_delete_' link.
// decrease delete_refs by 1.
if ( 1 == s->rule->d_a ) {
// remove from _delete_
if ( NULL != s->delete_pre ) {
s->delete_pre->delete_next = s->delete_next;
} else {
_delete_ = s->delete_next;
}
if ( NULL != s->delete_next ) {
s->delete_next->delete_pre = s->delete_pre;
}
s->delete_next = s->delete_pre = NULL;
_deleted_state_count--;
if ( 0 != s->active ) {
_fwt->ft_get_ipt()->delete_refs--;
}
}
s->rule = NULL;
// append it to 'free' link.
s->store_pre = NULL;
s->store_next = _free;
if ( NULL != _free ) {
_free->store_pre = s;
}
_free = s;
#ifdef DEBUGTIMER_ACTIVE
_fwt->_ActiveTCP--;
#endif
return 1;
}
/**
* Clear all states in _use link.
*
* This functions uncondictinally delete all states.
*
*
* return
* 0 - if any one fails.
* 1 - successful.
***/
int
firewallstate::fs_clear_states() {
int ret = 1;
struct state_entry* tmp = _use;
while ( NULL != tmp ) {
ret &= fs_delete_entry(tmp);
tmp = _use;
}
return ret;
}
/**
* This function checks whether there is a state entry that
* matches the given packet.
* If the state entry exists, then return a pointer to that entry.
* Otherwise, return NULL.
*
***/
struct state_entry*
firewallstate::fs_check_entry(Packet* p) const {
const struct click_ip *iph = p->ip_header();
const struct click_tcp *thd = p->tcp_header();
uint32_t src_ip = (uint32_t)(iph->ip_src.s_addr);
uint32_t dst_ip = (uint32_t)(iph->ip_dst.s_addr);
uint16_t src_port = (uint16_t)ntohs(thd->th_sport);
uint16_t dst_port = (uint16_t)ntohs(thd->th_dport);
struct state_entry* s;
s = _use;
while ( NULL != s ) {
#if 1
if ( ((src_ip == s->src_ip)&&
(dst_ip == s->dst_ip)&&
(src_port == s->src_port)&&
(dst_port == s->dst_port)) ||
((src_ip == s->dst_ip)&&
(dst_ip == s->src_ip)&&
(src_port == s->src_port)&&
(dst_port == s->dst_port)) ||
((src_ip == s->src_ip)&&
(dst_ip == s->dst_ip)&&
(src_port == s->dst_port)&&
(dst_port == s->src_port)) ||
((src_ip == s->dst_ip)&&
(dst_ip == s->src_ip)&&
(src_port == s->dst_port)&&
(dst_port == s->src_port))
) {
// found it.
return s;
}
#endif
#if 0
if ( src_ip == s->src_ip ) {
if ( dst_ip == s->dst_ip ) {
if ( src_port == s->src_port ) {
if ( dst_port == s->dst_port ) {
// found;
return s;
}
} else if ( dst_port == s->src_port ) {
if ( src_port == s-> dst_port ) {
// found;
return s;
}
}
}
} else if ( dst_ip == s->src_ip ) {
if ( src_ip == s->dst_ip ) {
if ( src_port == s->src_port ) {
if ( dst_port == s->dst_port ) {
// found;
return s;
}
} else if ( dst_port == s->src_port ) {
if ( src_port == s-> dst_port ) {
// found;
return s;
}
}
}
}
#endif
s = s->store_next;
}
return NULL;
}
struct entry*
firewalltable::ft_find_appended_entry_by_seq(uint16_t seq) {
return find_appended_entry_by_seq(ipt, seq);
}
/**
* return:
* 0 - fail.
* 1 - successful.
****/
int
firewallstate::fs_suspend_state(struct state_entry* state) {
// grab a chunk of memory
struct state_entry* s;
if ( NULL != _free ) {
s = _free;
_free = _free->store_next;
} else {
s = (struct state_entry*)(CLICK_LALLOC(sizeof(struct state_entry)));
}
// fill up the memory. -- costly.
memcpy(s, state, sizeof(struct state_entry));
s->store_next = s->store_pre = NULL;
// append to _suspend_.
if ( NULL == _suspend_ ) {
state->suspend_pre = NULL;
state->suspend_next = NULL;
_suspend_ = state;
return 1;
}
struct state_entry* tmp = _suspend_;
while ( NULL != tmp->suspend_next ) {
// suspend in ascending order.
if ( s->seq > tmp->seq ) {
tmp = tmp->suspend_next;
} else {
s->suspend_next = tmp;
s->suspend_pre = tmp->suspend_pre;
if ( NULL != tmp->suspend_pre ) {
tmp->suspend_pre->suspend_next = s;
}
tmp->suspend_pre = s;
return 1;
}
}
if ( s->seq > tmp->seq ) {
s->suspend_pre = tmp;
s->suspend_next = tmp->suspend_next;
tmp->suspend_next = s;
return 1;
} else {
s->suspend_next = tmp;
s->suspend_pre = tmp->suspend_pre;
if ( NULL != tmp->suspend_pre ) {
tmp->suspend_pre->suspend_next = s;
}
tmp->suspend_pre = s;
return 1;
}
}
/**
* This function will attach the suspended states
* to the given entry.
* Those states have the same seq with the given entry.
*
* return
* 0 - fail.
* 1 - successful.
*
****/
int
firewallstate::fs_attach_suspend_states(struct entry* e) {
if ( NULL == _suspend_ ) {
return 1;
}
struct state_entry* state = _suspend_;
while ( NULL != state ) {
if ( e->seq < state->seq ) {
state = state->suspend_next;
} else if ( state->seq == e->seq ) {
// append state to e->connection
state->sib_next = e->connection;
if ( NULL != e->connection ) {
e->connection->sib_pre = state;
}
state->sib_pre = NULL;
e->connection = state;
// append state to _use.
state->store_next = _use;
if ( NULL != _use ) {
_use->store_pre = state;
}
state->store_pre = NULL;
_use = state;
// teardown from _suspend_.
if ( NULL != state->suspend_pre ) {
state->suspend_pre->suspend_next = state->suspend_next;
}
if ( NULL != state->suspend_next ) {
state->suspend_next->suspend_pre = state->suspend_pre;
}
// set to active.
state->active = 0x01;
state->seq = 0;
// move to the next
state = state->suspend_next;
} else {
return 1;
}
}
return 1;
}
/**
* This function attach the given state_entry to the given entry.
* And set: 1) storage management, and 2) state management appropriately.
* After calling this function, the state_entry is ready.
* That is to say, the state_entry is ready to work, if there is traffic
* coming.
*
* e : given entry that the state_entry will be attached to.
* s : given state_entry that will attach to the given entry.
*
* return
* 0 - fail.
* 1 - successful.
***/
int
firewallstate::fs_attach_state(struct entry* e, struct state_entry* s) {
struct state_entry *tmp = NULL;
// can grab from _free?
if ( NULL != _free ) {
tmp = _free;
_free = _free->store_next;
if ( NULL != _free ) {
_free->store_pre = NULL;
}
// can't grab from _free, allocate it yourself.
} else {
tmp = new state_entry();
if ( NULL == tmp ) {
fprintf(stderr, "Could not allocate state entry: out of memory!\n");
fflush(stderr);
while (1);
}
}
// fill up new state node.
memcpy(tmp, s, sizeof(state_entry));
// append to _use. storage management.
tmp->store_pre = NULL;
tmp->store_next = _use;
if ( NULL != _use ) {
_use->store_pre = tmp;
}
_use = tmp;
// append to 'e', state management.
tmp->rule = e;
tmp->sib_pre = NULL;
tmp->sib_next = e->connection;
if ( NULL != e->connection ) {
e->connection->sib_pre = tmp;
}
// set to active.
tmp->active = 0x01;
tmp->seq = 0;
return 1;
}
/**
* This function prints out the given state entry.
* The main purpose of this function is for debugging.
* When the traffic rate is high, the output of this print function
* might make little sense.
* --------------------------------------------------------------
* When employ this function in debugging, it is recommended to
* make the traffic rate low enough, e.g., 10 packets per second.
* --------------------------------------------------------------
*
* s : pointer to the given state entry that will be printed.
* p : pointer to the given packet that might potentially just trigger
* an update of state.
* purpose : 0 - update failure, 1 - update success, 2 - none purpose.
*
* The format of the print looks like:
*
* 192.168.1.1:1024 - 192.168.1.2:80 [SYN_1___] (s) [120+0]:[-] [-s--]
* 192.168.1.2:80 - 192.168.1.1:1024 [SYN_2___] (s) [200+0]:[121] [-sa-]
* 192.168.1.1:1024 - 192.168.1.2:80 [EST_____] (s) [121+1024]:[201] [--a-]
* 192.168.1.1:1024 - 192.168.1.2:80 [FIN_1___] (s) [1146+10]:[201] [--af]
*
* 192.168.1.2:80 - 192.168.1.1:1024 [CLOSE_W_] (s) [201+0]:[1157] [--a-]
* 192.168.1.2:80 - 192.168.1.1:1024 [LAST_ACK] (s) [202+0]:[1157] [--af]
* 192.168.1.1:1024 - 192.168.1.1:80 [CLOSE___] (s) [1157+0]:[203] [--a-]
*
* Characters in the parentheses can be one of the following:
* s, f or -.
* (s) represents this packet's has successfully updated the state
* entry's state. purpose=0.
* (f) represents this packet's has failed to update the state entry's state.
* purpose=1.
* (-) represents no packet trigger this print, it's called by other reasons.
* purpose=2.
*
* The first column indicates the packet's source ip.
* The second column indicates whether it's a packet. (since this function may be
* called by other reasons other than packet's trigger.)
* The third column indicates the packet's destination ip.
* The fourth column indicates the state after the packet's update.
* The fith column indicates whether this packet successully update.
* The sixth column indicates [seq+len]:[ack_seq]
* The seventh column indicates flags of the pacekts: [reset, syn, ack, fin]
*
*
* Note, for other reasons other than a packet's trigger, the second column
* could be '+', which means the addresses are not a real packet's. Instead,
* those ip/port addresses are observed from the state entry record.
* If the second column indicates '-', then the addresses come from a real
* packet that trigger an update which then calls this print function to print out
* the latest state.
*
* If Pakcket is NULL, then the sixth and seventh column will not present.
*
***/
void
firewallstate::fs_print_state(const struct state_entry* s,
Packet *p = NULL,
uint8_t purpose = 2 ) const
{
uint32_t src_ip;
uint32_t dst_ip;
uint16_t src_port;
uint16_t dst_port;
// Called by other reason.
if ( NULL == p ) {
src_ip = static_cast<uint32_t>(ntohl(s->src_ip));
dst_ip = static_cast<uint32_t>(ntohl(s->dst_ip));
src_port = s->src_port;
dst_port = s->dst_port;
printf("%hhu.%hhu.%hhu.%hhu:%hu + %hhu.%hhu.%hhu.%hhu:%hu [%s] (-)\n",
static_cast<uint8_t>((src_ip>>24) & 0x0ff),
static_cast<uint8_t>((src_ip>>16) & 0x0ff),
static_cast<uint8_t>((src_ip>> 8) & 0x0ff),
static_cast<uint8_t>(src_ip & 0x0ff), src_port,
static_cast<uint8_t>((dst_ip>>24) & 0x0ff),
static_cast<uint8_t>((dst_ip>>16) & 0x0ff),
static_cast<uint8_t>((dst_ip>> 8) & 0x0ff),
static_cast<uint8_t>(dst_ip & 0x0ff), dst_port,
readable_state[static_cast<int>(s->state)]
);
} else {
const struct click_ip *iph = p->ip_header();
const struct click_tcp *thd = p->tcp_header();
src_ip = static_cast<uint32_t>(ntohl(iph->ip_src.s_addr));
dst_ip = static_cast<uint32_t>(ntohl(iph->ip_dst.s_addr));
src_port = static_cast<uint16_t>(ntohs(thd->th_sport));
dst_port = static_cast<uint16_t>(ntohs(thd->th_dport));
uint32_t seq = static_cast<uint32_t>(ntohl(thd->th_seq));
uint32_t ack = static_cast<uint32_t>(ntohl(thd->th_ack));
printf("%hhu.%hhu.%hhu.%hhu:%hu - %hhu.%hhu.%hhu.%hhu:%hu [%s] (%s) <%u>:<%u>\n",
static_cast<uint8_t>((src_ip>>24) & 0x0ff),
static_cast<uint8_t>((src_ip>>16) & 0x0ff),
static_cast<uint8_t>((src_ip>> 8) & 0x0ff),
static_cast<uint8_t>(src_ip & 0x0ff), src_port,
static_cast<uint8_t>((dst_ip>>24) & 0x0ff),
static_cast<uint8_t>((dst_ip>>16) & 0x0ff),
static_cast<uint8_t>((dst_ip>> 8) & 0x0ff),
static_cast<uint8_t>(dst_ip & 0x0ff), dst_port,
readable_state[static_cast<int>(s->state)],
(0 == purpose) ? ("s") : (1==purpose ? "f" : "-"),
seq, ack);
}
}
/*******************************************************************/
// Definition of class firewalltable.
//
firewalltable::firewalltable():
_DebugID(0),_PassTCP(0), _PassUDP(0), _PassOther(0),
_DropTCP(0), _DropUDP(0),_DropOther(0), _ActiveTCP(0), _ActiveUDP(0),
ipt(allocChain())
{
if ( NULL == ipt ) {
fprintf(stderr, "[fetal] firewalltable: initialization failed! (ipt==NULL)\n");
fflush(stderr);
while(1);
}
// Note, firewallstate is not initiated here.
fws = NULL;
}
firewalltable::~firewalltable()
{
struct entry* tmp = ipt->head->next;
while(tmp){
free(tmp->pre);
tmp = tmp->next;
}
free(ipt->tail);
free(ipt);
}
bool
firewalltable::ft_append_entry(struct entry* e_in)
{
if ( NULL != e_in )
{
struct entry* e = allocEntry();
if (!copyEntry(e, e_in)) {
return false;
}
return addEntryAtTail(ipt, e);
}
else
{
printf("ERROR: Entry is NULL!");
return false;
}
}
bool
firewalltable::ft_replace_entry(struct entry* e_in, int index)
{
if (!e_in)
return false;
if (index > ipt->size - 1)
{
printf("ERROR: Index is out of bound");
return false;
}
struct entry* e = allocEntry();
if (!copyEntry(e, e_in))
return false;
struct entry* tmp = getEntryByIndex(ipt, index);
e->pre = tmp->pre;
e->next = tmp->next;
e->pre->next = e;
e->next->pre = e;
free(tmp);
return true;
}
bool
firewalltable::ft_insert_entry(struct entry* e_in, int index)
{
if (!e_in)
return false;
if (index > ipt->size - 1)
{
printf("ERROR: Index is out of bound");
return false;
}
struct entry* e = allocEntry();
if (!copyEntry(e, e_in))
return false;
struct entry* tmp = getEntryByIndex(ipt, index);
e->pre = tmp->pre;
e->next = tmp;
tmp->pre = e;
e->pre->next = e;
ipt->size++;
return true;
}
/***
* This function receives an entry.
* ft_delete_entry() first search against the rule table to find
* an exactly same rule with the given entry.
*
* `exactly same` means IP addresses, PORTs, protocol and action are
* all identical.
*
* Then ft_delete_entry() deletes the rule from the rule table
* Finally, ft_delete_entry() free the memory.
*
***/
bool
firewalltable::ft_delete_entry(struct entry* e)
{
struct entry* tmp = ipt->head->next;
while(tmp->next)
{
if (isEntryEqual(ipt, e, tmp))
{
tmp->pre->next = tmp->next;
tmp->next->pre = tmp->pre;
free(tmp);
ipt->size--;
return true;
}
tmp = tmp->next;
}
return false;
}
/**
* This functions is similar to ft_match_entry(), except that
* ft_check_entry() returns a boolean value indicating whether
* the given entry matches a particular rule in the rule table.
*
* ft_match_entry() returns an action (ALLOW/DENY) when the given
* entry matches a particular rule in the rule table.
* If the given entry does not match any of the rules in the rule table,
* then ft_match_entry() will return DENY.
*
***/
bool
firewalltable::ft_check_entry(struct entry* e)
{
struct entry* tmp = ipt->head->next;
while(tmp->next)
{
if (isEntryMatch(ipt, tmp, e))
return true;
tmp = tmp->next;
}
return false;
}
/***
* This function matches a given entry against the firewall rules.
* It's for stateless firewall.
*
* The input is an entry pointer.
* This given entry is made from packet that is going to be tested whether to dropped or not.
*
* This function invoke "isEntryMatch()", which consider wildcard matching.
* That is to say, the given entry may not exactly matches a particular rule in the
* firewall table. But the given entry may hit a rule with wildcard.
*
***/
enum action
firewalltable::ft_match_entry(struct entry* e)
{
enum action ret = DROP;
struct entry* tmp = ipt->head->next;
while(tmp->next)
{
if (isEntryMatch(ipt, tmp, e)) {
// If it's ICMP/UDP, then set it to active.
if ( 1 == tmp->protocol || 17 == tmp->protocol ) {
tmp->connection = (struct state_entry*)(0x01);
tmp->active_time = rule_active_time;
}
return tmp->action;
}
tmp = tmp->next;
}
return ret;
}
/***
* This function matches a given entry against the firewall rules.
* It's for stateful firewall.
***/
enum action
firewalltable::ft_match_entry(struct entry* e, Packet* p)
{
uint8_t flags = fws->fs_get_flag_by_packet(p);
// If it does not contain ONLY syn, then drop it.
if ( (0x00 == (TH_SYN & flags)) || (0x00 != (~(TH_SYN) & flags)) ) {
return DROP;
}
// Otherwise, might seek to add a new entry.
enum action ret = DROP;
int result = 0;
struct entry* tmp = ipt->head->next;
while(tmp->next)
{
// Hit a match in the rule table.
if ( isEntryMatch(ipt, tmp, e) ) {
// If this packet is accpeted.
if ( DROP != tmp->action ) {
// craete a new state entry.
result = fws->fs_add_entry(p, e, tmp);
// If it fails to crate a new state entry.
if ( 0 == result ) {
return DROP;
// Otherwise return whatever action except DROP.
} else {
return tmp->action;
}
// Otherwise, not accpeted.
} else {
return DROP;
}
}
tmp = tmp->next;
}
// If no hit, then return DROP.
return ret;
}
/**
* This functions clears all the rules and states.
* First clear all states.
* Then clear all rules.
***/
int
firewalltable::ft_clear()
{
int ret = 1;
// clear all states
ret &= fws->fs_clear_states();
if ( 0 == ret ) {
fprintf(stderr, "[error] firewalltable: Could not clear states.\n");
fflush(stderr);
return 0;
}
ret &= ft_clear_rules();
if ( 0 == ret ) {
fprintf(stderr, "[error] firewalltable: Could not clear rules\n");
fflush(stderr);
return 0;
}
ipt->delete_refs = 0;
ipt->_delete_ = NULL;
ipt->_append_ = NULL;
ipt->_delete_size_ = 0;
ipt->_append_size_ = 0;
ipt->delete_seq = 0;
return 1;
}
int
firewalltable::ft_clear_rules() {
// then clear all rules.
struct entry* tmp;
while(ipt->head->next != ipt->tail){
tmp = ipt->head->next;
ipt->head->next = tmp->next;
tmp->next->pre = ipt->head;
free(tmp);
}
ipt->size = 0;
return 1;
}
void
firewalltable::ft_print ()
{
printChain(ipt);
}
// stateful firewall migration.
int
firewalltable::ft_add_to_delete(struct entry* victim) {
return add_to_delete(ipt, victim);
}
/**
* This function will finally update `delete_refs`
*
* return
* 0 - fail.
* 1 - successful.
**/
int
firewalltable::ft_update_state_by_tag(Packet* p) {
return fws->fs_update_state_by_tag(p);
}
/**
* This function will finally update `delete_refs`
*
* return
* 0 - fail.
* 1 - successful.
**/
int
firewalltable::ft_update_rule_by_tag(Packet* p) {
const struct click_ip *iph = p->ip_header();
const uint8_t* pdata = NULL;
struct entry te;
te.src_ip = (uint32_t)(iph->ip_src.s_addr);
te.des_ip = (uint32_t)(iph->ip_dst.s_addr);
te.src_ip_mask = 0xffffffff;
te.des_ip_mask = 0xffffffff;
te.protocol = (uint8_t)(iph->ip_p);
switch ( te.protocol ) {
/* ICMP or Pacer */
case 1 : case 252: {
te.src_port_min = 0;
te.src_port_max = 0;
te.des_port_min = 0;
te.des_port_max = 0;
break;
}
/* UDP */
case 17: {
pdata = (uint8_t*)((uint8_t*)iph + (iph->ip_hl << 2));
te.src_port_min = ntohs(*(uint16_t*)pdata);
te.src_port_max = te.src_port_min;
te.des_port_min = ntohs(*(uint16_t*)(pdata+2));
te.des_port_max = te.des_port_min;
break;
}
/* Other packets */
default: {
fprintf(stderr, "protocol: %d\n", te.protocol);
//fprintf(stderr, "[warn] firewalltable: unexpected TCP!\n");
fflush(stderr);
return 1;
}
}
/* ICMP, UDP */
if ( 1 == te.protocol || 17 == te.protocol ) {
struct entry* tmp = ipt->_delete_;
if ( NULL == tmp ) {
#ifdef FIREWALLTABLE_EVAL
//fprintf(stderr, "[warn] firewalltable: _delete_ is empty while receiving tagged pacekt.\n");
//fflush(stderr);
#endif
return 1;
}
while ( NULL != tmp ) {
// found it.
if ( isEntryMatch(ipt, tmp, &te) ) {
// it's active.
if ( NULL != tmp->connection ) {
// set it to inactive.
tmp->connection = NULL;
tmp->active_time = 0;
ipt->delete_refs--;
}
return 1;
}
tmp = tmp->delete_next;
}
#ifdef FIREWALLTABLE_EVAL
//fprintf(stderr, "[warn] firewalltable: Found tagged packet but not in`delete` link\n");
//fflush(stderr);
#endif
/* Pacer */
} else if ( 252 == te.protocol ) {
// Set all delete_refs to zero. So, fwmanager::fw_enforce_delete
// will be called immediately after current functions returns.
struct entry* tmp = ipt->_delete_;
if ( NULL != tmp ) {
ipt->delete_refs = 0;
}
}
return 1;
}
/**
* return the point of the entry that matches the
* given entry.
* Use "isEntryEqual" to search. That is:
* (IP, PORTs, protocol, action)
* must be identical.
*
* tmp->d_a: if this entry is in _delete_, then tmp->d_a = 1;
* if this entry is in _append_, then tmp->d_a = 2;
* otherwise, tmp->d_a = 0;
*
* d_a : flag for searching.
* 0 - normal search. ignore entry's d_a field.
* 1 - search for the first one whose d_a is not set as 1.
* 2 - search for the first one whose d_a is not set as 2.
* other value - work like 0.
* return :
* returns the reference of te pointer.
* NULL, if there is no matched.
* */
struct entry*
firewalltable::ft_return_entry(const struct entry* e, uint8_t d_a = 0) {
struct entry* tmp = ipt->head->next;
while( tmp->next ) {
if ( isEntryEqual(ipt, tmp, e) ) {
if ( 0 == d_a || d_a != tmp->d_a ) {
return tmp;
}
}
tmp = tmp->next;
}
return NULL;
}
uint32_t
firewalltable::ft_get_delete_size() {
return get_delete_size(ipt);
}
struct entry*
firewalltable::ft_pop_from_delete() {
return pop_from_delete(ipt);
}
struct state_entry*
firewalltable::ft_pop_from_deleted_state() {
return fws->fs_pop_from_deleted_state();
}
int
firewalltable::ft_add_to_append(struct entry* e_in) {
if ( NULL != e_in ) {
struct entry* e = allocEntry();
e->src_ip = e_in->src_ip;
e->src_ip_mask = e_in->src_ip_mask;
e->des_ip = e_in->des_ip;
e->des_ip_mask = e_in->des_ip_mask;
e->src_port_min = e_in->src_port_min;
e->src_port_max = e_in->src_port_max;
e->des_port_min = e_in->des_port_min;
e->des_port_max = e_in->des_port_max;
e->protocol = e_in->protocol;
e->action = e_in->action;
e->seq = e_in->seq;
//e->connection = NULL;
e->d_a = 2;
// check whether there exists matching states.
fws->fs_attach_suspend_states(e);
return add_to_append(ipt, e);
} else {
fprintf(stderr, "[error] firewalltable: entry is NULL!\n");
fflush(stderr);
return 0;
}
}
int
firewalltable::ft_add_state_to_delete(struct entry* e) {
return fws->fs_add_state_to_delete(e);
}
/***
* This function finds the appropriate entry from the given 'append' link.
* Then call functions to append the state_entry to the entry that was found.
*
* return
* 0 - fail.
* 1 - successful.
***/
int
firewalltable::ft_attach_state(struct entry* e, struct state_entry* s) {
if ( NULL == e || NULL == s ) {
return 0;
}
struct entry* tmp = e;
while ( NULL != tmp ) {
// found it.
if ( tmp->seq == s->seq ) {
return fws->fs_attach_state(tmp, s);
} else {
tmp = tmp->append_next;
}
}
return 0;
}
/**
* States that cannot match any rules will be suspended until
* the expected rule arrives.
* return
* 0 - fail.
* 1 - successful.
***/
int
firewalltable::ft_suspend_state(struct state_entry* s) {
int ret = fws->fs_suspend_state(s);
return ret;
}
/**
* return
* 0 - fail.
* 1 - successful.
**/
int
firewalltable::ft_enforce_append() {
struct entry* append = ipt->_append_;
struct entry* last = append;
if ( NULL == append ) {
fprintf(stderr, "[warn] firewalltable: _append_ is empty when enforce append.\n");
fflush(stderr);
}
while ( NULL != last ) {
append = last->append_next;
last->append_next = NULL;
last->append_pre = NULL;
last->d_a = 0;
last->seq = 0;
last = append;
}
ipt->_append_ = NULL;
ipt->_append_size_ = 0;
return 1;
}
int
firewalltable::initialize(ErrorHandler *errh) {
UNUSED(errh);
return 0;
}
void
firewalltable::ft_flush_state_timers() {
if ( NULL != fws ) {
fws->fs_flush_timers();
}
}
void
firewalltable::ft_flush_timers() {
struct entry* tmp = ipt->head->next;
while ( NULL != tmp->next ) {
// not TCP rule.
if ( 6 != tmp->protocol ) {
if ( tmp->active_time > 0 ) {
tmp->active_time--;
// If this rule gets timeout.
if ( 0 == tmp->active_time ) {
// This rule is in _delete_ link.
if ( 1 == tmp->d_a ) {
tmp->connection = NULL;
ipt->delete_refs--;
}
}
}
}
tmp = tmp->next;
}
}
// Will be called by the element, DebugTimer periodically.
// Print any statistics here.
void
firewalltable::ft_print_debug() {
fprintf(stdout, "ID, #ActiveTCP, #ActiveUDP, #PassTCP, #PassUDP, #DropTCP, #DropUDP\n");
fprintf(stdout, "%u,%u,%u,%u,%u,%u,%u\n",
_DebugID, _ActiveTCP, _ActiveUDP, _PassTCP, _PassUDP, _DropTCP, _DropUDP);
}
// this function will be called whenever CLEARANCE of debug info is required.
void
firewalltable::ft_clear_debug() {
_DebugID = _ActiveTCP = _ActiveUDP = _PassTCP = _PassUDP =
_PassOther =_DropTCP = _DropUDP = _DropOther = 0;
}
CLICK_ENDDECLS
EXPORT_ELEMENT(firewalltable)
ELEMENT_MT_SAFE(firewalltable)
|
[
"guozetang@gmail.com"
] |
guozetang@gmail.com
|
2b077b41ac734acc8bc5d394a5d17dca00b5c54a
|
200613ed3a6e1328bb40f77759fa656c0a874c77
|
/src/App/Classes/Game/TongBiNiuNiu/GameSceneUI/GameRoleNode.cpp
|
b9b041402eecc38a4f02fb73ef9c00f605e50d43
|
[] |
no_license
|
iuvei/ChessGameApp
|
eb57164a8a8e41490a5ee70dda8fc323028a8db6
|
a8765f4f90954cc6281a98b7f243be0afc50689c
|
refs/heads/master
| 2020-04-19T19:30:38.562729
| 2018-01-06T16:52:49
| 2018-01-06T16:52:49
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 10,609
|
cpp
|
#include "GameRoleNode.h"
#include "../../CustomUtilsSrc/AnimationMgr/AnimationMgr.h"
USING_NS_CC;
using namespace ui;
USING_TBNN_NAMESPACE;
GameRoleNode::GameRoleNode():
m_pHead(nullptr),
m_notify(nullptr),
m_clipNickName(nullptr)
{
auto scaleTo = ScaleTo::create(0.1f,1.0f);
auto show = Show::create();
m_actTip = Spawn::create(scaleTo,show,nullptr);
m_actTip->retain();
}
GameRoleNode::~GameRoleNode()
{
CC_SAFE_RELEASE(m_actTip);
CC_SAFE_RELEASE(m_actScore);
}
bool GameRoleNode::init()
{
bool bRes = false;
do
{
CC_BREAK_IF(!Node::init());
LOAD_CSB("game/GameRoleItem.csb");
m_spHeadBg = static_cast<Sprite*>(m_root->getChildByName("head_bg"));
CC_ASSERT(m_spHeadBg != nullptr);
/*
m_textName = static_cast<Text*>(m_root->getChildByName("name_text"));
CC_ASSERT(m_textName != nullptr);*/
m_clipNickName = ClipText::createClipText(Size(100, 20), "", "Arial",14);
CC_ASSERT(m_clipNickName != nullptr);
m_clipNickName->setTextColor(Color4B::YELLOW);
m_clipNickName->setTextAnchorPoint(Vec2(0, 0));
m_clipNickName->setPosition(Vec2(21, 40));
m_spHeadBg->addChild(m_clipNickName);
m_textCoin = static_cast<Text*>(m_spHeadBg->getChildByName("coin_text"));
CC_ASSERT(m_textCoin != nullptr);
m_spBanker = static_cast<Sprite*>(m_root->getChildByName("banker"));
CC_ASSERT( m_spBanker != nullptr);
m_spOpenCard = static_cast<Sprite*>(m_root->getChildByName("opencard"));
CC_ASSERT( m_spOpenCard != nullptr);
m_spChatBg = static_cast<ImageView*>(m_root->getChildByName("chat_bg"));
CC_ASSERT(m_spChatBg != nullptr);
m_spBrow = static_cast<Sprite*>(m_spChatBg->getChildByName("chat_face"));
CC_ASSERT(m_spBrow != nullptr);
m_labChat = Label::createWithSystemFont("", "Arial", 20,Size(150,0));
m_labChat->setPosition(m_spChatBg->getContentSize().width * 0.5, m_spChatBg->getContentSize().height * 0.6);
m_labChat->setVerticalAlignment(TextVAlignment::CENTER);
m_spChatBg->addChild(m_labChat);
m_atlasScore = static_cast<TextAtlas*>(m_root->getChildByName("score_atlas"));
CC_ASSERT(nullptr != m_atlasScore);
m_atlasScore->setString("");
//m_atlasScore->setScale(2.0f);
m_atlasScore->setLocalZOrder(1);
auto fadein = FadeIn::create(0.2f);
auto moveUp = MoveBy::create(0.5f, Vec2(0, 20.0f));
auto fadeOut = FadeOut::create(0.2f);
m_actScore = Sequence::create(Spawn::create(fadein,moveUp, NULL), DelayTime::create(2.0f),fadeOut, NULL);
m_actScore->retain();
this->reSet();
bRes = true;
} while (false);
return bRes;
}
void GameRoleNode::onEnterTransitionDidFinish()
{
Node::onEnterTransitionDidFinish();
m_listener = EventListenerTouchOneByOne::create();
m_listener->setSwallowTouches(false);
m_listener->onTouchBegan = [this](Touch *pTouch,Event *event)
{
Vec2 pos = pTouch->getLocation();
pos = m_spHeadBg->convertToNodeSpace(pos);
Rect rect = Rect(0,0,m_spHeadBg->getContentSize().width,m_spHeadBg->getContentSize().height);
m_beginInTouch = rect.containsPoint(pos);
return this->isVisible();
};
m_listener->onTouchEnded = [this](Touch *pTouch, Event *event)
{
Vec2 pos = pTouch->getLocation();
pos = m_spHeadBg->convertToNodeSpace(pos);
Rect rect = Rect(0,0,m_spHeadBg->getContentSize().width,m_spHeadBg->getContentSize().height);
if (m_beginInTouch && rect.containsPoint(pos))
{
if (m_notify)
{
m_notify->uiMsg(UI_MSG_BASE::UI_MSG_GAME, GAME_UI::ROLE_INFO, &m_dwUserId, sizeof(DWORD));
}
}
};
_eventDispatcher->addEventListenerWithSceneGraphPriority(m_listener, this);
}
void GameRoleNode::onExit()
{
_eventDispatcher->removeEventListener(m_listener);
Node::onExit();
}
void GameRoleNode::reSet(bool bShowSelf /*= true*/)
{
this->setVisible(bShowSelf);
this->switchToBanker(false);
this->switchToOpenCard(false);
m_spChatBg->setVisible(false);
m_atlasScore->setPositionY(-35);
m_atlasScore->setOpacity(0);
m_atlasScore->setString("");
}
void GameRoleNode::updateRoleInfo(const DWORD &nRoleId,const char *szName, const SCORE &lCoin,bool bLeave /*= false*/)
{
m_dwUserId = nRoleId;
//更新头像文件
UserData *pUser = HallDataMgr::getInstance()->m_UserList.at(nRoleId);
if (nullptr == m_pHead)
{
m_pHead = HeaderRequest::createwithFaceID(
pUser->m_date.wFaceID,
pUser->m_date.dwCustomID,
pUser->m_date.dwUserID,
pUser->m_date.cbGender);
m_pHead->setPosition(0.0f,30.0f);
m_root->addChild(m_pHead);
}
else
{
/*
auto ptexture = HallDataMgr::getInstance()->m_Headlist.at(nRoleId);
if (ptexture)
{
m_pHead->setTexture(ptexture);
m_pHead->setTextureRect(cocos2d::Rect(0, 0, FACE_CX, FACE_CY));
}
*/
if (0 != pUser->m_date.dwCustomID)
{
auto ptexture = HallDataMgr::getInstance()->m_Headlist.at(nRoleId);
if (ptexture)
{
m_pHead->setTexture(ptexture);
m_pHead->setTextureRect(cocos2d::Rect(0, 0, FACE_CX, FACE_CY));
}
}
else
{
auto faceID = pUser->m_date.wFaceID%10;
std::string headstr = 1 == pUser->m_date.cbGender? "man" : "woman";
headstr = __String::createWithFormat("public_res/im_head_%s_%d.png", headstr.c_str(), faceID)->getCString();
m_pHead->initWithFile(headstr);
}
}
m_pHead->setHeadSize(89);
/*
if (pUser->m_date.cbUserStatus == US_FREE || pUser->m_date.cbUserStatus == US_SIT)
{
//更新名字
m_clipNickName->setString(szName);
}
*/
//更新名字
m_clipNickName->setString(szName);
char buf[64] = "";
//更新元宝
sprintf(buf,"%lld",lCoin);
m_textCoin->setString(buf);
this->setVisible(!bLeave);
}
void GameRoleNode::switchToBanker(bool bBanker)
{
m_spBanker->setVisible(bBanker);
m_spBanker->setLocalZOrder(1);
}
void GameRoleNode::switchToOpenCard(bool bOpenCard,const enGameRoleDir &dir /*= kMY_ROLE*/)
{
/*if (kMY_ROLE == dir)
{
m_spOpenCard->setPosition(Vec2(105, -50));
}
else
{
m_spOpenCard->setPosition(Vec2(0, -110));
}*/
m_spOpenCard->setVisible(bOpenCard);
}
void GameRoleNode::textChat(const enGameChairIndex &dir, const char *str)
{
m_spBrow->setVisible(false);
//调整位置
changeChatPos(dir);
m_labChat->setString(str);
m_labChat->setVisible(true);
//调整九宫格尺寸
Size labSize = m_labChat->getContentSize();
if (labSize.height >= 45)
{
m_spChatBg->setContentSize(Size(168, labSize.height + 15));
}
else
{
m_spChatBg->setContentSize(Size(168, 45));
}
m_labChat->setPosition(m_spChatBg->getContentSize().width * 0.5, m_spChatBg->getContentSize().height * 0.55);
}
void GameRoleNode::browChat(const enGameChairIndex &dir, const int &idx)
{
m_labChat->setVisible(false);
m_spChatBg->setContentSize(Size(168, 45));
//调整位置
changeChatPos(dir);
char buf[12] = "";
//索引加一
int tmp = idx;
if (10 > tmp)
{
sprintf(buf, "e0%d.png",tmp);
}
else
{
sprintf(buf, "e%d.png",tmp);
}
SpriteFrame *pFrame = SpriteFrameCache::getInstance()->getSpriteFrameByName(buf);
if (nullptr == pFrame)
{
return;
}
m_spBrow->setSpriteFrame(pFrame);
m_spBrow->setVisible(true);
}
void GameRoleNode::changeChatPos(const enGameChairIndex &dir)
{
if (tbnn_kGameChair1 == dir
|| tbnn_kGameChair2 == dir
|| tbnn_kGameChair3 == dir)
{
m_spChatBg->setAnchorPoint(Vec2(1.0f,0.5f));
m_spChatBg->loadTexture("game_chat_1.9.png",Widget::TextureResType::PLIST);
m_spChatBg->setPosition(Vec2(-80,67));
}
else
{
m_spChatBg->setAnchorPoint(Vec2(0.0f,0.5f));
m_spChatBg->loadTexture("game_chat_0.9.png",Widget::TextureResType::PLIST);
m_spChatBg->setPosition(Vec2(80,67));
}
m_spChatBg->stopAction(m_actTip);
m_spChatBg->runAction(m_actTip);
this->schedule(SEL_SCHEDULE(&GameRoleNode::chatTipUpdater), 2.0f);
}
void GameRoleNode::refreshScore(LONGLONG llscore)
{
std::string buf = formatScore(llscore);
char szscore[64] = "";
if (llscore > 0)
{
sprintf(szscore, "/%lld",llscore);
buf = "+" + buf;
m_atlasScore->setProperty(szscore, "game/addnum.png", 19, 23, "/");
}
else if (llscore < 0)
{
sprintf(szscore, "/%lld",-llscore);
buf = "-" + buf;
m_atlasScore->setProperty(szscore, "game/subnum.png", 19, 23, "/");
}
m_atlasScore->stopAction(m_actScore);
m_atlasScore->runAction(m_actScore);
}
void GameRoleNode::showCaiJinAnimation()
{
auto sp = Sprite::createWithSpriteFrameName("blank.png");
m_root->addChild(sp);
sp->setPosition(0, 0);
tagAnimationParam param = tagAnimationParam();
param.m_fDelay = 0.1f;
param.m_strName = tbnn_CAIJIN_ANIMATION;
auto animate = AnimationMgr::getInstance()->getAnimate(param);
sp->runAction(animate);
}
void GameRoleNode::chatTipUpdater(float dt)
{
this->unschedule(SEL_SCHEDULE(&GameRoleNode::chatTipUpdater));
m_spChatBg->setVisible(false);
}
std::string GameRoleNode::formatScore( LONGLONG llscore)
{
//处理下注数量
char buf[64];
LONGLONG score = llscore > 0 ? llscore : -llscore;
float fScore = 0.0f;
if (score / 100000000 > 99)
{
fScore = score / 100000000.0f;
sprintf(buf,"%lld 亿",(LONGLONG)fScore);
}
else if (score > 100000000)
{
fScore = score / 100000000.0f;
sprintf(buf,"%.2f 亿",fScore);
}
else if (score > 1000000)
{
fScore = score / 10000;
sprintf(buf,"%d 万",(int)fScore);
}
else if (score > 10000)
{
fScore = score / 10000.0f;
sprintf(buf,"%.2f 万",fScore);
}
else
{
sprintf(buf,"%lld",score);
}
return std::string(buf);
}
|
[
"liuyeying1103@163.com"
] |
liuyeying1103@163.com
|
2ba287e53b5ad6bb04d96d41e541fa19327ee10a
|
ff5d91e9eee4dd41e85d418120f11daec71cf93b
|
/2018/nazionali/caduta/sol/ottima_buggata3.cpp
|
bc45e5d1cdac46c44014e9a0867de504add1c508
|
[] |
no_license
|
olimpiadi-informatica/oii
|
d0023c5fa00100cadc6a13b1e153fca0017177ca
|
ce6bc7e8b40a32c01611f4b20ee72f8a9318eafd
|
refs/heads/master
| 2021-05-16T02:35:15.742339
| 2020-03-14T21:56:18
| 2020-03-14T21:56:18
| 28,759,072
| 31
| 6
| null | 2019-12-15T12:37:53
| 2015-01-04T00:55:52
|
C++
|
UTF-8
|
C++
| false
| false
| 9,461
|
cpp
|
#include <algorithm>
#include <vector>
#include <assert.h>
#include <stdio.h>
typedef enum {
OK,
RISOLTO,
IMPOSSIBILE
} stato_t;
typedef struct {
int domino1;
int domino2;
} coppia_t;
stato_t correggi(int N, int altezze[], coppia_t* scambio) {
for (int i=0; i<N; i++) {
altezze[i] = altezze[i]-1;
if (altezze[i] > N) altezze[i] = N;
}
// Calcola fin dove cadono le tessere se si parte da un certo punto.
// Complessità O(N).
std::vector<int> fall_until(N);
fall_until[N-1] = altezze[N-1] + N;
for (int i=N-1; i>-1; i--) {
if (altezze[i] == 0) {
fall_until[i] = i;
continue;
}
int j = i+1;
while (j <= i+altezze[i] && j < N) {
if (j != fall_until[j]) {
j = fall_until[j];
} else if (j < i+altezze[i]) {
j++;
} else break;
}
fall_until[i] = j;
}
if (fall_until[0] >= N-1) return OK;
// Calcolo di varie informazioni ausiliari.
// Ultima tessera che cade partendo dall'inizio.
int last_first_segment = fall_until[0];
// Prima tessera possibile da cui partire perchè cada tutto da lì in fondo.
int first_last_segment = N-1;
for (int i=N-1; i>-1; i--) {
if (fall_until[i] >= N-1) {
first_last_segment = i;
}
}
assert(last_first_segment < first_last_segment);
// Tessera subito dopo la tessera i da cui partire perchè cada tutto da
// quella tessera fino alla fine di quel segmento. È utile (e calcolato)
// solo per il primo e l'ultimo segmento.
std::vector<int> next_start(N, N-1);
int next_to_reach = N-1;
for (int i=N-1; i>first_last_segment; i--) {
next_start[i] = next_to_reach;
if (fall_until[i] >= N-1) {
next_to_reach = i;
}
}
next_to_reach = last_first_segment;
for (int i=last_first_segment; i>-1; i--) {
next_start[i] = next_to_reach;
if (fall_until[i] >= last_first_segment) {
next_to_reach = i;
}
}
// Fin dove cadrebbero le tessere nell'ultimo segmento se assumo che da i
// in poi abbiano tutte quante altezza 0 e che si parta dalla prima
// tessera di ogni segmento. È utile solo per il primo e l'ultimo segmento.
std::vector<int> last_fall(N, 0);
int endpoint = 0;
for (int i=0; i<N; i++) {
last_fall[i] = endpoint;
if (i+altezze[i]>endpoint) endpoint = i+altezze[i];
}
// Primo tentativo: cerco una tessera nell'ultimo segmento che sia
// abbastanza alta per poter essere messa nel primo segmento e raggiungere
// start_last_segment, ovvero
// last_first_segment + altezze[i] >= first_last_segment
// e che inoltre sia tale che, anche se fosse sostituita con una tessera
// di altezza 0, arriverei comunque a far cadere next_start[i], quindi
// last_fall[i] >= next_start[i]
// Se trovo una tessera che soddisfa entrambe le caratteristiche, mi basta
// scambiarla con last_first_segment.
//
// Un'altra possibilità analoga è se esiste un domino abbastanza alto per
// coprire dalla fine del primo all'inizio dell'ultimo segmento, tale che
// mettere un domino alto 0 al suo posto non rompe il primo segmento. Ovvero,
// vale che
// last_first_segment + altezze[i] >= first_last_segment
// e che
// last_fall[i] >= next_start[i]
// come nel caso di uno scambio primo <--> ultimo segmento.
for (int i=0; i<N; i++) {
// Solo nel primo e nell'ultimo segmento
if (i > last_first_segment && i < first_last_segment) continue;
if (last_first_segment + altezze[i] < first_last_segment) continue;
if (last_fall[i] < next_start[i]) continue;
scambio->domino1 = last_first_segment;
scambio->domino2 = i;
return RISOLTO;
}
// Secondo tentativo: cerco una tessera nell'ultimo segmento che sia
// abbastanza alta per poter essere messa nel primo segmento e raggiungere
// next_start[i], ovvero per cui valga
// last_first_segment + altezze[i] >= next_start[i]
// Questo tentativo funziona chiaramente solo per uno scambio con l'ultimo
// segmento, visto che una tessera messa dopo non può far cadere tessere
// che la precedono.
for (int i=first_last_segment; i<N; i++) {
if (last_first_segment + altezze[i] < next_start[i]) continue;
scambio->domino1 = last_first_segment;
scambio->domino2 = i;
return RISOLTO;
}
// Terzo tentativo: se non sono in nessuna di queste situazioni, mi serve
// una tessera i dall'ultimo segmento e una tessera j dal primo segmento
// tali che
// j+altezze[i] >= first_last_segment
// e che
// i+altezze[j] >= next_start[i]
// ovvero tali che dal primo segmento si arrivi all'ultimo e che l'ultimo
// segmento non rimanga spezzato in due. Dato i, i candidati per j sono
// compresi nel segmento
// [first_last_segment-altezze[i], last_first_segment]
// e posso scegliere j come la tessera di massima altezza in
// quell'intervallo. A quel punto rimane solo da verificare la seconda
// condizione. Per fare tutto ciò, processo le tessere dell'ultimo
// segmento in ordine crescente di altezza.
//
// Alternativamente, potrebbe essere sufficiente portare avanti una tessera
// del primo segmento in modo da arrivare a coprire fino all'ultimo segmento
// ma contemporaneamente da non spezzare il primo segmento: le condizioni
// necessarie sono le stesse.
std::vector<int> candidates;
for (int i=first_last_segment; i<N; i++) candidates.push_back(i);
for (int i=0; i<last_first_segment; i++) candidates.push_back(i);
// TODO: sostituire con un radix/counting/... sort, se è più veloce.
std::sort(candidates.begin(), candidates.end(), [&] (const int& a, const int& b) {
return altezze[a] < altezze[b] || (altezze[a] == altezze[b] && a < b);
});
// Poichè altezze[last_first_segment] = 0, finchè il candidato non migliora
// sappiamo che non avremo risposta, o altrimenti la avremmo avuta nei
// tentativi precedenti.
int best_j_candidate = last_first_segment;
int last_tested_j_candidate = last_first_segment;
for (auto i: candidates) {
for (int jc = last_tested_j_candidate; jc >= first_last_segment-altezze[i]; jc--) {
last_tested_j_candidate = jc;
if (altezze[jc] > altezze[best_j_candidate])
best_j_candidate = jc;
}
if (best_j_candidate == last_first_segment) continue;
if (i+altezze[best_j_candidate] < next_start[i]) continue;
scambio->domino1 = best_j_candidate;
scambio->domino2 = i;
return RISOLTO;
}
// Quarto caso: se sto portando avanti una tessera del primo segmento,
// potrei ritrovarmi con la tessera portata indietro che non arriva a
// coprire fino a next_start, ma fino a una tessera che riesce comunque a
// far cadere la tessera portata in avanti che poi fa cadere fino a
// next_start.
//
// i + altezze[j] >= j
candidates.clear();
for (int i=0; i<last_first_segment; i++) candidates.push_back(i);
// TODO: sostituire con un radix/counting/... sort, se è più veloce.
std::sort(candidates.begin(), candidates.end(), [&] (const int& a, const int& b) {
return altezze[a] < altezze[b] || (altezze[a] == altezze[b] && a < b);
});
best_j_candidate = last_first_segment;
last_tested_j_candidate = last_first_segment;
for (auto i: candidates) {
for (int jc = last_tested_j_candidate; jc >= first_last_segment-altezze[i]; jc--) {
last_tested_j_candidate = jc;
if (altezze[jc] - jc > altezze[best_j_candidate] - best_j_candidate)
best_j_candidate = jc;
}
if (best_j_candidate == last_first_segment) continue;
if (i+altezze[best_j_candidate] < best_j_candidate) continue;
scambio->domino1 = best_j_candidate;
scambio->domino2 = i;
return RISOLTO;
}
// Nessun altro scambio è possibile: chiaramente il primo dei due domini
// deve appartenere al primo segmento (altrimenti non si arriva mai al
// secondo segmento). Scambiare internamente al primo segmento è già stato
// considerato, scambiare con l'ultimo anche. In entrambi i casi è
// necessario che il domino messo nel primo segmento arrivi a coprire fino
// all'inizio dell'ultimo, e che lo scambio non spezzi l'altro segmento.
// Questo può avvenire solo se la tessera rimossa era inutile per chiudere
// il segmento, se la tessera che l'ha sostituita è comunque abbastanza
// alta o se la tessera che arriva all'inizio dell'ultimo segmento ripara
// il gap che si viene a creare, da cui i tre casi considerati sopra.
// Uno scambio tra una tessera del primo segmento e un qualsiasi altro
// segmento che non sia nè il primo nè l'ultimo richiede che entrambi i
// domini arrivino a coprire più avanti di dove arrivavano prima, ovvero
// che
// altezze[i] + j > altezze[j] + j
// altezze[j] + i > altezze[i] + i
// che però è chiaramente impossibile.
// Se nessuno scambio funziona, il problema è impossibile
return IMPOSSIBILE;
}
|
[
"williamdiluigi@gmail.com"
] |
williamdiluigi@gmail.com
|
555e6e114618b00fe3e8c3ff63ed9de770e8bc5a
|
b98f6ff030075bfcd185a3908f440342849c3195
|
/Path_Sum_II.cpp
|
58de68fbcea7a1e5411263b67a359a9d79662b43
|
[] |
no_license
|
youlingman/leetcode
|
1b72d1d824fa077d13efda631f7080888ec5df65
|
05d192332d41485ea00f833c3f7fe214f1f18cd7
|
refs/heads/master
| 2021-01-01T18:11:23.420713
| 2014-08-22T14:18:47
| 2014-08-22T14:18:47
| null | 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,281
|
cpp
|
/* Path Sum II
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
return
[
[5,4,11,2],
[5,8,4,5]
]
*/
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > ans;
vector<int> path;
pathSum(root, sum, ans, path);
return ans;
}
private:
void pathSum(TreeNode *root, int sum, vector<vector<int> > &ans, vector<int> &path) {
if(root == NULL) return;
path.push_back(root->val);
// reach a leaf node
if(root->left == NULL && root->right == NULL) {
if(sum == root->val)
ans.push_back(path);
path.pop_back();
return;
}
pathSum(root->left, sum - root->val, ans, path);
pathSum(root->right, sum - root->val, ans, path);
path.pop_back();
}
};
|
[
"chenyoucyl@gmail.com"
] |
chenyoucyl@gmail.com
|
9f3ac646b5e6848ce028a9f2cfb93f1d5d6bebbd
|
d34f94a4740256901edfb2ee2325505ca834ba30
|
/C++/skola/rabbit.cpp
|
f33f9a4e1e609041b8f4dfea0722160bc6b7b177
|
[] |
no_license
|
dimitarkole/CPlusPlusTasks
|
706a15e533e657a91fe5c7d0ccee2cc129a2ac5f
|
8b3adf02ab359babdc36b73085a83fb9055b0716
|
refs/heads/master
| 2020-12-04T23:07:48.601834
| 2020-01-05T14:25:05
| 2020-01-05T14:25:05
| 231,928,854
| 1
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 294
|
cpp
|
#include<iostream>
using namespace std;
int main()
{
int a;
for(int i=1;i<=3;i++)
{
cin>>a;
if(a==1)cout<<"("<<(char)92<<"_"<<"/"<<")"<<endl;
else if(a==2)cout<<"("<<"o"<<"."<<"o"<<")"<<endl;
else if(a==3)cout<<"("<<"_"<<"."<<"_"<<")"<<endl;
}
}
|
[
"dim_kolev2002@abv.bg"
] |
dim_kolev2002@abv.bg
|
fcf08d456dee4e6c03fe586fa653758a29cc3ea3
|
465bc0b9904bd8ba029444c699f33aa55e0f4192
|
/Übung_7_1/Übung_7_1.cpp
|
d9297a39de30f9c1c2ba8dd7063765fe57ddec77
|
[] |
no_license
|
xJasminxu/-bungen-Programmieren-1
|
da0f4cfe26c745aefb6534da62aed24386a6fee3
|
1aa308a0c7b062357bfec265d56ce6c057eea1a8
|
refs/heads/master
| 2023-02-01T03:52:36.873795
| 2020-12-17T23:27:07
| 2020-12-17T23:27:07
| 322,436,611
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 468
|
cpp
|
// Übung_7_1.cpp : Diese Datei enthält die Funktion "main". Hier beginnt und endet die Ausführung des Programms.
//
#include <iostream>
#include "Rechner.h"
using namespace statistik;
int main()
{
int einarray[10] = { 1, 1, 3, 3, 3, 5, 5, 7, 8, 9};
Rechner rechne = Rechner();
rechne.setarray(10, einarray);
std::cout << "Modalwert = " << rechne.Modalwert() << std::endl;
std::cout << "Geometrischer Mittelwert = " << rechne.Mittelwert() << std::endl;
}
|
[
"xujasmin@gmx.de"
] |
xujasmin@gmx.de
|
78aca62aa4b0b7a2e915b94b25017f6b1e068ec2
|
d7ff1908ab98cd2fe1fe1c80bb47c841d82abd1e
|
/TestCarDatabase/CvvImage.cpp
|
3aa75c91ff0d68b05f46c4f14872e8b654694038
|
[] |
no_license
|
Aliang-SEU/Face-Recognition-with-Single-Training-Sample
|
af8bf86277be63ee32068fe6e2fef7e0884a840f
|
b8deea3fac93fe784936afe3bdb2d84c74e75135
|
refs/heads/master
| 2020-03-11T12:19:30.681111
| 2018-08-22T01:42:30
| 2018-08-22T01:42:30
| 129,994,239
| 4
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,281
|
cpp
|
#include "StdAfx.h"
#include "CvvImage.h"
//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////
CV_INLINE RECT NormalizeRect( RECT r );
CV_INLINE RECT NormalizeRect( RECT r )
{
int t;
if( r.left > r.right )
{
t = r.left;
r.left = r.right;
r.right = t;
}
if( r.top > r.bottom )
{
t = r.top;
r.top = r.bottom;
r.bottom = t;
}
return r;
}
CV_INLINE CvRect RectToCvRect( RECT sr );
CV_INLINE CvRect RectToCvRect( RECT sr )
{
sr = NormalizeRect( sr );
return cvRect( sr.left, sr.top, sr.right - sr.left, sr.bottom - sr.top );
}
CV_INLINE RECT CvRectToRect( CvRect sr );
CV_INLINE RECT CvRectToRect( CvRect sr )
{
RECT dr;
dr.left = sr.x;
dr.top = sr.y;
dr.right = sr.x + sr.width;
dr.bottom = sr.y + sr.height;
return dr;
}
CV_INLINE IplROI RectToROI( RECT r );
CV_INLINE IplROI RectToROI( RECT r )
{
IplROI roi;
r = NormalizeRect( r );
roi.xOffset = r.left;
roi.yOffset = r.top;
roi.width = r.right - r.left;
roi.height = r.bottom - r.top;
roi.coi = 0;
return roi;
}
void FillBitmapInfo( BITMAPINFO* bmi, int width, int height, int bpp, int origin )
{
assert( bmi && width >= 0 && height >= 0 && (bpp == 8 || bpp == 24 || bpp == 32));
BITMAPINFOHEADER* bmih = &(bmi->bmiHeader);
memset( bmih, 0, sizeof(*bmih));
bmih->biSize = sizeof(BITMAPINFOHEADER);
bmih->biWidth = width;
bmih->biHeight = origin ? abs(height) : -abs(height);
bmih->biPlanes = 1;
bmih->biBitCount = (unsigned short)bpp;
bmih->biCompression = BI_RGB;
if( bpp == 8 )
{
RGBQUAD* palette = bmi->bmiColors;
int i;
for( i = 0; i < 256; i++ )
{
palette[i].rgbBlue = palette[i].rgbGreen = palette[i].rgbRed = (BYTE)i;
palette[i].rgbReserved = 0;
}
}
}
CvvImage::CvvImage()
{
m_img = 0;
}
void CvvImage::Destroy()
{
cvReleaseImage( &m_img );
}
CvvImage::~CvvImage()
{
Destroy();
}
bool CvvImage::Create( int w, int h, int bpp, int origin )
{
const unsigned max_img_size = 10000;
if( (bpp != 8 && bpp != 24 && bpp != 32) ||
(unsigned)w >= max_img_size || (unsigned)h >= max_img_size ||
(origin != IPL_ORIGIN_TL && origin != IPL_ORIGIN_BL))
{
assert(0); // most probably, it is a programming error
return false;
}
if( !m_img || Bpp() != bpp || m_img->width != w || m_img->height != h )
{
if( m_img && m_img->nSize == sizeof(IplImage))
Destroy();
m_img = cvCreateImage( cvSize( w, h ), IPL_DEPTH_8U, bpp/8 );
}
if( m_img )
m_img->origin = origin == 0 ? IPL_ORIGIN_TL : IPL_ORIGIN_BL;
return m_img != 0;
}
void CvvImage::CopyOf( CvvImage& image, int desired_color )
{
IplImage* img = image.GetImage();
if( img )
{
CopyOf( img, desired_color );
}
}
#define HG_IS_IMAGE(img) \
((img) != 0 && ((const IplImage*)(img))->nSize == sizeof(IplImage) && \
((IplImage*)img)->imageData != 0)
void CvvImage::CopyOf( IplImage* img, int desired_color )
{
if( HG_IS_IMAGE(img) )
{
int color = desired_color;
CvSize size = cvGetSize( img );
if( color < 0 )
color = img->nChannels > 1;
if( Create( size.width, size.height,
(!color ? 1 : img->nChannels > 1 ? img->nChannels : 3)*8,
img->origin ))
{
cvConvertImage( img, m_img, 0 );
}
}
}
bool CvvImage::Load( const char* filename, int desired_color )
{
IplImage* img = cvLoadImage( filename, desired_color );
if( !img )
return false;
CopyOf( img, desired_color );
cvReleaseImage( &img );
return true;
}
bool CvvImage::LoadRect( const char* filename,
int desired_color, CvRect r )
{
if( r.width < 0 || r.height < 0 ) return false;
IplImage* img = cvLoadImage( filename, desired_color );
if( !img )
return false;
if( r.width == 0 || r.height == 0 )
{
r.width = img->width;
r.height = img->height;
r.x = r.y = 0;
}
if( r.x > img->width || r.y > img->height ||
r.x + r.width < 0 || r.y + r.height < 0 )
{
cvReleaseImage( &img );
return false;
}
if( r.x < 0 )
{
r.width += r.x;
r.x = 0;
}
if( r.y < 0 )
{
r.height += r.y;
r.y = 0;
}
if( r.x + r.width > img->width )
r.width = img->width - r.x;
if( r.y + r.height > img->height )
r.height = img->height - r.y;
cvSetImageROI( img, r );
CopyOf( img, desired_color );
cvReleaseImage( &img );
return true;
}
bool CvvImage::Save( const char* filename )
{
if( !m_img )
return false;
cvSaveImage( filename, m_img );
return true;
}
void CvvImage::Show( const char* window )
{
if( m_img )
cvShowImage( window, m_img );
}
void CvvImage::Show( HDC dc, int x, int y, int w, int h, int from_x, int from_y )
{
if( m_img && m_img->depth == IPL_DEPTH_8U )
{
uchar buffer[sizeof(BITMAPINFOHEADER) + 1024];
BITMAPINFO* bmi = (BITMAPINFO*)buffer;
int bmp_w = m_img->width, bmp_h = m_img->height;
FillBitmapInfo( bmi, bmp_w, bmp_h, Bpp(), m_img->origin );
from_x = MIN( MAX( from_x, 0 ), bmp_w - 1 );
from_y = MIN( MAX( from_y, 0 ), bmp_h - 1 );
int sw = MAX( MIN( bmp_w - from_x, w ), 0 );
int sh = MAX( MIN( bmp_h - from_y, h ), 0 );
SetDIBitsToDevice(
dc, x, y, sw, sh, from_x, from_y, from_y, sh,
m_img->imageData + from_y*m_img->widthStep,
bmi, DIB_RGB_COLORS );
}
}
void CvvImage::DrawToHDC( HDC hDCDst, RECT* pDstRect )
{
if( pDstRect && m_img && m_img->depth == IPL_DEPTH_8U && m_img->imageData )
{
uchar buffer[sizeof(BITMAPINFOHEADER) + 1024];
BITMAPINFO* bmi = (BITMAPINFO*)buffer;
int bmp_w = m_img->width, bmp_h = m_img->height;
CvRect roi = cvGetImageROI( m_img );
CvRect dst = RectToCvRect( *pDstRect );
if( roi.width == dst.width && roi.height == dst.height )
{
Show( hDCDst, dst.x, dst.y, dst.width, dst.height, roi.x, roi.y );
return;
}
if( roi.width > dst.width )
{
SetStretchBltMode(
hDCDst, // handle to device context
HALFTONE );
}
else
{
SetStretchBltMode(
hDCDst, // handle to device context
COLORONCOLOR );
}
FillBitmapInfo( bmi, bmp_w, bmp_h, Bpp(), m_img->origin );
::StretchDIBits(
hDCDst,
dst.x, dst.y, dst.width, dst.height,
roi.x, roi.y, roi.width, roi.height,
m_img->imageData, bmi, DIB_RGB_COLORS, SRCCOPY );
}
}
void CvvImage::Fill( int color )
{
cvSet( m_img, cvScalar(color&255,(color>>8)&255,(color>>16)&255,(color>>24)&255) );
}
|
[
"huangzhiliang555@vip.qq.com"
] |
huangzhiliang555@vip.qq.com
|
7d9cd2668f54322794db5128079c842ef5091b84
|
5cb8c619a56bd0e021f27dc5936d56ea96a2d2d4
|
/includes/Map/ClassicBomb.hpp
|
e59913ffb75838117a0d7404b93ffba3062e2a4e
|
[] |
no_license
|
Eygle/BombRaider
|
4120b3fd823311fffb4f9ff8df7d096110384bd6
|
5722b2c9995f553bd17f7a6a53982a7712f9362d
|
refs/heads/master
| 2021-01-10T17:14:41.307718
| 2015-12-06T13:32:49
| 2015-12-06T13:32:49
| 47,490,896
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 446
|
hpp
|
#ifndef __CLASSIC_BOMB_HPP__
# define __CLASSIC_BOMB_HPP__
# include "Map/ABomb.hpp"
namespace Map
{
class ClassicBomb : public ABomb
{
ClassicBomb(ClassicBomb const &);
ClassicBomb& operator=(ClassicBomb const &);
void explode();
public:
ClassicBomb(Character::Character *);
ClassicBomb(int, int, GameMap &, std::list<Explosion *> &,
std::list<ABomb *> &, Statistics const &);
~ClassicBomb();
};
};
#endif
|
[
"cavalec.johan@gmail.com"
] |
cavalec.johan@gmail.com
|
58e92b55d57d2451482eea09dcf042dc66cb9742
|
1d04a44976a0d0effd12b9f1bc18db7bc4c8f96d
|
/be/src/kudu/util/async_util.h
|
1e2830c69d741eba9d4ea265ffadc4f16a558466
|
[
"OpenSSL",
"Apache-2.0",
"BSD-3-Clause",
"dtoa",
"MIT",
"PSF-2.0",
"LicenseRef-scancode-mit-modification-obligations",
"bzip2-1.0.6",
"LicenseRef-scancode-unknown-license-reference",
"Minpack",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause",
"LicenseRef-scancode-openssl",
"LicenseRef-scancode-ssleay-windows"
] |
permissive
|
Pandinosaurus/Impala
|
d2d189e9efd93196d4fac36f91e926cca041f023
|
7dd2c8100f6d810bde13a0c9f8fb8449344cdcef
|
refs/heads/cdh5-trunk
| 2023-03-13T00:09:43.104849
| 2019-07-25T00:12:06
| 2019-08-14T21:51:53
| 149,855,108
| 1
| 0
|
Apache-2.0
| 2019-08-15T22:47:12
| 2018-09-22T07:24:05
|
C++
|
UTF-8
|
C++
| false
| false
| 2,229
|
h
|
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you 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.
//
// Utility functions which are handy when doing async/callback-based programming.
#ifndef KUDU_UTIL_ASYNC_UTIL_H
#define KUDU_UTIL_ASYNC_UTIL_H
#include "kudu/gutil/bind.h"
#include "kudu/gutil/macros.h"
#include "kudu/util/countdown_latch.h"
#include "kudu/util/status.h"
#include "kudu/util/status_callback.h"
namespace kudu {
// Simple class which can be used to make async methods synchronous.
// For example:
// Synchronizer s;
// SomeAsyncMethod(s.callback());
// CHECK_OK(s.Wait());
class Synchronizer {
public:
Synchronizer()
: l(1) {
}
void StatusCB(const Status& status) {
s = status;
l.CountDown();
}
StatusCallback AsStatusCallback() {
// Synchronizers are often declared on the stack, so it doesn't make
// sense for a callback to take a reference to its synchronizer.
//
// Note: this means the returned callback _must_ go out of scope before
// its synchronizer.
return Bind(&Synchronizer::StatusCB, Unretained(this));
}
Status Wait() {
l.Wait();
return s;
}
Status WaitFor(const MonoDelta& delta) {
if (PREDICT_FALSE(!l.WaitFor(delta))) {
return Status::TimedOut("Timed out while waiting for the callback to be called.");
}
return s;
}
void Reset() {
l.Reset(1);
}
private:
DISALLOW_COPY_AND_ASSIGN(Synchronizer);
Status s;
CountDownLatch l;
};
} // namespace kudu
#endif /* KUDU_UTIL_ASYNC_UTIL_H */
|
[
"jenkins@cloudera.com"
] |
jenkins@cloudera.com
|
f54acce07d41b5f55d5db7fbe63b4a5e7c1249d5
|
008a5f9ea2cf528186de5506a9841e99b5806896
|
/KinFitter/src/TFitParticleEtThetaPhiEMomFix.cc
|
8fcaf06951d8465333cd4fe5a754c40b95a17518
|
[] |
no_license
|
TopBrussels/TopTreeAnalysisBase
|
86ac6f9f4fbad008068612d076d165acc7dcb9f1
|
557647cc6693783a0d315a5806fa83ea6a3e29f4
|
refs/heads/CMSSW_80X
| 2021-01-17T03:53:26.988093
| 2017-09-13T14:43:50
| 2017-09-13T14:43:50
| 11,848,181
| 1
| 5
| null | 2019-12-03T09:37:10
| 2013-08-02T16:56:43
|
C++
|
UTF-8
|
C++
| false
| false
| 6,184
|
cc
|
// Classname: TFitParticleEtThetaPhiEMomFix
//
//________________________________________________________________
//
// TFitParticleEtThetaPhiEMomFix::
// --------------------
//
// Particle with a special parametrization useful in hadron
// colliders (3 free parameters (Et, Eta, Phi). The parametrization is
// chosen as follows:
//
// p = (EtCosPhi, EtSinPhi, Et/Tan(Theta)
// E = Et/Sin(Theta)
// E/p is kept constant to the initial value
using namespace std;
#include <iostream>
#include "../interface/TFitParticleEtThetaPhiEMomFix.h"
#include "TMath.h"
//ClassImp(TFitParticleEtThetaPhiEMomFix)
//----------------
// Constructor --
//----------------
TFitParticleEtThetaPhiEMomFix::TFitParticleEtThetaPhiEMomFix()
:TAbsFitParticle()
{
init(0, 0);
}
TFitParticleEtThetaPhiEMomFix::TFitParticleEtThetaPhiEMomFix( const TFitParticleEtThetaPhiEMomFix& fitParticle )
:TAbsFitParticle( fitParticle.GetName(), fitParticle.GetTitle() )
{
_nPar = fitParticle._nPar;
_u1 = fitParticle._u1;
_u2 = fitParticle._u2;
_u3 = fitParticle._u3;
_covMatrix.ResizeTo( fitParticle._covMatrix );
_covMatrix = fitParticle._covMatrix;
_iniparameters.ResizeTo( fitParticle._iniparameters );
_iniparameters = fitParticle._iniparameters;
_parameters.ResizeTo( fitParticle._parameters );
_parameters = fitParticle._parameters;
_pini = fitParticle._pini;
_pcurr = fitParticle._pcurr;
}
TFitParticleEtThetaPhiEMomFix::TFitParticleEtThetaPhiEMomFix(TLorentzVector* pini, const TMatrixD* theCovMatrix)
:TAbsFitParticle()
{
init(pini, theCovMatrix);
}
TFitParticleEtThetaPhiEMomFix::TFitParticleEtThetaPhiEMomFix(const TString &name, const TString &title,
TLorentzVector* pini, const TMatrixD* theCovMatrix)
:TAbsFitParticle(name, title)
{
init(pini, theCovMatrix);
}
TAbsFitParticle* TFitParticleEtThetaPhiEMomFix::clone( TString newname ) const {
// Returns a copy of itself
TAbsFitParticle* myclone = new TFitParticleEtThetaPhiEMomFix( *this );
if ( newname.Length() > 0 ) myclone->SetName(newname);
return myclone;
}
//--------------
// Destructor --
//--------------
TFitParticleEtThetaPhiEMomFix::~TFitParticleEtThetaPhiEMomFix() {
}
//--------------
// Operations --
//--------------
void TFitParticleEtThetaPhiEMomFix::init(TLorentzVector* pini, const TMatrixD* theCovMatrix ) {
_nPar = 3;
setIni4Vec(pini);
setCovMatrix(theCovMatrix);
}
TLorentzVector* TFitParticleEtThetaPhiEMomFix::calc4Vec( const TMatrixD* params ) {
// Calculates a 4vector corresponding to the given
// parameter values
if (params == 0) {
return 0;
}
if ( params->GetNcols() != 1 || params->GetNrows() !=_nPar ) {
cerr << "WrongMatrixSize" << GetName() << "::calc4Vec - Parameter matrix has wrong size." << endl;
return 0;
}
Double_t et = (*params)(0,0);
Double_t theta = (*params)(1,0);
Double_t phi = (*params)(2,0);
Double_t PoverE = sqrt(pow(_pini.X(),2) + pow(_pini.Y(),2) + pow(_pini.Z(),2))/_pini.E();
Double_t X = PoverE*et*TMath::Cos(phi);
Double_t Y = PoverE*et*TMath::Sin(phi);
Double_t Z = PoverE*et/TMath::Tan(theta);
Double_t E = et/TMath::Sin(theta);
TLorentzVector* vec = new TLorentzVector( X, Y, Z, E );
return vec;
}
void TFitParticleEtThetaPhiEMomFix::setIni4Vec(const TLorentzVector* pini) {
// Set the initial 4vector. Will also set the
// inital parameter values
if (pini == 0) {
_u1.SetXYZ(0., 0., 0.);
_u3.SetXYZ(0., 0., 0.);
_u2.SetXYZ(0., 0., 0.);
_pini.SetXYZT(0., 0., 0., 0.);
_pcurr = _pini;
_iniparameters.ResizeTo(_nPar,1);
_iniparameters(0,0) = 0.;
_iniparameters(1,0) = 0.;
_iniparameters(2,0) = 0.;
_parameters.ResizeTo(_nPar,1);
_parameters(0,0) = 0.;
_parameters(1,0) = 0.;
_parameters(2,0) = 0.;
} else {
Double_t et = pini->E()*fabs(sin(pini->Theta()));
Double_t theta = pini->Theta();
Double_t phi = pini->Phi();
_pini = (*pini);
_pcurr = _pini;
_iniparameters.ResizeTo(_nPar,1);
_iniparameters(0,0) = et;
_iniparameters(1,0) = theta;
_iniparameters(2,0) = phi;
_parameters.ResizeTo(_nPar,1);
_parameters = _iniparameters;
_u1.SetXYZ( TMath::Cos(phi), TMath::Sin(phi), 0.); // the base vector of Et
_u2.SetXYZ( TMath::Cos(phi)*TMath::Cos(theta), TMath::Sin(phi)*TMath::Cos(theta), -1.*TMath::Sin(theta) );// the base vector of Eta ( same as the base vector for Theta)
_u3.SetXYZ( -1.*TMath::Sin(phi), TMath::Cos(phi), 0. );// the base vector of Phi
}
}
TMatrixD* TFitParticleEtThetaPhiEMomFix::getDerivative() {
// returns derivative dP/dy with P=(p,E) and y=(et, theta, phi)
// the free parameters of the fit. The columns of the matrix contain
// (dP/d(et), dP/d(theta), dP/d(phi)).
TMatrixD* DerivativeMatrix = new TMatrixD(4,3);
(*DerivativeMatrix) *= 0.;
Double_t et = _parameters(0,0);
Double_t theta = _parameters(1,0);
Double_t phi = _parameters(2,0);
Double_t CotanTheta = 1./TMath::Tan(theta);
Double_t PoverE = sqrt(pow(_pini.X(),2) + pow(_pini.Y(),2) + pow(_pini.Z(),2))/_pini.E();
//1st column: dP/d(et)
(*DerivativeMatrix)(0,0) = PoverE*TMath::Cos(phi);
(*DerivativeMatrix)(1,0) = PoverE*TMath::Sin(phi);
(*DerivativeMatrix)(2,0) = PoverE*CotanTheta;
(*DerivativeMatrix)(3,0) = 1./TMath::Sin(theta);
//2nd column: dP/d(theta)
(*DerivativeMatrix)(0,1) = 0.;
(*DerivativeMatrix)(1,1) = 0.;
(*DerivativeMatrix)(2,1) = -1.*PoverE*et*(1.+CotanTheta*CotanTheta);
(*DerivativeMatrix)(3,1) = -1.*et*CotanTheta/(TMath::Sin(theta));
//3rd column: dP/d(phi)
(*DerivativeMatrix)(0,2) = -1.*PoverE*et*TMath::Sin(phi);
(*DerivativeMatrix)(1,2) = PoverE*et*TMath::Cos(phi);
(*DerivativeMatrix)(2,2) = 0.;
(*DerivativeMatrix)(3,2) = 0.;
return DerivativeMatrix;
}
TMatrixD* TFitParticleEtThetaPhiEMomFix::transform(const TLorentzVector& vec) {
// Returns the parameters corresponding to the given
// 4vector
// retrieve parameters
TMatrixD* tparams = new TMatrixD( _nPar, 1 );
(*tparams)(0,0) = vec.E()*fabs(sin(vec.Theta()));
(*tparams)(1,0) = vec.Theta();
(*tparams)(2,0) = vec.Phi();
return tparams;
}
|
[
""
] | |
d45671aa2f0350368e9fec72593a5c023a9c9101
|
5386865e2ea964397b8127aba4b2592d939cd9f2
|
/grupa C/olimpiada/oblasten/2011/raboti/Varna/C/PPL/robot.cpp
|
8d41c0f2492935a3801edb87f28052ac1c98b168
|
[] |
no_license
|
HekpoMaH/Olimpiads
|
e380538b3de39ada60b3572451ae53e6edbde1be
|
d358333e606e60ea83e0f4b47b61f649bd27890b
|
refs/heads/master
| 2021-07-07T14:51:03.193642
| 2017-10-04T16:38:11
| 2017-10-04T16:38:11
| 105,790,126
| 2
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 686
|
cpp
|
#include<iostream>
using namespace std;
int k=0,h,c[105][105],ch[1005]={0},m,n,a2,b2;
void rek(int a, int b){
if(k==h && ch[c[a][b]]==0){ch[c[a][b]]=1; k=0; rek(a2,b2);}
else if(a-1>=0 && ch[c[a-1][b]]==0) { k++; rek(a-1,b); }
else if(b-1>=0 && ch[c[a][b-1]]==0) {k++; rek(a,b-1);}
else if(a+1<m && ch[c[a+1][b]]==0) { k++; rek(a+1,b);}
else if(b+1<n && ch[c[a][b+1]]==0) { k++; rek(a,b+1);}
else return;
}
int main(){
int r,i,j,p=1,i2,j2,s=0;
cin>>m>>n>>r>>h;
for(i=0;i<m;i++){
for(j=0;j<n;j++){
c[i][j]=p;
if(p==r) {i2=i; j2=j;}
p++; }}
a2=i2; b2=j2;
rek(i2,j2);
for(i=1;i<=m*n;i++){
if(ch[i]==1) s=s+i;}
cout<<s;
return 0;
}
|
[
"dgg30"
] |
dgg30
|
27b7d7bd36d26c59f38f0f64e9f49c87b168884c
|
4ca447904892cf433b31250ddf10a760429d51ac
|
/Level 1 Foundation/5. Basic Data Structures/1. Stacks and Queues/12. Merge Overlapping Interval.cpp
|
302dbd693ceae0e7d959c2834df4f3790ec56dd8
|
[] |
no_license
|
Sounak-Dey/Coding
|
cf771d4268a7071631aa99bc20e5280b5decc146
|
b0a01e5b5b05c9290f39c81ae7df054330e52800
|
refs/heads/master
| 2023-07-16T05:04:18.126147
| 2021-09-03T11:14:07
| 2021-09-03T11:14:07
| 369,949,860
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 1,260
|
cpp
|
#include<iostream>
#include<vector>
#include<stack>
#include<algorithm>
using namespace std;
void solve(vector<pair<int, int>> &intervals)
{
int n = intervals.size();
sort(intervals.begin(), intervals.end()); // sort on the basis of start time
stack<pair<int, int>> st, rv;
st.push(intervals[0]); // pushing first interval
for(int i=1; i<n; i++)
{
if(st.top().second >= intervals[i].first) //if ith interval operlaps with interval at stack top
{
st.top().second = max(st.top().second, intervals[i].second); // merging by pushing the larger end time
}
else // if ith interval doesn't overlap .. push it as a new interval
{
st.push(intervals[i]);
}
}
while(!st.empty()) // reversing the stack using another stack, to print in sorted manner of starting time
{
rv.push(st.top());
st.pop();
}
while(!rv.empty())
{
cout<<rv.top().first<<" "<<rv.top().second<<endl;
rv.pop();
}
}
int main()
{
int n;
cin>>n;
vector<pair<int, int>> intervals(n);
for(auto &i: intervals)
{
cin>>i.first;
cin>>i.second;
}
solve(intervals);
return 0;
}
|
[
"sounak.dey@iiitb.ac.in"
] |
sounak.dey@iiitb.ac.in
|
d606e64ef652c3e406f7976b32b4744bb256ede9
|
4978fc75df9363597b86ea34d3f728b174465717
|
/SalesSystemConsoleServer/include/SalesServer/QPlugins/QStatisticsGetter/statisticshandlers.cpp
|
5e4302486c0462c3286020dd984de3944baa384e
|
[] |
no_license
|
karpinochkin/sales-system
|
620d32aad51c602e5d394a2eccd349b3e59a27d7
|
30b86d9923c75acec8c87eafbc868203a3063009
|
refs/heads/master
| 2022-11-23T16:02:16.003061
| 2020-07-16T08:44:27
| 2020-07-16T08:44:27
| 280,083,197
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 6,360
|
cpp
|
#include "statisticshandlers.h"
using namespace Statistics;
QMoney::QMoney(QDatabaseConrol *db)
: db(db)
{
}
QVector<QVariant> QMoney::getFirstVector()
{
QVector<QPointSale> pointSales = db->pointSale->getPointSales();
QVector<QVariant> output;
for(auto pointSale : pointSales) {
output.push_back(QVariant::fromValue(pointSale));
}
return output;
}
QString QMoney::getKey(QVariant &val)
{
return unpack<QPointSale>(val).name;
}
QVector<QVariant> QMoney::getSecondVector(QVariant &val, QDateTime startDate, QDateTime endDate)
{
QPointSale pointSale = unpack<QPointSale>(val);
QVector<QReceipt> receipts = db->receipt->getReceiptsForPointSaleByDateRange(pointSale.id,
startDate,
endDate);
QVector<QVariant> output;
for (auto receipt : receipts) {
output.push_back(QVariant::fromValue(receipt));
}
return output;
}
QDateTime QMoney::getItemDateTime(QVariant &item)
{
QReceipt receipt = unpack<QReceipt>(item);
return receipt.dateTime;
}
void QMoney::updateResult(double *result, QVariant &item)
{
QReceipt receipt = unpack<QReceipt>(item);
*result += receipt.sum;
}
Statistics::QUsersMoney::QUsersMoney(QDatabaseConrol *db)
: db(db)
{
receiptHash.clear();
}
void QUsersMoney::hook(const StatisticsInput &info)
{
QMutex *mut = new QMutex;
mut->lock();
receiptHash.clear();
receiptHash = db->receipt->getReceiptsHash(info.startDate, info.endDate.addDays(1));
mut->unlock();
delete mut;
}
QVector<QVariant> QUsersMoney::getFirstVector()
{
QVector<QUser> users = db->user->getUsers();
QVector<QVariant> output;
for(auto user : users) {
output.push_back(QVariant::fromValue(user));
}
return output;
}
QString QUsersMoney::getKey(QVariant &val)
{
auto user = unpack<QUser>(val);
return user.surname + " " + user.name[0] + ". " + user.patronymic[0] + ".";
}
QVector<QVariant> QUsersMoney::getSecondVector(QVariant &val, QDateTime startDate, QDateTime endDate)
{
QUser user = unpack<QUser>(val);
QVector<QSoldPosition> soldPositions = db->soldPosition->getSoldPositionsForUser(user.id, startDate, endDate);
QVector<QVariant> output;
for (auto soldPosition : soldPositions) {
output.push_back(QVariant::fromValue(soldPosition));
}
return output;
}
QDateTime QUsersMoney::getItemDateTime(QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
return soldPosition.date;
}
void QUsersMoney::updateResult(double *result, QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
QMutex *mut = new QMutex;
auto i = receiptHash.find(soldPosition.idReceipt);
if (!i->isEmpty()) {
*result += receiptHash.take(soldPosition.idReceipt) .sum;
}
receiptHash.remove(soldPosition.idReceipt);
delete mut;
}
QNumberSoldProduct::QNumberSoldProduct(QDatabaseConrol *db, const int idProduct)
: db(db),
idProduct(idProduct)
{
}
QVector<QVariant> QNumberSoldProduct::getFirstVector()
{
QVector<QPointSale> pointSales = db->pointSale->getPointSales();
QVector<QVariant> output;
for(auto pointSale : pointSales) {
output.push_back(QVariant::fromValue(pointSale));
}
return output;
}
QString QNumberSoldProduct::getKey(QVariant &val)
{
return unpack<QPointSale>(val).name;
}
QVector<QVariant> QNumberSoldProduct::getSecondVector(QVariant &val, QDateTime startDate, QDateTime endDate)
{
QPointSale pointSale = unpack<QPointSale>(val);
QVector<QSoldPosition> soldPositions = db->soldPosition->getSoldPositionsForPointSale(pointSale.id,
startDate,
endDate);
QVector<QVariant> output;
for (auto soldPosition : soldPositions) {
output.push_back(QVariant::fromValue(soldPosition));
}
return output;
}
bool QNumberSoldProduct::checkHook(QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
if(soldPosition.idProduct == idProduct) {
return true;
}
return false;
}
QDateTime QNumberSoldProduct::getItemDateTime(QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
return soldPosition.date;
}
void QNumberSoldProduct::updateResult(double *result, QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
*result += soldPosition.count;
}
QNumberSoldProductsForPointSale::QNumberSoldProductsForPointSale(QDatabaseConrol *db,
const int idPointSale)
: db(db),
idPointSale(idPointSale)
{
}
QVector<QVariant> QNumberSoldProductsForPointSale::getFirstVector()
{
QVector<QProduct> products = db->product->getProducts();
QVector<QVariant> output;
for(auto product : products) {
output.push_back(QVariant::fromValue(product));
}
return output;
}
QString QNumberSoldProductsForPointSale::getKey(QVariant &val)
{
return unpack<QProduct>(val).name;
}
QVector<QVariant> QNumberSoldProductsForPointSale::getSecondVector(QVariant &val, QDateTime startDate, QDateTime endDate)
{
QProduct product = unpack<QProduct>(val);
QVector<QSoldPosition> soldPositions = db->soldPosition->getSoldPositionsForProduct(product.id, startDate, endDate);
QVector<QVariant> output;
for (auto soldPosition : soldPositions) {
output.push_back(QVariant::fromValue(soldPosition));
}
return output;
}
bool QNumberSoldProductsForPointSale::checkHook(QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
if (soldPosition.idPointSale == idPointSale) {
return true;
}
return false;
}
QDateTime QNumberSoldProductsForPointSale::getItemDateTime(QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
return soldPosition.date;
}
void QNumberSoldProductsForPointSale::updateResult(double *result, QVariant &item)
{
QSoldPosition soldPosition = unpack<QSoldPosition>(item);
*result += soldPosition.count;
}
|
[
"karpmoney@mail.ru"
] |
karpmoney@mail.ru
|
600f75301497051a01f68706f6d7821e3306df2b
|
b6c25fe3ea803e478b880eba549e873f6e71b099
|
/Win32/VitalUtils/VitalUtilsDlg.h
|
82097b256f4a324c16da7b62b8756c1837e9624f
|
[
"BSD-3-Clause"
] |
permissive
|
safetynet1950s/vitalutils
|
ac88baa8c44481f96ada0607c9b2550c826daa88
|
0816cfa40eead8114bd739e2dfc60bfd9af2e07f
|
refs/heads/master
| 2020-07-30T01:47:22.192678
| 2019-05-11T00:16:45
| 2019-05-11T00:16:45
| null | 0
| 0
| null | null | null | null |
UHC
|
C++
| false
| false
| 3,747
|
h
|
#pragma once
#include "afxwin.h"
#include "EditEx.h"
#include "afxcmn.h"
#include "OptRunScript.h"
#include "OptRecsDlg.h"
#include "OptRenameDlg.h"
#include "OptDelTrksDlg.h"
#include "OptCopyFilesDlg.h"
#include <map>
#include <set>
#include "Canvas.h"
using namespace std;
class CVitalUtilsDlg : public CDialogEx {
public:
CVitalUtilsDlg(CWnd* pParent = NULL); // 표준 생성자입니다.
#ifdef AFX_DESIGN_TIME
enum { IDD = IDD_VITALUTILS_DIALOG };
#endif
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 지원입니다.
// 구현입니다.
protected:
DECLARE_MESSAGE_MAP()
afx_msg void OnPaint();
afx_msg HCURSOR OnQueryDragIcon();
afx_msg void OnBnClickedBtnIdir();
afx_msg void OnBnClickedBtnOdir();
afx_msg void OnBnClickedRun();
afx_msg void OnTimer(UINT_PTR nIDEvent);
afx_msg void OnBnClickedCancel();
afx_msg void OnClose();
afx_msg void OnBnClickedClear();
afx_msg void OnSize(UINT nType, int cx, int cy);
afx_msg void OnDestroy();
afx_msg void OnGetdispinfoFilelist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnSelchangeTrklist();
afx_msg void OnNMDblclkFilelist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedRescan();
afx_msg void OnBnClickedTrkAll();
afx_msg void OnBnClickedTrkNone();
afx_msg void OnBnClickedFileAll();
afx_msg void OnBnClickedFileNone();
afx_msg void OnBnClickedSaveList();
afx_msg void OnBnClickedSelRunScript();
afx_msg void OnBnClickedSelCopyFiles();
afx_msg void OnBnClickedSelRenameDev();
afx_msg void OnBnClickedSelDelTrks();
afx_msg void OnBnClickedSelRecs();
afx_msg void OnBnClickedSelRenameTrks();
afx_msg void OnCbnSelchangeTrkOper();
afx_msg void OnLvnItemchangedFilelist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedSelect();
virtual BOOL OnInitDialog();
virtual BOOL PreTranslateMessage(MSG* pMsg);
virtual void OnOK();
virtual void OnCancel();
int GetNumVisibleLines();
public:
COptRunScriptDlg m_dlgRun;
COptCopyFilesDlg m_dlgCopy;
COptRecsDlg m_dlgRecs;
COptRenameDlg m_dlgRename;
COptDelTrksDlg m_dlgDelTrks;
public:
HICON m_hIcon;
// 각 윈도우 선택하는 버튼
CMFCButton m_ctrlSelRun;
CMFCButton m_ctrlSelCopyFiles;
CMFCButton m_ctrlSelRecs;
CMFCButton m_ctrlSelDelTrks;
CMFCButton m_ctrlSelRenameTrks;
CMFCButton m_ctrlSelRenameDev;
CMFCButton m_btnRun;
CMFCButton m_btnStop;
CMFCButton m_btnIdir;
CMFCButton m_btnScan;
CMFCButton m_btnSaveList;
CMFCButton m_btnTrkAll;
CMFCButton m_btnTrkNone;
CMFCButton m_btnFileAll;
CMFCButton m_btnFileNone;
CMFCButton m_btnOdir;
CMFCButton m_btnClear;
CMFCButton m_btnSelect;
int m_nLastTrkSel = -1;
int m_nLastFileSel = -1;
CRichEditCtrl m_ctrLog;
CString m_strIdir;
CString m_strOdir;
bool m_b64;
CListBox m_ctrList;
CString m_strProgress;
CListBox m_ctrlTrkList;
BOOL m_bSkip = TRUE;
BOOL m_bMakeSubDir = TRUE;
Canvas m_canFolder;
CStatic m_ctrlOdirStatic;
CStatic m_ctrlIdirStatic;
CStatic m_ctrProgress;
CEditEx m_ctrlFilter;
CComboBox m_ctrlSelOper;
CButton m_ctrlExact;
CStatic m_ctrlTrkCnt;
CStatic m_ctrlFileCnt;
CListCtrl m_ctrlFileList;
int m_nOldCy = 0, m_nOldCx = 0;
// LVS_OWNERDATA 속성인경우 SetItemText, SetItemData는 사용 불가하다
// 따라서 내가 item data를 처리해야 한다
vector<VITAL_FILE_INFO*> m_shown;
// filename의 ascending 으로 시작
int m_nSortItem = -1;
bool m_bSortAsc = true;
afx_msg void OnHdnItemclickFilelist(NMHDR *pNMHDR, LRESULT *pResult);
afx_msg void OnBnClickedTrkSelect();
CEditEx m_ctrlTrkFilter;
afx_msg void OnLvnBegindragFilelist(NMHDR *pNMHDR, LRESULT *pResult);
CEditEx m_ctrIdir;
CEditEx m_ctrOdir;
afx_msg void OnEnKillfocusIdir();
afx_msg void OnEnKillfocusOdir();
afx_msg void OnBnClickedIdirOpen();
};
|
[
"lucid80@gmail.com"
] |
lucid80@gmail.com
|
124a80388cd7527b50909e114927c132cef2550d
|
d975a6e48c0df5fa4dbbda9d93d99822bccdad6b
|
/inhertiance.cpp
|
ef5a6e3d614956a9351e1eaee3dff7e5856cf161
|
[] |
no_license
|
prashant2-4-4/Prashant-Pathak
|
bab4b94640e7545002d030b509c987e3658c5c12
|
8ca7d700f43046355857571fcc5b5a9e37dcd3b9
|
refs/heads/master
| 2021-07-10T13:21:20.100937
| 2020-10-28T07:33:46
| 2020-10-28T07:33:46
| 211,568,068
| 2
| 6
| null | 2020-10-28T07:33:48
| 2019-09-28T22:18:03
|
Python
|
UTF-8
|
C++
| false
| false
| 390
|
cpp
|
#include <iostream>
#include <string>
using namespace std;
class Human{
protected:
string name;
int age;
public:
void setage(string iname , int iage)
{
name = iname;
age = iage;
}
};
class student : public Human{
public:
void display()
{
cout << name << endl ;
}
};
int main()
{
student anil;
anil.setage("pras" , 24);
anil.display();
return 0;
}
|
[
"deepdarshan21@gmail.com"
] |
deepdarshan21@gmail.com
|
74abd1313429e9aa5b5d12579f459b8963be2c89
|
375c9bd8a820e512bd25110e094b8546a31898fc
|
/100/006.cpp
|
939b3e8ac160368f21f8716621dea6815f103260
|
[] |
no_license
|
quid9998/kyopro
|
a21256c9b12b4a6b3ff61d6ec48c93fe5aba78d7
|
2b279b9fe6eb399bac7e7d834ace9230ff408eae
|
refs/heads/master
| 2023-04-02T08:43:05.923958
| 2021-04-01T13:12:51
| 2021-04-01T13:12:51
| 349,601,820
| 0
| 0
| null | null | null | null |
UTF-8
|
C++
| false
| false
| 916
|
cpp
|
//自力AC,復習不要
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<long long, long long> P;
#define rep(i, n) for (ll i = 0; i < (ll)(n); i++)
#define agewari(a, b) ((ll)a + ((ll)b - 1)) / b
const int MOD = 1000000007;
const long long INF = 1LL << 60;
//数値を0埋めしたstringに変換
string ume(ll n)
{
string tmp = to_string(n);
if (tmp.size() == 1)
return "00" + tmp;
if (tmp.size() == 2)
return "0" + tmp;
return tmp;
}
int main()
{
ll n;
string s;
cin >> n >> s;
//候補を検証
ll ans = 0;
for (ll i = 0; i <= 999; i++)
{
string si = ume(i);
ll now = 0;
rep(j, n)
{
if (si[now] == s[j])
now++;
if (now == 3)
{
ans++;
break;
}
}
}
cout << ans << endl;
}
|
[
"polypterus666@gmail.com"
] |
polypterus666@gmail.com
|
dbf1b7b44e1355df142446ad84634f94c08eadbc
|
03c4096d19255a6e72b40949ff2e77ba79fa74f7
|
/HF-Jet/HFMLTrigger_LANL/HFMLTriggerOccupancy.h
|
736ba07d85e98736c9b559eb3c14240181c8de91
|
[] |
no_license
|
sPHENIX-Collaboration/analysis
|
c0687cd1b4ea9ec426e71303d2a8b4c34d19c11c
|
dc932e3355d09898bba525ac1e6292ade5c48d02
|
refs/heads/master
| 2023-08-31T22:22:52.275236
| 2023-08-29T22:53:04
| 2023-08-29T22:53:04
| 37,741,543
| 4
| 58
| null | 2023-09-13T19:37:21
| 2015-06-19T19:25:00
|
C
|
UTF-8
|
C++
| false
| false
| 2,813
|
h
|
#ifndef __HFMLTriggerOccupancy_H__
#define __HFMLTriggerOccupancy_H__
// --- need to check all these includes...
#include <fun4all/SubsysReco.h>
#include <limits.h>
#include <cmath>
#include <fstream> // std::fstream
#include <string>
#include <vector>
class TTree;
class TFile;
class TH1F;
class TH2F;
class TH3F;
class PHCompositeNode;
class PHG4CylinderGeomContainer;
class PHG4TruthInfoContainer;
class TrkrHitSetContainer;
class SvtxEvalStack;
class PdbParameterMap;
namespace HepMC
{
class GenEvent;
}
class HFMLTriggerOccupancy : public SubsysReco
{
public:
HFMLTriggerOccupancy(std::string filename);
int Init(PHCompositeNode *);
int InitRun(PHCompositeNode *);
int process_event(PHCompositeNode *);
int End(PHCompositeNode *);
double
get_eta_max() const
{
return _eta_max;
}
void
set_eta_max(double etaMax)
{
_eta_max = etaMax;
}
double
get_eta_min() const
{
return _eta_min;
}
void
set_eta_min(double etaMin)
{
_eta_min = etaMin;
}
//! The embedding ID for the HepMC subevent to be analyzed.
//! embedding ID for the event
//! positive ID is the embedded event of interest, e.g. jetty event from pythia
//! negative IDs are backgrounds, .e.g out of time pile up collisions
//! Usually, ID = 0 means the primary Au+Au collision background
int get_embedding_id() const { return _embedding_id; }
//
//! The embedding ID for the HepMC subevent to be analyzed.
//! embedding ID for the event
//! positive ID is the embedded event of interest, e.g. jetty event from pythia
//! negative IDs are backgrounds, .e.g out of time pile up collisions
//! Usually, ID = 0 means the primary Au+Au collision background
void set_embedding_id(int id) { _embedding_id = id; }
private:
int _ievent;
TFile *_f;
std::fstream m_jsonOut;
std::string _foutname;
double _eta_min;
double _eta_max;
//! The embedding ID for the HepMC subevent to be analyzed.
//! positive ID is the embedded event of interest, e.g. jetty event from pythia
//! negative IDs are backgrounds, .e.g out of time pile up collisions
//! Usually, ID = 0 means the primary Au+Au collision background
int _embedding_id;
unsigned int _nlayers_maps;
enum {kNCHip = 9};
// eval stack
SvtxEvalStack *_svtxevalstack;
TrkrHitSetContainer *m_hitsetcont;
PHG4CylinderGeomContainer *m_Geoms;
PHG4TruthInfoContainer *m_truthInfo;
PdbParameterMap *m_Flags;
TH1F *m_hNorm;
TH1F *m_hNChEta;
TH1F *m_hVertexZ;
TH2F *m_hitStaveLayer;
TH2F *m_hitModuleHalfStave;
TH2F *m_hitChipModule;
TH3F *m_hitLayerMap;
TH3F *m_hitPixelPhiMap;
TH3F *m_hitPixelPhiMapHL;
TH3F *m_hitPixelZMap;
TH1F *m_Multiplicity;
TH2F *m_LayerMultiplicity;
TH3F *m_LayerChipMultiplicity;
};
#endif // __HFMLTriggerOccupancy_H__
|
[
"yasser.corrales.morales@cern.ch"
] |
yasser.corrales.morales@cern.ch
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.