blob_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| path
stringlengths 6
201
| content_id
stringlengths 40
40
| detected_licenses
sequencelengths 0
26
| license_type
stringclasses 2
values | repo_name
stringlengths 7
95
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| branch_name
stringclasses 57
values | visit_date
timestamp[us] | revision_date
timestamp[us] | committer_date
timestamp[us] | github_id
int64 197k
639M
⌀ | star_events_count
int64 0
209k
| fork_events_count
int64 0
110k
| gha_license_id
stringclasses 11
values | gha_event_created_at
timestamp[us] | gha_created_at
timestamp[us] | gha_language
stringclasses 34
values | src_encoding
stringclasses 18
values | language
stringclasses 1
value | is_vendor
bool 1
class | is_generated
bool 2
classes | length_bytes
int64 11
9.86M
| extension
stringclasses 27
values | content
stringlengths 11
9.86M
| authors
sequencelengths 1
1
| author
stringlengths 0
70
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
e13a5b3f7c08d6d7a9e785532221179048f3bc2b | 006ff11fd8cfd5406c6f4318f1bafa1542095f2a | /Alignment/CommonAlignmentProducer/src/AlignmentTwoBoyDecayTrackSelector.cc | f901af53711c8fdfcf5fc27f07d9b4efa7df74a8 | [] | permissive | amkalsi/cmssw | 8ac5f481c7d7263741b5015381473811c59ac3b1 | ad0f69098dfbe449ca0570fbcf6fcebd6acc1154 | refs/heads/CMSSW_7_4_X | 2021-01-19T16:18:22.857382 | 2016-08-09T16:40:50 | 2016-08-09T16:40:50 | 262,608,661 | 0 | 0 | Apache-2.0 | 2020-05-09T16:10:07 | 2020-05-09T16:10:07 | null | UTF-8 | C++ | false | false | 10,315 | cc | //Framework
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Utilities/interface/EDMException.h"
//DataFormats
#include <DataFormats/TrackReco/interface/Track.h>
#include <DataFormats/METReco/interface/CaloMET.h>
#include <DataFormats/Math/interface/deltaPhi.h>
//STL
#include <math.h>
//ROOT
#include "TLorentzVector.h"
#include "Alignment/CommonAlignmentProducer/interface/AlignmentTwoBodyDecayTrackSelector.h"
//TODO put those namespaces into functions?
using namespace std;
using namespace edm;
// constructor ----------------------------------------------------------------
AlignmentTwoBodyDecayTrackSelector::AlignmentTwoBodyDecayTrackSelector(const edm::ParameterSet & cfg) :
theMissingETSource("met")
{
LogDebug("Alignment") << "> applying two body decay Trackfilter ...";
theMassrangeSwitch = cfg.getParameter<bool>( "applyMassrangeFilter" );
if (theMassrangeSwitch){
theMinMass = cfg.getParameter<double>( "minXMass" );
theMaxMass = cfg.getParameter<double>( "maxXMass" );
theDaughterMass = cfg.getParameter<double>( "daughterMass" );
theCandNumber = cfg.getParameter<unsigned int>( "numberOfCandidates" );//Number of candidates to keep
secThrBool = cfg.getParameter<bool> ( "applySecThreshold" );
thesecThr = cfg.getParameter<double>( "secondThreshold" );
LogDebug("Alignment") << "> Massrange min,max : " << theMinMass << "," << theMaxMass
<< "\n> Mass of daughter Particle : " << theDaughterMass;
}else{
theMinMass = 0;
theMaxMass = 0;
theDaughterMass = 0;
}
theChargeSwitch = cfg.getParameter<bool>( "applyChargeFilter" );
if(theChargeSwitch){
theCharge = cfg.getParameter<int>( "charge" );
theUnsignedSwitch = cfg.getParameter<bool>( "useUnsignedCharge" );
if(theUnsignedSwitch)
theCharge=std::abs(theCharge);
LogDebug("Alignment") << "> Desired Charge, unsigned: "<<theCharge<<" , "<<theUnsignedSwitch;
}else{
theCharge =0;
theUnsignedSwitch = true;
}
theMissingETSwitch = cfg.getParameter<bool>( "applyMissingETFilter" );
if(theMissingETSwitch){
theMissingETSource = cfg.getParameter<InputTag>( "missingETSource" );
LogDebug("Alignment") << "> missing Et Source: "<< theMissingETSource;
}
theAcoplanarityFilterSwitch = cfg.getParameter<bool>( "applyAcoplanarityFilter" );
if(theAcoplanarityFilterSwitch){
theAcoplanarDistance = cfg.getParameter<double>( "acoplanarDistance" );
LogDebug("Alignment") << "> Acoplanar Distance: "<<theAcoplanarDistance;
}
}
// destructor -----------------------------------------------------------------
AlignmentTwoBodyDecayTrackSelector::~AlignmentTwoBodyDecayTrackSelector()
{}
///returns if any of the Filters is used.
bool AlignmentTwoBodyDecayTrackSelector::useThisFilter()
{
return theMassrangeSwitch || theChargeSwitch || theAcoplanarityFilterSwitch;
}
// do selection ---------------------------------------------------------------
AlignmentTwoBodyDecayTrackSelector::Tracks
AlignmentTwoBodyDecayTrackSelector::select(const Tracks& tracks, const edm::Event& iEvent, const edm::EventSetup& iSetup)
{
Tracks result = tracks;
if (theMassrangeSwitch) {
if (theMissingETSwitch)
result = checkMETMass(result,iEvent);
else
result = checkMass(result);
}
LogDebug("Alignment") << "> TwoBodyDecay tracks all,kept: " << tracks.size() << "," << result.size();
return result;
}
template<class T>
struct higherTwoBodyDecayPt : public std::binary_function<T,T,bool>
{
bool operator()( const T& a, const T& b )
{
return a.first > b.first ;
}
};
///checks if the mass of the X is in the mass region
AlignmentTwoBodyDecayTrackSelector::Tracks
AlignmentTwoBodyDecayTrackSelector::checkMass(const Tracks& cands) const
{
Tracks result;
LogDebug("Alignment") <<"> cands size : "<< cands.size();
if (cands.size()<2) return result;
TLorentzVector track0;
TLorentzVector track1;
TLorentzVector mother;
typedef pair<const reco::Track*,const reco::Track*> constTrackPair;
typedef pair<double,constTrackPair> candCollectionItem;
vector<candCollectionItem> candCollection;
for (unsigned int iCand = 0; iCand < cands.size(); iCand++) {
track0.SetXYZT(cands.at(iCand)->px(),
cands.at(iCand)->py(),
cands.at(iCand)->pz(),
sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass ));
for (unsigned int jCand = iCand+1; jCand < cands.size(); jCand++) {
track1.SetXYZT(cands.at(jCand)->px(),
cands.at(jCand)->py(),
cands.at(jCand)->pz(),
sqrt( cands.at(jCand)->p()*cands.at(jCand)->p() + theDaughterMass*theDaughterMass ));
if (secThrBool==true && track1.Pt() < thesecThr && track0.Pt()< thesecThr) continue;
mother = track0 + track1;
const reco::Track *trk1 = cands.at(iCand);
const reco::Track *trk2 = cands.at(jCand);
bool correctCharge = true;
if (theChargeSwitch) correctCharge = this->checkCharge(trk1, trk2);
bool acoplanarTracks = true;
if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkAcoplanarity(trk1, trk2);
if (mother.M() > theMinMass &&
mother.M() < theMaxMass &&
correctCharge &&
acoplanarTracks) {
candCollection.push_back(candCollectionItem(mother.Pt(),
constTrackPair(trk1, trk2)));
}
}
}
if (candCollection.size()==0) return result;
sort(candCollection.begin(), candCollection.end(),
higherTwoBodyDecayPt<candCollectionItem>());
std::map<const reco::Track*,unsigned int> uniqueTrackIndex;
std::map<const reco::Track*,unsigned int>::iterator it;
for (unsigned int i=0;
i<candCollection.size() && i<theCandNumber;
i++) {
constTrackPair & trackPair = candCollection[i].second;
it = uniqueTrackIndex.find(trackPair.first);
if (it==uniqueTrackIndex.end()) {
result.push_back(trackPair.first);
uniqueTrackIndex[trackPair.first] = i;
}
it = uniqueTrackIndex.find(trackPair.second);
if (it==uniqueTrackIndex.end()) {
result.push_back(trackPair.second);
uniqueTrackIndex[trackPair.second] = i;
}
}
return result;
}
///checks if the mass of the X is in the mass region adding missing E_T
AlignmentTwoBodyDecayTrackSelector::Tracks
AlignmentTwoBodyDecayTrackSelector::checkMETMass(const Tracks& cands,const edm::Event& iEvent) const
{
Tracks result;
LogDebug("Alignment") <<"> cands size : "<< cands.size();
if (cands.size()==0) return result;
TLorentzVector track;
TLorentzVector met4;
TLorentzVector mother;
Handle<reco::CaloMETCollection> missingET;
iEvent.getByLabel(theMissingETSource ,missingET);
if (!missingET.isValid()) {
LogError("Alignment")<< "@SUB=AlignmentTwoBodyDecayTrackSelector::checkMETMass"
<< "> could not optain missingET Collection!";
return result;
}
typedef pair<double,const reco::Track*> candCollectionItem;
vector<candCollectionItem> candCollection;
for (reco::CaloMETCollection::const_iterator itMET = missingET->begin();
itMET != missingET->end();
++itMET) {
met4.SetXYZT((*itMET).px(),
(*itMET).py(),
(*itMET).pz(),
(*itMET).p());
for (unsigned int iCand = 0; iCand < cands.size(); iCand++) {
track.SetXYZT(cands.at(iCand)->px(),
cands.at(iCand)->py(),
cands.at(iCand)->pz(),
sqrt( cands.at(iCand)->p()*cands.at(iCand)->p() + theDaughterMass*theDaughterMass ));
mother = track + met4;
const reco::Track *trk = cands.at(iCand);
const reco::CaloMET *met = &(*itMET);
bool correctCharge = true;
if (theChargeSwitch) correctCharge = this->checkCharge(trk);
bool acoplanarTracks = true;
if (theAcoplanarityFilterSwitch) acoplanarTracks = this->checkMETAcoplanarity(trk, met);
if (mother.M() > theMinMass &&
mother.M() < theMaxMass &&
correctCharge &&
acoplanarTracks) {
candCollection.push_back(candCollectionItem(mother.Pt(), trk));
}
}
}
if (candCollection.size()==0) return result;
sort(candCollection.begin(), candCollection.end(),
higherTwoBodyDecayPt<candCollectionItem>());
std::map<const reco::Track*,unsigned int> uniqueTrackIndex;
std::map<const reco::Track*,unsigned int>::iterator it;
for (unsigned int i=0;
i<candCollection.size() && i<theCandNumber;
i++) {
it = uniqueTrackIndex.find(candCollection[i].second);
if (it==uniqueTrackIndex.end()) {
result.push_back(candCollection[i].second);
uniqueTrackIndex[candCollection[i].second] = i;
}
}
return result;
}
///checks if the mother has charge = [theCharge]
bool
AlignmentTwoBodyDecayTrackSelector::checkCharge(const reco::Track* trk1, const reco::Track* trk2)const
{
int sumCharge = trk1->charge();
if (trk2) sumCharge += trk2->charge();
if (theUnsignedSwitch) sumCharge = std::abs(sumCharge);
if (sumCharge == theCharge) return true;
return false;
}
///checks if the [cands] are acoplanar (returns empty set if not)
bool
AlignmentTwoBodyDecayTrackSelector::checkAcoplanarity(const reco::Track* trk1, const reco::Track* trk2)const
{
if (fabs(deltaPhi(trk1->phi(),trk2->phi()-M_PI)) < theAcoplanarDistance) return true;
return false;
}
///checks if the [cands] are acoplanar (returns empty set if not)
bool
AlignmentTwoBodyDecayTrackSelector::checkMETAcoplanarity(const reco::Track* trk1, const reco::CaloMET* met)const
{
if (fabs(deltaPhi(trk1->phi(),met->phi()-M_PI)) < theAcoplanarDistance) return true;
return false;
}
//===================HELPERS===================
///print Information on Track-Collection
void AlignmentTwoBodyDecayTrackSelector::printTracks(const Tracks& col) const
{
int count = 0;
LogDebug("Alignment") << ">......................................";
for(Tracks::const_iterator it = col.begin();it < col.end();++it,++count){
LogDebug("Alignment")
<<"> Track No. "<< count <<": p = ("<<(*it)->px()<<","<<(*it)->py()<<","<<(*it)->pz()<<")\n"
<<"> pT = "<<(*it)->pt()<<" eta = "<<(*it)->eta()<<" charge = "<<(*it)->charge();
}
LogDebug("Alignment") << ">......................................";
}
| [
"giulio.eulisse@gmail.com"
] | giulio.eulisse@gmail.com |
59d68e07d1197e5c92d194abdec105b8feaa053d | 6a5ebe5ee99f84755219fa6cdd6102646ab5bed1 | /contest/A. Find Divisible.cpp | 41f94f76e4ee354cc924cc0d6fca452654a682ff | [] | no_license | israt-urme/Codeforces | 89be84f03b1e5ade0fd55119b42d43d99f8567e2 | 77ccae1604c7837e97d2592f07514ab6536cca63 | refs/heads/master | 2023-06-07T00:11:17.741535 | 2021-06-28T11:59:41 | 2021-06-28T11:59:41 | 381,008,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 198 | cpp | #include<bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin>>n;
long long int l,r,x,y,i;
while(n--)
{
cin>>l>>r;
cout<<l<<" "<<l*2<<endl;
}
return 0;
}
| [
"urmejahan58@gmail.com"
] | urmejahan58@gmail.com |
323d2b2ca51b1eb942a5b8a887026a0968e86fe7 | de404537c0d5d1142bbf4e9d8a9ab874766f75c7 | /sdk/bindings/xpcom/include/nsIObserver.h | 4ee928c19449a4384d6f6a6b9f06039670ec91be | [] | no_license | smoeller1/Hackathon | 6b6a0d3d59c2845b5709dffce5a1f14b3cb8b4da | acfac96ec4cc8e79ca622303fa4b16cd01277c6d | refs/heads/master | 2022-11-19T18:47:28.730061 | 2018-10-19T17:43:02 | 2018-10-19T17:43:02 | 55,860,568 | 0 | 0 | null | 2022-11-16T05:23:59 | 2016-04-09T18:29:40 | C | UTF-8 | C++ | false | false | 3,334 | h | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM /home/vbox/tinderbox/5.0-sdk/src/libs/xpcom18a4/xpcom/ds/nsIObserver.idl
*/
#ifndef __gen_nsIObserver_h__
#define __gen_nsIObserver_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
/* starting interface: nsIObserver */
#define NS_IOBSERVER_IID_STR "db242e01-e4d9-11d2-9dde-000064657374"
#define NS_IOBSERVER_IID \
{0xdb242e01, 0xe4d9, 0x11d2, \
{ 0x9d, 0xde, 0x00, 0x00, 0x64, 0x65, 0x73, 0x74 }}
/**
* This interface is implemented by an object that wants
* to observe an event corresponding to a topic.
*
* @status FROZEN
*/
class NS_NO_VTABLE nsIObserver : public nsISupports {
public:
NS_DEFINE_STATIC_IID_ACCESSOR(NS_IOBSERVER_IID)
/**
* Observe will be called when there is a notification for the
* topic |aTopic|. This assumes that the object implementing
* this interface has been registered with an observer service
* such as the nsIObserverService.
*
* If you expect multiple topics/subjects, the impl is
* responsible for filtering.
*
* You should not modify, add, remove, or enumerate
* notifications in the implemention of observe.
*
* @param aSubject : Notification specific interface pointer.
* @param aTopic : The notification topic or subject.
* @param aData : Notification specific wide string.
* subject event.
*/
/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) = 0;
};
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIOBSERVER \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIOBSERVER(_to) \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { return _to Observe(aSubject, aTopic, aData); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIOBSERVER(_to) \
NS_IMETHOD Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData) { return !_to ? NS_ERROR_NULL_POINTER : _to->Observe(aSubject, aTopic, aData); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsObserver : public nsIObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIOBSERVER
nsObserver();
private:
~nsObserver();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsObserver, nsIObserver)
nsObserver::nsObserver()
{
/* member initializers and constructor code */
}
nsObserver::~nsObserver()
{
/* destructor code */
}
/* void observe (in nsISupports aSubject, in string aTopic, in wstring aData); */
NS_IMETHODIMP nsObserver::Observe(nsISupports *aSubject, const char *aTopic, const PRUnichar *aData)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIObserver_h__ */
| [
"simon@quasily.com"
] | simon@quasily.com |
d3b920d102d166ad45d2b213d81aa0d930494a56 | 9e19807e814828fdad56ead0496f3403ade3844e | /q1.cpp | 4abeed4cea7b2306481caf2a25af5c3b61c8db35 | [] | no_license | jasonzlou/projecteuler | ac50acb8c53371cf2151361ec14162e43400a725 | b8c9f1548dbe3bb87c85cb92524afe8801f0e153 | refs/heads/main | 2023-05-10T10:54:28.702614 | 2021-06-11T14:20:51 | 2021-06-11T14:20:51 | 308,991,921 | 0 | 0 | null | 2021-06-11T14:20:52 | 2020-10-31T23:46:57 | C++ | UTF-8 | C++ | false | false | 189 | cpp | #include <iostream>
using namespace std;
int main() {
int sum(0);
for (int i = 1; i < 1000; i++) {
if (i % 3 == 0 || i % 5 == 0) {
sum += i;
}
}
cout << sum;
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
b184f28a418c98a6ad3c63bad3cee0307ad90823 | 8545d068c19b60cf7d27a45e175534a034700ab3 | /WOFFCEdit/Camera.h | c4112bc1ea5458828721b2ea7b2595d49eff00b3 | [] | no_license | charliegillies/WFFC-Edit | 95b2dbf8aaf3016ca004a8ff79ff34915eaa4c2c | 958421962eeccc71aa3576e9d7f524097a4cf416 | refs/heads/master | 2020-05-16T05:00:51.150648 | 2019-04-29T16:00:09 | 2019-04-29T16:00:09 | 182,796,108 | 0 | 0 | null | 2019-04-22T13:44:06 | 2019-04-22T13:44:06 | null | UTF-8 | C++ | false | false | 1,020 | h | #pragma once
#include <d3d11.h>
#include "SimpleMath.h"
struct InputCommands;
class SceneObject;
class Camera {
private:
DirectX::SimpleMath::Vector3 m_camPosition;
DirectX::SimpleMath::Vector3 m_camOrientation;
DirectX::SimpleMath::Vector3 m_camLookAt;
DirectX::SimpleMath::Vector3 m_camLookDirection;
DirectX::SimpleMath::Vector3 m_camRight;
float m_camRotRate;
float m_moveSpeed;
HWND m_hwnd;
public:
Camera();
void setHWND(HWND hwnd);
void handleInput(InputCommands const& commands, const float deltaTime, const SceneObject* so);
bool moveTowards(const SceneObject* obj, const float time);
DirectX::SimpleMath::Vector3 screenToWorld(int width, int height, DirectX::SimpleMath::Matrix worldMatrix) const;
DirectX::SimpleMath::Matrix createViewMatrix();
DirectX::SimpleMath::Vector3 getDirection() const;
DirectX::SimpleMath::Vector3 getPosition() const;
DirectX::SimpleMath::Vector3 getLookAt() const;
DirectX::SimpleMath::Vector3 getUp() const;
std::wstring getDebugPosition() const;
};
| [
"charlie@hazardinteractive.com"
] | charlie@hazardinteractive.com |
f65306227667cfa2aae6ccf934d57b7c88b1d289 | 15bd9209ca102e939320bd344491efbe16bd8458 | /ESGenNPRestos/es_gennp_restos.cpp | a3cc164f5562e2f3e83d1bc82ef970e365283e00 | [] | no_license | emilroy02/ESGenNP | cc6f0855bc47322c0aa75e770002283b68bb1f7a | 708b4dfc67210418ab41516916c68ee607fa0f74 | refs/heads/master | 2023-01-21T21:31:01.021584 | 2019-11-22T09:21:16 | 2019-11-22T09:21:16 | 219,699,639 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,519 | cpp | #include "es_gennp_common.h"
#define ESGC_EXPORTS
#include "es_gennp.h"
#include "es_gennp_core_init.h"
#include "es_gennp_config_init.h"
#include "es_gennp_service.h"
#include "es_gennp_branding_restos.h"
#include "es_gennp_library_restos.h"
static ESGenNPService *pService = NULL;
static std::shared_ptr<ESGenNPBranding> CreateBrandingRestos()
{
return std::make_shared<ESGenNPBrandingRestos>();
}
static std::shared_ptr<ESGenNPLibrary> CreateLibraryRestos()
{
return std::make_shared<ESGenNPLibraryRestos>();
}
class ESGenNPCoreConfigurator
{
public:
ESGenNPCoreConfigurator ()
{
ESCoreConfig cfg;
cfg.pFNCreateBranding = CreateBrandingRestos;
cfg.pFNCreateLibrary = CreateLibraryRestos;
pService = ESGenNPCoreInit::ConfigureCore(cfg);
}
~ESGenNPCoreConfigurator (){}
};
static ESGenNPCoreConfigurator configurator;
extern "C" {
namespace ESGenNP {
#define COMMON_PRECONDITION if (!pService) { return ESGC_ERR_NOT_INITIALIZED;}
ESGC_API ESGCInit( void )
{
COMMON_PRECONDITION
return pService->ESGCInit();
}
ESGC_API ESGCClose( void )
{
COMMON_PRECONDITION
return pService->ESGCClose();
}
ESGC_API ESGCClientCreate( ESGC_CLIENT_HANDLE *phClientOut)
{
COMMON_PRECONDITION
return pService->ESGCClientCreate(phClientOut);
}
ESGC_API ESGCClientConnect(ESGC_CLIENT_HANDLE hClient, const std::string &ipAddress, const uint16_t port)
{
COMMON_PRECONDITION
return pService->ESGCClientConnect(hClient, ipAddress, port);
}
ESGC_API ESGCServerCreate( ESGC_SERVER_HANDLE *phServerOut)
{
COMMON_PRECONDITION
return pService->ESGCServerCreate(phServerOut);
}
ESGC_API ESGCServerStart(ESGC_SERVER_HANDLE hServer)
{
COMMON_PRECONDITION
return pService->ESGCServerStart(hServer);
}
ESGC_API ESGCServerStop(ESGC_SERVER_HANDLE hServer)
{
COMMON_PRECONDITION
return pService->ESGCServerStop(hServer);
}
ESGC_API ESGCRegisterEvent(ESGC_EVENTSRC_HANDLE hEventSrc, ESGC_EVENT_TYPE type, ESGC_EVENT_HANDLE *phEventOut)
{
COMMON_PRECONDITION
return pService->ESGCRegisterEvent(hEventSrc, type, phEventOut);
}
ESGC_API ESGCEventGetData(ESGC_EVENT_HANDLE hEvent, void *pBuffer, size_t *piSize, uint64_t iTimeout)
{
COMMON_PRECONDITION
return pService->ESGCEventGetData(hEvent, pBuffer, piSize, iTimeout);
}
}
}
| [
"50533057+emilroy02@users.noreply.github.com"
] | 50533057+emilroy02@users.noreply.github.com |
6b97a04470e9750b58efc09ea5f3a352e582058e | 711e5c8b643dd2a93fbcbada982d7ad489fb0169 | /XPSP1/NT/printscan/ui/printui/psetup.cxx | b1967d3ebe9e5c027d7742c992c1aee55aa00123 | [] | no_license | aurantst/windows-XP-SP1 | 629a7763c082fd04d3b881e0d32a1cfbd523b5ce | d521b6360fcff4294ae6c5651c539f1b9a6cbb49 | refs/heads/master | 2023-03-21T01:08:39.870106 | 2020-09-28T08:10:11 | 2020-09-28T08:10:11 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 11,776 | cxx | /*++
Copyright (C) Microsoft Corporation, 1996 - 1998
All rights reserved.
Module Name:
PSetup.cxx
Abstract:
Printer setup class to gain access to the ntprint.dll
setup code.
Author:
Steve Kiraly (SteveKi) 19-Jan-1996
Revision History:
--*/
#include "precomp.hxx"
#pragma hdrstop
#include "psetup.hxx"
#include "psetup5.hxx"
#include "drvver.hxx"
/********************************************************************
Printer setup class.
********************************************************************/
TPSetup::
TPSetup(
VOID
) : _bValid( FALSE ),
_pPSetup50( NULL )
{
//
// Attemp to load the 5.0 version.
//
_pPSetup50 = new TPSetup50();
if( VALID_PTR( _pPSetup50 ) )
{
_bValid = TRUE;
return;
} else {
delete _pPSetup50;
_pPSetup50 = NULL;
}
}
TPSetup::
~TPSetup(
VOID
)
{
delete _pPSetup50;
}
BOOL
TPSetup::
bValid(
VOID
)
{
return _bValid;
}
/********************************************************************
Member functions, most of these functions are just a channing
call to the valid verion of the setup library.
********************************************************************/
HDEVINFO
TPSetup::
PSetupCreatePrinterDeviceInfoList(
IN HWND hwnd
)
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupCreatePrinterDeviceInfoList( hwnd );
}
return INVALID_HANDLE_VALUE;
}
VOID
TPSetup::
PSetupDestroyPrinterDeviceInfoList(
IN HDEVINFO h
)
{
if( _pPSetup50 )
{
_pPSetup50->PSetupDestroyPrinterDeviceInfoList( h );
}
}
BOOL
TPSetup::
PSetupProcessPrinterAdded(
IN HDEVINFO hDevInfo,
IN HANDLE hLocalData,
IN LPCTSTR pszPrinterName,
IN HWND hwnd
)
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupProcessPrinterAdded( hDevInfo, (PPSETUP_LOCAL_DATA)hLocalData, pszPrinterName, hwnd );
}
return FALSE;
}
BOOL
TPSetup::
bGetSelectedDriverName(
IN HANDLE hLocalData,
IN OUT TString &strDriverName,
IN PLATFORM platform
) const
{
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = DRIVER_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strDriverName.bUpdate( DrvField.pszDriverName );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
BOOL
TPSetup::
bGetSelectedPrintProcessorName(
IN HANDLE hLocalData,
IN OUT TString &strPrintProcessor,
IN PLATFORM platform
) const
{
//
// This is only supported on NT5 version.
//
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = PRINT_PROCESSOR_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strPrintProcessor.bUpdate( DrvField.pszPrintProc );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
BOOL
TPSetup::
bGetSelectedInfName(
IN HANDLE hLocalData,
IN OUT TString &strInfName,
IN PLATFORM platform
) const
{
if( _pPSetup50 )
{
TStatusB bStatus;
DRIVER_FIELD DrvField;
DrvField.Index = INF_NAME;
bStatus DBGCHK = _pPSetup50->PSetupGetLocalDataField( (PPSETUP_LOCAL_DATA)hLocalData, platform, &DrvField );
if( bStatus )
{
bStatus DBGCHK = strInfName.bUpdate( DrvField.pszInfName );
_pPSetup50->PSetupFreeDrvField( &DrvField );
}
return bStatus;
}
return NULL;
}
DWORD
TPSetup::
PSetupInstallPrinterDriver(
IN HDEVINFO h,
IN HANDLE hLocalData,
IN LPCTSTR pszDriverName,
IN PLATFORM platform,
IN DWORD dwVersion,
IN LPCTSTR pszServerName,
IN HWND hwnd,
IN LPCTSTR pszPlatformName,
IN LPCTSTR pszSourcePath,
IN DWORD dwInstallFlags,
IN DWORD dwAddDrvFlags,
OUT TString *pstrNewDriverName,
IN BOOL bOfferReplacement
)
{
DWORD dwRet = ERROR_INVALID_FUNCTION;
if (_pPSetup50)
{
LPTSTR pszNewDriverName = NULL;
PPSETUP_LOCAL_DATA pLocalData = (PPSETUP_LOCAL_DATA)hLocalData;
if (!bOfferReplacement)
{
// request from ntprint to suppress the driver replacement offering
dwInstallFlags |= DRVINST_DONT_OFFER_REPLACEMENT;
}
// call ntprint.dll ....
dwRet = _pPSetup50->PSetupInstallPrinterDriver(h, pLocalData, pszDriverName, platform, dwVersion,
pszServerName, hwnd, pszPlatformName, pszSourcePath, dwInstallFlags, dwAddDrvFlags, &pszNewDriverName);
// check to return the replacement driver name (if any)
if (ERROR_SUCCESS == dwRet && pszNewDriverName && pszNewDriverName[0] && pstrNewDriverName)
{
if (!pstrNewDriverName->bUpdate(pszNewDriverName))
{
dwRet = ERROR_OUTOFMEMORY;
}
}
if (pszNewDriverName)
{
// free up the memory allocated from ntprint
_pPSetup50->PSetupFreeMem(pszNewDriverName);
}
}
return dwRet;
}
HANDLE
TPSetup::
PSetupGetSelectedDriverInfo(
IN HDEVINFO h
)
{
HANDLE hHandle = NULL;
if( _pPSetup50 )
hHandle = _pPSetup50->PSetupGetSelectedDriverInfo( h );
return hHandle == NULL ? INVALID_HANDLE_VALUE : hHandle ;
}
HANDLE
TPSetup::
PSetupDriverInfoFromName(
IN HDEVINFO h,
IN LPCTSTR pszModel
)
{
HANDLE hHandle = NULL;
if( _pPSetup50 )
hHandle = _pPSetup50->PSetupDriverInfoFromName( h, pszModel );
return hHandle == NULL ? INVALID_HANDLE_VALUE : hHandle ;
}
VOID
TPSetup::
PSetupDestroySelectedDriverInfo(
IN HANDLE hLocalData
)
{
if( _pPSetup50 )
{
_pPSetup50->PSetupDestroySelectedDriverInfo( (PPSETUP_LOCAL_DATA)hLocalData );
}
}
BOOL
TPSetup::
PSetupIsDriverInstalled(
IN LPCTSTR pszServerName,
IN LPCTSTR pszDriverName,
IN PLATFORM platform,
IN DWORD dwMajorVersion
) const
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupIsDriverInstalled( pszServerName, pszDriverName, platform, dwMajorVersion );
}
return FALSE;
}
INT
TPSetup::
PSetupIsTheDriverFoundInInfInstalled(
IN LPCTSTR pszServerName,
IN HANDLE hLocalData,
IN PLATFORM platform,
IN DWORD dwMajorVersion,
IN DWORD dwMajorVersion2
) const
{
if( _pPSetup50 )
{
return _pPSetup50->PSetupIsTheDriverFoundInInfInstalled( pszServerName, (PPSETUP_LOCAL_DATA)hLocalData, platform, dwMajorVersion2 );
}
return DRIVER_MODEL_NOT_INSTALLED;
}
BOOL
TPSetup::
PSetupSelectDriver(
IN HDEVINFO h,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDriver( h );
return FALSE;
}
BOOL
TPSetup::
PSetupRefreshDriverList(
IN HDEVINFO h
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupRefreshDriverList( h );
return FALSE;
}
BOOL
TPSetup::
PSetupPreSelectDriver(
IN HDEVINFO h,
IN LPCTSTR pszManufacturer,
IN LPCTSTR pszModel
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupPreSelectDriver( h, pszManufacturer, pszModel );
return FALSE;
}
HPROPSHEETPAGE
TPSetup::
PSetupCreateDrvSetupPage(
IN HDEVINFO h,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupCreateDrvSetupPage( h, hwnd );
return NULL;
}
HANDLE
TPSetup::
PSetupCreateMonitorInfo(
IN LPCTSTR pszServerName,
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupCreateMonitorInfo( hwnd, pszServerName);
return NULL;
}
VOID
TPSetup::
PSetupDestroyMonitorInfo(
IN OUT HANDLE h
)
{
if( _pPSetup50 )
_pPSetup50->PSetupDestroyMonitorInfo( h );
}
BOOL
TPSetup::
PSetupEnumMonitor(
IN HANDLE h,
IN DWORD dwIndex,
OUT LPTSTR pMonitorName,
IN OUT LPDWORD pdwSize
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupEnumMonitor( h, dwIndex, pMonitorName, pdwSize );
return FALSE;
}
BOOL
TPSetup::
PSetupInstallMonitor(
IN HWND hwnd
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupInstallMonitor( hwnd );
return FALSE;
}
BOOL
TPSetup::
PSetupBuildDriversFromPath(
IN HANDLE h,
IN LPCTSTR pszDriverPath,
IN BOOL bEnumSingleInf
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupBuildDriversFromPath( h, pszDriverPath, bEnumSingleInf );
return FALSE;
}
BOOL
TPSetup::
PSetupSetSelectDevTitleAndInstructions(
IN HDEVINFO hDevInfo,
IN LPCTSTR pszTitle,
IN LPCTSTR pszSubTitle,
IN LPCTSTR pszInstn
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupSetSelectDevTitleAndInstructions( hDevInfo, pszTitle, pszSubTitle, pszInstn );
return FALSE;
}
DWORD
TPSetup::
PSetupInstallPrinterDriverFromTheWeb(
IN HDEVINFO hDevInfo,
IN HANDLE pLocalData,
IN PLATFORM platform,
IN LPCTSTR pszServerName,
IN LPOSVERSIONINFO pOsVersionInfo,
IN HWND hwnd,
IN LPCTSTR pszSource
)
{
if( _pPSetup50 )
return _pPSetup50->PSetupInstallPrinterDriverFromTheWeb( hDevInfo, (PPSETUP_LOCAL_DATA)pLocalData, platform, pszServerName, pOsVersionInfo, hwnd, pszSource );
return ERROR_INVALID_FUNCTION;
}
BOOL
TPSetup::
PSetupIsOemDriver(
IN HDEVINFO hDevInfo,
IN HANDLE pLocalData,
IN OUT PBOOL pbIsOemDriver
) const
{
if( _pPSetup50 )
return _pPSetup50->PSetupIsOemDriver( hDevInfo, (PPSETUP_LOCAL_DATA)pLocalData, pbIsOemDriver );
SetLastError( ERROR_INVALID_FUNCTION );
return FALSE;
}
BOOL
TPSetup::
PSetupSetWebMode(
IN HDEVINFO hDevInfo,
IN BOOL bWebButtonOn
)
{
DWORD dwFlagsSet = bWebButtonOn ? SELECT_DEVICE_FROMWEB : 0;
DWORD dwFlagsClear = bWebButtonOn ? 0 : SELECT_DEVICE_FROMWEB;
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDeviceButtons( hDevInfo, dwFlagsSet, dwFlagsClear );
return FALSE;
}
BOOL
TPSetup::
PSetupShowOem(
IN HDEVINFO hDevInfo,
IN BOOL bShowOem
)
{
DWORD dwFlagsSet = bShowOem ? SELECT_DEVICE_HAVEDISK : 0;
DWORD dwFlagsClear = bShowOem ? 0 : SELECT_DEVICE_HAVEDISK;
if( _pPSetup50 )
return _pPSetup50->PSetupSelectDeviceButtons( hDevInfo, dwFlagsSet, dwFlagsClear );
return FALSE;
}
| [
"112426112@qq.com"
] | 112426112@qq.com |
44d019c7bb8f218518aae7a873dba7a528747f63 | de9f878d6e062dd7d60f9ab746aab7f5063ce251 | /run/abl/fullScale/fullScaleTurbArRefined2/constant/polyMesh/boundary | 189b56c110d67d3fd4b50f54c920e8c5cc6d157b | [] | no_license | stevietran/foam5 | ba2c03a263fef2480045d51267159838d83b1a0c | 256f7fd317b18df59208ffcd63e96d36e81bf62f | refs/heads/master | 2021-10-27T19:43:03.709356 | 2019-04-19T06:54:30 | 2019-04-19T06:54:30 | 167,189,514 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,687 | /*--------------------------------*- C++ -*----------------------------------*\
| ========= | |
| \\ / F ield | OpenFOAM: The Open Source CFD Toolbox |
| \\ / O peration | Version: 5.x |
| \\ / A nd | Web: www.OpenFOAM.org |
| \\/ M anipulation | |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class polyBoundaryMesh;
location "constant/polyMesh";
object boundary;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
6
(
frontField
{
type patch;
nFaces 172;
startFace 205628;
}
backField
{
type patch;
nFaces 172;
startFace 205800;
}
symPlane
{
type empty;
inGroups 1(empty);
nFaces 103200;
startFace 205972;
}
sideField
{
type empty;
inGroups 1(empty);
nFaces 103200;
startFace 309172;
}
ground
{
type wall;
inGroups 1(wall);
nFaces 600;
startFace 412372;
}
top
{
type patch;
nFaces 600;
startFace 412972;
}
)
// ************************************************************************* //
| [
"tranlevu001@e.ntu.edu.sg"
] | tranlevu001@e.ntu.edu.sg |
|
229b0831ae5f293cee1d21244c3afbbcafd2416c | 49cf7c9e66c9b93423f5c1323f79e383c60b25bf | /puzzle_heur.cpp | 2190ab593633b3a3fa1500ad8d2e016a44033d04 | [] | no_license | sahilagar/Puzzle-Solver | aecdbd9d1303ca8be3170eef6b1814596a0a5278 | 3b8f227cd165c17616cd42598c21e73c7c725995 | refs/heads/master | 2021-07-04T13:57:21.505282 | 2017-09-27T16:51:21 | 2017-09-27T16:51:21 | 105,044,539 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 752 | cpp | #include "puzzle_heur.h"
#include <cmath>
using namespace std;
int PuzzleManhattanHeuristic::compute(const Board& b)
{
int count = 0;
for (int i = 1; i < b.size(); i++){
int numIndex = -1;
for (int j = 0; j < b.size(); j++){
if (b[j] == i){ //find actual num index
numIndex = j;
break;
}
}
int rCorrect = i/b.dim();
int cCorrect = i%b.dim();
int rActual = numIndex/b.dim();
int cActual = numIndex%b.dim();
count += abs(rActual - rCorrect) + abs(cActual - cCorrect);
}
return count;
}
int PuzzleOutOfPlaceHeuristic::compute(const Board& b)
{
int count = 0;
for (int i=1; i < b.size(); i++)
{
if (b[i] != i){
count++;
}
}
return count;
}
int PuzzleBFSHeuristic::compute(const Board& b)
{
return 0;
} | [
"sahilagarwal@Sahils-MacBook-Pro.local"
] | sahilagarwal@Sahils-MacBook-Pro.local |
2792174f5436fefff6147afec3171ef6c531d2a5 | 366d1b9a999aaa856a325ae80268af20b995babe | /src/shogun/statistical_testing/internals/InitPerKernel.cpp | 960707e6d5a98c3ea39d5e200207654544fa45bb | [
"BSD-3-Clause",
"DOC",
"GPL-3.0-only"
] | permissive | karlnapf/shogun | bc3fcbeef377b8157bd8a9639211c2667b535846 | eebce07a4309bb7e1d3a4f0981efd49e687533b6 | refs/heads/develop | 2020-04-05T22:46:38.369312 | 2019-07-09T08:59:14 | 2019-07-09T08:59:14 | 4,420,161 | 1 | 1 | BSD-3-Clause | 2018-09-04T10:50:41 | 2012-05-23T13:12:40 | C++ | UTF-8 | C++ | false | false | 2,179 | cpp | /*
* Copyright (c) The Shogun Machine Learning Toolbox
* Written (w) 2016 - 2017 Soumyajit De
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* 2. 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.
*
* 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.
*
* The views and conclusions contained in the software and documentation are those
* of the authors and should not be interpreted as representing official policies,
* either expressed or implied, of the Shogun Development Team.
*/
#include <shogun/kernel/Kernel.h>
#include <shogun/statistical_testing/internals/InitPerKernel.h>
using namespace shogun;
using namespace internal;
InitPerKernel::InitPerKernel(std::shared_ptr<CKernel>& kernel) : m_kernel(kernel)
{
}
InitPerKernel::~InitPerKernel()
{
}
InitPerKernel& InitPerKernel::operator=(CKernel* kernel)
{
SG_REF(kernel);
m_kernel = std::shared_ptr<CKernel>(kernel, [](CKernel* ptr) { SG_UNREF(ptr); });
return *this;
}
InitPerKernel::operator CKernel*() const
{
return m_kernel.get();
}
| [
"heavensdevil6909@gmail.com"
] | heavensdevil6909@gmail.com |
c4823df5c6e89b24a3d4fd3e71b0219e41645a54 | b2c7b04f9a31cd3dbf837af7729df5e221528c05 | /Shooters!/SceneBase.h | 8c1d73db373a6251faa1b61ffea48e199cebbb0d | [] | no_license | Nati-Ryuon/Shooters | dddd756e3c930dddc4e38882424fee6bbbfc8b07 | 012bbd11c7dcc82fbf9ee069903d2b6035301628 | refs/heads/master | 2020-03-28T20:50:07.485546 | 2018-12-24T08:25:35 | 2018-12-24T08:25:35 | 149,106,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 802 | h | #pragma once
#include <memory>
/*
class SceneBase {
public:
virtual void draw() = 0;
virtual void update() = 0;
bool isFinished() {
return false;
}
std::unique_ptr<SceneBase> getNextScene() {
return next.get;
}
std::unique_ptr<SceneBase> getReturnScene() {
return prev.get;
}
std::unique_ptr<SceneBase> next;
std::unique_ptr<SceneBase> prev;
};
*/
class SceneBase {
protected:
bool returnScene;
bool saveScene;
std::unique_ptr<SceneBase> nextScene;
public:
SceneBase() : returnScene(false), nextScene(nullptr), saveScene(false) {}
bool isFinished() const;
bool getReturnScene() const;
bool getSaveScene() const;
bool nextSceneNullCheck() const { return nextScene != nullptr; }
std::unique_ptr<SceneBase> getNextScene();
virtual void draw() = 0;
virtual void update() = 0;
}; | [
"aries.zata@gmail.com"
] | aries.zata@gmail.com |
42a8a896b7485afff4ef829ca7203c98d5d9a801 | deb442f461c572cc4c241964ae1793f0b38767f8 | /WorldFinals/2011/D/D.cc | 377ee028272de77807fdd932b8ab20515f5cabbd | [] | no_license | yuha/ICPC | ef0c83bddf01f19db214d05a36dfc56a08f0192b | 4073e03ef904c0b2f77424b836265a35632d3014 | refs/heads/master | 2021-01-10T19:20:55.143360 | 2012-08-09T05:26:47 | 2012-08-09T05:26:47 | 2,208,133 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,101 | cc | #include <iostream>
#include <vector>
#include <map>
#include <cassert>
#include <climits>
#include <cstdlib>
using namespace std;
typedef vector<int> vi;
typedef vector<vi> vvi;
#define IN(x) (2*(x))
#define OUT(x) (2*(x)+1)
const int LARGE_COST = 10000;
ostream& operator<<(ostream& out, const vi& v)
{
for (int i = 0; i < v.size(); ++i) {
if (i) { out << ','; }
out << v[i];
}
return out;
}
// 閉路を1つ返す。
// 閉路がない場合は false を返す。
bool findLoopFrom(int N, const vvi& capacity, const vvi& costs, const vvi& flow, int s, vi& path)
{
vi dists(2*N, INT_MAX / 1000);
dists[s] = 0;
bool changed = true;
for (int k = 0; changed && k < 2*N; ++k) {
changed = false;
for (int i = 0; i < 2*N; ++i) {
for (int j = 0; j < 2*N; ++j) {
// i->j へ行ける?
if (capacity[i][j] - flow[i][j] > 0) {
if (dists[i] + costs[i][j] < dists[j]) {
dists[j] = dists[i] + costs[i][j];
path[j] = i;
changed = true;
}
}
// i->j へ、j->i をもとに戻りながらいける
if (flow[j][i] > 0) {
if (dists[i] - costs[j][i] < dists[j]) {
dists[j] = dists[i] - costs[j][i];
path[j] = -i - 1;
changed = true;
}
}
if (j == s && dists[s] < 0) {
return true;
}
}
}
}
// 負の閉路がある場合は実行可能
return dists[s] < 0;
}
// TODO: この関数は美しくない
bool findLoop(int N, const vvi& capacity, const vvi& costs, const vvi& flow,
int& s, vi& path)
{
for (s = 0; s < 2*N; ++s) {
bool foundLoop = true;
while (foundLoop && findLoopFrom(N, capacity, costs, flow, s, path)) {
foundLoop = false;
// path をたどって s から始まっているか確認......
// TODO: する必要はないんだけど...
vi visited(2*N, 0);
int prev, curr = s;
visited[curr] = true;
while (true) {
prev = curr;
curr = path[prev];
if (curr >= 0) {
} else {
curr = -curr - 1;
}
if (visited[curr]) {
if (curr == s)
return true;
break;
} else {
visited[curr] = true;
}
}
if (foundLoop)
return true;
}
}
return false;
}
void maxFlow(int N, const vvi& capacity, const vvi& costs, vvi& flow)
{
int s;
vi path(2*N);
while (findLoop(N, capacity, costs, flow, s, path)) {
int curr = s;
do {
int prev = curr;
curr = path[prev];
if (curr >= 0) {
// prev -> curr へ、flow を1つ増やす。
flow[curr][prev] += 1;
} else {
curr = -curr - 1;
// curr -> prev へ、flow を1つ減らす。
flow[prev][curr] -= 1;
}
} while (curr != s);
}
}
int solve(int N, int A, int B, int componentCount, vvi caps, const vvi& costs)
{
int ans = 0;
vvi flow(2*N, vi(2*N));
for (int m = 0; m <= N; ++m) {
// cout << "m = " << m << endl;
// capacity を更新
for (int i = 0; i < N; ++i) {
caps[IN(i)][OUT(i)] = m;
}
maxFlow(N, caps, costs, flow);
// ans の数を数える
int totalAns = 0;
int totalCost = 0;
for (int i = 0; i < N; ++i) {
for (int j = 0; j < N; ++j) {
if (flow[OUT(i)][IN(j)]) {
++totalAns;
// cout << "i -> j : " << i << " -> " << j << endl;
totalCost += costs[OUT(i)][IN(j)];
// cout << 1 << ' ';
} else {
// cout << 0 << ' ';
}
}
// cout << endl;
}
#if 0
cout << "component = " << componentCount << endl;
cout << "totalAns = " << totalAns << endl;
cout << "totalCost = " << totalCost << endl;
cout << "required = " << (-componentCount * LARGE_COST) << endl;
cout << "A, B, m = " << A << "," << B << "," << m << endl;
cout << m * B << endl;
cout << A * totalAns << endl;
#endif
// m <= A/B * totalAns
if (m * B <= A * totalAns && ans < totalAns && totalCost <= -componentCount * LARGE_COST)
ans = totalAns;
}
return ans;
}
int main(void)
{
int caseNo = 0;
for (int N, A, B; cin >> N >> A >> B, (N || A || B); ) {
vvi capacities(2*N, vi(2*N));
vvi costs(2*N, vi(2*N));
int componentCount = 0;
for (int i = 0; i < N; ++i) {
string s; cin >> s;
for (int j = 0; j < N; ++j) {
switch (s[j]) {
case '/':
break;
case 'C':
costs[OUT(i)][IN(j)] = -LARGE_COST;
capacities[OUT(i)][IN(j)] = 1;
++componentCount;
break;
case '.':
costs[OUT(i)][IN(j)] = -1;
capacities[OUT(i)][IN(j)] = 1;
break;
default:
cout << "!" << s[j] << endl;
abort();
break;
}
}
}
int ans = solve(N, A, B, componentCount, capacities, costs) - componentCount;
cout << "Case " << ++caseNo << ": ";
if (ans < 0)
cout << "impossible" << endl;
else
cout << ans << endl;
}
return 0;
}
| [
"mayah@mayah.jp"
] | mayah@mayah.jp |
650c27721a016095b964b2c24c75261215ae9007 | 46a1bfb511c488f85cc5d030ac5824b3c4995f66 | /Source/PyramidGame/Litetspel_Horus_Pyramid/Litetspel_Horus_Pyramid/Chain.h | 986695cc13f4846a6d24e912b15e975dca5a22c2 | [] | no_license | 0Oskar/G4_HillClimber | 43086ae0d26ca508acf13cd941dcf6ba6db13dee | 34dbcfd1be6b470308c0f1f19f0634aed3625193 | refs/heads/development | 2023-08-17T12:15:51.808041 | 2023-08-05T15:03:46 | 2023-08-05T15:03:46 | 251,297,246 | 2 | 0 | null | 2020-06-03T00:22:20 | 2020-03-30T12:26:17 | C++ | UTF-8 | C++ | false | false | 935 | h | #pragma once
#include "GameObject.h"
#define NR_OF_CHAIN_LINKS 128
class Chain
{
private:
bool m_visible;
bool m_shooting;
bool m_retracting;
Timer m_timer;
std::vector<GameObject*>* m_chainGObjects;
std::vector<bool> m_retractedLinks;
int m_nrOfUnretractedLinks;
GameObject* m_hookGObject;
GameObject* m_gaunletGObject;
XMVECTOR m_gauntletSpawnPosition;
float m_constant;
float m_linkLength;
float m_friction;
void simulateLinks(GameObject* link1, GameObject* link2, bool notFirst, float dt);
void linkRetractionUpdate();
void calculateGauntletLinkSpawnPosition();
public:
Chain();
~Chain();
void initialize(GameObject* hookGObject, GameObject* gaunletGObject, std::vector<GameObject*>* chainGObjects);
bool isVisible() const;
XMVECTOR getLinkPosition(uint32_t index);
void setVisibility(bool visible);
void setShooting(bool shooting);
void setRetracting(bool retracting);
void update(float dt);
}; | [
"medoosman@outlook.com"
] | medoosman@outlook.com |
2d0ac43f098bdf62be7402dd14eabc5830ba92da | 40ae1b4dd9c8bb8afe70b32994219dea18fd40af | /lib/src/resource/make.h | 8397662fa41cccb1266f67280cbedf3a64b7786d | [
"Apache-2.0"
] | permissive | gejza/xcdev | 817fe25462e8d3ed1bc032123da464eedc3d1f2e | 769b4f84bfb3e0972cc2aa743a0f70d271add138 | refs/heads/master | 2021-01-10T20:51:28.090672 | 2011-02-20T21:31:26 | 2011-02-20T21:31:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,442 | h | /*
File name: cbmake.h
Date: 2010/12/05 21:07
Subversion: $Id: $
Author: Milan Dunghubel <milan@mfis.cz>
Copyright (C) 2010 Milan Dunghubel <milan@mfis.cz>
*/
#ifndef _XC_CBMAKE_H_
#define _XC_CBMAKE_H_
#pragma once
#include <memory>
#include "cbdef.h"
class DBMake_t;
enum TableId_t
{
NS_TABLE = 2,
STR_TABLE = 23,
};
using namespace xc;
class Output_t
{
public:
virtual ~Output_t() {}
virtual void add(uint32_t table, const void*, size_t, const void*, size_t) = 0;
};
class Make_t
{
public:
Make_t(Output_t& out);
virtual ~Make_t();
void set_default(Lang_t lang) {
this->_def_lang = lang;
}
// string
StrId_t string(const char* str) {
return this->string(this->_def_lang, str);
}
StrId_t string(Lang_t lang, const char* str);
void string(const StrId_t id, Lang_t lang, const char* str);
void string(const std::string& msgid, const std::string& msgstr, Lang_t lang);
// hook
//void hook(const char* name, const Callback_t& cb);
// alias
void alias(const char* route, Lang_t lang, const char* alias);
Id_t add(const Menu_t& menu);
void add(const Template_t& templ);
// debug
const char* get_lang(Lang_t lang);
protected:
Id_t seq()
{
return ++_curid;
}
private:
Output_t& _out;
Lang_t _def_lang;
Id_t _curid;
};
#endif // _XC_CBMAKE_H_
/* end of cbmake.h */
| [
"gejza@gejza.net"
] | gejza@gejza.net |
2eb6aa9132fd0fd4b49550bb00964ef5d2c3b8f5 | a1d860da5b160fa48b8ab62ea204e1cae6655c61 | /SampleEnclave4CUDA/StorageEnclave/StorageEnclave.cpp | baec2b366d23db1c0f4019d3e902a4c40a328774 | [] | no_license | ECS-251-W2020/final-project-group-4 | 813584f4812dbf8b37742e84d57df480b371bebf | 1e5755b158585cfe810c4a9b9ce9768da831923c | refs/heads/master | 2021-01-06T05:51:49.278306 | 2020-03-16T02:33:45 | 2020-03-16T02:33:45 | 241,226,884 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 3,657 | cpp | #include "StorageEnclave_t.h"
#include "sgx_trts.h"
#include "../CUDADemo/constant.h"
unsigned char my_secret_arr[AES_NB] = {0};
unsigned char my_exp_key[AES_EXP_NB] = { 0 };
const unsigned char box_enclave[256] = {
// 0 1 2 3 4 5 6 7 8 9 a b c d e f
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, // 0
0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, // 1
0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, // 2
0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, // 3
0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, // 4
0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, // 5
0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, // 6
0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, // 7
0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, // 8
0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, // 9
0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, // a
0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, // b
0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, // c
0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, // d
0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, // e
0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 };// f
// Round Keys
const unsigned char rcon_enclave[10] = {
0x01, 0x02, 0x04, 0x08, 0x10,
0x20, 0x40, 0x80, 0x1b, 0x36 };
void key_expansion_enclave(unsigned char* key, unsigned char* w) {
unsigned char r, i, j, k, col[4];
col[0] = 0; col[1] = 0; col[2] = 0; col[3] = 0;
// first round key is just the key
for (j = 0; j < AES_NB; j++) {
for (i = 0; i < 4; i++) {
w[AES_NK * i + j] = key[AES_NK * i + j];
}
}
for (r = 1; r < AES_NR + 1; r++) {
for (j = 0; j < AES_NK; j++) {
for (i = 0; i < 4; i++) {
if (j % AES_NK != 0) {
col[i] = w[r * AES_NB + AES_NK * i + j - 1];
}
else {
col[i] = w[(r - 1) * AES_NB + AES_NK * i + AES_NK - 1];
}
}
if (j % AES_NK == 0) {
// rotate 4 bytes in word
k = col[0];
col[0] = col[1];
col[1] = col[2];
col[2] = col[3];
col[3] = k;
col[0] = box_enclave[col[0]];
col[1] = box_enclave[col[1]];
col[2] = box_enclave[col[2]];
col[3] = box_enclave[col[3]];
col[0] = col[0] ^ rcon_enclave[r - 1];
}
w[r * AES_NB + AES_NK * 0 + j] = w[(r - 1) * AES_NB + AES_NK * 0 + j] ^ col[0];
w[r * AES_NB + AES_NK * 1 + j] = w[(r - 1) * AES_NB + AES_NK * 1 + j] ^ col[1];
w[r * AES_NB + AES_NK * 2 + j] = w[(r - 1) * AES_NB + AES_NK * 2 + j] ^ col[2];
w[r * AES_NB + AES_NK * 3 + j] = w[(r - 1) * AES_NB + AES_NK * 3 + j] ^ col[3];
}
}
}
void set_secret4(unsigned char* secret) {
for (int i = 0; i < AES_NB; ++i) {
my_secret_arr[i] = secret[i];
}
key_expansion_enclave(my_secret_arr, my_exp_key);
}
void print_secret() {
ocall_print_secret(my_secret_arr);
}
void copy_secret_to_device(void *devicePtr) {
ocall_send_to_device(my_exp_key, devicePtr);
}
| [
"linmx0130@gmail.com"
] | linmx0130@gmail.com |
257e109cc0bc6baba7d73ddad1c0a57259d9f6f6 | d40efadec5724c236f1ec681ac811466fcf848d8 | /branches/Launcher_5_5/TabMOD.h | 198cb2c57e1e21c2b40eba9a713bc0922ca5ea88 | [] | no_license | svn2github/fs2open | 0fcbe9345fb54d2abbe45e61ef44a41fa7e02e15 | c6d35120e8372c2c74270c85a9e7d88709086278 | refs/heads/master | 2020-05-17T17:37:03.969697 | 2015-01-08T15:24:21 | 2015-01-08T15:24:21 | 14,258,345 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,991 | h | #if !defined(AFX_TABMOD_H__FB07B738_1087_4CB8_81B2_69E9FCC068FE__INCLUDED_)
#define AFX_TABMOD_H__FB07B738_1087_4CB8_81B2_69E9FCC068FE__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// TabMOD.h : header file
//
#include <string>
/////////////////////////////////////////////////////////////////////////////
// CTabMOD dialog
class CTabMOD : public CDialog
{
// Construction
public:
CTabMOD(CWnd* pParent = NULL); // standard constructor
void SetMOD(char *absolute_path);
void GetModCommandLine(std::string &result);
void GetActiveModName(char *result);
void SetSettings(const std::string &flags);
char *GetSettings(bool defaultSettings = false);
void OnApply(int flags);
void LoadSettings(int flags);
// Dialog Data
//{{AFX_DATA(CTabMOD)
enum { IDD = IDD_MOD };
CStatic m_mod_image;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CTabMOD)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CTabMOD)
afx_msg void OnModSelect();
afx_msg void OnModNone();
afx_msg void OnModWebsite();
afx_msg void OnModForum();
afx_msg void OnDestroy();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
HBITMAP LoadBitmap(char * path);
void SetMODImage(char *path);
void SetModName(char *path, char *name);
bool parse_ini_file(char * ini_name);
void CheckModSetting(char *mod_string);
private:
HBITMAP MOD_bitmap;
enum
{
INI_MOD_NAME,
INI_IMAGE_NAME,
INI_MOD_TEXT,
INI_URL_WEBSITE,
INI_URL_FORUM,
INI_MOD_PRI,
INI_MOD_SEC,
INI_MAX
};
bool mod_selected;
char *ini_text[INI_MAX];
char m_absolute_text[MAX_PATH];
char m_active_mod_name[MAX_PATH];
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_TABMOD_H__FB07B738_1087_4CB8_81B2_69E9FCC068FE__INCLUDED_)
| [
"taylor@387891d4-d844-0410-90c0-e4c51a9137d3"
] | taylor@387891d4-d844-0410-90c0-e4c51a9137d3 |
ffa815ce6cc0de319fff1413ad581dffa5330be7 | cf7e0b065f3edbb38b4d8bdf4d63d51fc3b0106f | /src/ocio/src/core/Mutex.h | 421ad29f59f0253cdb978d75ad5b4fde2b46c722 | [
"BSD-3-Clause",
"MIT",
"Zlib"
] | permissive | appleseedhq/windows-deps | 06478bc8ec8f4a9ec40399b763a038e5a76dfbf7 | 7955c4fa1c9e39080862deb84f5e4ddf0cf71f62 | refs/heads/master | 2022-11-21T07:16:35.646878 | 2019-12-11T19:46:46 | 2020-07-19T08:57:23 | 16,730,675 | 5 | 8 | null | 2020-07-19T08:57:25 | 2014-02-11T12:54:46 | C++ | UTF-8 | C++ | false | false | 4,229 | h | /*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
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 Sony Pictures Imageworks 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.
*/
#ifndef INCLUDED_OCIO_MUTEX_H
#define INCLUDED_OCIO_MUTEX_H
/*
PTEX SOFTWARE
Copyright 2009 Disney Enterprises, 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.
* The names "Disney", "Walt Disney Pictures", "Walt Disney Animation
Studios" or the names of its contributors may NOT be used to
endorse or promote products derived from this software without
specific prior written permission from Walt Disney Pictures.
Disclaimer: THIS SOFTWARE IS PROVIDED BY WALT DISNEY PICTURES AND
CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE ARE DISCLAIMED.
IN NO EVENT SHALL WALT DISNEY PICTURES, THE COPYRIGHT HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND BASED 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 DAMAGES.
*/
#include "Platform.h"
// #define DEBUG_THREADING
/** For internal use only */
OCIO_NAMESPACE_ENTER
{
#ifndef NDEBUG
template <class T>
class DebugLock : public T {
public:
DebugLock() : _locked(0) {}
void lock() { T::lock(); _locked = 1; }
void unlock() { assert(_locked); _locked = 0; T::unlock(); }
bool locked() { return _locked != 0; }
private:
int _locked;
};
#endif
/** Automatically acquire and release lock within enclosing scope. */
template <class T>
class AutoLock {
public:
AutoLock(T& m) : _m(m) { _m.lock(); }
~AutoLock() { _m.unlock(); }
private:
T& _m;
};
#ifndef NDEBUG
// add debug wrappers to mutex and spinlock
typedef DebugLock<_Mutex> Mutex;
typedef DebugLock<_SpinLock> SpinLock;
#else
typedef _Mutex Mutex;
typedef _SpinLock SpinLock;
#endif
typedef AutoLock<Mutex> AutoMutex;
typedef AutoLock<SpinLock> AutoSpin;
}
OCIO_NAMESPACE_EXIT
#endif
| [
"franz@appleseedhq.net"
] | franz@appleseedhq.net |
d6396a9f479955e4ed86937e7158790955ed26bd | 2bcf5e8abe74cd6bad2d0c14c8a4a2527a085bb7 | /devel/include/canbus/candata.h | 8cdd709f1def7ada403eb10b1b34893215929b84 | [] | no_license | mr-d-self-driving/ROS_Intell_Driving | 2b05efd336a82cce9e3a1d7d4aab137d36f44a57 | 1781959b4c447ce8369f3fd2bb82f3708daee8cc | refs/heads/master | 2022-01-12T15:54:23.729563 | 2019-06-11T10:01:02 | 2019-06-11T10:01:02 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,941 | h | // Generated by gencpp from file canbus/candata.msg
// DO NOT EDIT!
#ifndef CANBUS_MESSAGE_CANDATA_H
#define CANBUS_MESSAGE_CANDATA_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace canbus
{
template <class ContainerAllocator>
struct candata_
{
typedef candata_<ContainerAllocator> Type;
candata_()
: id(0)
, data() {
data.assign(0);
}
candata_(const ContainerAllocator& _alloc)
: id(0)
, data() {
(void)_alloc;
data.assign(0);
}
typedef uint32_t _id_type;
_id_type id;
typedef boost::array<uint8_t, 8> _data_type;
_data_type data;
typedef boost::shared_ptr< ::canbus::candata_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::canbus::candata_<ContainerAllocator> const> ConstPtr;
}; // struct candata_
typedef ::canbus::candata_<std::allocator<void> > candata;
typedef boost::shared_ptr< ::canbus::candata > candataPtr;
typedef boost::shared_ptr< ::canbus::candata const> candataConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::canbus::candata_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::canbus::candata_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace canbus
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': True, 'IsMessage': True, 'HasHeader': False}
// {'canbus': ['/home/silentroar/Desktop/ROS_Intell_Driving/src/canbus/msg'], 'std_msgs': ['/opt/ros/indigo/share/std_msgs/cmake/../msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::canbus::candata_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::canbus::candata_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::canbus::candata_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::canbus::candata_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::canbus::candata_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::canbus::candata_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::canbus::candata_<ContainerAllocator> >
{
static const char* value()
{
return "2f636bf314749eeb00e7f85696286658";
}
static const char* value(const ::canbus::candata_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x2f636bf314749eebULL;
static const uint64_t static_value2 = 0x00e7f85696286658ULL;
};
template<class ContainerAllocator>
struct DataType< ::canbus::candata_<ContainerAllocator> >
{
static const char* value()
{
return "canbus/candata";
}
static const char* value(const ::canbus::candata_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::canbus::candata_<ContainerAllocator> >
{
static const char* value()
{
return "uint32 id\n\
#uint32 timestamp\n\
uint8[8] data\n\
";
}
static const char* value(const ::canbus::candata_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::canbus::candata_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.id);
stream.next(m.data);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct candata_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::canbus::candata_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::canbus::candata_<ContainerAllocator>& v)
{
s << indent << "id: ";
Printer<uint32_t>::stream(s, indent + " ", v.id);
s << indent << "data[]" << std::endl;
for (size_t i = 0; i < v.data.size(); ++i)
{
s << indent << " data[" << i << "]: ";
Printer<uint8_t>::stream(s, indent + " ", v.data[i]);
}
}
};
} // namespace message_operations
} // namespace ros
#endif // CANBUS_MESSAGE_CANDATA_H
| [
"dengzhongw@126.com"
] | dengzhongw@126.com |
68fb674252569f9c147984987471c270abfa6c67 | 0025ed85a2b651749025fd31c7c837c21fc5fe3a | /PA5/pa5list.cpp | 87a557003864a7eb06e61cc864beb4f0f96f264f | [] | no_license | Annieli0717/USC-CSCI455x-Programming-Systems-Design | 940b71baf663f29053fdfe61cfd9ec57167711b6 | 54e0d88a2a92241d9d558a46eb9fc2c0d6cccf0b | refs/heads/master | 2020-05-26T11:13:53.299487 | 2019-09-16T21:10:37 | 2019-09-16T21:10:37 | 188,212,474 | 4 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,549 | cpp | // Name: Dunxuan Li (Annie)
// USC NetID: dunxuanl
// CS 455 PA5
// Spring 2019
// pa5list.cpp
// a program to test the linked list code necessary for a hash table chain
// You are not required to submit this program for pa5.
// We gave you this starter file for it so you don't have to figure
// out the #include stuff. The code that's being tested will be in
// listFuncs.cpp, which uses the header file listFuncs.h
// The pa5 Makefile includes a rule that compiles these two modules
// into one executable.
#include <iostream>
#include <string>
#include <cassert>
using namespace std;
#include "listFuncs.h"
int main() {
ListType node1 = new Node("Annie", 100);
ListType node2 = new Node("Miles", 90);
ListType node3 = new Node("Jack", 59);
ListType node4 = new Node("Kate", 0);
node1->next = node2;
node2->next = node3;
node3->next = node4;
ListType list = node1;
// Case 0: original list: print the list
printList(list);
// Case 1: return the size of a list
cout << "Size of linked list is " << listSize(list) << endl;
cout << endl;
// Case 2: look up an element
cout << "In the list: Annie's grade is " << listLookup(list, "Annie") << endl;
cout << "Not in the list: Kay's grade is " << listLookup(list, "Kay") << endl;
cout << endl;
// Case 3: change an element
cout << "In the list: Change Mile's grade to 100" << endl;
listChange(list, "Miles", 100);
printList(list);
cout << endl;
cout << "Not in the list: Change Michael's (does not exist) grade to 100" << endl;
listChange(list, "Micheal", 100);
printList(list);
cout << endl;
// Case 4: insert a new node
cout << " --- Insert Bob --- " << endl;
listInsertFront(list, "Bob", 200);
printList(list);
cout << "Size of linked list is " << listSize(list) << endl;
cout << endl;
// Case 5: remove a node
cout << "Remove Kate" << endl;
cout << "Has Kate been removed? " << listRemove(list, "Kate") << endl;
printList(list);
cout << endl;
cout << "Remove Bob" << endl;
cout << "Has Bob been removed? " << listRemove(list, "Bob") << endl;
printList(list);
cout << endl;
cout << "Has Annie been removed? " << listRemove(list, "Annie") << endl;
cout << "Has JAck been removed? " << listRemove(list, "Jack") << endl;
cout << "Has Miles been removed? " << listRemove(list, "Miles") << endl;\
printList(list);
listRemove(list, "Miles");
printList(list);
listInsertFront(list, "Annie", 100);
printList(list);
return 0;
}
| [
"noreply@github.com"
] | noreply@github.com |
0715e96633f1eed43ecacf2655500122e423df57 | ab55b51d139b480ee094b8f124af53e29fb011f9 | /common function/common_function.cpp | 87abfcdc1c59c4b76b8450ee0cf131916f380627 | [] | no_license | benson-zhang-sjtu/Leetcode | 732f36748444f9237ac8eebaf60d50348f3d735c | 6b7d1c46a7765fa20dc6d6898ecd1ed4f856e4a0 | refs/heads/master | 2021-01-12T12:20:06.000751 | 2016-11-14T07:06:14 | 2016-11-14T07:06:14 | 72,438,749 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 450 | cpp | #include<string>
#include<vector>
#include<sstream>
// String Split Function from Evan Teran. http://stackoverflow.com/questions/236129/split-a-string-in-c
void split(const string &s, char delim, vector<string> &elems)
{
stringstream ss;
ss.str(s);
string item;
while (getline(ss, item, delim))
{
elems.push_back(item);
}
}
vector<string> split(const string &s, char delim)
{
vector<string> elems;
split(s, delim, elems);
return elems;
} | [
"150576806@qq.com"
] | 150576806@qq.com |
d4c445f04fb098235dc9c27100e930fd0783f2cb | a3b306df800059a5b74975793251a28b8a5f49c7 | /Graphs/LX-2/molecule_otsu = False/BioImageXD-1.0/vtkBXD/Processing/vtkExtTIFFReader.h | 3085fae4c89f59de0f383badbece169fd1f68aa0 | [] | no_license | giacomo21/Image-analysis | dc17ba2b6eb53f48963fad931568576fda4e1349 | ea8bafa073de5090bd8f83fb4f5ca16669d0211f | refs/heads/master | 2016-09-06T21:42:13.530256 | 2013-07-22T09:35:56 | 2013-07-22T09:35:56 | 11,384,784 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 6,798 | h | /*=========================================================================
Program: Visualization Toolkit
Module: $RCSfile: vtkExtTIFFReader.h,v $
Language: C++
Date: $Date: 2003/11/04 21:26:04 $
Version: $Revision: 1.28 $
Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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.
=========================================================================*/
/*=========================================================================
Following modifications were made to original vtkTIFFReader by BioImageXD team
Copyright (c) 2005 Kalle Pahajoki. Modifications for raw mode support
Copyright (c) 2008 Lassi Paavolainen Support for multipage tiffs
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 name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
of any contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
* Modified source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
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 AUTHORS 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.
=========================================================================*/
// .NAME vtkExtTIFFReader - read TIFF files
// .SECTION Description
// vtkExtTIFFReader is a source object that reads TIFF files.
// It should be able to read most any TIFF file
//
// .SECTION See Also
// vtkTIFFWriter
#ifndef __vtkExtTIFFReader_h
#define __vtkExtTIFFReader_h
#include "vtkBXDProcessingWin32Header.h"
#include "vtkImageReader2.h"
//BTX
class vtkExtTIFFReaderInternal;
//ETX
class VTK_BXD_PROCESSING_EXPORT vtkExtTIFFReader : public vtkImageReader2
{
public:
static vtkExtTIFFReader *New();
vtkTypeRevisionMacro(vtkExtTIFFReader,vtkImageReader2);
virtual void PrintSelf(ostream& os, vtkIndent indent);
// Description:
// Is the given file name a tiff file file?
virtual int CanReadFile(const char* fname);
// Description:
// Get the file extensions for this format.
// Returns a string with a space separated list of extensions in
// the format .extension
virtual const char* GetFileExtensions()
{
return ".tif .tiff";
}
// Description:
// Return a descriptive name for the file format that might be useful
// in a GUI.
virtual const char* GetDescriptiveName()
{
return "TIFF";
}
// Description:
// Auxilary methods used by the reader internally.
void InitializeColors();
vtkSetMacro(RawMode,int);
vtkGetMacro(RawMode,int);
vtkBooleanMacro(RawMode,int);
//BTX
enum { NOFORMAT, RGB, GRAYSCALE, PALETTE_RGB, PALETTE_GRAYSCALE, OTHER };
void ReadImageInternal( void *, void *outPtr,
int *outExt, unsigned int size, int );
// Description:
// Method to access internal image. Not to be used outside the class.
vtkExtTIFFReaderInternal *GetInternalImage()
{ return this->InternalImage; }
//ETX
// Description:
// Method to check if set TIFF file is multipage
int GetNumberOfSubFiles() const;
protected:
vtkExtTIFFReader();
~vtkExtTIFFReader();
void GetColor( int index,
unsigned short *r, unsigned short *g, unsigned short *b );
unsigned int GetFormat();
virtual void ExecuteInformation();
virtual void ExecuteData(vtkDataObject *out);
int RequestUpdateExtent (
vtkInformation* vtkNotUsed(request),
vtkInformationVector** inputVector,
vtkInformationVector* outputVector);
void ReadGenericImage( void *out,
unsigned int width, unsigned int height,
unsigned int size );
int EvaluateImageAt( void*, void* );
private:
vtkExtTIFFReader(const vtkExtTIFFReader&); // Not implemented.
void operator=(const vtkExtTIFFReader&); // Not implemented.
unsigned short *ColorRed;
unsigned short *ColorGreen;
unsigned short *ColorBlue;
int TotalColors;
unsigned int ImageFormat;
vtkExtTIFFReaderInternal *InternalImage;
int *InternalExtents;
int RawMode;
};
#endif
| [
"fede.anne95@hotmail.it"
] | fede.anne95@hotmail.it |
8cc8a0ab618dfbdcea1d3c27db05fc053e1f28e5 | b53f1953f5520e5208f34bb87d42d86ead33dba6 | /src/Platform/Code/FactoryTool/GLAVS1A_IMEI_CODING_V0.20/Message.h | 66ba3f5edef16925a01a9cca3316d5419d0206d1 | [] | no_license | Jonkoping/data | e01b2ded3335742165ea3feb9c06e0d111ab5fb7 | 03de309b5f7998f394b2ed1d8b0bc0114ca686f3 | refs/heads/master | 2020-06-30T18:24:29.032625 | 2018-01-04T09:18:55 | 2018-01-04T09:18:55 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,312 | h | #if !defined(AFX_MESSAGE_H__AC5068A9_1F8E_451D_AFB1_FFDEA02CF34F__INCLUDED_)
#define AFX_MESSAGE_H__AC5068A9_1F8E_451D_AFB1_FFDEA02CF34F__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
// Message.h : header file
//
#include "Label.h"
/////////////////////////////////////////////////////////////////////////////
// CMessage dialog
class CMessage : public CDialog
{
// Construction
public:
CMessage(CWnd* pParent = NULL); // standard constructor
CBrush m_brush;
// Dialog Data
//{{AFX_DATA(CMessage)
enum { IDD = IDD_DIALOG_MESSAGE };
CLabel m_ERROR;
CButton m_OK;
CLabel m_MESSAGE;
//}}AFX_DATA
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CMessage)
protected:
virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support
//}}AFX_VIRTUAL
// Implementation
protected:
// Generated message map functions
//{{AFX_MSG(CMessage)
afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);
virtual BOOL OnInitDialog();
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_MESSAGE_H__AC5068A9_1F8E_451D_AFB1_FFDEA02CF34F__INCLUDED_)
| [
"faulfish@gmail.com"
] | faulfish@gmail.com |
cab6bca4eea5be100186e997cd577633e7a04b3e | 037d518773420f21d74079ee492827212ba6e434 | /blazetest/src/mathtest/smatsmatsub/MIbMIa.cpp | 190d25c414e62d7c9a4f84bdf976dd55aa281a44 | [
"BSD-3-Clause"
] | permissive | chkob/forked-blaze | 8d228f3e8d1f305a9cf43ceaba9d5fcd603ecca8 | b0ce91c821608e498b3c861e956951afc55c31eb | refs/heads/master | 2021-09-05T11:52:03.715469 | 2018-01-27T02:31:51 | 2018-01-27T02:31:51 | 112,014,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,922 | cpp | //=================================================================================================
/*!
// \file src/mathtest/smatsmatsub/MIbMIa.cpp
// \brief Source file for the MIbMIa sparse matrix/sparse matrix subtraction math test
//
// Copyright (C) 2012-2018 Klaus Iglberger - All Rights Reserved
//
// This file is part of the Blaze library. You can redistribute it and/or modify it under
// the terms of the New (Revised) BSD License. Redistribution and use in source and binary
// forms, with or without modification, are permitted provided that the following conditions
// are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
// conditions and the following disclaimer.
// 2. 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.
// 3. Neither the names of the Blaze development group nor the names of its contributors
// may be used to endorse or promote products derived from this software without specific
// prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
// EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
// SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
// TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
// BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
// ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
// DAMAGE.
*/
//=================================================================================================
//*************************************************************************************************
// Includes
//*************************************************************************************************
#include <cstdlib>
#include <iostream>
#include <blaze/math/IdentityMatrix.h>
#include <blazetest/mathtest/Creator.h>
#include <blazetest/mathtest/smatsmatsub/OperationTest.h>
#include <blazetest/system/MathTest.h>
//=================================================================================================
//
// MAIN FUNCTION
//
//=================================================================================================
//*************************************************************************************************
int main()
{
std::cout << " Running 'MIbMIa'..." << std::endl;
using blazetest::mathtest::TypeA;
using blazetest::mathtest::TypeB;
try
{
// Matrix type definitions
typedef blaze::IdentityMatrix<TypeA> MIa;
typedef blaze::IdentityMatrix<TypeB> MIb;
// Creator type definitions
typedef blazetest::Creator<MIa> CMIa;
typedef blazetest::Creator<MIb> CMIb;
// Running tests with small matrices
for( size_t i=0UL; i<=6UL; ++i ) {
RUN_SMATSMATSUB_OPERATION_TEST( CMIb( i ), CMIa( i ) );
}
// Running tests with large matrices
RUN_SMATSMATSUB_OPERATION_TEST( CMIb( 67UL ), CMIa( 67UL ) );
RUN_SMATSMATSUB_OPERATION_TEST( CMIb( 128UL ), CMIa( 128UL ) );
}
catch( std::exception& ex ) {
std::cerr << "\n\n ERROR DETECTED during sparse matrix/sparse matrix subtraction:\n"
<< ex.what() << "\n";
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
//*************************************************************************************************
| [
"klaus.iglberger@gmail.com"
] | klaus.iglberger@gmail.com |
32396f65214b91726694246524432d735eabd2ce | a162fdf1ccbb98ca9ddac790a087dc5c95e3fd43 | /include/entity/light.h | e3d1db894f8f7afb0d7ba3abe4940bdeda6b94d9 | [
"MIT"
] | permissive | tobiasbu/raytracer | 3f9c7a8eb516d3486d34b1a3ff44517c7b01b045 | bc1db0c6aea504b2dc59520fe6245d523fb11ffa | refs/heads/master | 2021-01-19T11:04:05.608699 | 2018-03-06T12:44:14 | 2018-03-06T12:44:14 | 87,923,949 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,855 | h |
#ifndef _LIGHT_H_
#define _LIGHT_H_
#include "render/color.h"
#include "math/vec3.h"
#include "math/mat4.h"
#include "entity/transform.h"
#include "math/mathdef.hpp"
class Light : public Transform
{
public:
float intensity; // fallof
Color color;
int type = 0;
Light()
:
color(Color::white),
intensity(0.1f)
{
position = vec3(0, -1, -1);
}
virtual ~Light() {}
virtual void illuminate(const vec3 & point, vec3 & lightDir, vec3 & lightColorIntensity, float & distance, float & radius) const = 0;
virtual void updateTransform() {
mat4 s = MatrixTransform::scale(mat4::identity, scale);
mat4 t = MatrixTransform::translate(mat4::identity, position);
mat4 r = MatrixTransform::rotate_x_deg(mat4::identity, angle.x);
r = MatrixTransform::rotate_y_deg(r, angle.y);
r = MatrixTransform::rotate_z_deg(r, angle.z);
// transform o row-major is T * R * S
// collum:
//matrix = s * r * t;
// another solution: precompute transformed object: only model matrix
matrix = t; // * r);
// compute inversed matrix
inversedMatrix = mat4::inverse(matrix);
calculateVectors();
}
};
class DirectionalLight : public Light
{
public:
vec3 direction;
DirectionalLight();
DirectionalLight(const vec3 & position, const vec3 & targetDirection, const Color & color = Color::white, float intensity = 4);
void illuminate(const vec3 & point, vec3 & lightDir, vec3 & lightColorIntensity, float & distance, float & radius) const;
//void updateTransform();
void setDirection(const vec3 & dir);
};
class PointLight : public Light
{
public:
float range = 1;
PointLight();
PointLight(const vec3 & position, const Color & color, float intensity = 4);
void illuminate(const vec3 & point, vec3 & lightDir, vec3 & lightColorIntensity, float & distance, float & radius) const;
//void updateTransform();
};
#endif | [
"flamenco.bluegrass@gmail.com"
] | flamenco.bluegrass@gmail.com |
aa310cc58ec0eba67ee8662b25aa9350ff6ef331 | b82e39723d9addefbee5231c6ba229049164a655 | /example-advanced/src/ofApp.cpp | a862870bbfb3d3a97f39bbea6ea9ff7d7bf280d3 | [
"LicenseRef-scancode-unknown-license-reference",
"MIT"
] | permissive | shenhuashan/ofxSMTP | 031cfc9d1db96b5895447672c70e83891beda7b1 | 2ea7a7af8a70b57e6e6b42932b699f3fa043a98f | refs/heads/master | 2022-02-22T21:18:52.728193 | 2018-06-08T05:15:43 | 2018-06-08T05:15:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,020 | cpp | //
// Copyright (c) 2013 Christopher Baker <https://christopherbaker.net>
//
// SPDX-License-Identifier: MIT
//
#include "ofApp.h"
void ofApp::setup()
{
ofSetLogLevel(OF_LOG_VERBOSE);
// Register for SSL Context events.
ofSSLManager::registerClientEvents(this);
// Set the name of the recipient for this example.
recipientEmail = "info@christopherbaker.net";
// Set the sender email and display name.
senderEmail = "Christopher Baker <info@christopherbaker.net>";
// Load credentials and account settings from an xml or json file.
// auto settings = ofxSMTP::Settings::loadFromXML("example-smtp-account-settings.xml");
auto settings = ofxSMTP::Settings::loadFromJSON("example-smtp-account-settings.json");
// See ofxSMTP::Settings for extensive configuration options.
// Pass the settings to the client.
smtp.setup(settings);
// Register event callbacks for message delivery (or failure) events
smtpDeliveryListener = smtp.events.onSMTPDelivery.newListener(this, &ofApp::onSMTPDelivery);
smtpExceptionListener = smtp.events.onSMTPException.newListener(this, &ofApp::onSMTPException);
}
void ofApp::draw()
{
// Print some information about the state of the outbox.
ofBackground(80);
std::stringstream ss;
ss << " Press <SPACEBAR> to Send Text" << std::endl;
ss << " Press <a> to Send an Image" << std::endl;
ss << "ofxSMTP: There are " + ofToString(smtp.getOutboxSize()) + " messages in your outbox.";
ofDrawBitmapStringHighlight(ss.str(), 10, 20);
}
void ofApp::keyPressed(int key)
{
if (key == ' ') // Press spacebar for a simple send.
{
// Send a simple short message.
smtp.send(recipientEmail, // Recipient email.
senderEmail, // Sender email.
"I'm trying out ofxSMTP!", // Subject line.
"It works!"); // Message body.
}
else if(key == 'a') // Press 'a' for an advanced send with attachment.
{
// You can construct complex messages using POCO's MailMessage object.
// See http://pocoproject.org/docs/Poco.Net.MailMessage.html
auto message = std::make_shared<Poco::Net::MailMessage>();
// Encode the sender and set it.
message->setSender(Poco::Net::MailMessage::encodeWord(senderEmail,
"UTF-8"));
// Mark the primary recipient and add them.
message->addRecipient(Poco::Net::MailRecipient(Poco::Net::MailRecipient::PRIMARY_RECIPIENT,
recipientEmail));
// Encode the subject and set it.
message->setSubject(Poco::Net::MailMessage::encodeWord("I'm sending you an image using ofxSMTP!",
"UTF-8"));
// Poco::Net::MailMessage will take ownership of the *PartSource files,
// so you don't have to worry about deleting the pointers.
message->addContent(new Poco::Net::StringPartSource("Hello world! How about an image?"));
// Poco::Net::MailMessage throws exceptions when a file is not found.
// Thus, we need to add attachments in a try / catch block.
try
{
message->addAttachment(Poco::Net::MailMessage::encodeWord("of.png","UTF-8"),
new Poco::Net::FilePartSource(ofToDataPath("of.png", true)));
}
catch (const Poco::OpenFileException& exc)
{
ofLogError("ofApp::keyPressed") << exc.name() << " : " << exc.displayText();
}
// Add an additional header, just because we can.
message->add("X-Mailer", "ofxSMTP (https://github.com/bakercp/ofxSMTP)");
// Add the message to our outbox.
smtp.send(message);
}
}
void ofApp::onSMTPDelivery(std::shared_ptr<Poco::Net::MailMessage>& message)
{
ofLogNotice("ofApp::onSMTPDelivery") << "Message Sent: " << message->getSubject();
}
void ofApp::onSMTPException(const ofxSMTP::ErrorArgs& evt)
{
ofLogError("ofApp::onSMTPException") << evt.error().displayText();
if (evt.message())
{
ofLogError("ofApp::onSMTPException") << evt.message()->getSubject();
}
}
void ofApp::onSSLClientVerificationError(Poco::Net::VerificationErrorArgs& args)
{
ofLogNotice("ofApp::onClientVerificationError") << std::endl << ofToString(args);
// If you want to proceed, you must allow the user to inspect the certificate
// and set `args.setIgnoreError(true);` if they want to continue.
// args.setIgnoreError(true);
}
void ofApp::onSSLPrivateKeyPassphraseRequired(std::string& passphrase)
{
// If you want to proceed, you must allow the user to input the assign the private key's
// passphrase to the `passphrase` argument. For example:
passphrase = ofSystemTextBoxDialog("Enter the Private Key Passphrase", "");
}
| [
"me@christopherbaker.net"
] | me@christopherbaker.net |
abaef2cc8993419f58ca4f4e85acb415b20164b2 | f23e3c03faf1ad3b51e2ce30d79479c12bfdfe58 | /include/geneticalgorithm.hpp | 8230a5edc9707002911167007a7450c53134f2d3 | [
"MIT"
] | permissive | gitter-badger/headless-logic | 1bb70322c320f38d92cf8f9e16f91228a3de7d17 | 54b6b1f5893df4214eda0a7be9cb3d2490117259 | refs/heads/master | 2020-12-27T21:32:08.174819 | 2016-08-24T22:05:58 | 2016-08-24T22:05:58 | 66,503,937 | 0 | 0 | null | 2016-08-24T22:19:22 | 2016-08-24T22:19:22 | null | UTF-8 | C++ | false | false | 9,315 | hpp | /*
* Copyright 2016 Stoned Xander
*
* 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 HEADLESS_LOGIC_GENETIC_ALGORITHM
#define HEADLESS_LOGIC_GENETIC_ALGORITHM
#include <random>
namespace Headless {
namespace Logic {
/**
* Here are proposed some implementations of General Algorithms.
* Currently available GAs are:
* - Trivial.
*/
namespace GA {
/**
* Trivial GA.
* 1. Generate first pool.
* 2. Evaluate pool against a testing environment.
* 3. Save the elite.
* 4. Create new pool from elite using set of operators.
* 5. Back to step 2 until error is superior to specified
* or until generation number is inferior to specified.
*
* To this purpose, we need the following concepts :
* @param <C> Candidates to be evaluated and modified.
*/
template <typename C> class Trivial {
public:
/**
* Constructor.
* @param pSize Pool Size.
*/
Trivial(unsigned int pSize) : _count(pSize) {
_pool = new C*[pSize];
_score = new double[pSize];
}
/**
* Destructor.
*/
~Trivial() {
delete []_pool;
delete []_score;
}
/**
* Training.
* @param <E> Creation and evaluation environment type. It must define
* the following methods:
* - void reserve(C**&, unsigned int)
* - void release(C**, unsigned int)
* - double evaluate (const C*)
* - C* clone(const C*)
* @param <... M> Set of operators/mutators types. A mutator must define
* the following methods:
* - double threshold()
* - void mutate(C**, unsigned int, C*);
* @param env Environment.
* @param maxGen Maximum number of generations.
* @param minErr Minimal accepable error.
* @param eliteSize Percentage of the pool to be taken for creating the next pool.
* @param store A store for results.
* @param size Size of the storage and maximum number of exit candidate.
* @param mutators Set of operators/mutators for new pool creation.
* @return The number of candidates stored in the specified buffer.
*/
template <typename E, typename... M> int train(E* env,
unsigned int maxGen, double minErr, double eliteSize,
C** store, unsigned int size,
M... mutators) {
unsigned int eliteCount = _count * eliteSize;
// We assume that the pool is empty and needs to be filled.
env->reserve(_pool, _count);
// Loop on generations.
for(unsigned int g = 0;
(g < maxGen) && (evaluate(env) > minErr);
++g) {
// At this point, the pool is full and sorted.
// Let's recycle candidates from eliteCount to _count - 1.
#pragma omp parallel for
for(unsigned int i = eliteCount; i < _count; ++i) {
// Randomly choose a mutators.
mutate(i, eliteCount, mutators...);
}
}
unsigned int number = eliteCount < size ? eliteCount : size;
for(unsigned int i = 0; i < number; ++i) {
store[i] = env->clone(_pool[i]);
}
// Clean-up the pool.
env->release(_pool, _count);
return number;
}
private:
/**
* make a new offspring out of the available mutators.
*/
template <typename M, typename... O> void mutate(unsigned int pos, unsigned int count,
M mutator, O... others) {
std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<double> dist(0.0, 1.0);
double rnd = dist(mt);
if(rnd < mutator->threshold()) {
mutator->mutate(_pool, count, _pool[pos]);
} else {
mutate(pos, count, others...);
}
}
template <typename M> void mutate(unsigned int pos, unsigned int count, M mutator) {
mutator->mutate(_pool, count, _pool[pos]);
}
/**
* Evaluate the pool against the environment.
* @param <E> Environment type.
* @param env Environment.
* @return Minimal error. At return time, the pool is sorted
* using candidates scores.
*/
template <typename E> double evaluate(E* env) {
// Evaluate ...
#pragma omp parallel for
for(unsigned int i = 0; i < _count; ++i) {
_score[i] = env->evaluate(_pool[i]);
}
// ... and sort.
qsort(0, _count - 1);
return _score[0];
}
/**
* Simple quick sort for our specific case.
* @param lo Lower bound.
* @param hi Higher bound.
*/
void qsort(unsigned int lo, unsigned int hi) {
if(lo < hi) {
// We don't make fat partitionning as we are manipulating
// fine-grained over-distributed scores. We should not
// have arrays of identical scores.
unsigned int pivot = partition(lo, hi);
if((pivot - lo) < (hi - (pivot + 1))) {
qsort(lo, pivot);
qsort(pivot + 1, hi);
} else {
qsort(pivot + 1, hi);
qsort(lo, pivot);
}
}
}
unsigned int partition(unsigned int lo, unsigned int hi) {
double pivot = _score[lo];
unsigned int i = lo - 1;
unsigned int j = hi + 1;
for(;;) {
do {
++i;
} while(_score[i] < pivot);
do {
--j;
} while(_score[j] > pivot);
if(i >= j) {
return j;
}
double score = _score[i];
C* candidate = _pool[i];
_score[i] = _score[j];
_pool[i] = _pool[j];
_score[j] = score;
_pool[j] = candidate;
}
return 0; // Should never happen.
}
private:
/**
* Candidate pool.
*/
C** _pool;
/**
* Pool score.
*/
double *_score;
/**
* Pool count.
*/
unsigned int _count;
};
} // Namespace 'GA'
} // Namespace 'Logic'
} // Namespace 'Headless'
#endif
| [
"somerandomgamedev@gmail.com"
] | somerandomgamedev@gmail.com |
948880aa5156d31bbee90e8ba81b0cb87c15feec | 3b6b94633ceb2b386549759ce9f5eb3376c9cc8f | /Array/N3RepeatNumber.cpp | 22c011ab50e60edf365eab7331c12eb17cf62a8b | [] | no_license | UtkarshGupta12/InterviewBit | 990a7dd49856b17d6e5dfe57c3dd000a58333cf8 | 8525051eb592686462b8a62b0542274729671023 | refs/heads/main | 2023-06-05T23:43:28.624879 | 2021-06-26T11:55:53 | 2021-06-26T11:55:53 | 362,963,727 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,424 | cpp | #include <iostream>
#include <string>
#include <bits/stdc++.h>
using namespace std;
int MVA2(const vector<int> &A)
{
//Moore Voting Algorithm for N/2
int ME=A[0],count1=1,i=1;
while(i<A.size())
{
if(A[i] == A[i-1])
count1++;
else if(A[i]!=A[i-1])
count1--;
i++;
if(count1 == 0)
{
ME = A[i];
if(i>=A.size())
ME = A[i-1];
count1 = 1;
}
}
return ME;
}
int MVA3(const vector<int> &A)
{
//Moore Voting Algorithm for N/2
int x=-1,y=-1,countx=0,county=0;
for(int i=0;i<A.size();i++)
{
if(x==A[i])
countx++;
else if(y==A[i])
county++;
else if(countx==0)
{
x = A[i];
countx=1;
}
else if(county==0)
{
y=A[i];
county=1;
}
else
{
county--;
countx--;
}
}
int nx = count(A.begin(), A.end(), x);
int ny = count(A.begin(), A.end(), y);
if(nx>=ny)
return x;
else
return y;
}
int Solution::repeatedNumber(const vector<int> &A)
{
int ME = MVA3(A);
int n = count(A.begin(), A.end(), ME);
//int nE = count(A.begin(), A.end(), A[A.size()-1]);
if(n > A.size()/3)
return ME;
else
return -1;
}
| [
"noreply@github.com"
] | noreply@github.com |
8b4956d17cd20bc7c4ac95dc6189263562b05f31 | 04f51a5ff3f3228cad23d75599f7832a89b381df | /카카오/2020 KAKAO BLIND RECRUITMENT/가사 검색.cpp | 19db7267cd137c20241b0661dde6fa94422e677b | [] | no_license | thsgustlr0318/algorithm | 241fea5f6be7399a000262233533cc11708ca65d | f7cca5dd6b2f69223adebfc2d6299d13aedd3154 | refs/heads/master | 2021-02-12T03:46:41.521266 | 2020-05-06T15:38:18 | 2020-05-06T15:38:18 | 244,558,586 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,952 | cpp | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <map>
#include <unordered_map>
using namespace std;
vector<string> v[10001], vr[10001];
//이분 탐색
//정확성, 효율성 모두 통과
vector<int> solution(vector<string> words, vector<string> queries) {
vector<int> answer;
int wsize = words.size(), qsize = queries.size();
answer.resize(qsize);
//단어 길이에 따라 v와 vr(reverse)에 단어 넣음
for (int i = 0; i < wsize; i++) {
int len = words[i].size();
v[len].push_back(words[i]);
reverse(words[i].begin(), words[i].end());
vr[len].push_back(words[i]);
}
//v, vr 정렬
for (int i = 1; i <= 10000; i++) {
if(!v[i].empty())
sort(v[i].begin(), v[i].end());
if(!vr[i].empty())
sort(vr[i].begin(), vr[i].end());
}
//모든 queries 단어 탐색
for (int i = 0; i < qsize; i++) {
string cur = queries[i];
int len = cur.size();
bool flag = true;
//만약 ?가 접두사에 오면
if (queries[i][0] == '?') {
flag = false;
reverse(cur.begin(), cur.end());
}
string low = cur, upp = cur;
//low: ?를 a로, upp: ?를 z로
//lower_bound와 upper_bound로 이분탐색
replace(low.begin(), low.end(), '?', 'a');
replace(upp.begin(), upp.end(), '?', 'z');
if (flag) {
auto it1 = lower_bound(v[len].begin(), v[len].end(), low);
auto it2 = upper_bound(v[len].begin(), v[len].end(), upp);
answer[i] = distance(v[len].begin(), it2) - distance(v[len].begin(), it1);
}
else {
auto it1 = lower_bound(vr[len].begin(), vr[len].end(), low);
auto it2 = upper_bound(vr[len].begin(), vr[len].end(), upp);
answer[i] = distance(vr[len].begin(), it2) - distance(vr[len].begin(), it1);
}
}
return answer;
}
int main()
{
vector<string> words = { "frodo", "front", "frost", "frozen", "frame", "kakao" };
vector<string> queries = {"fro??", "????o", "fr???", "fro???", "pro?"};
solution(words, queries);
}
//unordered_map
//정확성 통과, 효율성 3개 통과
/*
vector<int> solution(vector<string> words, vector<string> queries) {
vector<int> answer;
unordered_map<string, int> m;
int wordsize = words.size(), querysize = queries.size();
answer.resize(querysize);
for (int i = 0; i < wordsize; i++) {
string cur = words[i];
int len = words[i].size();
string temp = cur;
m[cur]++;
for (int i = 0; i < len; i++) {
temp[i] = '?';
m[temp]++;
}
temp = cur;
for (int i = len - 1; i > 0; i--) {
temp[i] = '?';
m[temp]++;
}
}
for (int i = 0; i < querysize; i++) {
answer[i] = m[queries[i]];
}
return answer;
}
}*/ | [
"61684785+thsgustlr0318@users.noreply.github.com"
] | 61684785+thsgustlr0318@users.noreply.github.com |
8a6e1803e8f16808776a23a5a6bcbff91f8617e6 | 53d6b97a9432090454f683c210c78255a33da347 | /point.hpp | 3195d15a03b5d011a0d344eb34aafce59bf3bd7d | [] | no_license | Ligvest/SocobanQtOgl | 2df44a8bb30f3377c05067549ea2bd2aff1b2346 | d3e5339b10e22e56107b95bbf96ff8869413ebbc | refs/heads/master | 2020-05-27T21:03:13.098212 | 2019-06-07T12:40:22 | 2019-06-07T12:40:22 | 188,790,016 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 364 | hpp | #ifndef POINT_HPP
#define POINT_HPP
class Point {
public:
Point(int iX, int iY);
int x() const;
void setX(int iX);
int y() const;
void setY(int iY);
Point operator-(const Point& rightPoint) const;
Point operator+(const Point& rightPoint) const;
private:
int iX_;
int iY_;
};
#endif // POINT_H
| [
"ligvesto@gmail.com"
] | ligvesto@gmail.com |
06c0352fde17494f0775b6a90edd760c473d395f | 0caf30e643f78229a7ef8742cc1d5386bc045ec1 | /programming-language/cpp/grid-service/NwfdMainApp/ProviderBase.h | 2dbb9fe156d2505921d06d5e496ce7d78ff4a395 | [] | no_license | AlexiaChen/Adrasteia | feb1957dd694f79315784000c6f73f35bc5ca18f | 1b9b29d5565a41250119e42c47aa0a4a588cef9c | refs/heads/master | 2020-11-29T11:59:50.580203 | 2018-09-09T10:49:10 | 2018-09-09T10:49:10 | 87,497,591 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,152 | h | /*************************************************************************
* Copyright (C), 2015,
* XXXXXXXXXXX Co.
* 文件名: ProviderBase.h
* 作 者: zhangl 版本:1.0 日 期:2015/05/08
* 描 述:缓存处理基类(接口)
* 其 他:
* 功能列表:
* 1. 定义缓存处理的基本操作方法
*
* 修改日志:
* No. 日期 作者 修改内容
* 1 2015/05/13 zhangl 添加Key-Value读写方法(for MemCached/redis)
* 2 2015/05/15 zhangl 添加memcached的特殊锁处理
*************************************************************************/
#ifndef PROVIDER_BASE_H
#define PROVIDER_BASE_H
#include "stdio.h"
/************************************************************************/
/* 类 名: ProviderBase */
/* 父 类: - */
/* 说 明: 缓存处理基类 */
/* 描 述: 所有类型的缓存都要继承此类,实现其接口定义的方法,操作缓存 */
/************************************************************************/
class ProviderBase
{
public:
ProviderBase();
virtual ~ProviderBase();
public:
// 基本内容
void SetProviderName(const char *strProviderName);
// 连接
virtual bool SetConnectParam(const char *strServerIP, int nPortNo);
virtual bool Connect(const char *strServerIP, int nPortNo);
virtual bool Connect();
virtual void DisConnect();
virtual bool ReConnect();
virtual bool ConnectStatus();
// 增删改查操作
// 1、 基本操作
virtual bool FlushDB();
virtual bool DelKey(const char * strKey);
virtual bool IsExistsKey(const char * strKey);
// 2、Key-Value 数据写/读(使用于Redis和Memcached)
virtual bool SetValue(const char * strKey, const char * szValue, int nValueSize, int nExpirationTime = 0);
virtual bool AppendValue(const char * strKey, const char * szValue, int nValueSize);
virtual char *GetValue(const char * strKey, int & nValueSize);
// 3、Redis Set类型
virtual bool AddSMember(const char * strKey, const char * strValue);
virtual bool RemoveSMember(const char * strKey, const char * strValue);
virtual bool GetSMembers(const char * strKey, char(*pValArray)[256], int &nCount);
virtual bool IsSMember(const char * strKey, const char * strValue);
// 4、Redis hash类型
virtual bool SetHValue(const char * strKey, const char * strField, const char * strValue);
virtual bool DelHField(const char * strKey, const char * strField);
virtual bool GetHValue(const char * strKey, const char * strField, char * strValue);
virtual char * GetHValue(const char * strKey, const char * strField);
// 5、特殊处理(for memcached)
virtual bool LockKey(const char * strKey, int nExpirationTime = 1);
virtual bool UnLockKey(const char *strKey);
virtual int GetLastError();
public:
char m_strProviderName[50]; // 名称
char m_strServerIP[32]; // 缓存 Server IP地址
int m_nPortNo; // 缓存 Server 端口
bool m_bConStatus; // 连接状态
};
#endif //PROVIDER_BASE_H
| [
"brainfvck@foxmail.com"
] | brainfvck@foxmail.com |
704e9c468a5c73db069b877b3bbb42f064271dcc | 0fccd1748ee7be55039e7bbfb4820197b5a85f0b | /2D Game Engine/2D Game Engine/MarkOfHunger.cpp | e10c74bf6b0334d998dc3423c51b32733a3a439d | [] | no_license | AustinChayka/C-Game | 11d297ac5fd38a280da4701ec16c5e18f8680c58 | 56bd96fddc38cb4bfca6f69c37748b1417a51d8a | refs/heads/master | 2022-02-13T02:39:14.724679 | 2019-05-30T22:10:43 | 2019-05-30T22:10:43 | 167,856,869 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 617 | cpp | #include "MarkOfHunger.h"
#include "Particle.h"
MarkOfHunger::MarkOfHunger() : Item("assets/Items/MarkOfHunger.png", "Mark of Hunger", "feed your soul") {}
MarkOfHunger::~MarkOfHunger() {}
void MarkOfHunger::OnKill(LevelManager * game, Player * p, GameObject * go) {
if(rand() % 3 == 0) {
p->Heal(1);
Particle * particle;
for(int i = 0; i < rand() % 5 + 7; i++) {
particle = new Particle(go->GetXCenter() + rand() % 20 - 10, go->GetYCenter() + rand() % 20 - 10, 5, 5, 255, 0, 0, 100);
particle->SetVY(-(rand() % 3 + 5));
particle->SetVX(rand() % 10 - 5);
game->AddObject(particle);
}
}
}
| [
"austinchayka@gmail.com"
] | austinchayka@gmail.com |
484e4864f1a965411f626116eae3985f9564c0fd | 86542fb3d5cd67dd9db3321ce93fc08fb9836cd5 | /include/opengm/inference/lp_inference.hxx | 0e1877aedf5f34e610b3da3b6fdd8739646bb643 | [
"MIT"
] | permissive | herr-biber/opengm | b9df4a15b8a589ffcbc35f73f58ebd9f078275d1 | b4682520500b8fbe9f7b5ef008d162156d33b59c | refs/heads/master | 2021-01-24T23:00:07.914480 | 2013-11-21T15:53:20 | 2013-11-21T15:53:20 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 10,463 | hxx | #pragma once
#ifndef OPENGM_GENERIC_LP_INFERENCE_HXX
#define OPENGM_GENERIC_LP_INFERENCE_HXX
#include <vector>
#include <string>
#include <sstream>
#include <iostream>
#include "opengm/opengm.hxx"
#include "opengm/inference/visitors/visitor.hxx"
#include "opengm/inference/inference.hxx"
#include "opengm/datastructures/buffer_vector.hxx"
#include "lp_inference_base.hxx"
namespace opengm {
template<class GM, class ACC,class LP_SOLVER>
class LPInference : public LpInferenceBase<GM,ACC>, public Inference<GM, ACC>
{
public:
enum Relaxation { FirstOrder,FirstOrder2 };
typedef ACC AccumulationType;
typedef GM GraphicalModelType;
OPENGM_GM_TYPE_TYPEDEFS;
typedef opengm::ShapeWalker<typename FactorType::ShapeIteratorType> FactorShapeWalkerType;
typedef VerboseVisitor<LPInference<GM,ACC,LP_SOLVER> > VerboseVisitorType;
typedef EmptyVisitor<LPInference<GM,ACC,LP_SOLVER> > EmptyVisitorType;
typedef TimingVisitor<LPInference<GM,ACC,LP_SOLVER> > TimingVisitorType;
typedef LP_SOLVER LpSolverType;
typedef typename LpSolverType::Parameter LpSolverParameter;
typedef double LpValueType;
typedef int LpIndexType;
typedef double LpArgType;
class Parameter {
public:
Parameter(
const bool integerConstraint = false,
const bool integerConstraintFactorVar = false,
const LpSolverParameter & lpSolverParamter= LpSolverParameter(),
const Relaxation relaxation = FirstOrder
)
:
integerConstraint_(integerConstraint),
integerConstraintFactorVar_(integerConstraintFactorVar),
lpSolverParameter_(lpSolverParamter),
relaxation_(relaxation){
}
bool integerConstraint_;
bool integerConstraintFactorVar_;
LpSolverParameter lpSolverParameter_;
Relaxation relaxation_;
};
LPInference(const GraphicalModelType&, const Parameter& = Parameter());
std::string name() const;
const GraphicalModelType& graphicalModel() const;
InferenceTermination infer();
void reset();
ValueType bound()const;
ValueType value()const;
template<class VisitorType>
InferenceTermination infer(VisitorType&);
void setStartingPoint(typename std::vector<LabelType>::const_iterator);
virtual InferenceTermination arg(std::vector<LabelType>&, const size_t = 1) const ;
template<class LPVariableIndexIterator,class CoefficientIterator>
void addConstraint(LPVariableIndexIterator , LPVariableIndexIterator , CoefficientIterator ,const ValueType , const ValueType , const std::string & name = std::string() );
private:
void setupLPObjective();
void addFirstOrderRelaxationConstraints();
const GraphicalModelType& gm_;
Parameter param_;
LpSolverType lpSolver_;
std::vector<LabelType> gmArg_;
};
template<class GM, class ACC, class LP_SOLVER>
LPInference<GM,ACC,LP_SOLVER>::LPInference
(
const GraphicalModelType& gm,
const Parameter& parameter
)
: LpInferenceBase<GM,ACC>(gm),
gm_(gm),
param_(parameter),
lpSolver_(parameter.lpSolverParameter_),
gmArg_(gm.numberOfVariables(),static_cast<LabelType>(0) )
{
//std::cout<<"add var 1.\n";
// ADD VARIABLES TO LP SOLVER
lpSolver_.addVariables(this->numberOfNodeLpVariables(),
param_.integerConstraint_ ? LpSolverType::Binary : LpSolverType::Continous, 0.0,1.0
);
//std::cout<<"add var ho.\n";
lpSolver_.addVariables(this->numberOfFactorLpVariables(),
param_.integerConstraintFactorVar_ ? LpSolverType::Binary : LpSolverType::Continous, 0.0,1.0
);
//std::cout<<"add var finished\n";
lpSolver_.addVarsFinished();
OPENGM_CHECK_OP(this->numberOfLpVariables(),==,lpSolver_.numberOfVariables(),"");
// SET UP OBJECTIVE AND UPDATE MODEL (SINCE OBJECTIVE CHANGED)
//std::cout<<"setupLPObjective.\n";
this->setupLPObjective();
//std::cout<<"setupLPObjectiveDone.\n";
lpSolver_.setObjectiveFinished();
// ADD CONSTRAINTS
//std::cout<<"addConstraints.\n";
this->addFirstOrderRelaxationConstraints();
lpSolver_.updateConstraints();
//std::cout<<"setupConstraintsDone\n";
lpSolver_.setupFinished();
}
template<class GM, class ACC, class LP_SOLVER>
void
LPInference<GM,ACC,LP_SOLVER>::setupLPObjective()
{
// max "value-table" size of factors
// and buffer can store the "value-table" of any factor
const IndexType maxFactorSize = findMaxFactorSize(gm_);
ValueType * factorValBuffer = new ValueType[maxFactorSize];
// objective for lpNodeVariables
for(IndexType vi = 0 ; vi<gm_.numberOfVariables();++vi){
if(this->hasUnary(vi)){
gm_[this->unaryFactorIndex(vi)].copyValues(factorValBuffer);
for(LabelType label=0;label<gm_.numberOfLabels(vi);++label)
lpSolver_.setObjective(this->lpNodeVi(vi,label),this->valueToMinSumValue(factorValBuffer[label]));
}
else{
for(LabelType label=0;label<gm_.numberOfLabels(vi);++label)
lpSolver_.setObjective(this->lpNodeVi(vi,label),0.0);
}
}
// objective for lpFactorVariables
for(IndexType fi = 0; fi<gm_.numberOfFactors();++fi){
if(gm_[fi].numberOfVariables() > 1){
gm_[fi].copyValues(factorValBuffer);
for(LabelType labelingIndex=0;labelingIndex<gm_[fi].size();++labelingIndex)
lpSolver_.setObjective(this->lpFactorVi(fi,labelingIndex),this->valueToMinSumValue(factorValBuffer[labelingIndex]));
}
}
// delete buffer which stored the "value-table" of any factor
delete[] factorValBuffer;
}
template<class GM, class ACC, class LP_SOLVER>
inline typename GM::ValueType
LPInference<GM,ACC,LP_SOLVER>::bound() const {
return static_cast<ValueType>(this->valueFromMinSumValue(lpSolver_.lpValue()));
}
template<class GM, class ACC, class LP_SOLVER>
template<class LPVariableIndexIterator,class CoefficientIterator>
void LPInference<GM,ACC,LP_SOLVER>::addConstraint(
LPVariableIndexIterator lpVarBegin,
LPVariableIndexIterator lpVarEnd,
CoefficientIterator coeffBegin,
const LPInference<GM,ACC,LP_SOLVER>::ValueType lowerBound,
const LPInference<GM,ACC,LP_SOLVER>::ValueType upperBound,
const std::string & name
){
lpSolver_.addConstraint(lpVarBegin,lpVarEnd,coeffBegin,lowerBound,upperBound,name);
}
template<class GM, class ACC, class LP_SOLVER>
void
LPInference<GM,ACC,LP_SOLVER>::addFirstOrderRelaxationConstraints(){
// set constraints
UInt64Type constraintCounter = 0;
// \sum_i \mu_i = 1
for(IndexType node = 0; node < gm_.numberOfVariables(); ++node) {
lpSolver_.addConstraint(1.0,1.0);
for(LabelType l = 0; l < gm_.numberOfLabels(node); ++l) {
lpSolver_.addToConstraint(constraintCounter,this->lpNodeVi(node,l),1.0);
}
++constraintCounter;
}
// \sum_i \mu_{f;i_1,...,i_n} - \mu{b;j}= 0
for(IndexType f = 0; f < gm_.numberOfFactors(); ++f) {
if(gm_[f].numberOfVariables() > 1) {
marray::Marray<UInt64Type> temp(gm_[f].shapeBegin(), gm_[f].shapeEnd());
UInt64Type counter = this->lpFactorVi(f,0);
for(marray::Marray<UInt64Type>::iterator mit = temp.begin(); mit != temp.end(); ++mit) {
*mit = counter++;
}
for(IndexType n = 0; n < gm_[f].numberOfVariables(); ++n) {
IndexType node = gm_[f].variableIndex(n);
for(LabelType l=0; l < gm_.numberOfLabels(node); ++l) {
lpSolver_.addConstraint(0.0,0.0);
lpSolver_.addToConstraint(constraintCounter,this->lpNodeVi(node,l),-1.0);
marray::View<UInt64Type> view = temp.boundView(n, l);
for(marray::View<UInt64Type>::iterator vit = view.begin(); vit != view.end(); ++vit) {
OPENGM_CHECK_OP(*vit,>=,this->lpFactorVi(f,0)," ");
lpSolver_.addToConstraint(constraintCounter,*vit,1.0);
}
++constraintCounter;
}
}
}
}
}
template<class GM, class ACC, class LP_SOLVER>
inline InferenceTermination
LPInference<GM,ACC,LP_SOLVER>::infer()
{
EmptyVisitorType v;
return infer(v);
}
template<class GM, class ACC, class LP_SOLVER>
template<class VisitorType>
InferenceTermination LPInference<GM,ACC,LP_SOLVER>::infer
(
VisitorType& visitor
)
{
visitor.begin();
lpSolver_.optimize();
for(IndexType gmVi=0;gmVi<gm_.numberOfVariables();++gmVi){
const LabelType nLabels = gm_.numberOfLabels(gmVi);
LpValueType maxVal = lpSolver_.lpArg(this->lpNodeVi(gmVi,0));
LabelType maxValLabel = 0;
for(LabelType l=1;l<nLabels;++l){
const LabelType val =lpSolver_.lpArg(this->lpNodeVi(gmVi,l));
OPENGM_CHECK_OP(val,<=,1.0,"");
OPENGM_CHECK_OP(val,>=,0.0,"");
if(val>maxVal){
maxValLabel=l;
maxVal=val;
}
}
gmArg_[gmVi]=maxValLabel;
}
visitor.end();
return NORMAL;
}
template<class GM, class ACC, class LP_SOLVER>
inline void
LPInference<GM,ACC,LP_SOLVER>::reset()
{
throw RuntimeError("LPInference::reset() is not implemented yet");
}
template<class GM, class ACC, class LP_SOLVER>
inline void
LPInference<GM,ACC,LP_SOLVER>::setStartingPoint
(
typename std::vector<typename LPInference<GM,ACC,LP_SOLVER>::LabelType>::const_iterator begin
) {
throw RuntimeError("setStartingPoint is not implemented for LPInference");
}
template<class GM, class ACC, class LP_SOLVER>
inline std::string
LPInference<GM,ACC,LP_SOLVER>::name() const
{
return "LPInference";
}
template<class GM, class ACC, class LP_SOLVER>
inline const typename LPInference<GM,ACC,LP_SOLVER>::GraphicalModelType&
LPInference<GM,ACC,LP_SOLVER>::graphicalModel() const
{
return gm_;
}
template<class GM, class ACC, class LP_SOLVER>
inline typename GM::ValueType
LPInference<GM,ACC,LP_SOLVER>::value() const {
std::vector<LabelType> states;
arg(states);
return gm_.evaluate(states);
}
template<class GM, class ACC, class LP_SOLVER>
inline InferenceTermination
LPInference<GM,ACC,LP_SOLVER>::arg
(
std::vector<LabelType>& x,
const size_t N
) const
{
if(N==1) {
x.resize(gm_.numberOfVariables());
for(size_t j=0; j<x.size(); ++j) {
x[j]=gmArg_[j];
}
return NORMAL;
}
else {
return UNKNOWN;
}
}
} // namespace opengm
#endif // #ifndef OPENGM_GENERIC_LP_INFERENCE_HXX
| [
"thorsten.beier@iwr.uni-heidelberg.de"
] | thorsten.beier@iwr.uni-heidelberg.de |
cf92f700e6ef11683c0e98fa92ecb712ff6faf1d | 9946a1c6e1291de309a8882891ca7fe42355710d | /src/parser.cpp | c7a84bbe3448e358e12f6d3e80e76a95452c0177 | [] | no_license | kirbisity/carNoiseFinder | 139b213ec792250fd1d90a97a716918a4a18b095 | 2a8b7e9f38c2f3e17fba006a5d3f17c1d1209159 | refs/heads/master | 2020-06-11T15:37:00.549721 | 2019-10-20T21:32:48 | 2019-10-20T21:32:48 | 194,012,250 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 767 | cpp | #include <sstream>
#include <vector>
#include <string>
/* in current directory */
#include "parser.h"
using namespace std;
vector<double> parse_tabs(string line) {
std::vector<double> tabs;
vector<string> items = split(line);
for (vector<string>::const_iterator i = items.begin(); i != items.end(); ++i) {
double speedentry = -1;
size_t idx = i->find("km/h", 0);
if (idx != string::npos) {
speedentry = atof(i->substr(0, (int)idx).c_str());
}
if (*i == "idle") {
speedentry = 0;
}
if (speedentry != -1) {
tabs.push_back(speedentry);
}
}
return tabs;
}
vector<string> split(string line) {
stringstream ss(line);
istream_iterator<string> begin(ss);
istream_iterator<string> end;
vector<string> items(begin, end);
return items;
}
| [
"zhuy11@rpi.edu"
] | zhuy11@rpi.edu |
f66a9d291d5b6ce6d4fe22062126fded9d521a27 | be0204c1b95839adee1ad204be022be38e32e2d6 | /Programmers/자물쇠와 열쇠.cpp | 57d3ff908b9e7018afc14f3e09dc57fada6c19e6 | [] | no_license | tlsdorye/Problem-Solving | 507bc8d3cf1865c10067ef2e8eb7cb2ee42e16dd | 5c112d2238bfb1fc092612a76f10c7785ba86c78 | refs/heads/master | 2021-06-12T19:19:19.337092 | 2021-04-23T06:39:43 | 2021-04-23T06:39:43 | 179,432,390 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,945 | cpp | #include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <stack>
using namespace std;
vector<vector<int>> rotate(vector<vector<int>>& key);
void print(vector<vector<int>>& map);
bool check(vector<vector<int>>& map, vector<vector<int>>& key, int x, int y, int N);
bool solution(vector<vector<int>> key, vector<vector<int>> lock) {
int M = key.size();
int N = lock.size();
int K = N + 2 * M - 2;
vector<vector<int>> map(K, vector<int>(K, 0));
for (int i = M - 1; i < N + M - 1; i++)
for (int j = M - 1; j < N + M - 1; j++)
map[i][j] = lock[i - M + 1][j - M + 1];
for (int k = 0; k < 4; k++)
{
key = rotate(key);
//print(key);
for (int i = 0; i < K - M + 1; i++)
{
bool flag = true;
for (int j = 0; j < K - M + 1; j++)
{
if (!check(map, key, i, j, N))
{
//printf("%2d %2d %2d: false\n", k, i, j);
flag = false;
}
else
{
//printf("%2d %2d %2d: true\n", k, i, j);
return true;
}
}
if (flag) break;
}
}
return false;
}
vector<vector<int>> rotate(vector<vector<int>>& key)
{
int M = key.size();
vector<vector<int>> ret(M, vector<int>(M, 0));
for (int i = 0; i < M; i++)
for (int j = 0; j < M; j++)
ret[i][j] = key[-j + M - 1][i];
return ret;
}
void print(vector<vector<int>>& map)
{
for (int i = 0; i < map.size(); i++, printf("\n"))
for (int j = 0; j < map[i].size(); j++)
printf("%d ", map[i][j]);
}
bool check(vector<vector<int>>& map, vector<vector<int>>& key, int x, int y, int N)
{
bool ret = true;
int M = key.size();
for (int i = x; i < x + M; i++)
for (int j = y; j < y + M; j++)
map[i][j] += key[i - x][j - y];
for (int i = M - 1; i < N + M - 1; i++)
{
for (int j = M - 1; j < N + M - 1; j++)
if (map[i][j] != 1)
{
ret = false;
break;
}
if (!ret) break;
}
for (int i = x; i < x + M; i++)
for (int j = y; j < y + M; j++)
map[i][j] -= key[i - x][j - y];
return ret;
} | [
"tlsdorye@gmail.com"
] | tlsdorye@gmail.com |
462fa9f66728e67254badcb1f8ec734cc4e43e74 | 58457320f8ecc206f5c37a84fdeae32f2d8b692f | /SecondPushButton.cpp | 57896975ec1878a7de49f18754f792e9eebaec86 | [] | no_license | freedomgll/DeskCallQt | 9dcffbe3f06537cf0b335453cdd1f371f3302f9c | cb5b1598cda1e65b372c341222c0eec15b5f36f1 | refs/heads/master | 2021-01-18T14:01:30.900037 | 2015-08-12T09:48:39 | 2015-08-12T09:48:39 | 39,882,671 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,312 | cpp | #include "SecondPushButton.h"
#include "FirstPushButton.h"
#include <QMessageBox>
#include <QtDebug>
SecondPushButton::SecondPushButton(void)
{
}
SecondPushButton::SecondPushButton(const QString & text, QString businessId, const QRect & rect, DeskCallQT * parent):CoderPushButton(text, rect, parent)
{
this->businessId = businessId;
connect(this, SIGNAL(clicked()),this,SLOT(clickAction()));
}
SecondPushButton::~SecondPushButton(void)
{
}
void SecondPushButton::clickAction()
{
if(this->text() == QStringLiteral("·µ»Ø/Return"))
{
ConfigSql confSql = ConfigSql();
QList<classT> classList;
foreach(QString regionid, this->parent->configSettings.RegionIDs)
{
classList.append(confSql.queryLClass(regionid));
}
QList<QRect> lRects =ConfigUtils::CaculateButtonRects(classList.size(),this->parent->width(),this->parent->height(),this->parent->configSettings.postion);
qDebug() << lRects;
QList<CoderPushButton *> buttonList;
for(int i = 0; i < classList.size(); ++i)
{
CoderPushButton *pushButton= new FirstPushButton(classList[i].classname, classList[i].classid, lRects[i], this->parent);
buttonList.append(pushButton);
}
this->parent->RecreateButtonList(buttonList);
}
else
{
QMessageBox msgBox;
msgBox.setText(this->businessId);
msgBox.exec();
}
}
| [
"freedomgll@163.com"
] | freedomgll@163.com |
39647b9606042e9148402b385fbc5e529999f387 | da50cb2f2da79a0f9503d57f685d070543402311 | /Source/CoopGame/Public/SHealthComponent.h | 8298c5479807290144cbfbbca568e37e53b3364c | [] | no_license | vsensu/CoopGame | d9831951e79b63d7f764f8b9fe613f05fcea9a25 | 02961ef871cbf7996d6818b13c94bcb6cf68bdfa | refs/heads/master | 2022-10-27T11:46:24.822795 | 2020-06-09T06:50:26 | 2020-06-09T06:50:26 | 267,760,381 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,245 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Components/ActorComponent.h"
#include "SHealthComponent.generated.h"
DECLARE_DYNAMIC_MULTICAST_DELEGATE_SixParams(FOnHealthChangedSignature, USHealthComponent*, HealthComp, float, Health, float, HealthDelta, const class UDamageType*, DamageType, class AController*, InstigatedBy, AActor*, DamageCauser);
UCLASS( ClassGroup=(COOP), meta=(BlueprintSpawnableComponent) )
class COOPGAME_API USHealthComponent : public UActorComponent
{
GENERATED_BODY()
public:
// Sets default values for this component's properties
USHealthComponent();
protected:
// Called when the game starts
virtual void BeginPlay() override;
UPROPERTY(Replicated, BlueprintReadOnly, Category="HealthComponent")
float Health;
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category="HealthComponent")
float DefaultHealth;
UFUNCTION()
void HandleTakeAnyDamage(AActor* DamagedActor, float Damage, const class UDamageType* DamageType, class AController* InstigatedBy, AActor* DamageCauser);
public:
UPROPERTY(BlueprintAssignable, Category="Events")
FOnHealthChangedSignature OnHealthChanged;
};
| [
"vsensu@foxmail.com"
] | vsensu@foxmail.com |
6058d43c3fd909898abf19a33ecb0fe385a8285c | 57a2ff675497083c6c126279d64da6caf10e1022 | /include/RE/BSResource/Info.h | 81ab6bb475ad050eb804f91932710700fb7f86b3 | [
"MIT"
] | permissive | lfrazer/CommonLibVR | be07b8837034e069addae3309da872bb606bd585 | 0fabedac02c4d97b7d54199098561be8c0c666ef | refs/heads/master | 2021-12-30T23:04:52.654616 | 2021-09-26T18:39:22 | 2021-09-26T18:39:22 | 252,837,323 | 7 | 7 | MIT | 2021-05-08T17:53:09 | 2020-04-03T20:45:36 | C++ | UTF-8 | C++ | false | false | 248 | h | #pragma once
namespace RE
{
namespace BSResource
{
struct Info
{
public:
// members
FILETIME modifyTime; // 00
FILETIME createTime; // 08
LARGE_INTEGER fileSize; // 10
};
STATIC_ASSERT(sizeof(Info) == 0x18);
}
}
| [
"ryan__mckenzie@hotmail.com"
] | ryan__mckenzie@hotmail.com |
daaa0a13aa163ede36bac38d824459892b879cec | 8a2e417c772eba9cf4653d0c688dd3ac96590964 | /prop-src/setltype.cc | 39f66c50d6bf929478b0d17220a18817abb01551 | [
"LicenseRef-scancode-public-domain",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | romix/prop-cc | 1a190ba6ed8922428352826de38efb736e464f50 | 3f7f2e4a4d0b717f4e4f3dbd4c7f9d1f35572f8f | refs/heads/master | 2023-08-30T12:55:00.192286 | 2011-07-19T20:56:39 | 2011-07-19T20:56:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,964 | cc | ///////////////////////////////////////////////////////////////////////////////
// This file is generated automatically using Prop (version 2.4.0),
// last updated on Jul 1, 2011.
// The original source file is "..\..\prop-src\setltype.pcc".
///////////////////////////////////////////////////////////////////////////////
#define PROP_TUPLE2_USED
#include <propdefs.h>
#line 1 "../../prop-src/setltype.pcc"
///////////////////////////////////////////////////////////////////////////////
//
// This file implements the type checker for the SETL-like sublanguage.
//
///////////////////////////////////////////////////////////////////////////////
#include "ir.h"
#include "ast.h"
#include "setl-ast.h"
#include "setlgen.h"
#include "type.h"
#include "env.h"
///////////////////////////////////////////////////////////////////////////////
//
// Method to elaborate a definition.
//
///////////////////////////////////////////////////////////////////////////////
Env type_of( Def def, const Env& E)
{
return E;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to elaborate a definition list.
//
///////////////////////////////////////////////////////////////////////////////
Env type_of( Defs defs, const Env& E)
{
return E;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to unify two expressions type.
//
///////////////////////////////////////////////////////////////////////////////
Bool unify( Exp exp, Ty a, Ty b)
{
if (! unify(a,b))
{
error( "%Ltype mismatch in expression: %f\n"
"%Lexpecting '%T' but found '%T'\n", exp, a, b);
return false;
}
else
return true;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to infer the type of an expression.
//
///////////////////////////////////////////////////////////////////////////////
Ty type_of( Exp exp, const Env& E)
{
Ty ty = NOty;
#line 61 "../../prop-src/setltype.pcc"
#line 121 "../../prop-src/setltype.pcc"
{
if (exp) {
switch (exp->tag__) {
case a_Exp::tag_LITERALexp: {
#line 63 "../../prop-src/setltype.pcc"
ty = type_of(_LITERALexp(exp)->LITERALexp);
#line 63 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_IDexp: {
#line 64 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 64 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_RELexp: {
#line 73 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 73 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_DOTexp: {
#line 74 "../../prop-src/setltype.pcc"
ty = component_ty(type_of(_DOTexp(exp)->_1,E),_DOTexp(exp)->_2);
#line 74 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_SELECTORexp: {
#line 75 "../../prop-src/setltype.pcc"
ty = component_ty(type_of(_SELECTORexp(exp)->_1,E),_SELECTORexp(exp)->_2);
#line 75 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_DEREFexp: {
#line 76 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 76 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_ARROWexp: {
#line 77 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 77 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_INDEXexp: {
#line 78 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 78 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_BINOPexp: {
#line 79 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 79 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_PREFIXexp: {
#line 80 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 80 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_POSTFIXexp: {
#line 81 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 81 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_APPexp: {
#line 82 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 82 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_ASSIGNexp: {
#line 83 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 83 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_IFexp: {
#line 84 "../../prop-src/setltype.pcc"
ty = mkvar();
#line 84 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_TUPLEexp: {
#line 85 "../../prop-src/setltype.pcc"
return mktuplety(type_of(_TUPLEexp(exp)->TUPLEexp,E));
#line 85 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_EXTUPLEexp: {
#line 86 "../../prop-src/setltype.pcc"
return extuplety(type_of(_EXTUPLEexp(exp)->EXTUPLEexp,E));
#line 86 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_RECORDexp: {
#line 88 "../../prop-src/setltype.pcc"
#line 89 "../../prop-src/setltype.pcc"
Tuple2<Ids, Tys>
#line 89 "../../prop-src/setltype.pcc"
t = type_of( _RECORDexp(exp)->RECORDexp, E);
return mkrecordty( t._1, t._2, false);
} break;
case a_Exp::tag_LISTexp: {
if (_LISTexp(exp)->_1) {
#line 94 "../../prop-src/setltype.pcc"
Tys head_tys = type_of( _LISTexp(exp)->_3, E);
Ty tail_ty = type_of( _LISTexp(exp)->_4, E);
Ty arg_ty = mkvar();
for_each (Ty, one_ty, head_tys)
unify( exp, one_ty, arg_ty);
Ty fun_ty = inst( _LISTexp(exp)->_1->cons_ty);
ty = mkvar();
unify( exp, fun_ty, mkfunty( mktuplety(
#line 102 "../../prop-src/setltype.pcc"
#line 102 "../../prop-src/setltype.pcc"
list_1_(arg_ty,list_1_(mkvar()))
#line 102 "../../prop-src/setltype.pcc"
#line 102 "../../prop-src/setltype.pcc"
), ty));
if (_LISTexp(exp)->_4 != NOexp)
unify( exp, tail_ty, ty);
#line 105 "../../prop-src/setltype.pcc"
} else {
L1:;
#line 121 "../../prop-src/setltype.pcc"
ty = NOty;
#line 121 "../../prop-src/setltype.pcc"
}
} break;
case a_Exp::tag_VECTORexp: {
#line 106 "../../prop-src/setltype.pcc"
return mkvar();
#line 106 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_CONSexp: {
if (_CONSexp(exp)->_1) {
if (_CONSexp(exp)->_3) {
#line 69 "../../prop-src/setltype.pcc"
Ty fun_ty = inst(_CONSexp(exp)->_1->cons_ty);
ty = mkvar();
unify(exp,fun_ty,mkfunty(type_of(_CONSexp(exp)->_3,E),ty));
#line 72 "../../prop-src/setltype.pcc"
} else {
#line 67 "../../prop-src/setltype.pcc"
ty = inst(_CONSexp(exp)->_1->cons_ty);
#line 67 "../../prop-src/setltype.pcc"
}
} else { goto L1; }
} break;
case a_Exp::tag_CASTexp: {
#line 107 "../../prop-src/setltype.pcc"
type_of(_CASTexp(exp)->_2,E); return _CASTexp(exp)->_1;
#line 107 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_QUALexp: {
#line 108 "../../prop-src/setltype.pcc"
return mkvar();
#line 108 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_EQexp: {
#line 109 "../../prop-src/setltype.pcc"
return bool_ty;
#line 109 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_UNIFYexp: {
#line 110 "../../prop-src/setltype.pcc"
return NOty;
#line 110 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_LTexp: {
#line 111 "../../prop-src/setltype.pcc"
return bool_ty;
#line 111 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_HASHexp: {
#line 112 "../../prop-src/setltype.pcc"
return integer_ty;
#line 112 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_THISCOSTexp: {
#line 113 "../../prop-src/setltype.pcc"
return integer_ty;
#line 113 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_COSTexp: {
#line 114 "../../prop-src/setltype.pcc"
return integer_ty;
#line 114 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_THISSYNexp: {
#line 115 "../../prop-src/setltype.pcc"
return _THISSYNexp(exp)->_2;
#line 115 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_SYNexp: {
#line 116 "../../prop-src/setltype.pcc"
return _SYNexp(exp)->_3;
#line 116 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_SENDexp: {
#line 92 "../../prop-src/setltype.pcc"
return mkvar();
#line 92 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_SETLexp: {
#line 117 "../../prop-src/setltype.pcc"
ty = NOty;
#line 117 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_LISTCOMPexp: {
#line 118 "../../prop-src/setltype.pcc"
ty = NOty;
#line 118 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_FORALLexp: {
#line 119 "../../prop-src/setltype.pcc"
ty = NOty;
#line 119 "../../prop-src/setltype.pcc"
} break;
case a_Exp::tag_EXISTSexp: {
#line 120 "../../prop-src/setltype.pcc"
ty = NOty;
#line 120 "../../prop-src/setltype.pcc"
} break;
default: {
#line 65 "../../prop-src/setltype.pcc"
_MARKEDexp(exp)->_1.set_loc(); ty = type_of(_MARKEDexp(exp)->_2,E);
#line 65 "../../prop-src/setltype.pcc"
} break;
}
} else {
#line 62 "../../prop-src/setltype.pcc"
ty = NOty;
#line 62 "../../prop-src/setltype.pcc"
}
}
#line 122 "../../prop-src/setltype.pcc"
#line 122 "../../prop-src/setltype.pcc"
ty = deref(ty);
if (boxed(exp))
exp->ty = ty;
return ty;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to infer the type of an expression list.
//
///////////////////////////////////////////////////////////////////////////////
Tys type_of( Exps es, const Env& E)
{
#line 138 "../../prop-src/setltype.pcc"
#line 140 "../../prop-src/setltype.pcc"
{
if (es) {
#line 140 "../../prop-src/setltype.pcc"
return list_1_(type_of(es->_1,E),type_of(es->_2,E));
#line 140 "../../prop-src/setltype.pcc"
} else {
#line 139 "../../prop-src/setltype.pcc"
return nil_1_;
#line 139 "../../prop-src/setltype.pcc"
}
}
#line 141 "../../prop-src/setltype.pcc"
#line 141 "../../prop-src/setltype.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to infer the type of an labeled expression list.
//
///////////////////////////////////////////////////////////////////////////////
#line 150 "../../prop-src/setltype.pcc"
Tuple2<Ids, Tys>
#line 150 "../../prop-src/setltype.pcc"
type_of( LabExps es, const Env& E)
{ Ids labels =
#line 151 "../../prop-src/setltype.pcc"
nil_1_
#line 151 "../../prop-src/setltype.pcc"
#line 151 "../../prop-src/setltype.pcc"
;
Tys tys =
#line 152 "../../prop-src/setltype.pcc"
#line 152 "../../prop-src/setltype.pcc"
nil_1_
#line 152 "../../prop-src/setltype.pcc"
#line 152 "../../prop-src/setltype.pcc"
;
#line 153 "../../prop-src/setltype.pcc"
#line 160 "../../prop-src/setltype.pcc"
{
for (;;) {
if (es) {
#line 156 "../../prop-src/setltype.pcc"
labels =
#line 157 "../../prop-src/setltype.pcc"
#line 157 "../../prop-src/setltype.pcc"
list_1_(es->_1.label,labels)
#line 157 "../../prop-src/setltype.pcc"
#line 157 "../../prop-src/setltype.pcc"
;
tys =
#line 158 "../../prop-src/setltype.pcc"
#line 158 "../../prop-src/setltype.pcc"
list_1_(type_of(es->_1.exp,E),tys)
#line 158 "../../prop-src/setltype.pcc"
#line 158 "../../prop-src/setltype.pcc"
;
es = es->_2;
#line 160 "../../prop-src/setltype.pcc"
} else { goto L2; }
}
L2:;
}
#line 161 "../../prop-src/setltype.pcc"
#line 161 "../../prop-src/setltype.pcc"
return
#line 162 "../../prop-src/setltype.pcc"
#line 162 "../../prop-src/setltype.pcc"
mkTuple2(labels,tys)
#line 162 "../../prop-src/setltype.pcc"
#line 162 "../../prop-src/setltype.pcc"
;
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to infer the type of a statement.
//
///////////////////////////////////////////////////////////////////////////////
void type_of (Stmt s, const Env& E)
{
#line 173 "../../prop-src/setltype.pcc"
#line 185 "../../prop-src/setltype.pcc"
{
if (s) {
switch (s->tag__) {
case a_Stmt::tag_ASSIGNstmt: {} break;
case a_Stmt::tag_BLOCKstmt: {} break;
case a_Stmt::tag_WHILEstmt: {} break;
case a_Stmt::tag_IFstmt: {} break;
case a_Stmt::tag_MATCHstmt: {} break;
case a_Stmt::tag_REWRITEstmt: {} break;
case a_Stmt::tag_REPLACEMENTstmt: {} break;
case a_Stmt::tag_FORALLstmt: {} break;
default: {} break;
}
} else {}
}
#line 185 "../../prop-src/setltype.pcc"
#line 185 "../../prop-src/setltype.pcc"
}
///////////////////////////////////////////////////////////////////////////////
//
// Method to infer the type of a list of statements.
//
///////////////////////////////////////////////////////////////////////////////
void type_of( Stmts ss, const Env& E)
{
#line 196 "../../prop-src/setltype.pcc"
#line 198 "../../prop-src/setltype.pcc"
{
for (;;) {
if (ss) {
#line 198 "../../prop-src/setltype.pcc"
type_of( ss->_1, E); ss = ss->_2;
#line 198 "../../prop-src/setltype.pcc"
} else { goto L3; }
}
L3:;
}
#line 199 "../../prop-src/setltype.pcc"
#line 199 "../../prop-src/setltype.pcc"
}
#line 201 "../../prop-src/setltype.pcc"
/*
------------------------------- Statistics -------------------------------
Merge matching rules = yes
Number of DFA nodes merged = 43
Number of ifs generated = 8
Number of switches generated = 2
Number of labels = 1
Number of gotos = 1
Adaptive matching = disabled
Fast string matching = disabled
Inline downcasts = disabled
--------------------------------------------------------------------------
*/
| [
"aaronngray@gmail.com"
] | aaronngray@gmail.com |
84104d1e1b3357829e1657394372afdf159b0178 | 3ad968797a01a4e4b9a87e2200eeb3fb47bf269a | /MFC CodeGuru/tools/odbc_classgen/W/VCP/FastTest/FastTestView.h | cfb7e74f35a87f9343c5b69f23d8ffe3d9cc9cc3 | [] | no_license | LittleDrogon/MFC-Examples | 403641a1ae9b90e67fe242da3af6d9285698f10b | 1d8b5d19033409cd89da3aba3ec1695802c89a7a | refs/heads/main | 2023-03-20T22:53:02.590825 | 2020-12-31T09:56:37 | 2020-12-31T09:56:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,753 | h | // FastTestView.h : interface of the CFastTestView class
//
/////////////////////////////////////////////////////////////////////////////
#if !defined(AFX_FASTTESTVIEW_H__7137DC99_B77C_11D1_AE72_0004AC31E75C__INCLUDED_)
#define AFX_FASTTESTVIEW_H__7137DC99_B77C_11D1_AE72_0004AC31E75C__INCLUDED_
#if _MSC_VER >= 1000
#pragma once
#endif // _MSC_VER >= 1000
#include "LocationsSet.h"
class CFastTestView : public CListView
{
protected: // create from serialization only
CFastTestView();
DECLARE_DYNCREATE(CFastTestView)
// Attributes
public:
CFastTestDoc* GetDocument();
// Operations
public:
CLocationsSet* m_pLocationsSet;
// Overrides
// ClassWizard generated virtual function overrides
//{{AFX_VIRTUAL(CFastTestView)
public:
virtual void OnDraw(CDC* pDC); // overridden to draw this view
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
protected:
virtual void OnInitialUpdate(); // called first time after construct
//}}AFX_VIRTUAL
// Implementation
public:
virtual ~CFastTestView();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected:
// Generated message map functions
protected:
//{{AFX_MSG(CFastTestView)
afx_msg void OnGetdispinfo(NMHDR* pNMHDR, LRESULT* pResult);
//}}AFX_MSG
DECLARE_MESSAGE_MAP()
};
#ifndef _DEBUG // debug version in FastTestView.cpp
inline CFastTestDoc* CFastTestView::GetDocument()
{ return (CFastTestDoc*)m_pDocument; }
#endif
/////////////////////////////////////////////////////////////////////////////
//{{AFX_INSERT_LOCATION}}
// Microsoft Developer Studio will insert additional declarations immediately before the previous line.
#endif // !defined(AFX_FASTTESTVIEW_H__7137DC99_B77C_11D1_AE72_0004AC31E75C__INCLUDED_)
| [
"pkedpekr@gmail.com"
] | pkedpekr@gmail.com |
b38c90b09967d05387ef94b5c859f981400c6cb1 | 95626140b639c93a5bc7d86c5ed7cead4d27372a | /Online Judge/HackerRank/Sherlock and Array.cpp | 6aab97fb4ebb7f802135e58e39aa80b51eea3fb5 | [] | no_license | asad-shuvo/ACM | 059bed7f91261af385d1be189e544fe240da2ff2 | 2dea0ef7378d831097efdf4cae25fbc6f34b8064 | refs/heads/master | 2022-06-08T13:03:04.294916 | 2022-05-13T12:22:50 | 2022-05-13T12:22:50 | 211,629,208 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,094 | cpp | #include <bits/stdc++.h>
using namespace std;
string ltrim(const string &);
string rtrim(const string &);
vector<string> split(const string &);
// Complete the balancedSums function below.
string balancedSums(vector<int> arr) {
int cm[arr.size()+5];
for(int i=0;i<arr.size();i++){
if(i==0){
cm[i]=arr[i];
continue;
}
cm[i]=arr[i]+cm[i-1];
}
int f=0;
for(int i=0;i<arr.size();i++){
int l=0,r=0;
if(i==0){
l=0;
r=cm[arr.size()-1]-cm[i];
}
else if(i==arr.size()-1){
r=0;
l=cm[i-1];
}
else{
l=cm[i-1];
r=cm[arr.size()-1]-cm[i];
}
if(l==r)f=1;
}
if(f==1)return "YES";
else return "NO";
}
int main()
{
ofstream fout(getenv("OUTPUT_PATH"));
string T_temp;
getline(cin, T_temp);
int T = stoi(ltrim(rtrim(T_temp)));
for (int T_itr = 0; T_itr < T; T_itr++) {
string n_temp;
getline(cin, n_temp);
int n = stoi(ltrim(rtrim(n_temp)));
string arr_temp_temp;
getline(cin, arr_temp_temp);
vector<string> arr_temp = split(rtrim(arr_temp_temp));
vector<int> arr(n);
for (int i = 0; i < n; i++) {
int arr_item = stoi(arr_temp[i]);
arr[i] = arr_item;
}
string result = balancedSums(arr);
fout << result << "\n";
}
fout.close();
return 0;
}
string ltrim(const string &str) {
string s(str);
s.erase(
s.begin(),
find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace)))
);
return s;
}
string rtrim(const string &str) {
string s(str);
s.erase(
find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(),
s.end()
);
return s;
}
vector<string> split(const string &str) {
vector<string> tokens;
string::size_type start = 0;
string::size_type end = 0;
while ((end = str.find(" ", start)) != string::npos) {
tokens.push_back(str.substr(start, end - start));
start = end + 1;
}
tokens.push_back(str.substr(start));
return tokens;
}
| [
"asad.shuvo.cse@gmail.com"
] | asad.shuvo.cse@gmail.com |
7b06942a85b29cc538ba9cbf78fe0a7ef5eca062 | 054edeb9e6e6c2d112d19af2ebe07b2e0c6c04b0 | /Micelle/include/CloudGenerator.h | 4d32a0cff000751474969015d250d52b024d7881 | [] | no_license | YuryUoL/DataSkeletonization | b6873d59c42bd1d42e517af153491c425cd0e95c | fd181dc076662d25a84a76dd067e343498206474 | refs/heads/master | 2020-03-31T21:28:14.359241 | 2019-03-15T12:42:54 | 2019-03-15T12:42:54 | 152,581,810 | 0 | 1 | null | 2018-11-19T10:07:09 | 2018-10-11T11:37:56 | C++ | UTF-8 | C++ | false | false | 320 | h | #ifndef CLOUDGENERATOR_H
#define CLOUDGENERATOR_H
#include "Definitions.h"
#include "Graph.h"
class CloudGenerator
{
public:
CloudGenerator();
static void generatePoints(int n, MyGraphType & G, double epsilon, std::list<Point> & points);
protected:
private:
};
#endif // CLOUDGENERATOR_H
| [
"yura.elkin@gmail.com"
] | yura.elkin@gmail.com |
6d016d68ee3475b6edfcedffe584b68b73b7f3f3 | 4c23be1a0ca76f68e7146f7d098e26c2bbfb2650 | /ic8h18/0.009/CC5H10OOH-B | 0ad74b9d185f0f7857aa19a185a907d826e6d578 | [] | no_license | labsandy/OpenFOAM_workspace | a74b473903ddbd34b31dc93917e3719bc051e379 | 6e0193ad9dabd613acf40d6b3ec4c0536c90aed4 | refs/heads/master | 2022-02-25T02:36:04.164324 | 2019-08-23T02:27:16 | 2019-08-23T02:27:16 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 842 | /*--------------------------------*- C++ -*----------------------------------*\
========= |
\\ / F ield | OpenFOAM: The Open Source CFD Toolbox
\\ / O peration | Website: https://openfoam.org
\\ / A nd | Version: 6
\\/ M anipulation |
\*---------------------------------------------------------------------------*/
FoamFile
{
version 2.0;
format ascii;
class volScalarField;
location "0.009";
object CC5H10OOH-B;
}
// * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * //
dimensions [0 0 0 0 0 0 0];
internalField uniform 5.1425e-39;
boundaryField
{
boundary
{
type empty;
}
}
// ************************************************************************* //
| [
"jfeatherstone123@gmail.com"
] | jfeatherstone123@gmail.com |
|
7988c1ec8e42adaa7cb0013284f5bf8c4eaa9180 | ea065794fe1b35dbc7923d539b4f85bd41277c2b | /n_queens.cc | 2386b4de07dc5444a7f61e39bf8ce4e2e2b819d5 | [] | no_license | sergiovasquez122/EPI_SOLUTIONS | 6e93e98ad8b0c3b8e0e162f5e8c04b7a6b24f47f | 6e39cf2a981d34516fd1037d0ce3c65d0ebb4133 | refs/heads/master | 2022-12-09T17:55:48.066759 | 2020-08-15T01:33:50 | 2020-08-15T01:33:50 | 268,199,261 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,146 | cc | #include <algorithm>
#include <iterator>
#include <vector>
#include "test_framework/generic_test.h"
using std::vector;
bool is_valid(vector<int>& partial, int candidate, int row){
for(int i = 0;i <= row - 1;++i){
if(candidate == partial[i] || std::abs(candidate - partial[i]) == row - i){
return false;
}
}
return true;
}
void helper(vector<vector<int>>& result, vector<int>& partial, int row, int n){
if(row == n){
result.push_back(partial);
return;
}
for(int i = 0;i < n;++i){
if(is_valid(partial, i, row)){
partial.push_back(i);
helper(result, partial, row + 1, n);
partial.pop_back();
}
}
}
vector<vector<int>> NQueens(int n) {
vector<vector<int>> result;
vector<int> partial;
helper(result, partial, 0, n);
return result;
}
int main(int argc, char* argv[]) {
std::vector<std::string> args{argv + 1, argv + argc};
std::vector<std::string> param_names{"n"};
return GenericTestMain(args, "n_queens.cc", "n_queens.tsv", &NQueens,
UnorderedComparator{}, param_names);
}
| [
"sergiovasquez122@gmail.com"
] | sergiovasquez122@gmail.com |
b19f7e9aeb6cf9a7d64c9c606d042b3e4ad41a7c | 7d1fa8db4712a57a2cab77a0d44340adbffbbdf6 | /GPU_Programming_Assignment/cDirectionalLight.h | 532a817195b2e04abaffcfe8594935f4baa9b086 | [] | no_license | ben-kiddie/GPU-Programming-Assignment | f02a5ce15c1d1f8c414a3c24950a62f7d0c64930 | a4914d49671325ea332102731059ec4042d0cd80 | refs/heads/master | 2023-08-16T02:29:13.976294 | 2021-10-11T15:00:58 | 2021-10-11T15:00:58 | 354,562,681 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 475 | h | #pragma once
#include "cLight.h"
class DirectionalLight : public Light
{
public:
DirectionalLight();
DirectionalLight(GLfloat red, GLfloat green, GLfloat blue,
GLfloat ambIntensity, GLfloat diffIntensity,
GLfloat xDirection, GLfloat yDirection, GLfloat zDirection);
~DirectionalLight();
void UseLight(GLuint ambientIntensityLocation, GLuint ambientColourLocation,
GLuint diffuseIntensityLocation, GLuint directionLocation);
private:
glm::vec3 mDirection;
};
| [
"76003977+ben-kiddie@users.noreply.github.com"
] | 76003977+ben-kiddie@users.noreply.github.com |
881011b2897260c46e031f813734aceb72672439 | 21dd1ece27a68047f93bac2bdf9e6603827b1990 | /VizKit-2 2.3/source/VisualObjectData.cpp | 15b0fe05fa431eed37365738739924ea9a156126 | [] | no_license | LupusDei/8LU-DSP | c626ce817b6b178c226c437537426f25597958a5 | 65860326bb89a36ff71871b046642b7dd45d5607 | refs/heads/master | 2021-01-17T21:51:19.971505 | 2010-09-24T15:08:01 | 2010-09-24T15:08:01 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,278 | cpp | /*
* Project: VizKit
* Version: 2.3
* Date: 20090823
* File: VisualObjectData.cpp
*
*/
/***************************************************************************
Copyright (c) 2004-2009 Heiko Wichmann (http://www.imagomat.de/vizkit)
This software is provided 'as-is', without any expressed 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.
***************************************************************************/
#include "VisualObjectData.h"
#include "VisualErrorHandling.h"
#include "VisualNetwork.h"
#include "VisualItemIdentifier.h"
using namespace VizKit;
VisualObjectData::VisualObjectData() {
data = NULL;
dataSizeAllocated = 0;
dataSizeUsed = 0;
dataSizeDeclared = 0;
dataSizeDeclaredHasBeenSetBool = false;
refCount = 1;
hasObjectBool = true;
itemIdentifier = new VisualItemIdentifier;
isDownloadingBool = false;
visualObjectMutex = new VisualObjectMutex;
}
VisualObjectData::VisualObjectData(const VisualItemIdentifier& anIdentifier) {
itemIdentifier = new VisualItemIdentifier(anIdentifier);
data = NULL;
dataSizeAllocated = 0;
dataSizeUsed = 0;
dataSizeDeclared = 0;
dataSizeDeclaredHasBeenSetBool = false;
refCount = 1;
hasObjectBool = true;
isDownloadingBool = false;
visualObjectMutex = new VisualObjectMutex;
}
VisualObjectData::~VisualObjectData() {
if (data != NULL) {
free(data);
}
delete itemIdentifier;
delete visualObjectMutex;
}
VisualObjectData::VisualObjectData(const VisualObjectData& other) {
this->copyObject(other);
}
VisualObjectData& VisualObjectData::operator=(const VisualObjectData& other) {
if (this == &other) return *this;
if (this->data != NULL) {
free(this->data);
}
delete this->itemIdentifier;
delete this->visualObjectMutex;
this->visualObjectMutex = NULL;
this->copyObject(other);
return *this;
}
bool VisualObjectData::operator<(const VisualObjectData& other) const {
return this->itemIdentifier < other.itemIdentifier;
}
bool VisualObjectData::operator>(const VisualObjectData& other) const {
return this->itemIdentifier > other.itemIdentifier;
}
bool VisualObjectData::operator==(const VisualObjectData& other) const {
return this->itemIdentifier == other.itemIdentifier;
}
bool VisualObjectData::operator!=(const VisualObjectData& other) const {
return this->itemIdentifier != other.itemIdentifier;
}
const VisualItemIdentifier VisualObjectData::getIdentifier() const {
return *(this->itemIdentifier);
}
bool VisualObjectData::addData(void* dataPtr, uint32 dataSize) {
bool success = true;
if (this->dataSizeAllocated < (this->dataSizeUsed + dataSize)) {
while (this->dataSizeAllocated < (this->dataSizeUsed + dataSize)) {
if (this->dataSizeAllocated == 0) {
uint32 initialAllocationSize = dataSize;
if ((this->dataSizeDeclaredHasBeenSetBool == true) && (this->dataSizeDeclared > dataSize)) {
initialAllocationSize = this->dataSizeDeclared;
}
this->data = (char*)malloc(initialAllocationSize * sizeof(char));
this->dataSizeAllocated = initialAllocationSize;
} else {
if ((this->dataSizeDeclaredHasBeenSetBool == true) && (this->dataSizeDeclared >= this->dataSizeUsed + dataSize)) {
this->dataSizeAllocated = this->dataSizeDeclared;
} else {
this->dataSizeAllocated *= 2;
}
this->data = (char*)realloc(this->data, this->dataSizeAllocated);
if (this->data == NULL) {
char errLog[256];
sprintf(errLog, "Err: Realloc failed in file: %s (line: %d) [%s])", __FILE__, __LINE__, __FUNCTION__);
writeLog(errLog);
}
}
}
}
memcpy(this->data + this->dataSizeUsed, dataPtr, dataSize);
this->dataSizeUsed += dataSize;
return success;
}
void VisualObjectData::freeData(void) {
if (this->data) {
free(this->data);
this->data = NULL;
this->dataSizeAllocated = 0;
this->dataSizeUsed = 0;
}
}
size_t VisualObjectData::getDataSizeUsed() {
return this->dataSizeUsed;
}
size_t VisualObjectData::getDataSizeDeclared() {
return this->dataSizeDeclared;
}
void VisualObjectData::setDataSizeDeclared(const size_t& aDataSizeDeclared) {
this->dataSizeDeclared = aDataSizeDeclared;
this->dataSizeDeclaredHasBeenSetBool = true;
}
bool VisualObjectData::dataSizeDeclaredHasBeenSet(void) {
return this->dataSizeDeclaredHasBeenSetBool;
}
void VisualObjectData::release() {
this->refCount--;
}
size_t VisualObjectData::getRefCount(void) {
return this->refCount;
}
bool VisualObjectData::hasObject(){
return this->hasObjectBool;
}
bool VisualObjectData::isDownloading(void) {
return this->isDownloadingBool;
}
void VisualObjectData::setIsDownloading(bool isDownloadingBoolean) {
this->isDownloadingBool = isDownloadingBoolean;
}
void VisualObjectData::enterCriticalRegion() {
this->visualObjectMutex->enterCriticalRegion();
}
void VisualObjectData::exitCriticalRegion() {
this->visualObjectMutex->exitCriticalRegion();
}
void VisualObjectData::copyObject(const VisualObjectData& other) {
this->itemIdentifier = new VisualItemIdentifier(*(other.itemIdentifier));
if (other.data != NULL) {
this->data = (char*)malloc(other.dataSizeAllocated);
memcpy(this->data, other.data, other.dataSizeUsed);
} else {
this->data = NULL;
}
this->visualObjectMutex = new VisualObjectMutex(*other.visualObjectMutex);
this->dataSizeAllocated = other.dataSizeAllocated;
this->dataSizeUsed = other.dataSizeUsed;
this->dataSizeDeclared = other.dataSizeDeclared;
this->dataSizeDeclaredHasBeenSetBool = other.dataSizeDeclaredHasBeenSetBool;
this->refCount = other.refCount;
this->hasObjectBool = other.hasObjectBool;
}
| [
"dougbradbury@doug-mbp15.local"
] | dougbradbury@doug-mbp15.local |
7fa69f37669371d0bb6980a8a0837ac01def031e | c1d4b3313aa6e48bebfeb4e3cfb7b5eeb54ced86 | /windows/cpp/samples/enc_mp4_avc_aac_push/stdafx.h | a233703f20cbec0ad838f3bdcdb9f1b66316d523 | [
"MIT"
] | permissive | avblocks/avblocks-samples | 447a15eed12d4ac03c929bc7b368fe37fadc0762 | 7388111a27c8110a9f7222e86e912fe38f444543 | refs/heads/main | 2021-06-04T13:41:30.387450 | 2021-02-01T00:28:09 | 2021-02-01T00:28:09 | 334,783,633 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 511 | h | // stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <string>
#include <iostream>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <algorithm>
#include <map>
#include <assert.h>
#include <Windows.h>
#include <Shlwapi.h>
#include <AVBlocks.h>
#include <PrimoReference++.h>
| [
"vkantchev@users.noreply.github.com"
] | vkantchev@users.noreply.github.com |
bdab3fdeffd05180d603fb7df4de2ec1a80176a2 | 1acaecec96efccb227b9fec39d1925dd17795928 | /Apresentacao/Paginas/Logado/CadastrarNovoProduto.cpp | 042795210de47f19a8f31e202af9b969321bafb1 | [] | no_license | SAMXPS/TP1-UnB | 45648feb2b14788c97f48a3cc1a4197b0217263a | bb47138226f5b514aa9130c9ff820214f3732dac | refs/heads/master | 2023-01-29T10:23:07.944702 | 2020-12-04T02:01:19 | 2020-12-04T02:01:19 | 293,830,312 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,055 | cpp | #include "../../Paginas.h"
#include <string.h>
Pagina* CadastrarNovoProduto::mostrar(GerenciadorDePagina* apresentador) {
Pagina* next = new PaginaInicialLogado(usuario);
std::string CODIGO_DE_PRODUTO, CLASSE, EMISSOR, PRAZO, DATA, TAXA, HORARIO, VALOR_MINIMO;
apresentador->escreveNoCentro("Cadastrar novo Produto");
apresentador->escreveNoCentro("");
apresentador->escreveNoCentro("Por favor, preencha os dados a seguir.");
apresentador->escreveNoCentro("");
apresentador->escreveNoCentro("CODIGO_DE_PRODUTO: ");
CODIGO_DE_PRODUTO = apresentador->lerInput();
apresentador->escreveNoCentro("CLASSE: ");
CLASSE = apresentador->lerInput();
apresentador->escreveNoCentro("EMISSOR: ");
EMISSOR = apresentador->lerInput();
apresentador->escreveNoCentro("PRAZO: ");
PRAZO = apresentador->lerInput();
apresentador->escreveNoCentro("DATA DE VENCIMENTO: ");
DATA = apresentador->lerInput();
apresentador->escreveNoCentro("TAXA: ");
TAXA = apresentador->lerInput();
apresentador->escreveNoCentro("HORARIO: ");
HORARIO = apresentador->lerInput();
apresentador->escreveNoCentro("VALOR_MINIMO: ");
VALOR_MINIMO = apresentador->lerInput();
Produto* produto;
try {
produto = new Produto(CODIGO_DE_PRODUTO, CLASSE, EMISSOR, std::stoi(PRAZO), DATA, std::stod(TAXA), HORARIO, std::stoi(VALOR_MINIMO));
} catch (const std::invalid_argument&err) {
return new PaginaErro(next, err.what());
} catch (...) {
return new PaginaErro(next, "erro desconhecido.");
}
apresentador->limparTela();
if (apresentador->getServicos()->getGerenciadorDeProduto()->cadastrarProduto(*produto)) {
apresentador->escreveNoCentro("Produto cadastrado com sucesso.");
} else {
apresentador->escreveNoCentro("Produto nao foi cadastrado. Algum problema no SQLite.");
}
apresentador->escreveNoCentro("");
apresentador->escreveNoCentro("Aperte enter para voltar");
apresentador->lerInput();
return next;
}
| [
"bsbcraftplays@gmail.com"
] | bsbcraftplays@gmail.com |
45b72820b5c4e7fe09f04c6cf34982cda521d717 | 1664303ee9ca94a2d72a4a6b5aa567f569de8e25 | /ArkDll/ArkLib.h | 1976b17732b11f179f95b26be8ced6162baf9fc2 | [] | no_license | laikun81/WpfApplication1 | 8c68fcfbf0893a76a04ee7a06ab63e5b1b09d192 | 2cd53ac229c7b2154ba555fa5acf8c0d76dbc37c | refs/heads/master | 2021-01-25T10:00:31.983636 | 2016-01-23T16:33:08 | 2016-01-23T16:33:08 | 42,751,536 | 0 | 0 | null | 2016-01-23T16:33:09 | 2015-09-18T23:24:36 | C# | UHC | C++ | false | false | 13,331 | h | ////////////////////////////////////////////////////////////////////////////////////////////////////
///
/// Ark Library Wrapper class
///
/// @author parkkh
/// @date Thursday, January 07, 2010 11:18:16 AM
///
/// Copyright(C) 2008-2011 Bandisoft, All rights reserved.
///
////////////////////////////////////////////////////////////////////////////////////////////////////
#ifndef _ARK_LIB_H_
#define _ARK_LIB_H_
#include "Ark.h"
#ifdef _WIN64
# ifdef _DEBUG
# define ARK_DLL_FILE_NAME _T("Ark64_d.dll")
# define ARKZIP_DLL_FILE_NAME _T("ArkZip64_d.dll")
# else
# define ARK_DLL_FILE_NAME _T("Ark64.dll")
# define ARKZIP_DLL_FILE_NAME _T("ArkZip64.dll")
# endif
# define ARK_DLL_RELEASE_FILE_NAME _T("Ark64.dll")
# define ARKZIP_DLL_RELEASE_FILE_NAME _T("ArkZip64.dll")
#elif defined(_WIN32)
# ifdef _DEBUG
# define ARK_DLL_FILE_NAME _T("Ark32_d.dll")
# define ARKZIP_DLL_FILE_NAME _T("ArkZip32_d.dll")
# else
# define ARK_DLL_FILE_NAME _T("Ark32.dll")
# define ARKZIP_DLL_FILE_NAME _T("ArkZip32.dll")
# endif
# define ARK_DLL_RELEASE_FILE_NAME _T("Ark32.dll")
# define ARKZIP_DLL_RELEASE_FILE_NAME _T("ArkZip32.dll")
#endif
#ifndef _WIN32
# ifdef __APPLE__
# define ARK_DLL_FILE_NAME "./ark64.dylib"
# else
# if defined(__x86_64__) || defined(__ia64__) || defined(_M_AMD64) || defined(_M_IA64) || defined(_WIN64) || defined(__alpha__) || defined(__s390__)
# define ARK_DLL_FILE_NAME "./ark64.so"
# else
# define ARK_DLL_FILE_NAME "./ark32.so"
# endif
# endif // __APPLE__
# define ARK_DLL_RELEASE_FILE_NAME ARK_DLL_FILE_NAME
#endif // _WIN32
#define ARK_EXPORTED_FUNCTION_NAME "CreateArk"
#define ARKCOMPRESSOR_EXPORTED_FUNCTION_NAME "CreateArkCompressor"
#ifndef _WIN32
# include <dlfcn.h>
# define HMODULE void*
# define LoadLibrary(name) dlopen(name, RTLD_NOW | RTLD_GLOBAL)
# define GetProcAddress(handle, func) dlsym(handle, func)
# define FreeLibrary(handle) dlclose(handle)
# include <string>
#endif
#ifndef _INC_TCHAR
# ifdef _UNICODE
# define _T(x) L##x
# else
# define _T(x) x
# endif
#endif
#ifdef _UNICODE
typedef const wchar_t* LPCTSTR;
#else
typedef const char* LPCTSTR;
#endif
typedef IArk* (*LPCREATEARK)(UINT32 version);
typedef IArkCompressor* (*LPCREATEARKCOMPRESSOR)(UINT32 version);
#ifndef ASSERT
# include <stdio.h>
# define ASSERT(x) printf("Assert at %s %d\n", __FILE__, __LINE__)
#endif
class CArkLib : public IArk
{
public :
CArkLib()
{
m_hDll = NULL;
m_pCreateArk = NULL;
m_pCreateArkCompressor = NULL;
m_pArk = NULL;
}
~CArkLib()
{
Destroy();
}
#ifndef _ARK_USE_AS_LIB
// .dll 로 사용하는 경우
ARKERR Create(LPCTSTR szDllPathName)
{
if(m_hDll) {ASSERT(0); return ARKERR_ALREADY_DLL_CREATED;}
m_hDll = LoadLibrary(szDllPathName);
if(m_hDll==NULL)
{
m_hDll = LoadLibrary(ARK_DLL_RELEASE_FILE_NAME);
if(m_hDll==NULL)
{
#ifndef _WIN32
printf("Load %s failed.(Reason: '%s')\n", szDllPathName, dlerror());
#endif
ASSERT(0);
return ARKERR_LOADLIBRARY_FAILED;
}
}
m_pCreateArk = (LPCREATEARK)GetProcAddress(m_hDll, ARK_EXPORTED_FUNCTION_NAME);
m_pCreateArkCompressor = (LPCREATEARKCOMPRESSOR)GetProcAddress(m_hDll, ARKCOMPRESSOR_EXPORTED_FUNCTION_NAME);
if(m_pCreateArk==NULL)
{
#ifndef _WIN32
printf("dlsym() failed.(Reason: '%s')\n", dlerror());
#endif
ASSERT(0);
FreeLibrary(m_hDll);
m_hDll = NULL;
return ARKERR_GETPROCADDRESS_FAILED;
}
m_pArk = (m_pCreateArk)(ARK_LIBRARY_VERSION);
if(m_pArk==NULL)
{
ASSERT(0);
FreeLibrary(m_hDll);
m_hDll = NULL;
return ARKERR_INVALID_VERSION;
}
return ARKERR_NOERR;
}
#endif // not _ARK_USE_AS_LIB
IArkCompressor* CreateCompressor()
{
return m_pCreateArkCompressor ? m_pCreateArkCompressor(ARK_LIBRARY_VERSION) : NULL;
}
/*
IArk* _CreateNewArk()
{
return m_pCreateArk ? (m_pCreateArk)(ARK_LIBRARY_VERSION) : NULL;
}
*/
IArk* GetIArk()
{
return m_pArk;
}
#ifdef _ARK_USE_AS_LIB
// .lib 로 사용하는 경우
ARKERR CreateLib()
{
m_pArk = CreateArkLib(ARK_LIBRARY_VERSION);
if(m_pArk==NULL)
{
ASSERT(0);
return ARKERR_INVALID_VERSION;
}
return ARKERR_NOERR;
}
#endif
BOOL32 IsCreated()
{
return m_pArk ? TRUE : FALSE;
}
void Destroy()
{
if(m_pArk)
m_pArk->Release();
m_pArk = NULL;
m_pCreateArk = NULL;
if(m_hDll) FreeLibrary(m_hDll);
m_hDll = NULL;
}
public : // IArk
ARKMETHOD(void) Release()
{
Destroy();
}
#ifndef _WIN32
// posix 용 std::string 인터페이스
ARKMETHOD(BOOL32) Open(std::string name, std::string pass){ return Open(name.c_str(), pass.c_str()); }
ARKMETHOD(BOOL32) Open(std::string name, const char* pass){ return Open(name.c_str(), pass); }
ARKMETHOD(BOOL32) ExtractOneTo(int index,std::string dest){ return ExtractOneTo(index, dest.c_str()); };
ARKMETHOD(BOOL32) ExtractAllTo(std::string dest) { return ExtractAllTo(dest.c_str()); };
ARKMETHOD(BOOL32) ExtractMultiFileTo(std::string dest) { return ExtractMultiFileTo(dest.c_str()); }
ARKMETHOD(ARK_FF) CheckFormat(std::string name) const { return CheckFormat(name.c_str()); }
#endif
ARKMETHOD(BOOL32) Open(LPCSTR filePath, LPCSTR password=NULL)
{
return m_pArk ? m_pArk->Open(filePath, password) : FALSE;
}
ARKMETHOD(BOOL32) Open(LPCWSTR filePath, LPCWSTR password=NULL)
{
return m_pArk ? m_pArk->Open(filePath, password) : FALSE;
}
ARKMETHOD(BOOL32) Open(ARKBYTE* src, int srcLen, LPCWSTR password=NULL)
{
return m_pArk ? m_pArk->Open(src, srcLen, password) : FALSE;
}
ARKMETHOD(BOOL32) Open(IArkSimpleInStream* srcStream, LPCWSTR password=NULL)
{
return m_pArk ? m_pArk->Open(srcStream, password) : FALSE;
}
ARKMETHOD(void) Close()
{
if(m_pArk) m_pArk->Close();
}
ARKMETHOD(BOOL32) TestArchive()
{
return m_pArk ? m_pArk->TestArchive() : FALSE;
}
ARKMETHOD(ARK_FF) CheckFormat(LPCSTR filePath) const
{
return m_pArk ? m_pArk->CheckFormat(filePath) : ARK_FF_UNKNOWN;
}
ARKMETHOD(ARK_FF) CheckFormat(LPCWSTR filePath) const
{
return m_pArk ? m_pArk->CheckFormat(filePath) : ARK_FF_UNKNOWN;
}
ARKMETHOD(ARK_FF) CheckFormat(const unsigned char* buffer, int bufLen) const
{
return m_pArk ? m_pArk->CheckFormat(buffer, bufLen) : ARK_FF_UNKNOWN;
}
ARKMETHOD(void) SetPassword(LPCSTR password)
{
if(m_pArk) m_pArk->SetPassword(password);
}
ARKMETHOD(void) SetPassword(LPCWSTR password)
{
if(m_pArk) m_pArk->SetPassword(password);
}
ARKMETHOD(int) GetFileItemCount() const
{
return m_pArk ? m_pArk->GetFileItemCount() : 0;
}
ARKMETHOD(const SArkFileItem*) GetFileItem(int index) const
{
return m_pArk ? m_pArk->GetFileItem(index) : NULL;
}
ARKMETHOD(ARK_FF) GetFileFormat() const
{
return m_pArk ? m_pArk->GetFileFormat() : ARK_FF_UNKNOWN;
}
ARKMETHOD(BOOL32) IsBrokenArchive() const
{
return m_pArk ? m_pArk->IsBrokenArchive() : FALSE;
}
ARKMETHOD(BOOL32) IsEncryptedArchive() const
{
return m_pArk ? m_pArk->IsEncryptedArchive() : FALSE;
}
ARKMETHOD(BOOL32) IsSolidArchive() const
{
return m_pArk ? m_pArk->IsSolidArchive() : FALSE;
}
ARKMETHOD(BOOL32) IsOpened() const
{
return m_pArk ? m_pArk->IsOpened() : FALSE;
}
ARKMETHOD(BOOL32) ExtractAllTo(LPCSTR szDestPath)
{
return m_pArk ? m_pArk->ExtractAllTo(szDestPath) : FALSE;
}
ARKMETHOD(BOOL32) ExtractAllTo(LPCWSTR szDestPath)
{
return m_pArk ? m_pArk->ExtractAllTo(szDestPath) : FALSE;
}
ARKMETHOD(BOOL32) ExtractAllTo(IArkSimpleOutStream* pOutStream)
{
return m_pArk ? m_pArk->ExtractAllTo(pOutStream) : FALSE;
}
ARKMETHOD(BOOL32) ExtractOneTo(int index, LPCSTR szDestPath)
{
return m_pArk ? m_pArk->ExtractOneTo(index, szDestPath) : FALSE;
}
ARKMETHOD(BOOL32) ExtractOneTo(int index, LPCWSTR szDestPath)
{
return m_pArk ? m_pArk->ExtractOneTo(index, szDestPath) : FALSE;
}
ARKMETHOD(BOOL32) ExtractOneTo(int index, IArkSimpleOutStream* pOutStream)
{
return m_pArk ? m_pArk->ExtractOneTo(index, pOutStream) : FALSE;
}
ARKMETHOD(BOOL32) ExtractOneTo(int index, ARKBYTE* outBuf, int outBufLen)
{
return m_pArk ? m_pArk->ExtractOneTo(index, outBuf, outBufLen) : FALSE;
}
ARKMETHOD(BOOL32) ExtractOneAs(int index, LPCWSTR filePathName, WCHAR resultPathName[ARK_MAX_PATH])
{
return m_pArk ? m_pArk->ExtractOneAs(index, filePathName, resultPathName) : FALSE;
}
ARKMETHOD(BOOL32) AddIndex2ExtractList(int nIndex)
{
return m_pArk ? m_pArk->AddIndex2ExtractList(nIndex) : FALSE;
}
ARKMETHOD(void) ClearExtractList()
{
if(m_pArk) m_pArk->ClearExtractList();
}
ARKMETHOD(int) GetExtractListCount() const
{
return m_pArk ? m_pArk->GetExtractListCount() : 0;
}
ARKMETHOD(BOOL32) ExtractMultiFileTo(LPCSTR szDestPath)
{
return m_pArk ? m_pArk->ExtractMultiFileTo(szDestPath) : FALSE;
}
ARKMETHOD(BOOL32) ExtractMultiFileTo(LPCWSTR szDestPath, LPCWSTR szPath2Remove=NULL)
{
return m_pArk ? m_pArk->ExtractMultiFileTo(szDestPath, szPath2Remove) : FALSE;
}
ARKMETHOD(BOOL32) ExtractMultiFileTo(IArkSimpleOutStream* pOutStream)
{
return m_pArk ? m_pArk->ExtractMultiFileTo(pOutStream) : FALSE;
}
ARKMETHOD(BOOL32) SetEvent(IArkEvent* pProgress)
{
return m_pArk ? m_pArk->SetEvent(pProgress) : FALSE;
}
ARKMETHOD(ARKERR) GetLastError() const
{
return m_pArk ? m_pArk->GetLastError() : ARKERR_LIBRARY_NOT_LOADED ;
}
ARKMETHOD(UINT32) GetLastSystemError() const
{
return m_pArk ? m_pArk->GetLastSystemError() : 0 ;
}
ARKMETHOD(void) SetCodePage(SArkCodepage cp)
{
if(m_pArk) m_pArk->SetCodePage(cp);
}
ARKMETHOD(LPCWSTR) EncryptionMethod2Str(ARK_ENCRYPTION_METHOD method) const
{
return m_pArk ? m_pArk->EncryptionMethod2Str(method) : NULL;
}
ARKMETHOD(LPCWSTR) CompressionMethod2Str(ARK_COMPRESSION_METHOD method) const
{
return m_pArk ? m_pArk->CompressionMethod2Str(method) : NULL;
}
ARKMETHOD(LPCWSTR) FileFormat2Str(ARK_FF ff) const
{
return m_pArk ? m_pArk->FileFormat2Str(ff) : NULL;
}
ARKMETHOD(void) SetGlobalOpt(const SArkGlobalOpt& opt)
{
if(m_pArk) m_pArk->SetGlobalOpt(opt);
}
ARKMETHOD(INT64) GetArchiveFileSize() const
{
return m_pArk ? m_pArk->GetArchiveFileSize() : 0;
}
ARKMETHOD(INT64) GetArchiveStartPos() const
{
return m_pArk ? m_pArk->GetArchiveStartPos() : 0;
}
ARKMETHOD(LPCWSTR) GetFilePathName() const
{
return m_pArk ? m_pArk->GetFilePathName() : NULL;
}
ARKMETHOD(int) FindIndex(LPCWSTR szFileNameW, LPCSTR szFileNameA, BOOL32 bCaseSensitive) const
{
return m_pArk ? m_pArk->FindIndex(szFileNameW, szFileNameA, bCaseSensitive) : -1;
}
ARKMETHOD(LPCWSTR) GetArchiveComment() const
{
return m_pArk ?m_pArk->GetArchiveComment() : NULL;
}
ARKMETHOD(ARK_MULTIVOL_STYLE) GetMultivolStyle() const
{
return m_pArk ?m_pArk->GetMultivolStyle() : ARK_MULTIVOL_STYLE_NONE;
}
ARKMETHOD(int) GetMultivolCount() const
{
return m_pArk ?m_pArk->GetMultivolCount() : 0;
}
ARKMETHOD(LPCWSTR) GetMultivolFilePathName(int volume) const
{
return m_pArk ?m_pArk->GetMultivolFilePathName(volume) : NULL;
}
ARKMETHOD(BOOL32) DetectCurrentArchivesCodepage(SArkDetectCodepage& dcp) const
{
return m_pArk ?m_pArk->DetectCurrentArchivesCodepage(dcp) : FALSE;
}
ARKMETHOD(BOOL32) ChangeCurrentArchivesCodepage(int codePage)
{
return m_pArk ?m_pArk->ChangeCurrentArchivesCodepage(codePage) : FALSE;
}
//////////////////////////
// undocumented
ARKMETHOD(LPCWSTR) _GetAlias()
{
return m_pArk ? m_pArk->_GetAlias() : NULL;
}
ARKMETHOD(void) _SetAlias(LPCWSTR szAlias)
{
if(m_pArk) m_pArk->_SetAlias(szAlias);
}
ARKMETHOD(const void*) _GetBondFileInfo()
{
return m_pArk ? m_pArk->_GetBondFileInfo() : 0;
}
ARKMETHOD(void) _SetUserKey(void* key)
{
if(m_pArk) m_pArk->_SetUserKey(key);
}
ARKMETHOD(UINT32) _CheckCRC32(LPCWSTR filePath)
{
return m_pArk ? m_pArk->_CheckCRC32(filePath) : 0;
}
ARKMETHOD(void*) _GetExtractor()
{
return m_pArk ? m_pArk->_GetExtractor(): NULL;
}
ARKMETHOD(void*) _GetInStream()
{
return m_pArk ? m_pArk->_GetInStream(): NULL;
}
ARKMETHOD(BOOL32) _DisableItem(int index)
{
return m_pArk ? m_pArk->_DisableItem(index): FALSE;
}
ARKMETHOD(void) _Test()
{
if(m_pArk) m_pArk->_Test();
}
// for c++ builder only
ARKMETHOD(BOOL32) _OpenW(LPCWSTR filePath, LPCWSTR password=NULL)
{
return m_pArk ? m_pArk->_OpenW(filePath, password) : FALSE;
}
ARKMETHOD(ARK_FF) _CheckFormatW(LPCWSTR filePath) const
{
return m_pArk ? m_pArk->_CheckFormatW(filePath) : ARK_FF_UNKNOWN;
}
ARKMETHOD(void) _SetPasswordW(LPCWSTR password)
{
if(m_pArk) m_pArk->_SetPasswordW(password);
}
ARKMETHOD(BOOL32) _ExtractAllToW(LPCWSTR folderPath)
{
return m_pArk ? m_pArk->_ExtractAllToW(folderPath) : FALSE;
}
ARKMETHOD(BOOL32) _ExtractOneToW(int index, LPCWSTR folderPath)
{
return m_pArk ? m_pArk->_ExtractOneToW(index, folderPath) : FALSE;
}
ARKMETHOD(BOOL32) _ExtractMultiFileToW(LPCWSTR szDestPath, LPCWSTR szPath2Remove=NULL)
{
return m_pArk ? m_pArk->_ExtractMultiFileToW(szDestPath, szPath2Remove) : FALSE;
}
private :
HMODULE m_hDll;
LPCREATEARK m_pCreateArk;
LPCREATEARKCOMPRESSOR m_pCreateArkCompressor;
IArk* m_pArk;
};
#endif // _ARK_LIB_H_
| [
"laikun81@gmail.com"
] | laikun81@gmail.com |
73e807b96d6354f32c01b626120c2deb5af8d652 | 60f8e23f9b3a1787ee9ccd98ac40b0993846a9e7 | /GameProject/OpenGL/ClearEffect.h | 2376c3aad6e629202d821498408184380ead3ec6 | [] | no_license | reo1316hw/GameWork | d85ea08f886b67c4c44acc7863ce556a13040c6c | 8732acb1ae4252d68713d07099172d628b11d393 | refs/heads/main | 2023-07-17T21:51:24.254196 | 2021-08-30T17:43:17 | 2021-08-30T17:43:17 | 362,292,162 | 0 | 0 | null | null | null | null | SHIFT_JIS | C++ | false | false | 734 | h | /*
@brief プリプロセッサ
*/
#pragma once
/*
@brief インクルード
*/
class ClearEffect : public ParticleEffectBase
{
public:
/*
@fn コンストラクタ
@param _pos クリアエフェクトの生成場所
@param _vel クリアエフェクトの速度
@param _objectTag アタッチしたゲームオブジェクトのタグ
@param _sceneTag シーンのタグ
*/
ClearEffect(Vector3 _pos, Vector3 _vel, const Tag& _objectTag ,SceneBase::Scene _sceneTag);
/*
@fn デストラクタ
*/
~ClearEffect() {};
/*
@fn クリアエフェクトのアップデート
@param _deltaTime 最後のフレームを完了するのに要した時間
*/
void UpdateGameObject(float _deltaTime)override;
private:
};
| [
"leohattori@icloud.com"
] | leohattori@icloud.com |
8ce30f14b330c0404cc2116ad87c73cf66606dbe | 4005eca13ea7e1a635cd2396a1a0eaee2c0bcbc0 | /tasks/tbb_overhead.cpp | 5d765150ed292f1284f9c511e11fa7dbfc125faa | [
"BSL-1.0"
] | permissive | sithhell/hpxbenchmarks | 9d2fe566373faab007d571953326cade63721703 | 3687081a1bab5ffa872576f4ff8267f32d4fcc85 | refs/heads/master | 2021-05-14T04:59:09.483841 | 2018-08-11T14:01:23 | 2018-08-11T14:01:23 | 116,657,438 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,187 | cpp | // Copyright (c) 2017-2018 Thomas Heller
//
// 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)
#include <benchmark/benchmark.h>
#include <tbb/tbb.h>
#include <support/dummy.hpp>
static void function_call_overhead(benchmark::State& state)
{
for (auto _: state)
{
dummy();
}
}
BENCHMARK(function_call_overhead)->UseRealTime();
struct dummy_task : tbb::task
{
tbb::task *execute()
{
dummy();
return nullptr;
}
};
static void tbb_overhead(benchmark::State& state)
{
for (auto _: state)
{
dummy_task &d = *new (tbb::task::allocate_root()) dummy_task();
tbb::task::spawn_root_and_wait(d);
}
}
BENCHMARK(tbb_overhead)->UseRealTime();
#include <cstdlib>
int main(int argc, char **argv)
{
benchmark::Initialize(&argc, argv);
const char *env = std::getenv("NUM_THREADS");
std::string thread_env = env == nullptr ? "1": std::string(env);
int num_threads = std::atoi(thread_env.c_str());
tbb::task_scheduler_init init(num_threads);
benchmark::RunSpecifiedBenchmarks();
return 0;
}
| [
"thomas.heller@cs.fau.de"
] | thomas.heller@cs.fau.de |
727ecd57d0082f883bbad100d586ae196da59b8c | 75807296ab0ad2cc3a173d6a759985207ef5d24d | /arithmetic/1048.cpp | 2c3a3f7ce1f6fc82d5939be4593919a958cc1f35 | [] | no_license | p719967821/algorithm | af81a07efaa1ce2adc5a13c9d52523799acb8442 | a02bd4a64b2a2596cdd3227b9c5229e0b77b7834 | refs/heads/master | 2021-03-20T13:36:47.306631 | 2020-03-14T14:06:18 | 2020-03-14T14:06:18 | 247,210,618 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 960 | cpp | /**矩阵连乘**/
#include <iostream>
#define N 101
using namespace std;
int n;
int row[N];//每个矩阵的行
int col[N];//每个矩阵的列
int s[N][N];//记录最少的次数
void dp();
int main()
{
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> row[i] >> col[i];
}
dp();
cout << s[0][n-1] << endl;
return 0;
}
void dp()
{
int i,j,k,len;
//初始化
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
if(i == j)
{
s[i][j] = 0;
}
else
{
s[i][j] = INT_MAX;
}
}
}
//开始从底向上规划
for(len = 1; len < n; len++)
{
for(i = 0,j = i + len; j < n; i++ , j++)
{
for(k = i; k < j; k++)
{
s[i][j] = min(s[i][j],s[i][k] + s[k+1][j] + row[i]*col[k]*col[j]);
}
}
}
} | [
"p719967821@163.com"
] | p719967821@163.com |
52b09468911186ba91cb2a6e54591c717f20fcd6 | 1b06d5bf179f0d75a30a4b020dd88fc5b57a39bc | /Repository/Aspic/spi_monitor.cp | bad914d8d3fc5d16e951470a498dbcf21179322b | [] | no_license | ofirr/bill_full_cvs | b508f0e8956b5a81d6d6bca6160054d7eefbb2f1 | 128421e23c7eff22afe6292f88a01dbddd8b1974 | refs/heads/master | 2022-11-07T23:32:35.911516 | 2007-07-06T08:51:59 | 2007-07-06T08:51:59 | 276,023,188 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 86,504 | cp | /*
SpiFcp Channel activity monitor
William Silverman
Last update by $Author: bill $
$Date: 2006/06/27 05:30:38 $
Currently locked by $Locker: $
$Revision: 1.29 $
$Source: /home/bill/Repository/Aspic/spi_monitor.cp,v $
Copyright (C) 1998, Weizmann Institute of Science - Rehovot, ISRAEL
*/
-monitor(initialize).
-language([evaluate,compound,colon]).
-export([get_public_channels/1, get_public_values/1,
public_channels/1, public_channels/2,
new_channel/3, new_channel/4, new_public_channel/4,
options/2,
public_object/3,
reset/0, scheduler/1]).
-include(spi_constants).
RAN => 4. /* uniform 0..1 variate */
LN => 9. /* natural logarithm */
REALTIME => 12.
MAXTIME => 99999999999999999999999999999999999999999999999999999999999.0.
DEBUG(Note) => write_channel(debug_note(Note), Scheduler).
DUMMY_CHANNEL(NewChannel) =>
(Schedule ? NewChannel :
make_channel(Dummy, _) |
new_channel(ChannelName, Channel, 0,
SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX),
0, _, Dummy, _, _, SpiOffsets),
self).
%STOPPED => DEBUG(stopped(Reply)).
STOPPED => Reply = _.
/*
** Arguments of SPIOFFSETS correspond to the C-executable (spicomm.c)
** sub-functions: Post, Close, Step, Index, Rate (see spi_constants.cp).
**
** To test one or more C-executables, set the other arguments "unbound" - e.g.
**
** SPIOFFSETS => {unbound, unbound, SpiOffset, SpiOffset, unbound}
**
** to allow the monitor to call the C step function and the C index function,
** and to execute the other operations with fcp code. Note that the
** C index function and the C rate function are not implemented in fcp for
** non-standard weighters.
*/
SPIOFFSETS => {SpiOffset, SpiOffset, SpiOffset, SpiOffset, SpiOffset}.
%SPIOFFSETS => {unbound, unbound, unbound, unbound, unbound}.
initialize(In) :-
In =?= [] :
true;
In =\= [] :
SpiOffset = _,
Options = [3], % preset depth - others default
Ordinal = 1,
Randomize = 0,
SpiOffsets = SPIOFFSETS,
DefaultWeighter = SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX) |
processor # link(lookup(spicomm, SpiOffset), OkComm),
check_spicomm(OkComm, SpiOffsets, SpiOffsets'),
serve.
check_spicomm(Ok, DefaultSpiOffsets, SpiOffsets) :-
Ok =\= true :
DefaultSpiOffsets = _,
SpiOffsets = {unbound, unbound, unbound, unbound, unbound} |
computation # comment(("No spicomm" : "No non-standard weighters."));
Ok =?= true :
SpiOffsets = DefaultSpiOffsets.
/*
** server monitors the input stream (In).
**
** It recognises:
**
** get_public_channels(SortedList?^)
** get_public_values(SortedList?^)
** public_channels(SortedList)
** public_channels(SortedList, Scheduler^)
** public_object(Name, Initial, Vector?^)
** new_channel(ChannelName, Channel, BaseRate)
** new_channel(ChannelName, Channel, ComputeWeight, BaseRate)
** options(New, Old?^)
** randomize
** record(List?^)
** reset
** reset(DefaultWeighter, Randomize, SpiOffsets, Ordinal)
** scheduler(Scheduler^)
** serialize
** spifunctions(List)
** status(List?^)
**
** and the debugging aids:
**
** debug(Debug?^)
** end_debug
**
** Monitor State
**
** Options - for spi_utils functions
**
** Parameters - {Channels, Values}
** Channels - sorted (bounded) list of public channels:
** {name,channel,baserate}
** {name,channel,computeweight,baserate}
** Values - sorted (bounded) list of public values:
** {name,value}
** Scheduler - Channel to Scheduling input
** Randomize - state of scheduling: 0 or SPI_RANDOM_FLAG
**
** Side-effects
**
** Close Scheduler at end of In or reset command.
*/
serve(In, Options, Ordinal, Randomize, SpiOffsets, DefaultWeighter) :-
true :
make_vector(OBJECT_ARITY, SpiTime, Outputs),
store_vector(OBJECT_VALUES, TIME_INITIAL_VALUE, SpiTime),
Channels = [{[], _, -1, ""}],
NamedValues = [{TIME_OBJECT_NAME, SpiTime}, {[], _}],
Parameters = {Channels, NamedValues} |
arg(OBJECT_VALUES, Outputs, Values),
arg(OBJECT_REQUESTS, Outputs, Requests),
filter_time_requests(Requests?, Requests'),
spi_object # monitor(TIME_OBJECT_NAME, _InitialValue, SpiTime,
Values, Requests'?),
processor # link(lookup(math, MathOffset), OkMath),
server,
start_scheduling.
filter_time_requests(Requests, Filtered) :-
Requests ? Close, Close =?= close(_False) |
spitime_cant_do(Close),
self;
Requests ? Store, Store =?= store(_NewValue, _False) |
spitime_cant_do(Store),
self;
Requests ? Other,
otherwise :
Filtered ! Other |
self;
Requests =?= [] :
Filtered = [].
spitime_cant_do(Request) :-
arity(Request, Arity),
arg(Arity, Request, False),
we(False) :
False = false;
otherwise |
fail(TIME_OBJECT_NAME - Request, forbidden).
server(In, Options, Parameters, Scheduler) :-
In ? debug(Debug) :
Debug = Debug'?,
write_channel(debug(Debug'), Scheduler) |
self;
In ? end_debug :
write_channel(end_debug, Scheduler) |
self;
In ? end_record(Stream) :
Stream = Stream'?,
write_channel(end_record(Stream'), Scheduler) |
self;
In ? get_public_channels(List?^),
Parameters =?= {Channels, _NamedValues} |
copy_bounded(Channels, List),
self;
In ? get_public_values(List?^),
Parameters =?= {_Channels, NamedValues} |
copy_bounded(NamedValues, List),
self;
In ? public_channels(List) |
merge_parameter_list(List, Parameters, Parameters', Scheduler, _),
self;
In ? public_channels(List, ReadyScheduler) |
merge_parameter_list(List, Parameters, Parameters',
Scheduler, ReadyScheduler),
self;
In ? public_object(Name, Initial, Vector?^) |
merge_parameter_list(Name(Vector), Parameters, Parameters',
Scheduler, Ready),
wait_object_ready,
self;
In ? New , New = new_channel(_Creator, _Channel, _BaseRate) :
write_channel(New, Scheduler) |
self;
In ? New , New = new_channel(_Creator, _Channel, _ComputeWeight,
_BaseRate) :
write_channel(New, Scheduler) |
self;
In ? options(New, Old) :
Options' = New? |
unify_without_failure(Options, Old),
self;
In ? randomize :
write_channel(randomize(SPI_RANDOM_FLAG), Scheduler) |
self;
In ? record(Record) :
Record = Record'?,
write_channel(record(Record'), Scheduler) |
self;
In ? reset :
write_channel(state(DefaultWeighter, Randomize, SpiOffsets, _Ordinal),
Scheduler),
In'' = [reset(DefaultWeighter?, Randomize?, SpiOffsets?, 1) | In'] |
self;
In ? reset(DefaultWeighter, Randomize, SpiOffsets, Ordinal),
Parameters =?= {_Channels, NamedValues} :
close_channel(Scheduler) |
close_public_objects,
serve;
In ? scheduler(Scheduler^) |
self;
In ? serialize :
write_channel(randomize(0), Scheduler) |
self;
In ? spifunctions(List) :
write_channel(spifunctions(List), Scheduler) |
self;
In ? status(Status) :
Status = Status'?,
write_channel(status(Status'), Scheduler) |
self;
In ? Other,
otherwise |
self,
fail(Other, unknown);
In =?= [],
Parameters =?= {_Channels, NamedValues} :
Options = _,
close_channel(Scheduler) |
close_public_objects.
close_public_objects(NamedValues) :-
NamedValues ? _Name(Vector),
arity(Vector, OBJECT_ARITY),
read_vector(OBJECT_VALUES, Vector, _Value) :
write_vector(OBJECT_REQUESTS, close(_), Vector) |
self;
/* If not a vector or different arity or unstored, just ignore it! */
NamedValues ? _Name(_Value),
otherwise |
self;
NamedValues ? _Name(Variable),
unknown(Variable) |
self;
NamedValues =?= [] :
true.
/***************************** Utilities ************************************/
/* merge_parameter_list
**
** Input:
**
** List - sorted list of: Name(Value)
** Name(Channel^, BaseRate)
** Name(Channel^, ComputeWeight, BaseRate)
** or: Name(Object)
** Parameters - {Channels, NamedValues}
** NamedValues - (bounded) sorted list of: Name(Value).
** Channels - (bounded) sorted list of:
** Name(Channel, BaseRate, ComputeWeight).
** Scheduler - FCP channel to scheduling monitor.
**
** Output:
**
** NewParameters - {NewChannels, NewNamedValues}
** NewNamedValues - updated named value list.
** NewChannels - updated channels list.
** ReadyScheduler - Scheduler.
**
** Processing:
**
** PriorNamedValue - Name of previous element of NamedValues - initially 0.
** PriorChannel - Name of previous element of Publics - initially 0.
** Merge (new) Named Channels to NewChannels,
** (new) Named Values to NewNamedValues
** Call scheduling to create each new Channel.
** Call computation to define each new named value (in list);
** do not define objects.
*/
merge_parameter_list(List, Parameters, NewParameters,
Scheduler, ReadyScheduler) :-
Parameters =?= {Channels, NamedValues} :
PriorChannel = 0,
PriorName = 0,
NewParameters = {NewChannels?, NewNamedValues?} |
merge_parameters.
merge_parameters(List, Channels, NewChannels, PriorChannel,
NamedValues, NewNamedValues, PriorName,
Scheduler, ReadyScheduler) :-
List =?= [] :
PriorChannel = _,
PriorName = _,
ReadyScheduler = Scheduler,
NewChannels = Channels,
NewNamedValues = NamedValues;
List =?= Name(Vector), string(Name),
NamedValues =?= [Name(NamedValue) | _] :
PriorChannel = _,
PriorName = _,
Vector = NamedValue,
NewChannels = Channels,
NewNamedValues = NamedValues,
ReadyScheduler = Scheduler;
List =?= Name(_), string(Name),
NamedValues ? NamedValue, NamedValue = PriorName'(_),
PriorName' @< Name :
PriorName = _,
NewNamedValues ! NamedValue |
self;
List ? Name(Value), string(Name),
NamedValues ? NamedValue, NamedValue =?= Name(NameValue) :
PriorName = _,
Value = NameValue,
NewNamedValues ! NamedValue,
PriorName' = Name |
self;
List = [Name(_) | _], string(Name),
NamedValues ? NamedValue, NamedValue = PriorName'(_),
PriorName' @< Name :
PriorName = _,
NewNamedValues ! NamedValue |
self;
List =?= Name(Vector), string(Name),
NamedValues =?= [Name1(_) | _],
PriorName @< Name, Name @< Name1 :
PriorChannel = _,
NewChannels = Channels,
NewNamedValues = [Name(Vector?) | NamedValues],
ReadyScheduler = Scheduler;
List ? Name(Value), string(Name),
NamedValues =?= [Name1(_) | _],
PriorName @< Name, Name @< Name1 :
List'' = [Name(Value) | List'],
NamedValues' = [Name(SystemValue) | NamedValues] |
computation # dictionary(add, Name, SystemValue, Result),
wait_name_added;
List ? Name(NewChannel, BaseRate), string(Name),
PriorChannel @< Name,
we(NewChannel),
Channels ? Public, Public = Name(SpiChannel, _ComputeWeight, BaseRate),
vector(SpiChannel),
read_vector(SPI_CHANNEL_REFS, SpiChannel, References),
References++ :
PriorChannel = _,
NewChannel = SpiChannel,
store_vector(SPI_CHANNEL_REFS, References', SpiChannel),
NewChannels ! Public,
PriorChannel' = Name |
self;
List ? Name(_NewChannel, BaseRate), string(Name),
Channels ? Entry, Entry = Name(_SpiChannel, _ComputeWeight, OtherBaseRate),
BaseRate =\= OtherBaseRate :
NewChannels ! Entry |
fail(public_channel(rate_conflict(Name - BaseRate =\= OtherBaseRate))),
self;
List = [Name(_NewChannel, _BaseRate) | _], string(Name),
Channels ? Entry,
Entry = PriorChannel'(_, _, _),
PriorChannel' @< Name :
PriorChannel = _,
NewChannels ! Entry |
self;
List ? Name(NewChannel, BaseRate), string(Name),
we(NewChannel),
Channels =?= [Name1(_, _, _) | _],
string(Name),
PriorChannel @< Name, Name @< Name1 :
NewChannel = NewChannel'?,
List'' = [Name(NewChannel', BaseRate) | List'],
Channels' =
[Name(SpiChannel?, SPI_DEFAULT_WEIGHT_NAME, BaseRate) | Channels],
write_channel(new_public_channel(Name, SpiChannel,
SPI_DEFAULT_WEIGHT_NAME, BaseRate),
Scheduler) |
self;
List ? Name(NewChannel, CW, BaseRate), string(Name),
PriorChannel @< Name,
we(NewChannel),
Channels ? Public, Public = Name(SpiChannel, ComputeWeight, BaseRate),
vector(SpiChannel),
read_vector(SPI_CHANNEL_REFS, SpiChannel, References),
References++ :
PriorChannel = _,
CW = ComputeWeight?,
NewChannel = SpiChannel,
store_vector(SPI_CHANNEL_REFS, References', SpiChannel),
NewChannels ! Public,
PriorChannel' = Name |
self;
List ? Name(_NewChannel, _ComputeWeight, BaseRate), string(Name),
Channels ? Entry, Entry = Name(_SpiChannel, _, OtherBaseRate),
BaseRate =\= OtherBaseRate :
NewChannels ! Entry |
fail(public_channel(rate_conflict(Name - BaseRate =\= OtherBaseRate))),
self;
List ? Name(_NewChannel, ComputeWeight, _BaseRate), string(Name),
Channels ? Entry, Entry = Name(_SpiChannel, OtherComputeWeight, _),
ComputeWeight =\= OtherComputeWeight :
NewChannels ! Entry |
fail(public_channel(compute_weight_conflict(Name -
ComputeWeight =\= OtherComputeWeight))),
self;
List = [Name(_NewChannel, _ComputeWeight, _BaseRate) | _], string(Name),
Channels ? Entry,
Entry = PriorChannel'(_, _, _),
PriorChannel' @< Name :
PriorChannel = _,
NewChannels ! Entry |
self;
List ? Name(NewChannel, ComputeWeight, BaseRate), string(Name),
we(NewChannel),
Channels =?= [Name1(_, _, _) | _],
string(Name),
PriorChannel @< Name, Name @< Name1 :
NewChannel = NewChannel'?,
List'' = [Name(NewChannel', ComputeWeight, BaseRate) | List'],
Channels' = [Name(SpiChannel?, ComputeWeight, BaseRate) | Channels],
write_channel(new_public_channel(Name, SpiChannel,
ComputeWeight, BaseRate),
Scheduler) |
self;
otherwise :
PriorChannel = _,
PriorName = _,
ReadyScheduler = Scheduler,
NewNamedValues = NamedValues,
NewChannels = Channels |
fail(merge_parameters(List)).
wait_name_added(List, Channels, NewChannels, PriorChannel,
NamedValues, NewNamedValues, PriorName,
Scheduler, ReadyScheduler, Result) :-
known(Result) |
merge_parameters.
wait_object_ready(Name, Initial, Vector, Ready) :-
known(Ready), Name =\= TIME_OBJECT_NAME |
spi_object # create(Name, Initial, Vector);
otherwise :
Initial = _,
Name = _,
Ready = _,
Vector = _ .
/* copy_bounded
**
** Input:
**
** Bounded = (bounded) list of {Name, Channel, BaseRate}
**
** Output:
**
** List - copied exluding bounding entry
*/
copy_bounded(Bounded, List) :-
Bounded ? Entry,
Bounded' =\= [] :
List ! Entry |
self;
Bounded = [_] :
List = [].
/***************************** Scheduling ***********************************/
start_scheduling(Scheduler, MathOffset, Ordinal, SpiOffsets,
DefaultWeighter, Randomize,
OkMath, SpiTime):-
OkMath =\= true :
DefaultWeighter = _,
MathOffset = _,
Ordinal = _,
Randomize = _,
SpiOffsets = _,
SpiTime = [],
make_channel(Scheduler, _) |
fail(math_offset(OkMath));
OkMath =?= true,
info(REALTIME, Start_real_time) :
Waiter ! machine(idle_wait(Wakeup), _Ok),
make_channel(Scheduler, Schedule) |
make_channel_anchor(based, BasedAnchor),
make_channel_anchor(instantaneous, InstantaneousAnchor),
processor # Waiter?,
scheduling(Schedule, MathOffset, Ordinal, SpiOffsets, Waiter',
Scheduler, _Recording, _Debug,
SpiTime, true, Wakeup,
DefaultWeighter, Randomize,
{MAXTIME, _State}, Start_real_time,
BasedAnchor, InstantaneousAnchor).
make_channel_anchor(Name, Anchor) :-
true :
make_vector(CHANNEL_SIZE, Anchor, _),
store_vector(SPI_BLOCKED, FALSE, Anchor),
store_vector(SPI_CHANNEL_TYPE, SPI_CHANNEL_ANCHOR, Anchor),
store_vector(SPI_CHANNEL_RATE, 0.0, Anchor),
store_vector(SPI_CHANNEL_REFS, 1, Anchor),
store_vector(SPI_SEND_ANCHOR, SendAnchor, Anchor),
make_vector(2, LinksS, _),
SendAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksS, []},
store_vector(SPI_NEXT_MS, SendAnchor, LinksS),
store_vector(SPI_PREVIOUS_MS, SendAnchor, LinksS),
store_vector(SPI_SEND_WEIGHT, 0, Anchor),
store_vector(SPI_RECEIVE_ANCHOR, ReceiveAnchor, Anchor),
make_vector(2, LinksR, _),
ReceiveAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksR, []},
store_vector(SPI_NEXT_MS, ReceiveAnchor, LinksR),
store_vector(SPI_PREVIOUS_MS, ReceiveAnchor, LinksR),
store_vector(SPI_RECEIVE_WEIGHT, 0, Anchor),
store_vector(SPI_WEIGHT_TUPLE,
SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX), Anchor),
store_vector(SPI_NEXT_CHANNEL, Anchor, Anchor),
store_vector(SPI_PREVIOUS_CHANNEL, Anchor, Anchor),
store_vector(SPI_CHANNEL_NAME, Name, Anchor).
/*
** scheduling monitors the stream generated using the scheduler channel.
**
** It recognises:
**
** close(ChannelTuple)
** close(ChannelTuple, Reply)
** cutoff(Now', State^)
** default_weighter(NewWeighter)
** input(Schedule?^, Schedule')
** new_channel(ChannelName, Channel^, BaseRate)
** new_channel(ChannelName, Channel^, ComputeWeight, BaseRate)
** new_public_channel(ChannelName, Channel, ComputeWeight, BaseRate)
** ordinal(Old?^, New)
** randomize(NewRandomize)
** record(Record?^)
** record_item(Item)
** end_record(Record'?^)
** start(Signature, OpList, Value, Chosen)
** start(Signature, OpList, Value, Chosen, Prefix)
**
** and the debugging aids:
**
** debug(Debug?^)
** end_debug
** diagnostic(ApplicationDiagnostic)
** spifunctions(CharacterCodes)
** pause(Continue)
** state(DefaultWeighter^, Randomize^, SpiOffsets^, Ordinal^)
** status(ListOf NamedDetails^)
** step
** step(Resume)
**
** Scheduler State:
**
** DefaultWeighter - assigned to new Channel, unless Weighter provide
** Ordinal - Unique index assigned to a private file - also in Status
** SpiOffsets - magic numbers (or "unknown") for C-coded functions
**
** Status:
**
** Cutoff 2-Tuple
** Limit - least upper bound of internal timer (SpiTime) - initially large
** Status - Variable set to Now time when Limit exceeded (see below)
** SpiTime - 0-based internal clock
** Start_real_time - real time when Cutoff set (Now = 0) - not in status list
** Waiting - waiting for Wakeup signal = true/false
**
** BasedAnchor - anchor for circular list of based-rate Channels
** InstantaneousAnchor - anchor for circular list of infinite rate Channels
**
** Signal:
**
** Wakeup - (usually) idle indicator; also communication completion
**
** Output (Streams):
**
** Debug - scheduling debugging info
** Record - recorded actions for analysis
** Waiter - Logix system requests to wait for idle
**
** Processing:
**
** Maintain time SpiTime (Now)
**
** Whenever the system becomes idle, execute(SpiOffset, {SPI_STEP, ...})
** to select and complete a transmission (internal execute is used when
** the SPI function is unknown).
**
** Record:
**
** Changes to SpiTime (Now)
** Start Communication
** Complete Transmission
*/
STATUS => [anchors([BasedAnchor, InstantaneousAnchor]),
cutoff_limit(CutoffLimit), cutoff_status(CutoffStatus?),
debug(Debug?), spi_time(SpiTime), now(Now), ordinal(Ordinal),
randomize(Randomize), record(Record?),
waiting(Waiting), weighter(DefaultWeighter)].
scheduling(Schedule, MathOffset, Ordinal, SpiOffsets, Waiter,
Scheduler, Record, Debug,
SpiTime, Waiting, Wakeup,
DefaultWeighter, Randomize,
Cutoff, Start_real_time,
BasedAnchor, InstantaneousAnchor) :-
Schedule =?= [] :
BasedAnchor = _,
DefaultWeighter = _,
InstantaneousAnchor = _,
MathOffset = _,
Ordinal = _,
Randomize = _,
Scheduler = _,
SpiOffsets = _,
SpiTime = _,
Start_real_time = _,
Waiting = _,
Wakeup = _,
close_vector(OBJECT_REQUESTS, SpiTime),
Waiter = [],
Record = [],
Debug = [] |
unify_without_failure(Cutoff, {_, []});
/* Close channels - i.e. decrement counts and release when unreferenced. */
Schedule ? close(Channels),
known(Channels),
arg(SPI_CLOSE, SpiOffsets, SpiOffset),
SpiOffset =?= unbound :
STOPPED |
execute_close(Channels, Reply),
self;
Schedule ? close(Channels),
known(Channels),
arg(SPI_CLOSE, SpiOffsets, SpiOffset),
SpiOffset =\= unbound :
execute(SpiOffset, {SPI_CLOSE, Channels, Reply}),
STOPPED |
self;
Schedule ? close(Channels, Reply?^),
known(Channels),
arg(SPI_CLOSE, SpiOffsets, SpiOffset),
SpiOffset =?= unbound :
STOPPED |
execute_close(Channels, Reply),
self;
Schedule ? close(Channels, Reply?^),
known(Channels),
arg(SPI_CLOSE, SpiOffsets, SpiOffset),
SpiOffset =\= unbound :
execute(SpiOffset, {SPI_CLOSE, Channels, Reply}),
STOPPED |
self;
/* Set the time limit - maximum value for SpiTime */
Schedule ? cutoff(Limit, State), Limit >= 0, State = State'?,
info(REALTIME, Start_real_time') :
Start_real_time = _,
Cutoff' = {Limit, State'} |
unify_without_failure(Cutoff, {_Limit, []}),
continue_waiting + (Reply = true);
Schedule ? default_weighter(Weighter),
arg(SPI_INDEX, SpiOffsets, SpiOffset),
SpiOffset =\= unbound |
reset_default_weighter(SpiOffset, Weighter, DefaultWeighter,
DefaultWeighter'),
self;
/* Splice input filter. */
Schedule ? input(Schedule'', Schedule'^) |
self;
/* Create a new channel. */
Schedule ? new_channel(ChannelName, Channel, BaseRate) |
index_channel_name(ChannelName, Ordinal, ChannelName', Ordinal'),
new_channel + (ComputeWeight = DefaultWeighter),
continue_waiting;
Schedule ? new_channel(ChannelName, Channel, ComputeWeight, BaseRate),
string(ComputeWeight) |
index_channel_name(ChannelName, Ordinal, ChannelName', Ordinal'),
new_channel + (ComputeWeight = ComputeWeight(_)),
continue_waiting;
Schedule ? new_channel(ChannelName, Channel, ComputeWeight, BaseRate),
tuple(ComputeWeight), arity(ComputeWeight) > 1 |
index_channel_name(ChannelName, Ordinal, ChannelName', Ordinal'),
new_channel,
continue_waiting;
Schedule ? new_public_channel(ChannelName, Channel, BaseRate) |
new_channel + (ComputeWeight = DefaultWeighter),
continue_waiting;
Schedule ? new_public_channel(ChannelName, Channel,
ComputeWeight, BaseRate),
string(ComputeWeight) |
new_channel + (ComputeWeight = ComputeWeight(_)),
continue_waiting;
Schedule ? new_public_channel(ChannelName, Channel,
ComputeWeight, BaseRate),
tuple(ComputeWeight), arity(ComputeWeight) > 1 |
new_channel,
continue_waiting;
Schedule ? ordinal(Ordinal', Ordinal^) |
self;
/* Return the current head of the recording stream. */
Schedule ? record(Stream) :
Stream = Record? |
self;
Schedule ? record_item(Item) :
Record ! Item,
Debug ! Item |
self;
/* Close the recording stream, and start a new one. */
Schedule ? end_record(Stream) :
store_vector(OBJECT_VALUES, 0.0, SpiTime),
Record = [],
Stream = Record'? |
self;
/* Start a transmission process. */
Schedule ? Start, Start =?= start(PostId, OpList, Value, Chosen),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =?= unbound,
tuple(PostId), arg(1, PostId, PName) :
Record ! start(PName),
Debug ! start(PostId) |
execute_post,
continue_waiting;
Schedule ? Start, Start =?= start(PName, OpList, Value, Chosen),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =?= unbound,
string(PName) :
Record ! start(PName),
Debug ! start(PName) |
execute_post + (PostId = {PName}),
continue_waiting;
Schedule ? Start, Start =?= start(PId, OpList, Value, Chosen, Prefix),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =?= unbound,
tuple(PId), arg(1, PId, PName),
string(PName),
string_to_dlist(PName, PNL, []),
convert_to_string(Prefix, Prefix'),
string_to_dlist(Prefix', PL, [CHAR_COLON | PNL]),
list_to_string(PL, PrefixedId) :
PostId = (Prefix' : PId),
Record ! start(PrefixedId),
Debug ! start(PostId) |
execute_post,
continue_waiting;
Schedule ? Start, Start =?= start({PName}, OpList, Value, Chosen, Prefix),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =?= unbound,
string(PName),
string_to_dlist(PName, PNL, []),
convert_to_string(Prefix, Prefix'),
string_to_dlist(Prefix', PL, [CHAR_COLON | PNL]),
list_to_string(PL, PrefixedId) :
PostId = (Prefix' : {PName}),
Record ! start(PrefixedId),
Debug ! start(PostId) |
execute_post,
continue_waiting;
Schedule ? Start, Start =?= start(PId, OpList, Value, Chosen),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =\= unbound,
tuple(PId), arg(1, PId, PName),
string(PName) :
execute(SpiOffset, {SPI_POST, PId, OpList, Value, Chosen, Reply}),
Record ! start(PName),
Debug ! start(PId) |
continue_waiting;
Schedule ? Start, Start =?= start(PName, OpList, Value, Chosen),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =\= unbound,
string(PName) :
execute(SpiOffset, {SPI_POST, {PName}, OpList, Value, Chosen, Reply}),
Record ! start(PName),
Debug ! start(PName) |
continue_waiting;
Schedule ? Start, Start =?= start(PId, OpList, Value, Chosen, Prefix),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =\= unbound,
tuple(PId), arg(1, PId, PName),
string(PName),
string_to_dlist(PName, PNL, []),
convert_to_string(Prefix, Prefix'),
string_to_dlist(Prefix', PL, [CHAR_COLON | PNL]),
list_to_string(PL, PrefixedId) :
PostId = (Prefix' : PId),
execute(SpiOffset, {SPI_POST, PostId, OpList, Value, Chosen, Reply}),
Record ! start(PrefixedId),
Debug ! start(PostId) |
continue_waiting;
Schedule ? Start, Start =?= start(PName, OpList, Value, Chosen, Prefix),
known(OpList),
arg(SPI_POST, SpiOffsets, SpiOffset),
SpiOffset =\= unbound,
string(PName),
string_to_dlist(PName, PNL, []),
convert_to_string(Prefix, Prefix'),
string_to_dlist(Prefix', PL, [CHAR_COLON | PNL]),
list_to_string(PL, PrefixedId) :
PostId = (Prefix' : {PName}),
execute(SpiOffset, {SPI_POST, PostId, OpList, Value, Chosen, Reply}),
Record ! start(PrefixedId),
Debug ! start(PostId) |
continue_waiting;
Schedule ? update_references(Updates),
Updates ? {Channel, Addend},
vector(Channel), arity(Channel, CHANNEL_SIZE),
integer(Addend), Addend > 0,
read_vector(SPI_CHANNEL_REFS, Channel, Refs),
Refs += Addend,
list(Updates') :
store_vector(SPI_CHANNEL_REFS, Refs', Channel),
Schedule'' = [update_references(Updates') | Schedule'] |
self;
Schedule ? update_references(Updates),
Updates ? {Channel, Addend},
vector(Channel), arity(Channel, CHANNEL_SIZE),
integer(Addend), Addend > 0,
read_vector(SPI_CHANNEL_REFS, Channel, Refs),
Refs += Addend,
Updates' =?= [] :
store_vector(SPI_CHANNEL_REFS, Refs', Channel) |
self;
/**************************** Debugging aids ********************************/
Schedule ? debug(Stream) :
Stream = Debug? |
self;
Schedule ? debug_note(Note) :
Debug ! Note |
self;
Schedule ? end_debug :
Debug = [],
Debug' = _ |
self;
Schedule ? diagnostic(Diagnostic) :
Debug ! Diagnostic |
screen # display(("Application Diagnostic" -> Diagnostic)),
self;
Schedule ? spifunctions(List),
arity(SpiOffsets, Arity),
make_tuple(Arity, SpiOffsets'),
arg(SPI_CLOSE, SpiOffsets', Close),
arg(SPI_POST, SpiOffsets', Post),
arg(SPI_STEP, SpiOffsets', Step),
arg(SPI_INDEX, SpiOffsets', Index),
arg(SPI_RATE, SpiOffsets', Rate) :
SpiOffsets = _,
Close = Close'?,
Post = Post'?,
Step = Step'?,
Index = Index'?,
Rate = Rate'? |
processor # link(lookup(spicomm, SpiOffset), _Ok),
spifunctions,
self;
/**************************** Debugger aids *********************************/
/* Pause processing until Continue is set. */
Schedule ? pause(Continue),
unknown(Wakeup) |
pause_scheduling(Continue,
Schedule', Schedule'',
Waiting, Waiting',
Wakeup, Wakeup',
Start_real_time, Start_real_time'),
self;
Schedule ? state(DefaultWeighter^, Randomize^, SpiOffsets^, Ordinal^) |
self;
Schedule ? status(Status),
read_vector(OBJECT_VALUES, SpiTime, Now),
Cutoff = {CutoffLimit, CutoffStatus} :
Status = STATUS |
self;
/* Step and resume */
Schedule ? step,
unknown(Wakeup) :
Schedule'' = [pause(resume) | Schedule'],
Wakeup' = done |
self;
/* Step and pause processing until Continue is set. */
Schedule ? step(Continue),
unknown(Wakeup) :
Schedule'' = [pause(Continue) | Schedule'],
Wakeup' = done |
self;
/***************************************************************************/
Schedule ? randomize(NewRandomize),
Randomize' := NewRandomize /\ SPI_RANDOM_FLAG :
Randomize = _ |
self;
Schedule ? Other,
otherwise,
unknown(Wakeup) |
fail("unrecognized request" - Other),
self;
Wakeup =?= done,
arg(SPI_STEP, SpiOffsets, SpiOffset),
SpiOffset =?= unbound,
arg(SPI_RATE, SpiOffsets, RateOffset),
read_vector(OBJECT_VALUES, SpiTime, Now) :
Waiting = _,
Waiting' = false,
store_vector(OBJECT_VALUES, Now'?, SpiTime) |
sum_weights(BasedAnchor, RateOffset, 0, Total),
logix_total(MathOffset, BasedAnchor, Now, Total,
RateOffset, Now', Wakeup'),
self;
Wakeup =?= done,
arg(SPI_STEP, SpiOffsets, SpiOffset),
SpiOffset =\= unbound,
read_vector(OBJECT_VALUES, SpiTime, Now) :
Waiting = _,
execute(SpiOffset, {SPI_STEP, Now, BasedAnchor, Now', Wakeup'}),
store_vector(OBJECT_VALUES, Now'?, SpiTime),
Debug ! step(Waiting, Wakeup, Wakeup'),
Waiting' = false |
self;
/*
* RCId refers to Request Channel Id (as of now, a string).
* CNID refers to Channel Name Id (as of now a string or a 2-tuple).
* CH refers to a spi-channel (as of now, a vector with 12 sub-channels).
* PId refers to a process signature (the originator of a request).
*/
Wakeup =?= true(PId1, RCId1, CH1, PId2, RCId2, CH2),
PId1 =\= (_ : _), PId2 =\= (_ : _),
arg(1, PId1, PName1),
arg(1, PId2, PName2),
read_vector(OBJECT_VALUES, SpiTime, Now),
read_vector(SPI_CHANNEL_NAME, CH1, CNId1),
read_vector(SPI_CHANNEL_NAME, CH2, CNId2) :
Waiting = _,
Wakeup' = _,
Waiter ! machine(idle_wait(Wakeup'), _Ok),
Waiting' = true,
Record = [Now, end(PName1(RCId1, SENT_ARROW, CNId1)),
end(PName2(RCId2, RECEIVED_ARROW, CNId2)) | Record'?],
Debug ! done(Now, PId1(RCId1, CH1), PId2(RCId2, CH2)) |
self;
Wakeup =?= true(PId1, RCId1, CH1, PId2, RCId2, CH2),
PId1 = (Prefix1 : SId1), arg(1, SId1, PName1),
string_to_dlist(PName1, PNL1, []),
string_to_dlist(Prefix1, PX1, [CHAR_COLON | PNL1]),
list_to_string(PX1, PrefixedName1),
PId2 = (Prefix2 : SId2), arg(1, SId2, PName2),
string_to_dlist(PName2, PNL2, []),
string_to_dlist(Prefix2, PX2, [CHAR_COLON | PNL2]),
list_to_string(PX2, PrefixedName2),
read_vector(OBJECT_VALUES, SpiTime, Now),
read_vector(SPI_CHANNEL_NAME, CH1, CNId1),
read_vector(SPI_CHANNEL_NAME, CH2, CNId2) :
Waiting = _,
Wakeup' = _,
Waiter ! machine(idle_wait(Wakeup'), _Ok),
Waiting' = true,
Record = [Now, end(PrefixedName1(RCId1, SENT_ARROW, CNId1)),
end(PrefixedName2(RCId2, RECEIVED_ARROW, CNId2)) | Record'?],
Debug ! done(Now, PId1(RCId1, CH1), PId2(RCId2, CH2)) |
self;
Wakeup =?= true,
Cutoff =?= {CutoffLimit, CutoffStatus},
read_vector(OBJECT_VALUES, SpiTime, Now) :
Waiting = _,
Wakeup' = _,
Waiting' = false,
Idle = idle(Now),
Record ! Idle,
Debug ! Idle,
CutoffStatus ! Idle,
Cutoff' = {CutoffLimit, CutoffStatus'} |
self;
Cutoff = {CutoffLimit, CutoffStatus},
read_vector(OBJECT_VALUES, SpiTime, Now),
Now >= CutoffLimit,
info(REALTIME, End_real_time),
Real_time := End_real_time - Start_real_time :
BasedAnchor = _,
InstantaneousAnchor = _,
MathOffset = _,
Schedule = _,
Scheduler = _,
Waiting = _,
Wakeup = _,
Waiter = [machine(idle_wait(Done), _Ok)],
Record = [],
Debug = [],
CutoffStatus = (done @ Now: seconds = Real_time) |
computation # display(CutoffStatus),
wait_done.
/*
* Supply default actions for selected requests.
* (Could improve (?) close(...) to actually close the channels.)
*/
wait_done(Schedule, DefaultWeighter, Randomize, SpiOffsets, Ordinal, Done,
SpiTime) :-
DUMMY_CHANNEL(new_channel(ChannelName, Channel, _Rate));
DUMMY_CHANNEL(new_channel(ChannelName, Channel, _Weight, _Rate));
DUMMY_CHANNEL(new_public_channel(ChannelName, Channel, _Weight, _Rate));
Schedule ? close(_, Reply) :
Reply = [] |
self;
Schedule ? default_weighter(Weighter),
arg(SPI_INDEX, SpiOffsets, SpiOffset),
SpiOffset =\= unbound |
reset_default_weighter(SpiOffset, Weighter, DefaultWeighter,
DefaultWeighter'),
self;
Schedule ? diagnostic(_) |
self;
Schedule ? randomize(NewRandomize),
Randomize' := NewRandomize /\ SPI_RANDOM_FLAG :
Randomize = _ |
self;
Schedule ? Other,
Other =\= close(_, _),
Other =\= default_weighter(_),
Other =\= diagnostic(_),
Other =\= randomize(_),
Other =\= new_channel(_, _, _),
Other =\= new_channel(_, _, _, _),
Other =\= new_public_channel(_, _, _, _) |
self;
unknown(Schedule),
known(Done) :
Schedule' = [] |
self;
Schedule =?= [] :
Done = _,
close_vector(OBJECT_REQUESTS, SpiTime) |
self#reset(DefaultWeighter, Randomize, SpiOffsets, Ordinal).
continue_waiting(Schedule, MathOffset, Ordinal, SpiOffsets, Waiter,
Scheduler, Record, Debug,
SpiTime, Waiting, Wakeup,
DefaultWeighter, Randomize,
Cutoff, Start_real_time,
BasedAnchor, InstantaneousAnchor,
Reply) :-
/* Reply for spifcp transmission */
Reply =?= true(PId1, RCId1, CH1, PId2, RCId2, CH2),
PId1 =\= (_ : _), PId2 =\= (_ : _),
tuple(PId1), arg(1, PId1, PName1),
tuple(PId2), arg(1, PId2, PName2),
read_vector(OBJECT_VALUES, SpiTime, Now),
read_vector(SPI_CHANNEL_NAME, CH1, CNId1),
read_vector(SPI_CHANNEL_NAME, CH2, CNId2) :
Record = [Now, end(PName1(RCId1, SENT_ARROW, CNId1)),
end(PName2(RCId2, RECEIVED_ARROW, CNId2)) | Record'?],
Debug ! done(Now, PId1(RCId1, CH1), PId2(RCId2, CH2)) |
scheduling;
/* Reply for biospi transmission */
Reply =?= true(PId1, RCId1, CH1, PId2, RCId2, CH2),
PId1 = (Prefix1 : SId1), arg(1, SId1, PName1),
string_to_dlist(PName1, PNL1, []),
string_to_dlist(Prefix1, PX1, [CHAR_COLON | PNL1]),
list_to_string(PX1, PrefixedName1),
PId2 = (Prefix2 : SId2), arg(1, SId2, PName2),
string_to_dlist(PName2, PNL2, []),
string_to_dlist(Prefix2, PX2, [CHAR_COLON | PNL2]),
list_to_string(PX2, PrefixedName2),
read_vector(OBJECT_VALUES, SpiTime, Now),
read_vector(SPI_CHANNEL_NAME, CH1, CNId1),
read_vector(SPI_CHANNEL_NAME, CH2, CNId2) :
Record = [Now, end(PrefixedName1(RCId1, SENT_ARROW, CNId1)),
end(PrefixedName2(RCId2, RECEIVED_ARROW, CNId2))
| Record'?],
Debug ! done(Now, PId1(RCId1, CH1), PId2(RCId2, CH2)) |
scheduling;
otherwise,
Reply =\= true :
Debug ! Reply |
fail(continue_waiting - Reply),
scheduling;
Waiting =?= true, Reply =?= true :
Debug ! ("Waiting = true, Reply = true, Wakeup" = Wakeup)|
scheduling;
Waiting =\= true, Reply =?= true :
Wakeup = _,
Waiter ! machine(idle_wait(Wakeup'), _Ok),
Waiting' = true,
Debug ! ("Reply = true", "Waiting" = Waiting, "Wakeup'" = Wakeup') |
scheduling;
/* check for paused. */
Reply =?= true,
unknown(Waiting) :
Debug ! ("Reply = true, unknown(Waiting), Waiting" = Waiting) |
scheduling.
pause_scheduling(Continue,
Schedule, ResetSchedule,
Waiting, ResetWaiting,
Wakeup, ResetWakeup,
Start_real_time, Reset_real_time) :-
info(REALTIME, Pause_real_time),
Biased_real_time := Start_real_time + Pause_real_time :
SavedInput = SaveInput? |
pause_continue.
pause_continue(Continue,
Schedule, ResetSchedule,
Waiting, ResetWaiting,
Wakeup, ResetWakeup,
Biased_real_time, Reset_real_time,
SavedInput, SaveInput) :-
Schedule ? Input,
Input =?= status(Status) :
Status ! pausing,
ResetSchedule ! status(Status') |
self;
Schedule ? Input,
Input =\= status(_),
unknown(Continue) :
SaveInput ! Input |
self;
Schedule =?= [],
unknown(Continue) :
SavedInput = _,
SavedInput' = [],
Continue' = resume |
self;
Continue = step(Continue') :
SaveInput ! pause(Continue'),
Continue'' = resume |
self;
Continue =?= resume,
info(REALTIME, Resume_real_time),
Reset_real_time^ := Biased_real_time - Resume_real_time :
ResetSchedule = SavedInput,
SaveInput = Schedule,
ResetWaiting = Waiting,
Wakeup = ResetWakeup.
index_channel_name(Name, Ordinal, Name', Ordinal') :-
unknown(Name) :
Name' = Name,
Ordinal' = Ordinal;
/* Transitional */
string(Name),
string_to_dlist(Name, CS1, []),
/* "public" for spifcp */
string_to_dlist("public.", CS2, _Tail) :
CS1 = CS2,
Ordinal' = Ordinal,
Name' = Name;
string(Name),
string_to_dlist(Name, CS1, []),
/* "public" for biospi */
string_to_dlist("public.", CS2, _Tail) :
CS1 = CS2,
Ordinal' = Ordinal,
Name' = Name;
/* drop - also next otherwise */
string(Name),
otherwise,
integer(Ordinal),
Ordinal'^ := Ordinal + 1 :
Name' = Name(Ordinal);
string(Name),
otherwise,
real(Ordinal),
Ordinal'^ := Ordinal + 0.000001 :
Name' = Name(Ordinal);
otherwise :
Name' = Name,
Ordinal' = Ordinal.
spifunctions(List, SpiOffset, Close, Post, Step, Index, Rate) :-
List ? CHAR_c :
Close = SpiOffset? |
self;
List ? CHAR_p :
Post = SpiOffset? |
self;
List ? CHAR_s :
Step = SpiOffset? |
self;
List ? CHAR_i :
Index = SpiOffset? |
self;
List ? CHAR_r :
Rate = SpiOffset? |
self;
List ? Other,
otherwise,
list_to_string([CHAR_DOUBLE_QUOTE,Other,CHAR_DOUBLE_QUOTE], String) |
fail(not_a_function - String),
self;
string(List),
string_to_dlist(List, List', []) |
self;
List =?= [] :
SpiOffset = _ |
unify_without_failure(unbound, Close),
unify_without_failure(unbound, Post),
unify_without_failure(unbound, Step),
unify_without_failure(unbound, Index),
unify_without_failure(unbound, Rate);
otherwise :
List' = [] |
fail(not_a_function(List)),
self.
new_channel(ChannelName, Channel, BaseRate, ComputeWeight, Randomize, Reply,
Scheduler, BasedAnchor, InstantaneousAnchor, SpiOffsets) :-
we(Channel),
bitwise_or(SPI_UNKNOWN, Randomize, ChannelType),
arg(SPI_INDEX, SpiOffsets, SpiOffset), SpiOffset =\= unbound,
arg(1, ComputeWeight, WeighterName) :
execute(SpiOffset, {SPI_INDEX, WeighterName, WeighterIndex, Result}),
make_vector(CHANNEL_SIZE, Channel, _),
store_vector(SPI_BLOCKED, FALSE, Channel),
store_vector(SPI_CHANNEL_TYPE, ChannelType, Channel),
store_vector(SPI_CHANNEL_RATE, 0.0, Channel),
store_vector(SPI_CHANNEL_REFS, 1, Channel),
store_vector(SPI_SEND_ANCHOR, SendAnchor, Channel),
make_vector(2, LinksS, _),
SendAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksS, []},
store_vector(SPI_NEXT_MS, SendAnchor, LinksS),
store_vector(SPI_PREVIOUS_MS, SendAnchor, LinksS),
store_vector(SPI_SEND_WEIGHT, 0, Channel),
store_vector(SPI_RECEIVE_ANCHOR, ReceiveAnchor, Channel),
make_vector(2, LinksR, _),
ReceiveAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksR, []},
store_vector(SPI_NEXT_MS, ReceiveAnchor, LinksR),
store_vector(SPI_PREVIOUS_MS, ReceiveAnchor, LinksR),
store_vector(SPI_RECEIVE_WEIGHT, 0, Channel),
store_vector(SPI_WEIGHT_TUPLE, WeighterTuple?, Channel),
store_vector(SPI_NEXT_CHANNEL, Channel, Channel),
store_vector(SPI_PREVIOUS_CHANNEL, Channel, Channel),
store_vector(SPI_CHANNEL_NAME, ChannelName, Channel) |
complete_weighter_tuple(Result, ComputeWeight, WeighterIndex,
WeighterTuple, Result'),
based_or_instantaneous;
we(Channel),
bitwise_or(SPI_UNKNOWN, Randomize, ChannelType),
arg(SPI_INDEX, SpiOffsets, unbound),
ComputeWeight =?= SPI_DEFAULT_WEIGHT_NAME(_) :
make_vector(CHANNEL_SIZE, Channel, _),
store_vector(SPI_BLOCKED, FALSE, Channel),
store_vector(SPI_CHANNEL_TYPE, ChannelType, Channel),
store_vector(SPI_CHANNEL_RATE, 0.0, Channel),
store_vector(SPI_CHANNEL_REFS, 1, Channel),
store_vector(SPI_SEND_ANCHOR, SendAnchor, Channel),
make_vector(2, LinksS, _),
SendAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksS, []},
store_vector(SPI_NEXT_MS, SendAnchor, LinksS),
store_vector(SPI_PREVIOUS_MS, SendAnchor, LinksS),
store_vector(SPI_SEND_WEIGHT, 0, Channel),
store_vector(SPI_RECEIVE_ANCHOR, ReceiveAnchor, Channel),
make_vector(2, LinksR, _),
ReceiveAnchor = {SPI_MESSAGE_ANCHOR, "", [], 0, 0, 0, [], LinksR, []},
store_vector(SPI_NEXT_MS, ReceiveAnchor, LinksR),
store_vector(SPI_PREVIOUS_MS, ReceiveAnchor, LinksR),
store_vector(SPI_RECEIVE_WEIGHT, 0, Channel),
store_vector(SPI_WEIGHT_TUPLE,
SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX), Channel),
store_vector(SPI_NEXT_CHANNEL, Channel, Channel),
store_vector(SPI_PREVIOUS_CHANNEL, Channel, Channel),
store_vector(SPI_CHANNEL_NAME, ChannelName, Channel) |
based_or_instantaneous + (Result = true);
otherwise :
BasedAnchor = _,
InstantaneousAnchor = _,
Randomize = _,
Scheduler = _,
SpiOffsets = _,
Reply = error(new_channel(ChannelName, Channel, BaseRate, ComputeWeight)).
based_or_instantaneous(ChannelName, BaseRate, Result, Scheduler, Reply,
Channel, BasedAnchor, InstantaneousAnchor) :-
Result =?= true,
BaseRate =?= infinite :
BasedAnchor = _,
store_vector(SPI_CHANNEL_TYPE, SPI_INSTANTANEOUS, Channel),
Reply = Result,
DEBUG((ChannelName: instantaneous)) |
queue_channel(Channel, InstantaneousAnchor);
Result =?= true,
convert_to_real(BaseRate, RealRate),
RealRate =< 0.0 :
BasedAnchor = _,
InstantaneousAnchor = _,
store_vector(SPI_CHANNEL_TYPE, SPI_SINK, Channel),
Reply = true,
DEBUG((ChannelName: sink(unnatural(BaseRate))));
Result =?= true,
convert_to_real(BaseRate, RealRate),
RealRate > 0.0 :
InstantaneousAnchor = _,
store_vector(SPI_CHANNEL_RATE, RealRate, Channel),
Reply = Result,
DEBUG((ChannelName: based_channel)) |
queue_channel(Channel, BasedAnchor);
Result =?= true,
otherwise :
BasedAnchor = _,
Channel = _,
InstantaneousAnchor = _,
Scheduler = _,
store_vector(SPI_CHANNEL_TYPE, SPI_SINK, Channel),
Reply = "invalid base rate"(ChannelName - BaseRate),
DEBUG((ChannelName: sink(invalid(BaseRate))));
Result =\= true :
BasedAnchor = _,
BaseRate = _,
Channel = _,
ChannelName = _,
InstantaneousAnchor = _,
Scheduler = _,
store_vector(SPI_CHANNEL_TYPE, SPI_SINK, Channel),
Reply = Result,
DEBUG((ChannelName : sink(Result))).
complete_weighter_tuple(Reply, ComputeWeight, WeighterIndex,
WeighterTuple, Reply1) :-
Reply = true,
arg(2, ComputeWeight, Index) :
Index = WeighterIndex,
WeighterTuple = ComputeWeight,
Reply1 = Reply;
Reply = true,
otherwise :
WeighterIndex = _,
WeighterTuple = SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX),
Reply1 = Reply |
fail(invalid_weighter_index(ComputeWeight));
Reply =\= true :
ComputeWeight = _,
WeighterIndex = _,
WeighterTuple = SPI_DEFAULT_WEIGHT_NAME(SPI_DEFAULT_WEIGHT_INDEX),
Reply1 = Reply.
queue_channel(Channel, Anchor) :-
read_vector(SPI_PREVIOUS_CHANNEL, Anchor, OldPrevious) :
store_vector(SPI_PREVIOUS_CHANNEL, OldPrevious, Channel),
store_vector(SPI_NEXT_CHANNEL, Anchor, Channel),
store_vector(SPI_NEXT_CHANNEL, Channel, OldPrevious),
store_vector(SPI_PREVIOUS_CHANNEL, Channel, Anchor).
reset_default_weighter(SpiOffset, New, Old, Default) :-
string(New) :
execute(SpiOffset, {SPI_INDEX, New, Index, Reply}) |
check_new_default + (New = New(_));
tuple(New),
arg(1, New, Name) :
execute(SpiOffset, {SPI_INDEX, Name, Index, Reply}) |
check_new_default;
otherwise :
SpiOffset = _,
Default = Old |
fail(invalid_new_default_weighter(New)).
check_new_default(Reply, Index, New, Old, Default) :-
Reply =?= true,
arg(2, New, Ix) :
Old = _,
Ix = Index,
Default = New;
Reply =?= true,
otherwise :
Default = Old |
fail(mismatch_new_default_weighter_index(New - Index));
Reply =\= true :
Index = _,
Default = Old |
fail(Reply(New)).
/************************* execute - testing *********************************/
execute_post(MathOffset, PostId, OpList, Value, Chosen, Reply) :-
true :
Common = {PostId, Messages, Value, Chosen},
Messages = AddMessages? |
post_pass0(OpList, Instantaneous, 0, Count, Ok),
post_pass1,
post_pass2.
execute_close(Channels, Reply) :-
tuple(Channels),
N := arity(Channels) |
close_channels(Channels, N, Reply).
/************************** close procedures *********************************/
close_channels(Channels, N, Reply) :-
N > 0,
arg(N, Channels, Channel),
N--,
vector(Channel),
read_vector(SPI_CHANNEL_REFS, Channel, Refs),
Refs--,
Refs' > 0 :
store_vector(SPI_CHANNEL_REFS, Refs', Channel) |
self;
N > 0,
arg(N, Channels, Channel),
N--,
vector(Channel),
read_vector(SPI_CHANNEL_REFS, Channel, Refs),
Refs--,
Refs' =:= 0,
read_vector(SPI_NEXT_CHANNEL, Channel, Next),
read_vector(SPI_PREVIOUS_CHANNEL, Channel, Previous) :
store_vector(SPI_CHANNEL_REFS, 0, Channel),
store_vector(SPI_NEXT_CHANNEL, Next, Previous),
store_vector(SPI_PREVIOUS_CHANNEL, Previous, Next),
store_vector(SPI_NEXT_CHANNEL, Channel, Channel),
store_vector(SPI_PREVIOUS_CHANNEL, Channel, Channel),
Reply ! N |
self;
N > 0,
arg(N, Channels, Channel),
N--,
vector(Channel),
read_vector(SPI_CHANNEL_REFS, Channel, Refs),
Refs--,
Refs' < 0 :
Reply = "Error - Problem in ReferenceCount"(Channel),
Reply' = _ |
self;
N =< 0 :
Channels = _,
Reply = [];
otherwise :
Reply = close_failed(N, Channels).
/************************ post procedures ********************************/
post_pass0(OpList, Instantaneous, Number, Count, Ok) :-
OpList ? Operation,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
integer(Multiplier), Multiplier > 0,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType),
bitwise_and(ChannelType, SPI_TYPE_MASK, SPI_INSTANTANEOUS),
Number++ :
Instantaneous ! Operation |
self;
OpList ? Operation,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
integer(Multiplier), Multiplier > 0,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType),
bitwise_and(ChannelType, SPI_TYPE_MASK, SPI_BIMOLECULAR) |
self;
OpList ? Operation,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
integer(Multiplier), Multiplier > 0,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType),
bitwise_and(ChannelType, SPI_TYPE_MASK, SPI_HOMODIMERIZED) |
self;
OpList ? Operation,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
integer(Multiplier), Multiplier > 0,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType),
bitwise_and(ChannelType, SPI_TYPE_MASK, SPI_UNKNOWN),
arg(SPI_MS_TYPE, Operation, MessageType),
read_vector(SPI_WEIGHT_TUPLE, Channel, WeightTuple),
arg(2, WeightTuple, Index),
bitwise_and(ChannelType, SPI_RANDOM_FLAG, RandomFlag) :
store_vector(SPI_CHANNEL_TYPE, FinalType, Channel) |
update_channel_type,
self;
OpList =?= [] :
Count = Number,
Instantaneous = [],
Ok = true;
otherwise |
post_pass0_skip.
update_channel_type(Index, MessageType, RandomFlag, FinalType) :-
Index =?= SPI_DEFAULT_WEIGHT_INDEX,
MessageType =\= SPI_DIMER,
bitwise_or(SPI_BIMOLECULAR, RandomFlag, ChannelType) :
FinalType = ChannelType;
Index =?= SPI_DEFAULT_WEIGHT_INDEX,
MessageType =?= SPI_DIMER,
bitwise_or(SPI_HOMODIMERIZED, RandomFlag, ChannelType) :
FinalType = ChannelType;
Index =\= SPI_DEFAULT_WEIGHT_INDEX,
MessageType =\= SPI_DIMER,
bitwise_or(SPI_BIMOLECULAR_PRIME, RandomFlag, ChannelType) :
FinalType = ChannelType;
Index =\= SPI_DEFAULT_WEIGHT_INDEX,
MessageType =?= SPI_DIMER,
bitwise_or(SPI_HOMODIMERIZED_PRIME, RandomFlag, ChannelType) :
FinalType = ChannelType.
post_pass0_skip(OpList, Instantaneous, Number, Count, Ok) :-
OpList ? Operation,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
integer(Multiplier), Multiplier =< 0 |
post_pass0;
OpList ? Operation,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType),
bitwise_and(ChannelType, SPI_TYPE_MASK, SPI_SINK) |
post_pass0;
otherwise :
Count = Number,
Instantaneous = [],
Ok = invalid_transmission - OpList.
post_pass1(MathOffset, Common, Instantaneous, Count, Ok, Ok1) :-
Ok = true,
Count-- =:= 1,
Instantaneous ? Operation,
Instantaneous' =?= [],
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, ChannelType^) |
post_instantaneous;
Ok = true,
Count-- > 1,
Decrement := real(1)/Count :
execute(MathOffset, {RAN, 0, Uniform}) |
choose_instantaneous_operation(Uniform, Decrement,
Instantaneous, Instantaneous',
Operation, Channel, ChannelType),
post_instantaneous;
otherwise :
Common = _,
Count = _,
Instantaneous = _,
MathOffset = _,
Ok1 = Ok .
choose_instantaneous_operation(Uniform, Decrement, I1, I2, Operation,
Channel, ChannelType) :-
I1 ? Op,
I1' =\= [],
Uniform > Decrement,
Uniform -= Decrement :
I2 ! Op |
self;
I1 ? Op,
otherwise,
arg(SPI_MS_CHANNEL, Op, Ch),
read_vector(SPI_CHANNEL_TYPE, Ch, CT) :
Decrement = _,
Uniform = _,
Channel = Ch,
ChannelType = CT,
I2 = I1',
Operation = Op.
post_pass2(OpList, Reply, Common, Messages, AddMessages, Ok1) :-
Ok1 =?= true,
OpList ? Operation,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
Type =\= SPI_SINK,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
Multiplier > 0,
arg(SPI_MS_TYPE, Operation, MessageType),
arg(SPI_MS_CID, Operation, RCId),
arg(SPI_MS_TAGS, Operation, Tags),
arity(Operation) =:= SPI_MS_SIZE :
AddMessages ! Message? |
queue_message + (Ambient = []),
self;
Ok1 =?= true,
OpList ? Operation,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
Type =\= SPI_SINK,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
Multiplier > 0,
arg(SPI_MS_TYPE, Operation, MessageType),
arg(SPI_MS_CID, Operation, RCId),
arg(SPI_MS_TAGS, Operation, Tags),
arity(Operation) =:= SPI_AMBIENT_MS_SIZE,
arg(SPI_MS_AMBIENT, Operation, Ambient) :
AddMessages ! Message? |
queue_message,
self;
Ok1 =?= true,
OpList ? Operation,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
Type =\= SPI_SINK,
arg(SPI_MS_MULTIPLIER, Operation, Multiplier),
Multiplier =< 0 |
self;
Ok1 =?= true,
OpList ? Operation,
arg(SPI_MS_CHANNEL, Operation, Channel),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
Type =?= SPI_SINK |
self;
Ok1 =?= true,
OpList =?= [] :
Common = _,
Messages = _,
AddMessages = [],
Reply = true;
otherwise :
Common = _,
Messages = _,
OpList = _,
Reply = Ok1,
AddMessages = [].
/*
* Suffix Q refers to a channel queue element.
* Suffix R refers to a message request element.
*/
post_instantaneous(MathOffset, Common, Instantaneous, Count, Ok1,
Operation, Channel, ChannelType) :-
arity(Operation) =:= SPI_MS_SIZE,
bitwise_and(ChannelType, SPI_RANDOM_FLAG, 0),
arg(SPI_MS_TYPE, Operation, SPI_SEND),
read_vector(SPI_RECEIVE_ANCHOR, Channel, EndR),
arg(SPI_MESSAGE_LINKS, EndR, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message) |
do_instantaneous_transmit + (MTX = SPI_RECEIVE_TAG, Ambient = []);
arity(Operation) =:= SPI_MS_SIZE,
bitwise_and(ChannelType, SPI_RANDOM_FLAG, 0),
arg(SPI_MS_TYPE, Operation, SPI_RECEIVE),
read_vector(SPI_SEND_ANCHOR, Channel, EndR),
arg(SPI_MESSAGE_LINKS, EndR, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message) |
do_instantaneous_transmit + (MTX = SPI_SEND_TAG, Ambient = []);
arity(Operation) =:= SPI_MS_SIZE,
bitwise_and(ChannelType, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
arg(SPI_MS_TYPE, Operation, SPI_SEND),
read_vector(SPI_RECEIVE_ANCHOR, Channel, Anchor),
read_vector(SPI_RECEIVE_WEIGHT, Channel, Weight) :
execute(MathOffset, {RAN, 0, Uniform}) |
post_instantaneous_random + (MTX = SPI_RECEIVE_TAG, Ambient = []);
arity(Operation) =:= SPI_MS_SIZE,
bitwise_and(ChannelType, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
arg(SPI_MS_TYPE, Operation, SPI_RECEIVE),
read_vector(SPI_SEND_ANCHOR, Channel, Anchor),
read_vector(SPI_SEND_WEIGHT, Channel, Weight) :
execute(MathOffset, {RAN, 0, Uniform}) |
post_instantaneous_random + (MTX = SPI_SEND_TAG, Ambient = []);
arity(Operation) =:= SPI_AMBIENT_MS_SIZE,
arg(SPI_MS_AMBIENT, Operation, Ambient),
bitwise_and(ChannelType, SPI_RANDOM_FLAG, 0),
arg(SPI_MS_TYPE, Operation, SPI_SEND),
read_vector(SPI_RECEIVE_ANCHOR, Channel, EndR),
arg(SPI_MESSAGE_LINKS, EndR, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message) |
do_instantaneous_transmit + (MTX = SPI_RECEIVE_TAG);
arity(Operation) =:= SPI_AMBIENT_MS_SIZE,
arg(SPI_MS_AMBIENT, Operation, Ambient),
bitwise_and(ChannelType, SPI_RANDOM_FLAG, 0),
arg(SPI_MS_TYPE, Operation, SPI_RECEIVE),
read_vector(SPI_SEND_ANCHOR, Channel, EndR),
arg(SPI_MESSAGE_LINKS, EndR, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message) |
do_instantaneous_transmit + (MTX = SPI_SEND_TAG);
arity(Operation) =:= SPI_AMBIENT_MS_SIZE,
arg(SPI_MS_AMBIENT, Operation, Ambient),
bitwise_and(ChannelType, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
arg(SPI_MS_TYPE, Operation, SPI_SEND),
read_vector(SPI_RECEIVE_ANCHOR, Channel, Anchor),
read_vector(SPI_RECEIVE_WEIGHT, Channel, Weight) :
execute(MathOffset, {RAN, 0, Uniform}) |
post_instantaneous_random + (MTX = SPI_RECEIVE_TAG);
arity(Operation) =:= SPI_AMBIENT_MS_SIZE,
arg(SPI_MS_AMBIENT, Operation, Ambient),
bitwise_and(ChannelType, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
arg(SPI_MS_TYPE, Operation, SPI_RECEIVE),
read_vector(SPI_SEND_ANCHOR, Channel, Anchor),
read_vector(SPI_SEND_WEIGHT, Channel, Weight) :
execute(MathOffset, {RAN, 0, Uniform}) |
post_instantaneous_random + (MTX = SPI_SEND_TAG);
otherwise :
Channel = _,
ChannelType = _,
Common = _,
Count = _,
Instantaneous = _,
MathOffset = _,
Ok1 = invalid_transmission - Operation.
post_instantaneous_random(MathOffset, Common, Instantaneous, Count, Ok1,
Operation, MTX, Ambient, Anchor, Uniform, Weight) :-
Select := Uniform*Weight |
choose_random_start(Anchor, Select, Message),
do_instantaneous_transmit + (EndR = Message).
do_instantaneous_transmit(MathOffset, Common, Instantaneous, Count, Ok1,
Operation, MTX, Ambient, EndR, Message) :-
arg(SPI_MS_CID, Message, RCIdQ),
arg(SPI_MS_CHANNEL, Message, ChannelQ),
arg(SPI_COMMON, Message, CommonQ),
arg(MTX, Message, MessageTag),
CommonQ = {PIdQ, MsList, ValueQ, ChosenQ},
Common = {PIdR, _MsList, ValueR, ChosenR},
arg(SPI_MS_CID, Operation, RCIdR),
arg(SPI_MS_CHANNEL, Operation, ChannelR),
arg(SPI_MS_TAGS, Operation, OperationTag),
Ambient =?= [] :
Count = _,
EndR = _,
Instantaneous = _,
MathOffset = _,
ValueQ = ValueR,
ChosenQ = MessageTag,
ChosenR = OperationTag,
Ok1 = true(PIdQ, RCIdQ, ChannelQ, PIdR, RCIdR, ChannelR) |
discount(MsList);
arg(SPI_MS_CID, Message, RCIdQ),
arg(SPI_MS_CHANNEL, Message, ChannelQ),
arg(SPI_COMMON, Message, CommonQ),
arg(MTX, Message, MessageTag),
CommonQ = {PIdQ, MsList, ValueQ, ChosenQ},
Common = {PIdR, _MsList, ValueR, ChosenR},
arg(SPI_MS_CID, Operation, RCIdR),
arg(SPI_MS_CHANNEL, Operation, ChannelR),
arg(SPI_MS_TAGS, Operation, OperationTag),
Ambient =\= [],
arg(SPI_AMBIENT_CHANNEL, Message, AmbientQ),
Ambient =\= AmbientQ :
Count = _,
EndR = _,
Instantaneous = _,
MathOffset = _,
ValueQ = ValueR,
ChosenQ = MessageTag,
ChosenR = OperationTag,
Ok1 = true(PIdQ, RCIdQ, ChannelQ, PIdR, RCIdR, ChannelR) |
discount(MsList);
Ambient =\= [],
arg(SPI_AMBIENT_CHANNEL, Message, AmbientQ),
Ambient =?= AmbientQ,
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =\= EndR |
self;
Ambient =\= [],
arg(SPI_AMBIENT_CHANNEL, Message, AmbientQ),
Ambient =?= AmbientQ,
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =?= EndR :
Operation = _,
MTX = _ |
post_pass1 + (Ok = true);
arg(SPI_COMMON, Message, CommonQ),
arg(SPI_OP_CHOSEN, CommonQ, Chosen), not_we(Chosen),
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =\= EndR |
self;
arg(SPI_MS_TYPE, Message, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =\= EndR |
self;
arg(SPI_MS_TYPE, Message, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =?= EndR :
Ambient = _,
Operation = _,
MTX = _ |
post_pass1 + (Ok = true);
% This can happen (to the monitor).
Common = {_, _, _, Chosen}, not_we(Chosen) :
Ambient = _,
EndR = _,
Operation = _,
Message = _,
MTX = _ |
post_pass1 + (Ok = true);
% This Message has the same Chosen as the Operation -
% mixed communications which ARE NOT homodimerized.
arg(SPI_COMMON, Message, CommonQ),
CommonQ = {_, _, _, Chosen},
Common = {_, _, _, Chosen},
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =\= EndR |
self;
arg(SPI_COMMON, Message, CommonQ),
CommonQ = {_, _, _, Chosen},
Common = {_, _, _, Chosen},
arg(SPI_MESSAGE_LINKS, Message, MessageLinks),
read_vector(SPI_NEXT_MS, MessageLinks, Message'),
Message' =?= EndR :
Ambient = _,
Operation = _,
MTX = _ |
post_pass1 + (Ok = true).
/*************************** step procedures *********************************/
sum_weights(Channel, RateOffset, Sum, Total) :-
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel'),
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
Type =?= SPI_CHANNEL_ANCHOR :
RateOffset = _,
Total = Sum;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_BIMOLECULAR),
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_SEND_WEIGHT, Channel', SendWeight),
read_vector(SPI_RECEIVE_WEIGHT, Channel', ReceiveWeight),
Sum += Rate*SendWeight*ReceiveWeight |
self;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_HOMODIMERIZED),
read_vector(SPI_DIMER_ANCHOR, Channel', Anchor),
arg(SPI_MESSAGE_LINKS, Anchor, FirstLink),
read_vector(SPI_NEXT_MS, FirstLink, Message),
arg(SPI_MESSAGE_LINKS, Message, DimerLink),
read_vector(SPI_NEXT_MS, DimerLink, DimerMs),
arg(SPI_MS_TYPE, DimerMs, MsType),
MsType =\= SPI_MESSAGE_ANCHOR,
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_DIMER_WEIGHT, Channel', DimerWeight),
Sum += Rate*DimerWeight*(DimerWeight-1)/2 |
self;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_FLAG, SPI_PRIME_FLAG) :
execute(RateOffset, {SPI_RATE, Channel', Addend, Reply}) |
prime_weight_cumulate(Reply, Addend, Sum, Sum'),
self;
otherwise,
vector(Channel),
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel') |
self.
prime_weight_cumulate(Reply, Addend, Sum, Cumulated) :-
Reply =?= true,
Sum += Addend :
Cumulated = Sum'.
logix_total(MathOffset, Anchor, Now, Total, RateOffset, NewNow, Wakeup) :-
Total =< 0 :
Anchor = _,
MathOffset = _,
RateOffset = _,
NewNow = Now,
Wakeup = true;
Total > 0 :
execute(MathOffset, {RAN, 0, Uniform1}),
execute(MathOffset, {RAN, 0, Uniform2}),
execute(MathOffset, {LN, Uniform2, NegativeExponential}) |
logix_transmit.
logix_transmit(RateOffset, Anchor, Now, Total,
Uniform1, Uniform2, NegativeExponential,
NewNow, Wakeup) :-
Residue := Uniform1*Total,
NewNow^ := Now - NegativeExponential/Total |
select_channel + (Channel = Anchor).
select_channel(RateOffset, Residue, Channel, Uniform1, Uniform2, Wakeup) :-
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_BIMOLECULAR),
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_SEND_WEIGHT, Channel', SendWeight),
SendWeight > 0,
read_vector(SPI_RECEIVE_WEIGHT, Channel', ReceiveWeight),
ReceiveWeight > 0,
Residue -= Rate*SendWeight*ReceiveWeight,
Residue' =< 0 :
RateOffset = _ |
do_bimolecular_transmit;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_BIMOLECULAR),
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_SEND_WEIGHT, Channel', SendWeight),
SendWeight > 0,
read_vector(SPI_RECEIVE_WEIGHT, Channel', ReceiveWeight),
ReceiveWeight > 0,
Residue -= Rate*SendWeight*ReceiveWeight,
Residue' > 0 |
self;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_HOMODIMERIZED),
read_vector(SPI_DIMER_ANCHOR, Channel', Anchor),
arg(SPI_MESSAGE_LINKS, Anchor, FirstLink),
read_vector(SPI_NEXT_MS, FirstLink, Message),
arg(SPI_MESSAGE_LINKS, Message, DimerLink),
read_vector(SPI_NEXT_MS, DimerLink, DimerMs),
arg(SPI_MS_TYPE, DimerMs, MsType),
MsType =\= SPI_MESSAGE_ANCHOR,
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_DIMER_WEIGHT, Channel', DimerWeight),
Residue -= Rate*DimerWeight*(DimerWeight-1)/2,
Residue' =< 0 :
RateOffset = _ |
do_homodimerized_transmit;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_MASK, SPI_HOMODIMERIZED),
read_vector(SPI_DIMER_ANCHOR, Channel', Anchor),
arg(SPI_MESSAGE_LINKS, Anchor, FirstLink),
read_vector(SPI_NEXT_MS, FirstLink, Message),
arg(SPI_MESSAGE_LINKS, Message, DimerLink),
read_vector(SPI_NEXT_MS, DimerLink, DimerMs),
arg(SPI_MS_TYPE, DimerMs, MsType),
MsType =\= SPI_MESSAGE_ANCHOR,
read_vector(SPI_CHANNEL_RATE, Channel', Rate),
read_vector(SPI_DIMER_WEIGHT, Channel', DimerWeight),
Residue -= Rate*DimerWeight*(DimerWeight-1)/2,
Residue' > 0 |
self;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
vector(Channel'),
read_vector(SPI_BLOCKED, Channel', Blocked),
Blocked =?= FALSE,
read_vector(SPI_CHANNEL_TYPE, Channel', Type),
bitwise_and(Type, SPI_PRIME_FLAG, SPI_PRIME_FLAG),
bitwise_and(Type, SPI_PRIME_MASK, Type') :
execute(RateOffset, {SPI_RATE, Channel', Subtrahend, Reply}) |
prime_weight_decrement;
read_vector(SPI_NEXT_CHANNEL, Channel, Channel'),
otherwise |
self.
prime_weight_decrement(RateOffset, Residue, Channel, Uniform1, Uniform2,
Wakeup, Type, Subtrahend, Reply) :-
Reply = true,
Subtrahend =< 0 :
Type = _ |
select_channel;
Reply = true,
Subtrahend > 0,
Residue -= Subtrahend,
Residue' > 0 :
Type = _ |
select_channel;
Reply = true,
Subtrahend > 0,
Residue -= Subtrahend,
Residue' =< 0,
Type =?= SPI_BIMOLECULAR_PRIME :
RateOffset = _ |
do_bimolecular_transmit;
Reply = true,
Subtrahend > 0,
Residue -= Subtrahend,
Residue' =< 0,
Type =?= SPI_HOMODIMERIZED_PRIME :
RateOffset = _ |
do_homodimerized_transmit.
/****** based transmit - complete a transmission for a pair of messages ******/
do_bimolecular_transmit(Channel, Uniform1, Uniform2, Wakeup) :-
read_vector(SPI_SEND_ANCHOR, Channel, SendAnchor),
read_vector(SPI_RECEIVE_ANCHOR, Channel, ReceiveAnchor),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
bitwise_and(Type, SPI_RANDOM_FLAG, 0),
arg(SPI_MESSAGE_LINKS, SendAnchor, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send),
arg(SPI_MESSAGE_LINKS, ReceiveAnchor, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive) :
Uniform1 = _,
Uniform2 = _ |
do_bimolecular_send(Channel, Wakeup, Send, Send, Receive, Receive);
read_vector(SPI_SEND_ANCHOR, Channel, SendAnchor),
read_vector(SPI_RECEIVE_ANCHOR, Channel, ReceiveAnchor),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
bitwise_and(Type, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
read_vector(SPI_SEND_WEIGHT, Channel, SendWeight),
SendSelect := Uniform1*SendWeight,
read_vector(SPI_RECEIVE_WEIGHT, Channel, ReceiveWeight),
ReceiveSelect := Uniform2*ReceiveWeight |
choose_random_start(SendAnchor, SendSelect, StartS),
choose_random_start(ReceiveAnchor, ReceiveSelect, StartR),
do_bimolecular_send(Channel, Wakeup, StartS, StartS, StartR, StartR).
do_bimolecular_send(Channel, Wakeup, Send, EndSend, Receive, EndReceive) :-
arg(SPI_MS_TYPE, Send, SPI_SEND),
arg(SPI_MS_CID, Send, SendRCId),
arg(SPI_MS_CHANNEL, Send, SendChannel),
arg(SPI_SEND_TAG, Send, SendTag),
arg(SPI_COMMON, Send, SendCommon),
arg(SPI_AMBIENT_CHANNEL, Send, []),
arg(SPI_MS_TYPE, Receive, SPI_RECEIVE),
arg(SPI_MS_CID, Receive, ReceiveRCId),
arg(SPI_MS_CHANNEL, Receive, ReceiveChannel),
arg(SPI_RECEIVE_TAG, Receive, ReceiveTag),
arg(SPI_COMMON, Receive, ReceiveCommon),
SendCommon =?= {SendPId, SendList, SendValue, SendChosen},
ReceiveCommon =?= {ReceivePId, ReceiveList, ReceiveValue, ReceiveChosen} :
Channel = _,
EndReceive = _,
EndSend = _,
SendChosen = SendTag,
ReceiveChosen = ReceiveTag,
ReceiveValue = SendValue?,
Wakeup = true(SendPId, SendRCId, SendChannel,
ReceivePId, ReceiveRCId, ReceiveChannel) |
discount(SendList),
discount(ReceiveList);
arg(SPI_MS_TYPE, Send, SPI_SEND),
arg(SPI_MS_CHANNEL, Send, SendChannel),
arg(SPI_SEND_TAG, Send, SendTag),
arg(SPI_MS_CID, Send, SendRCId),
arg(SPI_COMMON, Send, SendCommon),
arg(SPI_AMBIENT_CHANNEL, Send, SendAmbient),
SendAmbient =\= [],
arg(SPI_MS_TYPE, Receive, SPI_RECEIVE),
arg(SPI_MS_CID, Receive, ReceiveRCId),
arg(SPI_MS_CHANNEL, Receive, ReceiveChannel),
arg(SPI_RECEIVE_TAG, Receive, ReceiveTag),
arg(SPI_COMMON, Receive, ReceiveCommon),
ReceiveCommon =?= {ReceivePId, ReceiveList, ReceiveValue, ReceiveChosen},
SendCommon =?= {SendPId, SendList, SendValue, SendChosen},
arg(SPI_AMBIENT_CHANNEL, Receive, ReceiveAmbient),
SendAmbient =\= ReceiveAmbient :
Channel = _,
EndReceive = _,
EndSend = _,
SendChosen = SendTag,
ReceiveChosen = ReceiveTag,
ReceiveValue = SendValue?,
Wakeup = true(SendPId, SendRCId, SendChannel,
ReceivePId, ReceiveRCId, ReceiveChannel) |
discount(SendList),
discount(ReceiveList);
arg(SPI_MS_TYPE, Send, SPI_SEND),
arg(SPI_AMBIENT_CHANNEL, Send, SendAmbient),
SendAmbient =\= [],
arg(SPI_AMBIENT_CHANNEL, Receive, ReceiveAmbient),
SendAmbient =?= ReceiveAmbient,
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send') |
bimolecular_send_blocked;
arg(SPI_MS_TYPE, Send, SPI_SEND),
arg(SPI_COMMON, Send, SendCommon),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
arg(SPI_COMMON, Receive, ReceiveCommon),
% This Send has the same Chosen as the Receive -
% mixed communications which ARE NOT homodimerized.
SendCommon =?= {_, _, _, Chosen},
ReceiveCommon =?= {_, _, _, Chosen},
read_vector(SPI_NEXT_MS, SendLinks, Send') |
bimolecular_send_blocked;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =\= EndSend |
self;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_RECEIVE) |
self;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Receive', ReceiveLinks'),
read_vector(SPI_NEXT_MS, ReceiveLinks', Receive''),
Receive'' =\= EndReceive |
self;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =?= EndReceive |
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_RECEIVE) |
self;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Receive', ReceiveLinks'),
read_vector(SPI_NEXT_MS, ReceiveLinks', Receive''),
Receive'' =\= EndReceive |
self;
arg(SPI_MS_TYPE, Send, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Send, SendLinks),
read_vector(SPI_NEXT_MS, SendLinks, Send'),
Send' =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Receive', ReceiveLinks'),
read_vector(SPI_NEXT_MS, ReceiveLinks', Receive''),
Receive'' =?= EndReceive |
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done
/*
otherwise |
computation # spi_utils # show_value(channel = Channel,[],C),
computation # spi_utils # show_value(send = Send, [3], S),
computation # spi_utils # show_value(receive = Receive, [3], R),
computation # spi_utils # show_value(endsend = EndSend, [3], ES),
computation # spi_utils # show_value(endreceive = EndReceive, [3], ER),
screen#display((C,S,R,ES,ER),length(0))
*/
.
bimolecular_send_blocked(Channel, Wakeup, Send, EndSend, Receive, EndReceive) :-
Send =\= EndSend |
do_bimolecular_send;
Send =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_RECEIVE) |
do_bimolecular_send;
Send =?= EndSend,
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Receive'),
Receive' =\= EndReceive,
arg(SPI_MS_TYPE, Receive', SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Receive', ReceiveLinks'),
read_vector(SPI_NEXT_MS, ReceiveLinks', Receive''),
Receive'' =\= EndReceive |
do_bimolecular_send;
otherwise :
Receive = _,
Send = _,
EndReceive = _,
EndSend = _,
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done.
do_homodimerized_transmit(Channel, Uniform1, Uniform2, Wakeup) :-
read_vector(SPI_DIMER_ANCHOR, Channel, DimerAnchor),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
bitwise_and(Type, SPI_RANDOM_FLAG, 0),
arg(SPI_MESSAGE_LINKS, DimerAnchor, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Receive),
arg(SPI_MESSAGE_LINKS, Receive, ReceiveLinks),
read_vector(SPI_NEXT_MS, ReceiveLinks, Dimer) :
Uniform1 = _,
Uniform2 = _ |
do_homodimerized_send(Channel, Wakeup, Receive, Dimer, Dimer);
read_vector(SPI_DIMER_ANCHOR, Channel, DimerAnchor),
read_vector(SPI_CHANNEL_TYPE, Channel, Type),
bitwise_and(Type, SPI_RANDOM_FLAG, SPI_RANDOM_FLAG),
read_vector(SPI_DIMER_WEIGHT, Channel, DimerWeight),
ReceiveSelect := Uniform1*DimerWeight,
DimerSelect := Uniform2*DimerWeight |
choose_random_start(DimerAnchor, ReceiveSelect, Receive),
choose_random_start(DimerAnchor, DimerSelect, StartD),
do_homodimerized_send(Channel, Wakeup, Receive, StartD, StartD).
do_homodimerized_send(Channel, Wakeup, Receive, Dimer, EndDimer) :-
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_MS_CID, Receive, ReceiveRCId),
arg(SPI_MS_CHANNEL, Receive, ReceiveChannel),
arg(SPI_RECEIVE_TAG, Receive, ReceiveTag),
arg(SPI_COMMON, Receive, ReceiveCommon),
arg(SPI_MS_CID, Dimer, DimerRCId),
arg(SPI_MS_CHANNEL, Dimer, DimerChannel),
arg(SPI_DIMER_TAG, Dimer, DimerTag),
arg(SPI_COMMON, Dimer, DimerCommon),
ReceiveCommon =?= {ReceivePId, ReceiveList, ReceiveValue, ReceiveChosen},
we(ReceiveChosen),
DimerCommon =?= {DimerPId, DimerList, DimerValue, DimerChosen},
we(DimerChosen),
arg(SPI_AMBIENT_CHANNEL, Receive, []) :
Channel = _,
EndDimer = _,
ReceiveChosen = ReceiveTag,
DimerChosen = DimerTag,
ReceiveValue = DimerValue?,
Wakeup = true(ReceivePId, ReceiveRCId, ReceiveChannel,
DimerPId, DimerRCId, DimerChannel) |
discount(ReceiveList),
discount(DimerList);
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_MS_CID, Receive, ReceiveRCId),
arg(SPI_MS_CHANNEL, Receive, ReceiveChannel),
arg(SPI_RECEIVE_TAG, Receive, ReceiveTag),
arg(SPI_COMMON, Receive, ReceiveCommon),
arg(SPI_MS_CID, Dimer, DimerRCId),
arg(SPI_MS_CHANNEL, Dimer, DimerChannel),
arg(SPI_DIMER_TAG, Dimer, DimerTag),
arg(SPI_COMMON, Dimer, DimerCommon),
ReceiveCommon =?= {ReceivePId, ReceiveList, ReceiveValue, ReceiveChosen},
we(ReceiveChosen),
DimerCommon =?= {DimerPId, DimerList, DimerValue, DimerChosen},
we(DimerChosen),
arg(SPI_AMBIENT_CHANNEL, Receive, ReceiveAmbient),
ReceiveAmbient =\= [],
arg(SPI_AMBIENT_CHANNEL, Dimer, DimerAmbient),
ReceiveAmbient =\= DimerAmbient :
Channel = _,
EndDimer = _,
ReceiveChosen = ReceiveTag,
DimerChosen = DimerTag,
ReceiveValue = DimerValue?,
Wakeup = true(ReceivePId, ReceiveRCId, ReceiveChannel,
DimerPId, DimerRCId, DimerChannel) |
discount(ReceiveList),
discount(DimerList);
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_AMBIENT_CHANNEL, Receive, ReceiveAmbient),
ReceiveAmbient =\= [],
arg(SPI_AMBIENT_CHANNEL, Dimer, DimerAmbient),
ReceiveAmbient =?= DimerAmbient,
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =\= EndDimer |
self;
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_AMBIENT_CHANNEL, Receive, ReceiveAmbient),
ReceiveAmbient =\= [],
arg(SPI_AMBIENT_CHANNEL, Dimer, DimerAmbient),
ReceiveAmbient =?= DimerAmbient,
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =?= EndDimer :
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done;
% Test Receive has the same Chosen as Dimer -
% communications which ARE homodimerized AND mixed.
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_COMMON, Receive, ReceiveCommon),
arg(SPI_COMMON, Dimer, DimerCommon),
ReceiveCommon =?= {_, _, _, Chosen},
DimerCommon =?= {_, _, _, Chosen},
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =\= EndDimer |
self;
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_DIMER),
arg(SPI_COMMON, Receive, ReceiveCommon),
arg(SPI_COMMON, Dimer, DimerCommon),
ReceiveCommon =?= {_, _, _, Chosen},
DimerCommon =?= {_, _, _, Chosen},
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =?= EndDimer :
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done;
% Skip the Anchor.
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =\= EndDimer |
self;
arg(SPI_MS_TYPE, Receive, SPI_DIMER),
arg(SPI_MS_TYPE, Dimer, SPI_MESSAGE_ANCHOR),
arg(SPI_MESSAGE_LINKS, Dimer, DimerLinks),
read_vector(SPI_NEXT_MS, DimerLinks, Dimer'),
Dimer' =?= EndDimer :
store_vector(SPI_BLOCKED, TRUE, Channel),
Wakeup = done
/*
;
otherwise |
computation # spi_utils # show_value(channel = Channel,[],C),
computation # spi_utils # show_value(receive = Receive, [3], R),
computation # spi_utils # show_value(dimer = Dimer, [3], D),
computation # spi_utils # show_value(enddimer = EndDimer, [3], ED),
screen#display((C,R,D,ED),length(0))
*/
.
/***************************** Utilities ************************************/
choose_random_start(Message, Select, Start) :-
arg(SPI_MESSAGE_LINKS, Message, Links),
read_vector(SPI_NEXT_MS, Links, Message'),
arg(SPI_MS_MULTIPLIER, Message', Multiplier),
Select -= Multiplier,
Select' > 0 |
self;
arg(SPI_MESSAGE_LINKS, Message, Links),
read_vector(SPI_NEXT_MS, Links, Message'),
arg(SPI_MS_MULTIPLIER, Message', Multiplier),
Select -= Multiplier,
Select' =< 0 :
Start = Message'.
discount(MsList) :-
MsList ? Message,
arg(SPI_MS_TYPE, Message, MessageType),
arg(SPI_MS_CHANNEL, Message, Channel),
arg(SPI_MS_MULTIPLIER, Message, Multiplier),
arg(SPI_MESSAGE_LINKS, Message, Links),
read_vector(SPI_NEXT_MS, Links, NextMessage),
arg(SPI_MESSAGE_LINKS, NextMessage, NextLinks),
read_vector(SPI_PREVIOUS_MS, Links, PreviousMessage),
arg(SPI_MESSAGE_LINKS, PreviousMessage, PreviousLinks),
MessageType = SPI_SEND,
read_vector(SPI_SEND_WEIGHT, Channel, Weight),
Weight -= Multiplier :
store_vector(SPI_SEND_WEIGHT, Weight', Channel),
store_vector(SPI_NEXT_MS, NextMessage, PreviousLinks),
store_vector(SPI_PREVIOUS_MS, PreviousMessage, NextLinks) |
self;
MsList ? Message,
arg(SPI_MS_TYPE, Message, MessageType),
arg(SPI_MS_CHANNEL, Message, Channel),
arg(SPI_MS_MULTIPLIER, Message, Multiplier),
arg(SPI_MESSAGE_LINKS, Message, Links),
read_vector(SPI_NEXT_MS, Links, NextMessage),
arg(SPI_MESSAGE_LINKS, NextMessage, NextLinks),
read_vector(SPI_PREVIOUS_MS, Links, PreviousMessage),
arg(SPI_MESSAGE_LINKS, PreviousMessage, PreviousLinks),
MessageType =?= SPI_RECEIVE,
read_vector(SPI_RECEIVE_WEIGHT, Channel, Weight),
Weight -= Multiplier :
store_vector(SPI_RECEIVE_WEIGHT, Weight', Channel),
store_vector(SPI_NEXT_MS, NextMessage, PreviousLinks),
store_vector(SPI_PREVIOUS_MS, PreviousMessage, NextLinks) |
self;
MsList ? Message,
arg(SPI_MS_TYPE, Message, MessageType),
arg(SPI_MS_CHANNEL, Message, Channel),
arg(SPI_MS_MULTIPLIER, Message, Multiplier),
arg(SPI_MESSAGE_LINKS, Message, Links),
read_vector(SPI_NEXT_MS, Links, NextMessage),
arg(SPI_MESSAGE_LINKS, NextMessage, NextLinks),
read_vector(SPI_PREVIOUS_MS, Links, PreviousMessage),
arg(SPI_MESSAGE_LINKS, PreviousMessage, PreviousLinks),
MessageType =?= SPI_DIMER,
read_vector(SPI_DIMER_WEIGHT, Channel, Weight),
Weight -= Multiplier :
store_vector(SPI_DIMER_WEIGHT, Weight', Channel),
store_vector(SPI_NEXT_MS, NextMessage, PreviousLinks),
store_vector(SPI_PREVIOUS_MS, PreviousMessage, NextLinks) |
self;
MsList ? Other,
otherwise |
show#stuff(item, Other),
show#stuff(end, MsList'),
arg(3, Other, Channel),
show#stuff(channel, Channel),
self;
MsList =?= [] |
true.
queue_message(MessageType, RCId, Channel, Multiplier, Tags, Ambient,
Common, Message) :-
MessageType =?= SPI_SEND,
read_vector(SPI_SEND_WEIGHT, Channel, Weight),
Weight += Multiplier,
read_vector(SPI_SEND_ANCHOR, Channel, Anchor) :
store_vector(SPI_SEND_WEIGHT, Weight', Channel),
Message = {MessageType, RCId, Channel, Multiplier,
Tags, 0, Common, Links?, Ambient} |
queue_to_anchor;
MessageType =?= SPI_RECEIVE,
read_vector(SPI_RECEIVE_WEIGHT, Channel, Weight),
Weight += Multiplier,
read_vector(SPI_RECEIVE_ANCHOR, Channel, Anchor) :
store_vector(SPI_RECEIVE_WEIGHT, Weight', Channel),
Message = {MessageType, RCId, Channel, Multiplier,
0, Tags, Common, Links?, Ambient} |
queue_to_anchor;
MessageType =?= SPI_DIMER,
read_vector(SPI_DIMER_WEIGHT, Channel, Weight),
Weight += Multiplier,
read_vector(SPI_DIMER_ANCHOR, Channel, Anchor),
Tags = {SendTag, ReceiveTag} :
store_vector(SPI_DIMER_WEIGHT, Weight', Channel),
Message = {MessageType, RCId, Channel, Multiplier,
SendTag, ReceiveTag, Common, Links?, Ambient} |
queue_to_anchor.
queue_to_anchor(Message, Anchor, Channel, Links) :-
arg(SPI_MESSAGE_LINKS, Anchor, AnchorLinks),
read_vector(SPI_PREVIOUS_MS, AnchorLinks, PreviousMessage),
arg(SPI_MESSAGE_LINKS, PreviousMessage, PreviousLinks) :
store_vector(SPI_BLOCKED, FALSE, Channel),
make_vector(2, Links, _),
store_vector(SPI_PREVIOUS_MS, PreviousMessage, Links),
store_vector(SPI_NEXT_MS, Anchor, Links),
store_vector(SPI_NEXT_MS, Message, PreviousLinks),
store_vector(SPI_PREVIOUS_MS, Message, AnchorLinks).
/*
do_execute(Id, Offset, Command) :-
true : execute(Offset, Command) |
computation # spi_utils #
show_value(do_execute(Id, Offset, Command),[5],O),
screen#display(ok(O),wait(O));
otherwise |
computation # spi_utils #
show_value(do_execute(Id, Offset, Command),[5],O),
screen#display(failed(O),wait(O)).
*/
| [
"bill"
] | bill |
86553a230f372d90ccd00722cb96cabcf82a1a83 | 0841c948188711d194835bb19cf0b4dae04a5695 | /mds/sources/center/src/centermdsmanager.cpp | 66afa956be9567134a17f36c1ffe528ac247847b | [] | no_license | gjhbus/sh_project | 0cfd311b7c0e167e098bc4ec010822f1af2d0289 | 1d4d7df4e92cff93aba9d28226d3dbce71639ed6 | refs/heads/master | 2020-06-15T16:11:33.335499 | 2016-06-15T03:41:22 | 2016-06-15T03:41:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,727 | cpp | #include "centermdsmanager.h"
CenterMdsManager::CenterMdsManager() {
buffer_ = new uint8_t[0x10000];
buffer_len_ = 0x10000;
db_backup_count_ = DEFAULT_BACKUP_COUNT; // mds backup count, include itself
}
CenterMdsManager::~CenterMdsManager() {
Clear();
if ( buffer_ ) {
delete [] buffer_;
buffer_ = NULL;
}
}
CenterMdsManager& CenterMdsManager::operator=(const CenterMdsManager &manager) {
if ( this != &manager ) {
Clear();
db_backup_count_ = manager.db_backup_count_;
MdsList t = manager.mds_list_;
for (MdsList::iterator i = t.begin(); i != t.end(); ++i) {
Mds *tmp_mds = new Mds();
tmp_mds->key = (*i)->key;
tmp_mds->bucket_bs = (*i)->bucket_bs;
mds_list_.push_back(tmp_mds);
mds_set_.insert((*i)->key);
}
}
return *this;
}
bool CenterMdsManager::Add(const std::string &key) {
FATAL("Conshash add mds(%s)", STR(key));
MdsSet::iterator it = mds_set_.find(key);
if ( mds_set_.end() != it ) {
WARN("Mds %s has inserted to manager", STR(key));
return false;
}
uint32_t mds_count = mds_list_.size() + 1;
Mds *tmp_mds = new Mds();
tmp_mds->key = key;
tmp_mds->bucket_bs.reset();
if ( 1 == mds_count ) {
tmp_mds->bucket_bs.set();
mds_list_.push_back(tmp_mds);
mds_set_.insert(key);
return true;
}
for ( MdsList::iterator i = mds_list_.begin(); mds_list_.end() != i; ++i ) {
uint32_t bucket_count = (*i)->bucket_bs.count();
uint32_t divisor = bucket_count / mds_count;
uint32_t tmp_bucket_count = 0;
for ( uint32_t j = 0; j < (*i)->bucket_bs.size() && tmp_bucket_count < divisor; ++j ) {
if ( (*i)->bucket_bs.test(j) ) {
(*i)->bucket_bs.reset(j);
tmp_mds->bucket_bs.set(j);
++tmp_bucket_count;
}
}
}
mds_list_.push_back(tmp_mds);
mds_set_.insert(key);
return true;
}
bool CenterMdsManager::Remove(const std::string &key) {
FATAL("Conshash remove mds(%s)", STR(key));
MdsSet::iterator it = mds_set_.find(key);
if ( mds_set_.end() == it ) {
WARN("Mds %s has removed from manager", STR(key));
return false;
}
MdsList::iterator i;
for (i = mds_list_.begin(); mds_list_.end() != i; ++i) {
if ( key == (*i)->key ) {
break;
}
}
if ( i == mds_list_.end() ) {
return false;
}
if ( 1 == mds_list_.size() ) {
delete *i;
mds_list_.clear();
mds_set_.clear();
return true;
}
Mds *mds = (*i);
mds_list_.erase(i);
mds_set_.erase(key);
uint32_t mds_count = mds_list_.size();
uint32_t bucket_count = mds->bucket_bs.count();
uint32_t divisor = bucket_count / mds_count;
uint32_t j = 0;
for ( i = mds_list_.begin(); mds_list_.end() != i; ++i ) {
uint32_t tmp_bucket_count = 0;
while ( j < mds->bucket_bs.size() && tmp_bucket_count < divisor ) {
if ( mds->bucket_bs.test(j) ) {
mds->bucket_bs.reset(j);
(*i)->bucket_bs.set(j);
++tmp_bucket_count;
}
++j;
}
}
// distribute remain mds bucket to previous mdses in mds_list_
i = mds_list_.begin();
while ( j < mds->bucket_bs.size() ) {
if ( mds->bucket_bs.test(j) ) {
mds->bucket_bs.reset(j);
(*i)->bucket_bs.set(j);
++i;
if ( mds_list_.end() == i )
i = mds_list_.begin();
}
++j;
}
delete mds;
return true;
}
BinaryParser::BigAVal *CenterMdsManager::Serialize() {
uint8_t *output = buffer_;
uint8_t *outend = output + buffer_len_;
uint8_t *tmp_output;
BinaryParser::AVal bv;
BinaryParser::BigAVal pbv;
uint32_t buf_len = BUCKET_COUNT / 8;
if ( 0 != BUCKET_COUNT % 8 )
++buf_len;
char *buf = new char[buf_len];
// backup count
output = BinaryParser::EncodeInt32(output, outend, db_backup_count_);
// count of mds
output = BinaryParser::EncodeInt32(output, outend, mds_list_.size());
for (MdsList::iterator i = mds_list_.begin(); i != mds_list_.end(); ++i) {
// key of mds
bv.val = (uint8_t*)STR((*i)->key);
bv.len = (*i)->key.length();
tmp_output = BinaryParser::EncodeBuffer(output, outend, &bv);
if ( !tmp_output ) {
UpdateOutput(&output, &outend);
output = BinaryParser::EncodeBuffer(output, outend, &bv);
} else {
output = tmp_output;
}
// bucket bitmap of mds
memset(buf, 0, buf_len);
uint32_t len = bitsToBuffer((*i)->bucket_bs, buf, buf_len);
pbv.val = (uint8_t*)buf;
pbv.len = len;
tmp_output = BinaryParser::EncodeBigBuffer(output, outend, &pbv);
if ( !tmp_output ) {
UpdateOutput(&output, &outend);
output = BinaryParser::EncodeBigBuffer(output, outend, &pbv);
} else {
output = tmp_output;
}
}
delete []buf;
bv_.val = buffer_;
bv_.len = output - buffer_;
return &bv_;
}
bool CenterMdsManager::Deserialize(const std::string &val) {
Clear();
BinaryParser parser;
parser.SetDecode((uint8_t *)STR(val));
std::string bits;
db_backup_count_ = parser.DecodeInt32();
uint32_t mds_count = parser.DecodeInt32();
for (uint32_t i = 0; i < mds_count; i++) {
Mds *mds = new Mds();
mds->key = parser.DecodeString();
bits = parser.DecodeBigString();
bufferToBits(STR(bits), bits.length(), mds->bucket_bs);
mds_list_.push_back(mds);
mds_set_.insert(mds->key);
}
FATAL("Deserialize conshash, mds list size(%u)", mds_list_.size());
return true;
}
void CenterMdsManager::Clear() {
db_backup_count_ = DEFAULT_BACKUP_COUNT;
for (MdsList::iterator i = mds_list_.begin(); i != mds_list_.end(); ++i)
delete *i;
mds_list_.clear();
mds_set_.clear();
}
void CenterMdsManager::GetMdsChange(const std::tr1::unordered_map<std::string, ProcessCenter*> &config,
std::vector<std::string> &add_list, std::vector<std::string> &remove_list) {
add_list.clear();
remove_list.clear();
std::tr1::unordered_map<std::string, ProcessCenter*> del_mds = config;
std::tr1::unordered_map<std::string, ProcessCenter*>::iterator it;
for (MdsList::iterator i = mds_list_.begin(); i != mds_list_.end(); ++i) {
it = del_mds.find((*i)->key);
if ( del_mds.end() == it )
remove_list.push_back((*i)->key);
else
del_mds.erase(it);
}
FOR_UNORDERED_MAP(del_mds, std::string, ProcessCenter*, i) {
add_list.push_back(MAP_KEY(i));
}
}
bool CenterMdsManager::Empty() {
return mds_list_.empty();
}
bool CenterMdsManager::Check() {
std::bitset<BUCKET_COUNT> bucket_bs;
bucket_bs.reset();
for ( MdsList::iterator i = mds_list_.begin(); mds_list_.end() != i; ++i ) {
for ( uint32_t j = 0; j < (*i)->bucket_bs.size(); ++j ) {
if ( (*i)->bucket_bs.test(j) ) {
if ( bucket_bs.test(j) ) {
WARN("Consthash error: bucket[%d] has been distributed, distribute to"\
" %s failed", j, STR((*i)->key));
return false;
}
bucket_bs.set(j);
}
}
}
if ( bucket_bs.count() != bucket_bs.size() ) {
WARN("Consthash error: there exist buckets have not been distributed");
return false;
}
for ( MdsList::iterator i = mds_list_.begin(); mds_list_.end() != i; ++i ) {
INFO("Mds(%s) bucket count(%d)", STR((*i)->key), (*i)->bucket_bs.count());
}
return true;
}
void CenterMdsManager::UpdateOutput(uint8_t **output, uint8_t **outend) {
buffer_len_ *= 2;
uint8_t *tmp = new uint8_t[buffer_len_];
uint32_t pos = (*output)-buffer_;
memcpy(tmp, buffer_, pos);
delete[] buffer_;
buffer_ = tmp;
*output = buffer_ + pos;
*outend = buffer_ + buffer_len_;
}
| [
"greatmiffa@gmail.com"
] | greatmiffa@gmail.com |
b59330533c58091e1006616b872064f3c3bc362b | 6b2a8dd202fdce77c971c412717e305e1caaac51 | /solutions_5688567749672960_0/C++/gawarkiewicz/solution.cpp | 3adb842b91c4ff15a5fbcb1a51bca1492ec315ba | [] | no_license | alexandraback/datacollection | 0bc67a9ace00abbc843f4912562f3a064992e0e9 | 076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf | refs/heads/master | 2021-01-24T18:27:24.417992 | 2017-05-23T09:23:38 | 2017-05-23T09:23:38 | 84,313,442 | 2 | 4 | null | null | null | null | UTF-8 | C++ | false | false | 1,401 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <queue>
#include <tuple>
using namespace std;
long long rev(long long num)
{
long long ret = 0;
while (num)
{
ret = ret * 10 + (num % 10);
num /= 10;
}
return ret;
}
map<long long, int> brute()
{
map<long long, int> m;
queue<tuple<long long, int>> q;
q.push(make_tuple(1, 1));
m[1] = 1;
while (!q.empty())
{
auto p = q.front();
q.pop();
if (get<1>(p) > 10000)
continue;
auto n = get<0>(p);
auto c = get<1>(p);
auto n1 = n + 1;
auto n2 = rev(n);
if (m[n1] == 0)
{
m[n1] = c + 1;
q.push(make_tuple(n1, c + 1));
}
if (m[n2] == 0)
{
m[n2] = c + 1;
q.push(make_tuple(n2, c + 1));
}
}
return m;
}
void learn()
{
auto m = brute();
cout << m.rbegin()->first << endl; // max
long long allTo = 0;
for (auto& p : m)
{
if (p.first != allTo + 1) break;
allTo++;
}
cout << allTo << endl;
/*
vector<pair<int, long long>> m2;
for (auto& p : m)
{
m2.push_back(make_pair(p.second, p.first));
}
sort(m2.begin(), m2.end());
for (auto& p : m2)
{
cout << p.first << " " << p.second << endl;
}*/
}
int main()
{
//learn();
auto m = brute();
int N;
cin >> N;
for (int q = 1; q <= N; ++q)
{
long long T;
cin >> T;
cout << "Case #" << q << ": " << m[T] << endl;
}
return 0;
} | [
"root@debian"
] | root@debian |
9ed4f8cc291b3331538f97e7aa3b22215a021e95 | dfd13ecff989c05937dc875fd910c3d1ba33ced8 | /include/wx/dlimpexp.h | b745fe6fe70c2569d24ef03c210c176dc3ee329c | [] | no_license | thevisad/deps-wxWidgets | b306f3a0abce654ded29594014e1dc13e5f57823 | 56c92c2e17c7f361748bf1f52519b132e2cac33e | refs/heads/master | 2021-01-16T20:47:07.548645 | 2013-10-23T17:41:15 | 2013-10-23T17:41:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,090 | h | /*
* Name: wx/dlimpexp.h
* Purpose: Macros for declaring DLL-imported/exported functions
* Author: Vadim Zeitlin
* Modified by:
* Created: 16.10.2003 (extracted from wx/defs.h)
* Copyright: (c) 2003 Vadim Zeitlin <vadim@wxwidgets.org>
* Licence: wxWindows licence
*/
/*
This is a C file, not C++ one, do not use C++ comments here!
*/
#ifndef _WX_DLIMPEXP_H_
#define _WX_DLIMPEXP_H_
#if defined(HAVE_VISIBILITY)
# define WXEXPORT __attribute__ ((visibility("default")))
# define WXIMPORT __attribute__ ((visibility("default")))
#elif defined(__WINDOWS__)
/*
__declspec works in BC++ 5 and later, Watcom C++ 11.0 and later as well
as VC++.
*/
# if defined(__VISUALC__) || defined(__BORLANDC__) || defined(__WATCOMC__) || (defined(__WINDOWS__) && defined(__INTELC__))
# define WXEXPORT __declspec(dllexport)
# define WXIMPORT __declspec(dllimport)
/*
While gcc also supports __declspec(dllexport), it creates unusably huge
DLL files since gcc 4.5 (while taking horribly long amounts of time),
see http://gcc.gnu.org/bugzilla/show_bug.cgi?id=43601. Because of this
we rely on binutils auto export/import support which seems to work
quite well for 4.5+.
*/
# elif defined(__GNUC__) && !wxCHECK_GCC_VERSION(4, 5)
/*
__declspec could be used here too but let's use the native
__attribute__ instead for clarity.
*/
# define WXEXPORT __attribute__((dllexport))
# define WXIMPORT __attribute__((dllimport))
# endif
#elif defined(__WXPM__)
# if defined (__WATCOMC__)
# define WXEXPORT __declspec(dllexport)
/*
__declspec(dllimport) prepends __imp to imported symbols. We do NOT
want that!
*/
# define WXIMPORT
# elif defined(__EMX__)
# define WXEXPORT
# define WXIMPORT
# elif (!(defined(__VISAGECPP__) && (__IBMCPP__ < 400 || __IBMC__ < 400 )))
# define WXEXPORT _Export
# define WXIMPORT _Export
# endif
#elif defined(__CYGWIN__)
# define WXEXPORT __declspec(dllexport)
# define WXIMPORT __declspec(dllimport)
#endif
/* for other platforms/compilers we don't anything */
#ifndef WXEXPORT
# define WXEXPORT
# define WXIMPORT
#endif
/*
We support building wxWidgets as a set of several libraries but we don't
support arbitrary combinations of libs/DLLs: either we build all of them as
DLLs (in which case WXMAKINGDLL is defined) or none (it isn't).
However we have a problem because we need separate WXDLLIMPEXP versions for
different libraries as, for example, wxString class should be dllexported
when compiled in wxBase and dllimported otherwise, so we do define separate
WXMAKING/USINGDLL_XYZ constants for each component XYZ.
*/
#ifdef WXMAKINGDLL
# if wxUSE_BASE
# define WXMAKINGDLL_BASE
# endif
# define WXMAKINGDLL_NET
# define WXMAKINGDLL_CORE
# define WXMAKINGDLL_ADV
# define WXMAKINGDLL_QA
# define WXMAKINGDLL_HTML
# define WXMAKINGDLL_GL
# define WXMAKINGDLL_XML
# define WXMAKINGDLL_XRC
# define WXMAKINGDLL_AUI
# define WXMAKINGDLL_PROPGRID
# define WXMAKINGDLL_RIBBON
# define WXMAKINGDLL_RICHTEXT
# define WXMAKINGDLL_MEDIA
# define WXMAKINGDLL_STC
# define WXMAKINGDLL_WEBVIEW
#endif /* WXMAKINGDLL */
/*
WXDLLIMPEXP_CORE maps to export declaration when building the DLL, to import
declaration if using it or to nothing at all if we don't use wxWin as DLL
*/
#ifdef WXMAKINGDLL_BASE
# define WXDLLIMPEXP_BASE WXEXPORT
# define WXDLLIMPEXP_DATA_BASE(type) WXEXPORT type
# if defined(HAVE_VISIBILITY)
# define WXDLLIMPEXP_INLINE_BASE WXEXPORT
# else
# define WXDLLIMPEXP_INLINE_BASE
# endif
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_BASE WXIMPORT
# define WXDLLIMPEXP_DATA_BASE(type) WXIMPORT type
# if defined(HAVE_VISIBILITY)
# define WXDLLIMPEXP_INLINE_BASE WXIMPORT
# else
# define WXDLLIMPEXP_INLINE_BASE
# endif
#else /* not making nor using DLL */
# define WXDLLIMPEXP_BASE
# define WXDLLIMPEXP_DATA_BASE(type) type
# define WXDLLIMPEXP_INLINE_BASE
#endif
#ifdef WXMAKINGDLL_NET
# define WXDLLIMPEXP_NET WXEXPORT
# define WXDLLIMPEXP_DATA_NET(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_NET WXIMPORT
# define WXDLLIMPEXP_DATA_NET(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_NET
# define WXDLLIMPEXP_DATA_NET(type) type
#endif
#ifdef WXMAKINGDLL_CORE
# define WXDLLIMPEXP_CORE WXEXPORT
# define WXDLLIMPEXP_DATA_CORE(type) WXEXPORT type
# if defined(HAVE_VISIBILITY)
# define WXDLLIMPEXP_INLINE_CORE WXEXPORT
# else
# define WXDLLIMPEXP_INLINE_CORE
# endif
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_CORE WXIMPORT
# define WXDLLIMPEXP_DATA_CORE(type) WXIMPORT type
# if defined(HAVE_VISIBILITY)
# define WXDLLIMPEXP_INLINE_CORE WXIMPORT
# else
# define WXDLLIMPEXP_INLINE_CORE
# endif
#else /* not making nor using DLL */
# define WXDLLIMPEXP_CORE
# define WXDLLIMPEXP_DATA_CORE(type) type
# define WXDLLIMPEXP_INLINE_CORE
#endif
#ifdef WXMAKINGDLL_ADV
# define WXDLLIMPEXP_ADV WXEXPORT
# define WXDLLIMPEXP_DATA_ADV(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_ADV WXIMPORT
# define WXDLLIMPEXP_DATA_ADV(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_ADV
# define WXDLLIMPEXP_DATA_ADV(type) type
#endif
#ifdef WXMAKINGDLL_QA
# define WXDLLIMPEXP_QA WXEXPORT
# define WXDLLIMPEXP_DATA_QA(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_QA WXIMPORT
# define WXDLLIMPEXP_DATA_QA(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_QA
# define WXDLLIMPEXP_DATA_QA(type) type
#endif
#ifdef WXMAKINGDLL_HTML
# define WXDLLIMPEXP_HTML WXEXPORT
# define WXDLLIMPEXP_DATA_HTML(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_HTML WXIMPORT
# define WXDLLIMPEXP_DATA_HTML(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_HTML
# define WXDLLIMPEXP_DATA_HTML(type) type
#endif
#ifdef WXMAKINGDLL_GL
# define WXDLLIMPEXP_GL WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_GL WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_GL
#endif
#ifdef WXMAKINGDLL_XML
# define WXDLLIMPEXP_XML WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_XML WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_XML
#endif
#ifdef WXMAKINGDLL_XRC
# define WXDLLIMPEXP_XRC WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_XRC WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_XRC
#endif
#ifdef WXMAKINGDLL_AUI
# define WXDLLIMPEXP_AUI WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_AUI WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_AUI
#endif
#ifdef WXMAKINGDLL_PROPGRID
# define WXDLLIMPEXP_PROPGRID WXEXPORT
# define WXDLLIMPEXP_DATA_PROPGRID(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_PROPGRID WXIMPORT
# define WXDLLIMPEXP_DATA_PROPGRID(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_PROPGRID
# define WXDLLIMPEXP_DATA_PROPGRID(type) type
#endif
#ifdef WXMAKINGDLL_RIBBON
# define WXDLLIMPEXP_RIBBON WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_RIBBON WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_RIBBON
#endif
#ifdef WXMAKINGDLL_RICHTEXT
# define WXDLLIMPEXP_RICHTEXT WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_RICHTEXT WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_RICHTEXT
#endif
#ifdef WXMAKINGDLL_MEDIA
# define WXDLLIMPEXP_MEDIA WXEXPORT
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_MEDIA WXIMPORT
#else /* not making nor using DLL */
# define WXDLLIMPEXP_MEDIA
#endif
#ifdef WXMAKINGDLL_STC
# define WXDLLIMPEXP_STC WXEXPORT
# define WXDLLIMPEXP_DATA_STC(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_STC WXIMPORT
# define WXDLLIMPEXP_DATA_STC(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_STC
# define WXDLLIMPEXP_DATA_STC(type) type
#endif
#ifdef WXMAKINGDLL_WEBVIEW
# define WXDLLIMPEXP_WEBVIEW WXEXPORT
# define WXDLLIMPEXP_DATA_WEBVIEW(type) WXEXPORT type
#elif defined(WXUSINGDLL)
# define WXDLLIMPEXP_WEBVIEW WXIMPORT
# define WXDLLIMPEXP_DATA_WEBVIEW(type) WXIMPORT type
#else /* not making nor using DLL */
# define WXDLLIMPEXP_WEBVIEW
# define WXDLLIMPEXP_DATA_WEBVIEW(type) type
#endif
/*
GCC warns about using __attribute__ (and also __declspec in mingw32 case) on
forward declarations while MSVC complains about forward declarations without
__declspec for the classes later declared with it, so we need a separate set
of macros for forward declarations to hide this difference:
*/
#if defined(HAVE_VISIBILITY) || (defined(__WINDOWS__) && defined(__GNUC__))
#define WXDLLIMPEXP_FWD_BASE
#define WXDLLIMPEXP_FWD_NET
#define WXDLLIMPEXP_FWD_CORE
#define WXDLLIMPEXP_FWD_ADV
#define WXDLLIMPEXP_FWD_QA
#define WXDLLIMPEXP_FWD_HTML
#define WXDLLIMPEXP_FWD_GL
#define WXDLLIMPEXP_FWD_XML
#define WXDLLIMPEXP_FWD_XRC
#define WXDLLIMPEXP_FWD_AUI
#define WXDLLIMPEXP_FWD_PROPGRID
#define WXDLLIMPEXP_FWD_RIBBON
#define WXDLLIMPEXP_FWD_RICHTEXT
#define WXDLLIMPEXP_FWD_MEDIA
#define WXDLLIMPEXP_FWD_STC
#define WXDLLIMPEXP_FWD_WEBVIEW
#else
#define WXDLLIMPEXP_FWD_BASE WXDLLIMPEXP_BASE
#define WXDLLIMPEXP_FWD_NET WXDLLIMPEXP_NET
#define WXDLLIMPEXP_FWD_CORE WXDLLIMPEXP_CORE
#define WXDLLIMPEXP_FWD_ADV WXDLLIMPEXP_ADV
#define WXDLLIMPEXP_FWD_QA WXDLLIMPEXP_QA
#define WXDLLIMPEXP_FWD_HTML WXDLLIMPEXP_HTML
#define WXDLLIMPEXP_FWD_GL WXDLLIMPEXP_GL
#define WXDLLIMPEXP_FWD_XML WXDLLIMPEXP_XML
#define WXDLLIMPEXP_FWD_XRC WXDLLIMPEXP_XRC
#define WXDLLIMPEXP_FWD_AUI WXDLLIMPEXP_AUI
#define WXDLLIMPEXP_FWD_PROPGRID WXDLLIMPEXP_PROPGRID
#define WXDLLIMPEXP_FWD_RIBBON WXDLLIMPEXP_RIBBON
#define WXDLLIMPEXP_FWD_RICHTEXT WXDLLIMPEXP_RICHTEXT
#define WXDLLIMPEXP_FWD_MEDIA WXDLLIMPEXP_MEDIA
#define WXDLLIMPEXP_FWD_STC WXDLLIMPEXP_STC
#define WXDLLIMPEXP_FWD_WEBVIEW WXDLLIMPEXP_WEBVIEW
#endif
/* for backwards compatibility, define suffix-less versions too */
#define WXDLLEXPORT WXDLLIMPEXP_CORE
#define WXDLLEXPORT_DATA WXDLLIMPEXP_DATA_CORE
/*
MSVC up to 6.0 needs to be explicitly told to export template instantiations
used by the DLL clients, use this macro to do it like this:
template <typename T> class Foo { ... };
WXDLLIMPEXP_TEMPLATE_INSTANCE_BASE( Foo<int> )
(notice that currently we only need this for wxBase and wxCore libraries)
*/
#if defined(__VISUALC__) && (__VISUALC__ <= 1200)
#ifdef WXMAKINGDLL_BASE
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_BASE(decl) \
template class WXDLLIMPEXP_BASE decl;
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_CORE(decl) \
template class WXDLLIMPEXP_CORE decl;
#else
/*
We need to disable this warning when using this macro, as
recommended by Microsoft itself:
http://support.microsoft.com/default.aspx?scid=kb%3ben-us%3b168958
*/
#pragma warning(disable:4231)
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_BASE(decl) \
extern template class WXDLLIMPEXP_BASE decl;
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_CORE(decl) \
extern template class WXDLLIMPEXP_CORE decl;
#endif
#else /* not VC <= 6 */
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_BASE(decl)
#define WXDLLIMPEXP_TEMPLATE_INSTANCE_CORE(decl)
#endif /* VC6/others */
#endif /* _WX_DLIMPEXP_H_ */
| [
"admin@rajko.info"
] | admin@rajko.info |
99e87a1cd607da1f7ca52899b0bb70d711a71cc9 | 8a1a2fdd8fe6a1e6625d4fa4d28013be829856a2 | /hw5/main_window.cpp | 9e2467a188ff2f7559130b7b6b25eb5b53ec21dd | [] | no_license | bkwsuper24/Brian_Wang_Projects | dd3b11d6ce84fff85a693ec89171c399fd185196 | 19e1e20f34b8954b2ff6b677c2b53082b9b507b2 | refs/heads/master | 2021-01-10T14:18:50.476023 | 2015-10-26T10:03:42 | 2015-10-26T10:03:42 | 44,517,145 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 13,596 | cpp | #include "main_window.h"
#include "datastore.h"
#include "db_parser.h"
#include "product_parser.h"
#include "util.h"
#include <sstream>
#include <iostream>
#include "msort.h"
#include <fstream>
Main_Window::Main_Window(std::string ifile)
{
parser.addProductParser(new ProductBookParser);
parser.addProductParser(new ProductClothingParser);
parser.addProductParser(new ProductMovieParser);
if(parser.parse(ifile, ds))
{
return;
}
currentuser = ds.UserVector[0]->getName();
//Title
setWindowTitle("Amazon Shop");
// Overall layout
OverallLayout = new QHBoxLayout();
//this is smaller layout within overall layout
SearchOptionLayout = new QVBoxLayout();
OverallLayout->addLayout(SearchOptionLayout);
//Terms text
SearchTermsLabel = new QLabel("Search Terms");
SearchOptionLayout->addWidget(SearchTermsLabel);
//Creating line edit to enter terms to search
SearchTermsInput = new QLineEdit();
SearchOptionLayout->addWidget(SearchTermsInput);
//Creating exclusive group check-box
CheckboxLayout = new QHBoxLayout();
SearchOptionLayout->addLayout(CheckboxLayout);
AND = new QRadioButton(tr("AND"));
CheckboxLayout->addWidget(AND);
OR = new QRadioButton(tr("OR"));
CheckboxLayout->addWidget(OR);
AND->setAutoExclusive(true);
AND->setChecked(true);
//Add the search button
SearchButton = new QPushButton("SEARCH");
connect(SearchButton, SIGNAL(clicked()), this, SLOT(SEARCH()));
SearchOptionLayout->addWidget(SearchButton);
//Add the alphabetical merge-sort button
SortOptionLayout = new QHBoxLayout();
SearchOptionLayout->addLayout(SortOptionLayout);
AlphaSortButton = new QPushButton("Sort Search Alphabetically");
connect(AlphaSortButton, SIGNAL(clicked()), this, SLOT(AlphaSort()));
SortOptionLayout->addWidget(AlphaSortButton);
//Add the review merge-sort button
ReviewSortButton = new QPushButton("Sort Search by Average Rating");
connect(ReviewSortButton, SIGNAL(clicked()), this, SLOT(RSort()));
SortOptionLayout->addWidget(ReviewSortButton);
//Create dropdown menu to select user
UserDropdown = new QComboBox();
//iterating through user vector to print into menu
for(unsigned int i=0; i<ds.getUserVector().size(); i++)
{
std::vector<User*> myVector= ds.getUserVector();
User* user= myVector[i];
QString qstr= QString::fromStdString(user->getName());
UserDropdown->addItem(qstr);
}
SearchOptionLayout->addWidget(UserDropdown);
connect(UserDropdown, SIGNAL(currentIndexChanged(int)), this, SLOT(filler(int)));
//Horizontal layout for add and view cart buttons
CartOptionLayout = new QHBoxLayout();
SearchOptionLayout->addLayout(CartOptionLayout);
//Create add cart button
AddCartButton = new QPushButton("Add-to-Cart");
connect(AddCartButton, SIGNAL(clicked()), this, SLOT(ADDCART()));
CartOptionLayout->addWidget(AddCartButton);
//Create view cart button
ViewCartButton = new QPushButton("View-Cart");
connect(ViewCartButton, SIGNAL(clicked()), this, SLOT(VIEWCART()));
CartOptionLayout->addWidget(ViewCartButton);
//Enter valid file to save to text
SaveLabel = new QLabel("Type valid file to save to");
SearchOptionLayout->addWidget(SaveLabel);
//Creating line edit to enter terms to search
SaveInput = new QLineEdit();
SearchOptionLayout->addWidget(SaveInput);
//Save database to a file button
SaveButton = new QPushButton("Save Text File");
connect(SaveButton, SIGNAL(clicked()), this, SLOT(SAVE()));
SearchOptionLayout->addWidget(SaveButton);
//Quit program button
QuitButton = new QPushButton("QUIT");
connect(QuitButton, SIGNAL(clicked()), this, SLOT(QUIT()));
SearchOptionLayout->addWidget(QuitButton);
//Create product list and layout
ProductLayout = new QVBoxLayout();
OverallLayout->addLayout(ProductLayout);
//Create text for Products
ProductsLabel = new QLabel("Products That Match Search");
ProductLayout->addWidget(ProductsLabel);
//Create empty list that will have products from search
ProductList = new QListWidget();
prodref = ProductList;
connect(ProductList, SIGNAL(currentRowChanged(int)), this, SLOT(ProductChange(int)));
ProductLayout->addWidget(ProductList);
//Create review list and layout
ReviewLayout = new QVBoxLayout();
OverallLayout->addLayout(ReviewLayout);
//Create text for Reviews
ReviewsLabel = new QLabel("Reviews of Product");
ReviewLayout->addWidget(ReviewsLabel);
//Create empty list that will have reviews of products from search
ReviewList = new QListWidget();
ReviewLayout->addWidget(ReviewList);
//Create add reviews layout
AddReviewLayout = new QVBoxLayout();
OverallLayout->addLayout(AddReviewLayout);
//Create text for adding reviews
AddReviewsLabel = new QLabel("Add a Review Section");
AddReviewLayout->addWidget(AddReviewsLabel);
//Creating text for adding rating
AddReviewsRating = new QLabel("Enter an integer between 1-5");
AddReviewLayout->addWidget(AddReviewsRating);
//Creating line edit to enter rating of product
RatingLine = new QLineEdit();
AddReviewLayout->addWidget(RatingLine);
//Creating text for adding date
AddReviewsDate = new QLabel("Enter a date: YYYY-MM-DD");
AddReviewLayout->addWidget(AddReviewsDate);
//Creating line edit to enter date of product
DateLine = new QLineEdit();
AddReviewLayout->addWidget(DateLine);
//Creating text for string of text
AddReviewsText = new QLabel("Type in review text");
AddReviewLayout->addWidget(AddReviewsText);
//Creating line edit to enter string of text of product
TextLine = new QLineEdit();
AddReviewLayout->addWidget(TextLine);
AddReviewButton = new QPushButton("ADD REVIEW");
connect(AddReviewButton, SIGNAL(clicked()), this, SLOT(ADDREVIEW()));
AddReviewLayout->addWidget(AddReviewButton);
setLayout(OverallLayout);
}
Main_Window::~Main_Window()
{
}
void Main_Window::SEARCH()
{
ProductList->clear();
ReviewList->clear();
if(SearchTermsInput->text().isEmpty() == true)
{
return;
}
std::stringstream ss((SearchTermsInput->text().toStdString()));
std::string term;
std::vector<std::string> terms;
while(ss >> term)
{
term = convToLower(term);
terms.push_back(term);
}
if(AND->isChecked())
{
hits = ds.search(terms, 0);
}
else
{
hits = ds.search(terms, 1);
}
//int resultNo = 1;
std::string temp;
for(std::vector<Product*>::iterator it = hits.begin(); it != hits.end(); ++it)
{
temp = (*it)->displayString();
QString qs = QString::fromStdString(temp);
ProductList->addItem(qs);
}
SearchTermsInput->setText("");
}
//Comparator for sorting alphabetically
struct AlphaProdSort
{
bool operator()(Product* a, Product* b)
{
return(a->getName() < b->getName());
}
};
void Main_Window::AlphaSort()
{
ProductList->clear();
AlphaProdSort aps;
if(hits.size()==0)
{
return;
}
else
{
mergeSort(hits, aps);
std::string temp;
for(std::vector<Product*>::iterator it = hits.begin(); it != hits.end(); ++it)
{
temp = (*it)->displayString();
QString qs = QString::fromStdString(temp);
ProductList->addItem(qs);
}
}
}
//Comparator for sorting by average rating
struct RatingProdSort
{
DStore ds;
bool operator()(Product* a, Product* b)
{
std::vector<Review*> r1;
std::vector<Review*> r2;
double a1=0;
double b1=0;
double a1avg=0.0;
double b1avg=0.0;
std::map<std::string, std::vector<Review*> > temp;
temp = ds.getReviewMap();
std::map<std::string, std::vector<Review*> >::iterator it = temp.find(a->getName());
if(it != temp.end())
{
r1= it->second;
}
std::map<std::string, std::vector<Review*> >::iterator iter = temp.find(b->getName());
if(iter != temp.end())
{
r2= iter->second;
}
if(r1.size()==0)
{
a1avg = 0.0;
}
else
{
for(unsigned int i=0; i<r1.size(); i++)
{
a1 += r1[i]->rating;
}
a1avg = a1/r1.size();
}
if(r2.size()==0)
{
b1avg=0.0;
}
else
{
for(unsigned int i=0; i<r2.size(); i++)
{
b1 += r2[i]->rating;
}
b1avg = b1/r2.size();
}
return(a1avg > b1avg);
}
};
void Main_Window::RSort()
{
RatingProdSort rps;
rps.ds = ds;
ProductList->clear();
if(hits.size()==0)
{
cout<<hits.size()<<endl;
return;
}
else
{
mergeSort(hits, rps);
for(unsigned int i=0; i<hits.size(); i++)
{
hits[i]->displayString();
QString qs = QString::fromStdString(hits[i]->displayString());
ProductList->addItem(qs);
}
}
}
void Main_Window::ADDCART()
{
if(productCount < 0)
{
return;
}
else
{
currentuser = UserDropdown->currentText().toStdString();
ds.addCart(currentuser, hits[productCount]);
}
}
void Main_Window::filler(int index)
{
index4u = index;
}
void Main_Window::VIEWCART()
{
QWidget* CartBox = new QWidget();
currentuser = UserDropdown->currentText().toStdString();
CartBox->setWindowTitle(QString::fromStdString(currentuser));
QVBoxLayout* cartWindowLayout = new QVBoxLayout();
QLabel* cartWindowLabel = new QLabel("Shopping Cart");
cartWindowLayout->addWidget(cartWindowLabel);
QListWidget* cartList = new QListWidget();
connect(cartList, SIGNAL(currentRowChanged(int)), this, SLOT(ReviewChange(int)));
cartref = cartList;
cartWindowLayout->addWidget(cartList);
hits = ds.viewCart(currentuser);
for(unsigned int i=0; i<hits.size(); i++)
{
std::string strtemp = (hits[i])->displayString();
QString qs = QString::fromStdString(strtemp);
cartList->addItem(qs);
}
QPushButton* BuyButton = new QPushButton("Buy-Cart");
connect(BuyButton, SIGNAL(clicked()), this, SLOT(PUSHBUYBUTTON()));
cartWindowLayout->addWidget(BuyButton);
QPushButton* RemoveButton = new QPushButton("Remove-Cart");
connect(RemoveButton, SIGNAL(clicked()), this, SLOT(PUSHREMOVEBUTTON()));
cartWindowLayout->addWidget(RemoveButton);
QPushButton* CloseButton = new QPushButton("Close");
connect(CloseButton, SIGNAL(clicked()), CartBox, SLOT(close()));
cartWindowLayout->addWidget(CloseButton);
CartBox->setLayout(cartWindowLayout);
CartBox->show();
}
void Main_Window::SAVE()
{
if(SaveInput->text().isEmpty() == true)
{
QMessageBox::warning(this, "Error Save", "ENTER VALID FILENAME");
}
else
{
std::string filename (SaveInput->text().toStdString());
std::ofstream ofile(filename.c_str());
ds.dump(ofile);
ofile.close();
}
SaveInput->clear();
}
void Main_Window::QUIT()
{
QApplication::quit();
}
void Main_Window::ADDREVIEW()
{
if(DateLine->text().isEmpty() || TextLine->text().isEmpty() || RatingLine->text().isEmpty())
{
QMessageBox::warning(this, "Error Add Review", "ENTER SOMETHING IN DATE, TEXT REVIEW, AND RATING");
}
else if(RatingLine->text().isEmpty() == false && (DateLine->text().isEmpty() == false && TextLine->text().isEmpty() == false))
{
std::string date (DateLine->text().toStdString());
int rating1 (RatingLine->text().toInt());
std::string text (TextLine->text().toStdString());
if(rating1 <1 || rating1 >5)
{
QMessageBox::warning(this, "ERROR", "DID NOT ENTER VALID RATING RANGE");
}
int position = 0;
int position1 = 5;
int position2 = 8;
for(unsigned int i=0; i<6; i++)
{
if(date[i] == '-')
{
std::string year = date.substr(position,(i-position));
if(year.size() !=4)
{
QMessageBox::warning(this, "ERROR", "ENTER VALID YEAR RANGE AND FORMAT");
}
position = i+1;
}
}
for(unsigned int i=5; i<date.size(); i++)
{
if(date[i] == '-')
{
std:: string month = date.substr(position1, (i-position1));
if(month.size() != 2)
{
QMessageBox::warning(this, "ERROR", "ENTER VALID YEAR RANGE AND FORMAT");
}
position = i+1;
}
}
for(unsigned int i=8; i<date.size(); i++)
{
if(date[i] == '-')
{
std:: string month = date.substr(position2, (i-position2));
if(month.size() != 2)
{
QMessageBox::warning(this, "ERROR", "ENTER VALID MONTH/DAY RANGE AND FORMAT");
}
position = i+1;
}
}
Review *r = new Review();
r->prodName = hits[ProductList->currentRow()]->getName();
r->rating = rating1;
r->date = date;
r->reviewText = text;
ds.addReview(r);
displayReviews();
}
DateLine->clear();
TextLine->clear();
RatingLine->clear();
}
void Main_Window::ProductChange(int productcounter)
{
productCount = productcounter;
if(productCount < 0)
{
return;
}
else
{
displayReviews();
}
}
void Main_Window::ReviewChange(int usercartcounter)
{
UserCount = usercartcounter;
if(UserCount < 0)
{
return;
}
else
{
}
}
void Main_Window::displayReviews()
{
ReviewList->clear();
std::string name = hits[productCount]->getName();
std::map<std::string, std::vector <Review*> > reviewMap = ds.getReviewMap();
std::vector<Review*> reviews = reviewMap[name];
//msort(reviews, compname)
for(unsigned int i=0; i<reviews.size(); i++)
{
std::ostringstream oss;
oss << reviews[i]->rating << " " << reviews[i]->date << " " << reviews[i]->reviewText;
std::string temp = oss.str();
QString qstr1 = QString::fromStdString(temp);
ReviewList->addItem(qstr1);
}
}
void Main_Window::PUSHBUYBUTTON()
{
ds.buyCart(currentuser);
cartref->clear();
hits = ds.viewCart(currentuser);
for(unsigned int i=0; i<hits.size(); i++)
{
std::string strtemp = (hits[i])->displayString();
QString qs = QString::fromStdString(strtemp);
cartref->addItem(qs);
}
}
void Main_Window::PUSHREMOVEBUTTON()
{
ds.removeCart(currentuser, UserCount);
cartref->clear();
hits = ds.removeCart(currentuser, UserCount);
for(unsigned int i=0; i<hits.size(); i++)
{
std::string strtemp = (hits[i])->displayString();
QString qs = QString::fromStdString(strtemp);
cartref->addItem(qs);
}
}
| [
"briankwa@usc.edu"
] | briankwa@usc.edu |